/* glplpx6e.c */

/* (reserved for copyright notice) */

#include <float.h>
#include <math.h>
#include <stdlib.h>
#include "glplib.h"
#include "glplpx.h"
#include "glpssx.h"

/*----------------------------------------------------------------------
// lpx_exact - easy-to-use driver to the exact simplex method.
//
// SYNOPSIS
//
// #include "glplpx.h"
// int lpx_exact(LPX *lp);
//
// DESCRIPTION
//
// The routine lpx_exact is an easy-to-use driver to the two-phase
// primal simplex method based on exact (bignum) arithmetic.
//
// RETURNS
//
// The routine lpx_exact returns one of the following exit codes:
//
// LPX_E_OK       LP problem successfully solved.
//
// LPX_E_FAULT    either the LP problem has no rows and/or columns, or
//                the initial basis is invalid, or the basis matrix is
//                exactly singular.
//
// LPX_E_ITLIM    iterations limit exceeded.
//
// LPX_E_TMLIM    time limit exceeded.
----------------------------------------------------------------------*/

static void set_d_eps(mpq_t x, double val)
{     /* convert double val to rational x obtaining a more adequate
         fraction than provided by mpq_set_d due to allowing a small
         approximation error specified by a given relative tolerance;
         for example, mpq_set_d would give the following
         1/3 ~= 0.333333333333333314829616256247391... ->
             -> 6004799503160661/18014398509481984
         while this routine gives exactly 1/3 */
      int s, n, j;
      double f, p, q, eps = 1e-9;
      mpq_t temp;
      insist(-DBL_MAX <= val && val <= +DBL_MAX);
      if (val > 0.0)
         s = +1;
      else if (val < 0.0)
         s = -1;
      else
      {  mpq_set_si(x, 0, 1);
         goto done;
      }
      f = frexp(fabs(val), &n);
      /* |val| = f * 2^n, where 0.5 <= f < 1.0 */
      fp2rat(f, 0.1 * eps, &p, &q);
      /* f ~= p / q, where p and q are integers */
      mpq_init(temp);
      mpq_set_d(x, p);
      mpq_set_d(temp, q);
      mpq_div(x, x, temp);
      mpq_set_si(temp, 1, 1);
      for (j = 1; j <= abs(n); j++)
         mpq_add(temp, temp, temp);
      if (n > 0)
         mpq_mul(x, x, temp);
      else if (n < 0)
         mpq_div(x, x, temp);
      mpq_clear(temp);
      if (s < 0) mpq_neg(x, x);
      /* check that the desired tolerance has been attained */
      insist(fabs(val - mpq_get_d(x)) <= eps * (1.0 + fabs(val)));
done: return;
}

static void load_data(SSX *ssx, LPX *lp)
{     /* load LP problem data into simplex solver workspace */
      int m = ssx->m;
      int n = ssx->n;
      int nnz = ssx->A_ptr[n+1]-1;
      int j, k, type, loc, len, *ind;
      double lb, ub, coef, *val;
      insist(lpx_get_num_rows(lp) == m);
      insist(lpx_get_num_cols(lp) == n);
      insist(lpx_get_num_nz(lp) == nnz);
      /* types and bounds of rows and columns */
      for (k = 1; k <= m+n; k++)
      {  if (k <= m)
         {  type = lpx_get_row_type(lp, k);
            lb = lpx_get_row_lb(lp, k);
            ub = lpx_get_row_ub(lp, k);
         }
         else
         {  type = lpx_get_col_type(lp, k-m);
            lb = lpx_get_col_lb(lp, k-m);
            ub = lpx_get_col_ub(lp, k-m);
         }
         switch (type)
         {  case LPX_FR: type = SSX_FR; break;
            case LPX_LO: type = SSX_LO; break;
            case LPX_UP: type = SSX_UP; break;
            case LPX_DB: type = SSX_DB; break;
            case LPX_FX: type = SSX_FX; break;
            default: insist(type != type);
         }
         ssx->type[k] = type;
         set_d_eps(ssx->lb[k], lb);
         set_d_eps(ssx->ub[k], ub);
      }
      /* optimization direction */
      switch (lpx_get_obj_dir(lp))
      {  case LPX_MIN: ssx->dir = SSX_MIN; break;
         case LPX_MAX: ssx->dir = SSX_MAX; break;
         default: insist(lp != lp);
      }
      /* objective coefficients */
      for (k = 0; k <= m+n; k++)
      {  if (k == 0)
            coef = lpx_get_obj_coef(lp, 0);
         else if (k <= m)
            coef = 0.0;
         else
            coef = lpx_get_obj_coef(lp, k-m);
         set_d_eps(ssx->coef[k], coef);
      }
      /* constraint coefficients */
      ind = ucalloc(1+m, sizeof(int));
      val = ucalloc(1+m, sizeof(double));
      loc = 0;
      for (j = 1; j <= n; j++)
      {  ssx->A_ptr[j] = loc+1;
         len = lpx_get_mat_col(lp, j, ind, val);
         for (k = 1; k <= len; k++)
         {  loc++;
            ssx->A_ind[loc] = ind[k];
            set_d_eps(ssx->A_val[loc], val[k]);
         }
      }
      insist(loc == nnz);
      ufree(ind);
      ufree(val);
      return;
}

static int load_basis(SSX *ssx, LPX *lp)
{     /* load current LP basis into simplex solver workspace */
      int m = ssx->m;
      int n = ssx->n;
      int *type = ssx->type;
      int *stat = ssx->stat;
      int *Q_row = ssx->Q_row;
      int *Q_col = ssx->Q_col;
      int i, j, k;
      insist(lpx_get_num_rows(lp) == m);
      insist(lpx_get_num_cols(lp) == n);
      /* statuses of rows and columns */
      for (k = 1; k <= m+n; k++)
      {  if (k <= m)
            stat[k] = lpx_get_row_stat(lp, k);
         else
            stat[k] = lpx_get_col_stat(lp, k-m);
         switch (stat[k])
         {  case LPX_BS:
               stat[k] = SSX_BS;
               break;
            case LPX_NL:
               stat[k] = SSX_NL;
               insist(type[k] == SSX_LO || type[k] == SSX_DB);
               break;
            case LPX_NU:
               stat[k] = SSX_NU;
               insist(type[k] == SSX_UP || type[k] == SSX_DB);
               break;
            case LPX_NF:
               stat[k] = SSX_NF;
               insist(type[k] == SSX_FR);
               break;
            case LPX_NS:
               stat[k] = SSX_NS;
               insist(type[k] == SSX_FX);
               break;
            default:
               insist(stat != stat);
         }
      }
      /* build permutation matix Q */
      i = j = 0;
      for (k = 1; k <= m+n; k++)
      {  if (stat[k] == SSX_BS)
         {  i++;
            if (i > m) return 1;
            Q_row[k] = i, Q_col[i] = k;
         }
         else
         {  j++;
            if (j > n) return 1;
            Q_row[k] = m+j, Q_col[m+j] = k;
         }
      }
      insist(i == m && j == n);
      return 0;
}

int lpx_exact(LPX *lp)
{     SSX *ssx;
      int m = lpx_get_num_rows(lp);
      int n = lpx_get_num_cols(lp);
      int nnz = lpx_get_num_nz(lp);
      int i, j, k, type, pst, dst, ret, *stat;
      double lb, ub, *prim, *dual;
      /* the problem must have at least one row and one column */
      if (!(m > 0 && n > 0))
      {  print("lpx_exact: problem has no rows/columns");
         return LPX_E_FAULT;
      }
      /* check that all double-bounded variables have correct bounds */
      for (k = 1; k <= m+n; k++)
      {  if (k <= m)
         {  type = lpx_get_row_type(lp, k);
            lb = lpx_get_row_lb(lp, k);
            ub = lpx_get_row_ub(lp, k);
         }
         else
         {  type = lpx_get_col_type(lp, k-m);
            lb = lpx_get_col_lb(lp, k-m);
            ub = lpx_get_col_ub(lp, k-m);
         }
         if (type == LPX_DB && lb >= ub)
         {  print("lpx_exact: %s %d has invalid bounds",
               k <= m ? "row" : "column", k <= m ? k : k-m);
            return LPX_E_FAULT;
         }
      }
      /* create the simplex solver workspace */
      print("lpx_exact: %d rows, %d columns, %d non-zeros", m, n, nnz);
#ifdef GLP_USE_GMP
      print("GNU MP library is being used");
#else
      print("GLPK bignum module is being used");
      print("(Consider installing GNU MP to attain a much better perfor"
         "mance.)");
#endif
      ssx = ssx_create(m, n, nnz);
      /* load LP problem data into the workspace */
      load_data(ssx, lp);
      /* load current LP basis into the workspace */
      if (load_basis(ssx, lp))
      {  print("lpx_exact: initial LP basis is invalid");
         ret = LPX_E_FAULT;
         goto done;
      }
      /* inherit some control parameters from the LP object */
      ssx->it_lim = lpx_get_int_parm(lp, LPX_K_ITLIM);
      ssx->it_cnt = lpx_get_int_parm(lp, LPX_K_ITCNT);
      ssx->tm_lim = lpx_get_real_parm(lp, LPX_K_TMLIM);
      ssx->out_frq = 5.0;
      ssx->tm_beg = utime();
      ssx->tm_lag = 0.0;
      /* solve LP */
      ret = ssx_driver(ssx);
      /* copy back some statistics to the LP object */
      lpx_set_int_parm(lp, LPX_K_ITLIM, ssx->it_lim);
      lpx_set_int_parm(lp, LPX_K_ITCNT, ssx->it_cnt);
      lpx_set_real_parm(lp, LPX_K_TMLIM, ssx->tm_lim);
      /* analyze the return code */
      switch (ret)
      {  case 0:
            /* optimal solution found */
            pst = LPX_P_FEAS, dst = LPX_D_FEAS;
            break;
         case 1:
            /* problem has no feasible solution */
            pst = LPX_P_NOFEAS, dst = LPX_D_INFEAS;
            break;
         case 2:
            /* problem has unbounded solution */
            pst = LPX_P_FEAS, dst = LPX_D_NOFEAS;
            break;
         case 3:
            /* iterations limit exceeded (phase I) */
            pst = LPX_P_INFEAS, dst = LPX_D_INFEAS;
            break;
         case 4:
            /* iterations limit exceeded (phase II) */
            pst = LPX_P_FEAS, dst = LPX_D_INFEAS;
            break;
         case 5:
            /* time limit exceeded (phase I) */
            pst = LPX_P_INFEAS, dst = LPX_D_INFEAS;
            break;
         case 6:
            /* time limit exceeded (phase II) */
            pst = LPX_P_FEAS, dst = LPX_D_INFEAS;
            break;
         case 7:
            /* initial basis matrix is singular */
            ret = LPX_E_FAULT;
            goto done;
         default:
            insist(ret != ret);
      }
      ret = LPX_E_OK;
      /* obtain final basic solution components */
      stat = ucalloc(1+m+n, sizeof(int));
      prim = ucalloc(1+m+n, sizeof(double));
      dual = ucalloc(1+m+n, sizeof(double));
      for (k = 1; k <= m+n; k++)
      {  if (ssx->stat[k] == SSX_BS)
         {  i = ssx->Q_row[k]; /* x[k] = xB[i] */
            insist(1 <= i && i <= m);
            stat[k] = LPX_BS;
            prim[k] = mpq_get_d(ssx->bbar[i]);
            dual[k] = 0.0;
         }
         else
         {  j = ssx->Q_row[k] - m; /* x[k] = xN[j] */
            insist(1 <= j && j <= n);
            switch (ssx->stat[k])
            {  case SSX_NF:
                  stat[k] = LPX_NF;
                  prim[k] = 0.0;
                  break;
               case SSX_NL:
                  stat[k] = LPX_NL;
                  prim[k] = mpq_get_d(ssx->lb[k]);
                  break;
               case SSX_NU:
                  stat[k] = LPX_NU;
                  prim[k] = mpq_get_d(ssx->ub[k]);
                  break;
               case SSX_NS:
                  stat[k] = LPX_NS;
                  prim[k] = mpq_get_d(ssx->lb[k]);
                  break;
               default:
                  insist(ssx != ssx);
            }
            dual[k] = mpq_get_d(ssx->cbar[j]);
         }
      }
      /* and store them into the LP object */
      lpx_put_solution(lp, pst, dst, &stat[0], &prim[0], &dual[0],
         &stat[m], &prim[m], &dual[m]);
      ufree(stat);
      ufree(prim);
      ufree(dual);
done: /* delete the simplex solver workspace */
      ssx_delete(ssx);
      /* return to the application program */
      return ret;
}

/* eof */
