예제 #1
0
파일: lp.c 프로젝트: danielriosgarza/pyglpk
static PyObject* LPX_getkind(LPXObject *self, void *closure)
{
	PyObject *retval = NULL;
	retval = (PyObject*)(glp_get_num_int(LP) ? &PyInt_Type : &PyFloat_Type);
	Py_INCREF(retval);
	return retval;
}
예제 #2
0
static PyObject* Bar_getspecvarvalm(BarObject *self,
				    double(*valfuncs[])(glp_prob*, int)) {
  if (!Bar_Valid(self, 1)) return NULL;
  if (glp_get_num_int(LP) == 0) {
    PyErr_SetString(PyExc_TypeError,
		    "MIP values require mixed integer problem");
    return NULL;
  }
  double(*valfunc)(glp_prob*, int) = valfuncs[Bar_Row(self) ? 1 : 0];
  return PyFloat_FromDouble(valfunc(LP, Bar_Index(self)+1));
}
예제 #3
0
int glp_intopt(glp_prob *P, const glp_iocp *parm)
{     /* solve MIP problem with the branch-and-bound method */
      glp_iocp _parm;
      int i, j, ret;
      /* check problem object */
      if (P == NULL || P->magic != GLP_PROB_MAGIC)
         xerror("glp_intopt: P = %p; invalid problem object\n", P);
      if (P->tree != NULL)
         xerror("glp_intopt: operation not allowed\n");
      /* check control parameters */
      if (parm == NULL)
         parm = &_parm, glp_init_iocp((glp_iocp *)parm);
      if (!(parm->msg_lev == GLP_MSG_OFF ||
            parm->msg_lev == GLP_MSG_ERR ||
            parm->msg_lev == GLP_MSG_ON  ||
            parm->msg_lev == GLP_MSG_ALL ||
            parm->msg_lev == GLP_MSG_DBG))
         xerror("glp_intopt: msg_lev = %d; invalid parameter\n",
            parm->msg_lev);
      if (!(parm->br_tech == GLP_BR_FFV ||
            parm->br_tech == GLP_BR_LFV ||
            parm->br_tech == GLP_BR_MFV ||
            parm->br_tech == GLP_BR_DTH ||
            parm->br_tech == GLP_BR_PCH))
         xerror("glp_intopt: br_tech = %d; invalid parameter\n",
            parm->br_tech);
      if (!(parm->bt_tech == GLP_BT_DFS ||
            parm->bt_tech == GLP_BT_BFS ||
            parm->bt_tech == GLP_BT_BLB ||
            parm->bt_tech == GLP_BT_BPH))
         xerror("glp_intopt: bt_tech = %d; invalid parameter\n",
            parm->bt_tech);
      if (!(0.0 < parm->tol_int && parm->tol_int < 1.0))
         xerror("glp_intopt: tol_int = %g; invalid parameter\n",
            parm->tol_int);
      if (!(0.0 < parm->tol_obj && parm->tol_obj < 1.0))
         xerror("glp_intopt: tol_obj = %g; invalid parameter\n",
            parm->tol_obj);
      if (parm->tm_lim < 0)
         xerror("glp_intopt: tm_lim = %d; invalid parameter\n",
            parm->tm_lim);
      if (parm->out_frq < 0)
         xerror("glp_intopt: out_frq = %d; invalid parameter\n",
            parm->out_frq);
      if (parm->out_dly < 0)
         xerror("glp_intopt: out_dly = %d; invalid parameter\n",
            parm->out_dly);
      if (!(0 <= parm->cb_size && parm->cb_size <= 256))
         xerror("glp_intopt: cb_size = %d; invalid parameter\n",
            parm->cb_size);
      if (!(parm->pp_tech == GLP_PP_NONE ||
            parm->pp_tech == GLP_PP_ROOT ||
            parm->pp_tech == GLP_PP_ALL))
         xerror("glp_intopt: pp_tech = %d; invalid parameter\n",
            parm->pp_tech);
      if (parm->mip_gap < 0.0)
         xerror("glp_intopt: mip_gap = %g; invalid parameter\n",
            parm->mip_gap);
      if (!(parm->mir_cuts == GLP_ON || parm->mir_cuts == GLP_OFF))
         xerror("glp_intopt: mir_cuts = %d; invalid parameter\n",
            parm->mir_cuts);
      if (!(parm->gmi_cuts == GLP_ON || parm->gmi_cuts == GLP_OFF))
         xerror("glp_intopt: gmi_cuts = %d; invalid parameter\n",
            parm->gmi_cuts);
      if (!(parm->cov_cuts == GLP_ON || parm->cov_cuts == GLP_OFF))
         xerror("glp_intopt: cov_cuts = %d; invalid parameter\n",
            parm->cov_cuts);
      if (!(parm->clq_cuts == GLP_ON || parm->clq_cuts == GLP_OFF))
         xerror("glp_intopt: clq_cuts = %d; invalid parameter\n",
            parm->clq_cuts);
      if (!(parm->presolve == GLP_ON || parm->presolve == GLP_OFF))
         xerror("glp_intopt: presolve = %d; invalid parameter\n",
            parm->presolve);
      if (!(parm->binarize == GLP_ON || parm->binarize == GLP_OFF))
         xerror("glp_intopt: binarize = %d; invalid parameter\n",
            parm->binarize);
      if (!(parm->fp_heur == GLP_ON || parm->fp_heur == GLP_OFF))
         xerror("glp_intopt: fp_heur = %d; invalid parameter\n",
            parm->fp_heur);
#if 1 /* 28/V-2010 */
      if (!(parm->alien == GLP_ON || parm->alien == GLP_OFF))
         xerror("glp_intopt: alien = %d; invalid parameter\n",
            parm->alien);
#endif
#if 0 /* 11/VII-2013 */
      /* integer solution is currently undefined */
      P->mip_stat = GLP_UNDEF;
      P->mip_obj = 0.0;
#else
      if (!parm->use_sol)
         P->mip_stat = GLP_UNDEF;
      if (P->mip_stat == GLP_NOFEAS)
         P->mip_stat = GLP_UNDEF;
      if (P->mip_stat == GLP_UNDEF)
         P->mip_obj = 0.0;
      else if (P->mip_stat == GLP_OPT)
         P->mip_stat = GLP_FEAS;
#endif
      /* check bounds of double-bounded variables */
      for (i = 1; i <= P->m; i++)
      {  GLPROW *row = P->row[i];
         if (row->type == GLP_DB && row->lb >= row->ub)
         {  if (parm->msg_lev >= GLP_MSG_ERR)
               xprintf("glp_intopt: row %d: lb = %g, ub = %g; incorrect"
                  " bounds\n", i, row->lb, row->ub);
            ret = GLP_EBOUND;
            goto done;
         }
      }
      for (j = 1; j <= P->n; j++)
      {  GLPCOL *col = P->col[j];
         if (col->type == GLP_DB && col->lb >= col->ub)
         {  if (parm->msg_lev >= GLP_MSG_ERR)
               xprintf("glp_intopt: column %d: lb = %g, ub = %g; incorr"
                  "ect bounds\n", j, col->lb, col->ub);
            ret = GLP_EBOUND;
            goto done;
         }
      }
      /* bounds of all integer variables must be integral */
      for (j = 1; j <= P->n; j++)
      {  GLPCOL *col = P->col[j];
         if (col->kind != GLP_IV) continue;
         if (col->type == GLP_LO || col->type == GLP_DB)
         {  if (col->lb != floor(col->lb))
            {  if (parm->msg_lev >= GLP_MSG_ERR)
                  xprintf("glp_intopt: integer column %d has non-intege"
                     "r lower bound %g\n", j, col->lb);
               ret = GLP_EBOUND;
               goto done;
            }
         }
         if (col->type == GLP_UP || col->type == GLP_DB)
         {  if (col->ub != floor(col->ub))
            {  if (parm->msg_lev >= GLP_MSG_ERR)
                  xprintf("glp_intopt: integer column %d has non-intege"
                     "r upper bound %g\n", j, col->ub);
               ret = GLP_EBOUND;
               goto done;
            }
         }
         if (col->type == GLP_FX)
         {  if (col->lb != floor(col->lb))
            {  if (parm->msg_lev >= GLP_MSG_ERR)
                  xprintf("glp_intopt: integer column %d has non-intege"
                     "r fixed value %g\n", j, col->lb);
               ret = GLP_EBOUND;
               goto done;
            }
         }
      }
      /* solve MIP problem */
      if (parm->msg_lev >= GLP_MSG_ALL)
      {  int ni = glp_get_num_int(P);
         int nb = glp_get_num_bin(P);
         char s[50];
         xprintf("GLPK Integer Optimizer, v%s\n", glp_version());
         xprintf("%d row%s, %d column%s, %d non-zero%s\n",
            P->m, P->m == 1 ? "" : "s", P->n, P->n == 1 ? "" : "s",
            P->nnz, P->nnz == 1 ? "" : "s");
         if (nb == 0)
            strcpy(s, "none of");
         else if (ni == 1 && nb == 1)
            strcpy(s, "");
         else if (nb == 1)
            strcpy(s, "one of");
         else if (nb == ni)
            strcpy(s, "all of");
         else
            sprintf(s, "%d of", nb);
         xprintf("%d integer variable%s, %s which %s binary\n",
            ni, ni == 1 ? "" : "s", s, nb == 1 ? "is" : "are");
      }
#if 1 /* 28/V-2010 */
      if (parm->alien)
      {  /* use alien integer optimizer */
         ret = _glp_intopt1(P, parm);
         goto done;
      }
#endif
      if (!parm->presolve)
#if 0 /* 11/VII-2013 */
         ret = solve_mip(P, parm);
#else
         ret = solve_mip(P, parm, P, NULL);
#endif
      else
예제 #4
0
static int preprocess_and_solve_mip(glp_prob *P, const glp_iocp *parm)
{     /* solve MIP using the preprocessor */
      ENV *env = get_env_ptr();
      int term_out = env->term_out;
      NPP *npp;
      glp_prob *mip = NULL;
      glp_bfcp bfcp;
      glp_smcp smcp;
      int ret;
      if (parm->msg_lev >= GLP_MSG_ALL)
         xprintf("Preprocessing...\n");
      /* create preprocessor workspace */
      npp = npp_create_wksp();
      /* load original problem into the preprocessor workspace */
      npp_load_prob(npp, P, GLP_OFF, GLP_MIP, GLP_OFF);
      /* process MIP prior to applying the branch-and-bound method */
      if (!term_out || parm->msg_lev < GLP_MSG_ALL)
         env->term_out = GLP_OFF;
      else
         env->term_out = GLP_ON;
      ret = npp_integer(npp, parm);
      env->term_out = term_out;
      if (ret == 0)
         ;
      else if (ret == GLP_ENOPFS)
      {  if (parm->msg_lev >= GLP_MSG_ALL)
            xprintf("PROBLEM HAS NO PRIMAL FEASIBLE SOLUTION\n");
      }
      else if (ret == GLP_ENODFS)
      {  if (parm->msg_lev >= GLP_MSG_ALL)
            xprintf("LP RELAXATION HAS NO DUAL FEASIBLE SOLUTION\n");
      }
      else
         xassert(ret != ret);
      if (ret != 0) goto done;
      /* build transformed MIP */
      mip = glp_create_prob();
      npp_build_prob(npp, mip);
      /* if the transformed MIP is empty, it has empty solution, which
         is optimal */
      if (mip->m == 0 && mip->n == 0)
      {  mip->mip_stat = GLP_OPT;
         mip->mip_obj = mip->c0;
         if (parm->msg_lev >= GLP_MSG_ALL)
         {  xprintf("Objective value = %17.9e\n", mip->mip_obj);
            xprintf("INTEGER OPTIMAL SOLUTION FOUND BY MIP PREPROCESSOR"
               "\n");
         }
         goto post;
      }
      /* display some statistics */
      if (parm->msg_lev >= GLP_MSG_ALL)
      {  int ni = glp_get_num_int(mip);
         int nb = glp_get_num_bin(mip);
         char s[50];
         xprintf("%d row%s, %d column%s, %d non-zero%s\n",
            mip->m, mip->m == 1 ? "" : "s", mip->n, mip->n == 1 ? "" :
            "s", mip->nnz, mip->nnz == 1 ? "" : "s");
         if (nb == 0)
            strcpy(s, "none of");
         else if (ni == 1 && nb == 1)
            strcpy(s, "");
         else if (nb == 1)
            strcpy(s, "one of");
         else if (nb == ni)
            strcpy(s, "all of");
         else
            sprintf(s, "%d of", nb);
         xprintf("%d integer variable%s, %s which %s binary\n",
            ni, ni == 1 ? "" : "s", s, nb == 1 ? "is" : "are");
      }
      /* inherit basis factorization control parameters */
      glp_get_bfcp(P, &bfcp);
      glp_set_bfcp(mip, &bfcp);
      /* scale the transformed problem */
      if (!term_out || parm->msg_lev < GLP_MSG_ALL)
         env->term_out = GLP_OFF;
      else
         env->term_out = GLP_ON;
      glp_scale_prob(mip,
         GLP_SF_GM | GLP_SF_EQ | GLP_SF_2N | GLP_SF_SKIP);
      env->term_out = term_out;
      /* build advanced initial basis */
      if (!term_out || parm->msg_lev < GLP_MSG_ALL)
         env->term_out = GLP_OFF;
      else
         env->term_out = GLP_ON;
      glp_adv_basis(mip, 0);
      env->term_out = term_out;
      /* solve initial LP relaxation */
      if (parm->msg_lev >= GLP_MSG_ALL)
         xprintf("Solving LP relaxation...\n");
      glp_init_smcp(&smcp);
      smcp.msg_lev = parm->msg_lev;
      mip->it_cnt = P->it_cnt;
      ret = glp_simplex(mip, &smcp);
      P->it_cnt = mip->it_cnt;
      if (ret != 0)
      {  if (parm->msg_lev >= GLP_MSG_ERR)
            xprintf("glp_intopt: cannot solve LP relaxation\n");
         ret = GLP_EFAIL;
         goto done;
      }
      /* check status of the basic solution */
      ret = glp_get_status(mip);
      if (ret == GLP_OPT)
         ret = 0;
      else if (ret == GLP_NOFEAS)
         ret = GLP_ENOPFS;
      else if (ret == GLP_UNBND)
         ret = GLP_ENODFS;
      else
         xassert(ret != ret);
      if (ret != 0) goto done;
      /* solve the transformed MIP */
      mip->it_cnt = P->it_cnt;
#if 0 /* 11/VII-2013 */
      ret = solve_mip(mip, parm);
#else
      if (parm->use_sol)
      {  mip->mip_stat = P->mip_stat;
         mip->mip_obj = P->mip_obj;
      }
      ret = solve_mip(mip, parm, P, npp);
#endif
      P->it_cnt = mip->it_cnt;
      /* only integer feasible solution can be postprocessed */
      if (!(mip->mip_stat == GLP_OPT || mip->mip_stat == GLP_FEAS))
      {  P->mip_stat = mip->mip_stat;
         goto done;
      }
      /* postprocess solution from the transformed MIP */
post: npp_postprocess(npp, mip);
      /* the transformed MIP is no longer needed */
      glp_delete_prob(mip), mip = NULL;
      /* store solution to the original problem */
      npp_unload_sol(npp, P);
done: /* delete the transformed MIP, if it exists */
      if (mip != NULL) glp_delete_prob(mip);
      /* delete preprocessor workspace */
      npp_delete_wksp(npp);
      return ret;
}
예제 #5
0
int glp_print_mip(glp_prob *P, const char *fname)
{   /* write MIP solution in printable format */
    glp_file *fp;
    GLPROW *row;
    GLPCOL *col;
    int i, j, t, ae_ind, re_ind, ret;
    double ae_max, re_max;
    xprintf("Writing MIP solution to '%s'...\n", fname);
    fp = glp_open(fname, "w");
    if (fp == NULL)
    {   xprintf("Unable to create '%s' - %s\n", fname, get_err_msg());
        ret = 1;
        goto done;
    }
    xfprintf(fp, "%-12s%s\n", "Problem:",
             P->name == NULL ? "" : P->name);
    xfprintf(fp, "%-12s%d\n", "Rows:", P->m);
    xfprintf(fp, "%-12s%d (%d integer, %d binary)\n", "Columns:",
             P->n, glp_get_num_int(P), glp_get_num_bin(P));
    xfprintf(fp, "%-12s%d\n", "Non-zeros:", P->nnz);
    t = glp_mip_status(P);
    xfprintf(fp, "%-12s%s\n", "Status:",
             t == GLP_OPT    ? "INTEGER OPTIMAL" :
             t == GLP_FEAS   ? "INTEGER NON-OPTIMAL" :
             t == GLP_NOFEAS ? "INTEGER EMPTY" :
             t == GLP_UNDEF  ? "INTEGER UNDEFINED" : "???");
    xfprintf(fp, "%-12s%s%s%.10g (%s)\n", "Objective:",
             P->obj == NULL ? "" : P->obj,
             P->obj == NULL ? "" : " = ", P->mip_obj,
             P->dir == GLP_MIN ? "MINimum" :
             P->dir == GLP_MAX ? "MAXimum" : "???");
    xfprintf(fp, "\n");
    xfprintf(fp, "   No.   Row name        Activity     Lower bound  "
             " Upper bound\n");
    xfprintf(fp, "------ ------------    ------------- ------------- "
             "-------------\n");
    for (i = 1; i <= P->m; i++)
    {   row = P->row[i];
        xfprintf(fp, "%6d ", i);
        if (row->name == NULL || strlen(row->name) <= 12)
            xfprintf(fp, "%-12s ", row->name == NULL ? "" : row->name);
        else
            xfprintf(fp, "%s\n%20s", row->name, "");
        xfprintf(fp, "%3s", "");
        xfprintf(fp, "%13.6g ",
                 fabs(row->mipx) <= 1e-9 ? 0.0 : row->mipx);
        if (row->type == GLP_LO || row->type == GLP_DB ||
                row->type == GLP_FX)
            xfprintf(fp, "%13.6g ", row->lb);
        else
            xfprintf(fp, "%13s ", "");
        if (row->type == GLP_UP || row->type == GLP_DB)
            xfprintf(fp, "%13.6g ", row->ub);
        else
            xfprintf(fp, "%13s ", row->type == GLP_FX ? "=" : "");
        xfprintf(fp, "\n");
    }
    xfprintf(fp, "\n");
    xfprintf(fp, "   No. Column name       Activity     Lower bound  "
             " Upper bound\n");
    xfprintf(fp, "------ ------------    ------------- ------------- "
             "-------------\n");
    for (j = 1; j <= P->n; j++)
    {   col = P->col[j];
        xfprintf(fp, "%6d ", j);
        if (col->name == NULL || strlen(col->name) <= 12)
            xfprintf(fp, "%-12s ", col->name == NULL ? "" : col->name);
        else
            xfprintf(fp, "%s\n%20s", col->name, "");
        xfprintf(fp, "%s  ",
                 col->kind == GLP_CV ? " " :
                 col->kind == GLP_IV ? "*" : "?");
        xfprintf(fp, "%13.6g ",
                 fabs(col->mipx) <= 1e-9 ? 0.0 : col->mipx);
        if (col->type == GLP_LO || col->type == GLP_DB ||
                col->type == GLP_FX)
            xfprintf(fp, "%13.6g ", col->lb);
        else
            xfprintf(fp, "%13s ", "");
        if (col->type == GLP_UP || col->type == GLP_DB)
            xfprintf(fp, "%13.6g ", col->ub);
        else
            xfprintf(fp, "%13s ", col->type == GLP_FX ? "=" : "");
        xfprintf(fp, "\n");
    }
    xfprintf(fp, "\n");
    xfprintf(fp, "Integer feasibility conditions:\n");
    xfprintf(fp, "\n");
    glp_check_kkt(P, GLP_MIP, GLP_KKT_PE, &ae_max, &ae_ind, &re_max,
                  &re_ind);
    xfprintf(fp, "KKT.PE: max.abs.err = %.2e on row %d\n",
             ae_max, ae_ind);
    xfprintf(fp, "        max.rel.err = %.2e on row %d\n",
             re_max, re_ind);
    xfprintf(fp, "%8s%s\n", "",
             re_max <= 1e-9 ? "High quality" :
             re_max <= 1e-6 ? "Medium quality" :
             re_max <= 1e-3 ? "Low quality" : "SOLUTION IS WRONG");
    xfprintf(fp, "\n");
    glp_check_kkt(P, GLP_MIP, GLP_KKT_PB, &ae_max, &ae_ind, &re_max,
                  &re_ind);
    xfprintf(fp, "KKT.PB: max.abs.err = %.2e on %s %d\n",
             ae_max, ae_ind <= P->m ? "row" : "column",
             ae_ind <= P->m ? ae_ind : ae_ind - P->m);
    xfprintf(fp, "        max.rel.err = %.2e on %s %d\n",
             re_max, re_ind <= P->m ? "row" : "column",
             re_ind <= P->m ? re_ind : re_ind - P->m);
    xfprintf(fp, "%8s%s\n", "",
             re_max <= 1e-9 ? "High quality" :
             re_max <= 1e-6 ? "Medium quality" :
             re_max <= 1e-3 ? "Low quality" : "SOLUTION IS INFEASIBLE");
    xfprintf(fp, "\n");
    xfprintf(fp, "End of output\n");
#if 0 /* FIXME */
    xfflush(fp);
#endif
    if (glp_ioerr(fp))
    {   xprintf("Write error on '%s' - %s\n", fname, get_err_msg());
        ret = 1;
        goto done;
    }
    ret = 0;
done:
    if (fp != NULL) glp_close(fp);
    return ret;
}
예제 #6
0
파일: ppl_lpsol.c 프로젝트: hnxiao/ppl
static void
solve(char* file_name) {
  ppl_Constraint_System_t ppl_cs;
#ifndef NDEBUG
  ppl_Constraint_System_t ppl_cs_copy;
#endif
  ppl_Generator_t optimum_location;
  ppl_Linear_Expression_t ppl_le;
  int dimension, row, num_rows, column, nz, i, j, type;
  int* coefficient_index;
  double lb, ub;
  double* coefficient_value;
  mpq_t rational_lb, rational_ub;
  mpq_t* rational_coefficient;
  mpq_t* objective;
  ppl_Linear_Expression_t ppl_objective_le;
  ppl_Coefficient_t optimum_n;
  ppl_Coefficient_t optimum_d;
  mpq_t optimum;
  mpz_t den_lcm;
  int optimum_found;
  glp_mpscp glpk_mpscp;

  glpk_lp = glp_create_prob();
  glp_init_mpscp(&glpk_mpscp);

  if (verbosity == 0) {
    /* FIXME: find a way to suppress output from glp_read_mps. */
  }

#ifdef PPL_LPSOL_SUPPORTS_TIMINGS

  if (print_timings)
    start_clock();

#endif /* defined(PPL_LPSOL_SUPPORTS_TIMINGS) */

  if (glp_read_mps(glpk_lp, GLP_MPS_FILE, &glpk_mpscp, file_name) != 0)
    fatal("cannot read MPS file `%s'", file_name);

#ifdef PPL_LPSOL_SUPPORTS_TIMINGS

  if (print_timings) {
    fprintf(stderr, "Time to read the input file: ");
    print_clock(stderr);
    fprintf(stderr, " s\n");
    start_clock();
  }

#endif /* defined(PPL_LPSOL_SUPPORTS_TIMINGS) */

  glpk_lp_num_int = glp_get_num_int(glpk_lp);

  if (glpk_lp_num_int > 0 && !no_mip && !use_simplex)
     fatal("the enumeration solving method can not handle MIP problems");

  dimension = glp_get_num_cols(glpk_lp);

  /* Read variables constrained to be integer. */
  if (glpk_lp_num_int > 0 && !no_mip && use_simplex) {
    if (verbosity >= 4)
      fprintf(output_file, "Integer variables:\n");
    integer_variables = (ppl_dimension_type*)
      malloc((glpk_lp_num_int + 1)*sizeof(ppl_dimension_type));
    for (i = 0, j = 0; i < dimension; ++i) {
      int col_kind = glp_get_col_kind(glpk_lp, i+1);
      if (col_kind == GLP_IV || col_kind == GLP_BV) {
        integer_variables[j] = i;
        if (verbosity >= 4) {
          ppl_io_fprint_variable(output_file, i);
          fprintf(output_file, " ");
        }
        ++j;
      }
    }
  }
  coefficient_index = (int*) malloc((dimension+1)*sizeof(int));
  coefficient_value = (double*) malloc((dimension+1)*sizeof(double));
  rational_coefficient = (mpq_t*) malloc((dimension+1)*sizeof(mpq_t));


  ppl_new_Constraint_System(&ppl_cs);

  mpq_init(rational_lb);
  mpq_init(rational_ub);
  for (i = 1; i <= dimension; ++i)
    mpq_init(rational_coefficient[i]);

  mpz_init(den_lcm);

  if (verbosity >= 4)
    fprintf(output_file, "\nConstraints:\n");

  /* Set up the row (ordinary) constraints. */
  num_rows = glp_get_num_rows(glpk_lp);
  for (row = 1; row <= num_rows; ++row) {
    /* Initialize the least common multiple computation. */
    mpz_set_si(den_lcm, 1);
    /* Set `nz' to the number of non-zero coefficients. */
    nz = glp_get_mat_row(glpk_lp, row, coefficient_index, coefficient_value);
    for (i = 1; i <= nz; ++i) {
      set_mpq_t_from_double(rational_coefficient[i], coefficient_value[i]);
      /* Update den_lcm. */
      mpz_lcm(den_lcm, den_lcm, mpq_denref(rational_coefficient[i]));
    }

    lb = glp_get_row_lb(glpk_lp, row);
    ub = glp_get_row_ub(glpk_lp, row);

    set_mpq_t_from_double(rational_lb, lb);
    set_mpq_t_from_double(rational_ub, ub);

    mpz_lcm(den_lcm, den_lcm, mpq_denref(rational_lb));
    mpz_lcm(den_lcm, den_lcm, mpq_denref(rational_ub));

    ppl_new_Linear_Expression_with_dimension(&ppl_le, dimension);

    for (i = 1; i <= nz; ++i) {
      mpz_mul(tmp_z, den_lcm, mpq_numref(rational_coefficient[i]));
      mpz_divexact(tmp_z, tmp_z, mpq_denref(rational_coefficient[i]));
      ppl_assign_Coefficient_from_mpz_t(ppl_coeff, tmp_z);
      ppl_Linear_Expression_add_to_coefficient(ppl_le, coefficient_index[i]-1,
                                               ppl_coeff);
    }

    type = glp_get_row_type(glpk_lp, row);
    add_constraints(ppl_le, type, rational_lb, rational_ub, den_lcm, ppl_cs);

    ppl_delete_Linear_Expression(ppl_le);
  }

  free(coefficient_value);
  for (i = 1; i <= dimension; ++i)
    mpq_clear(rational_coefficient[i]);
  free(rational_coefficient);
  free(coefficient_index);

#ifndef NDEBUG
  ppl_new_Constraint_System_from_Constraint_System(&ppl_cs_copy, ppl_cs);
#endif

  /*
    FIXME: here we could build the polyhedron and minimize it before
    adding the variable bounds.
  */

  /* Set up the columns constraints, i.e., variable bounds. */
  for (column = 1; column <= dimension; ++column) {

    lb = glp_get_col_lb(glpk_lp, column);
    ub = glp_get_col_ub(glpk_lp, column);

    set_mpq_t_from_double(rational_lb, lb);
    set_mpq_t_from_double(rational_ub, ub);

    /* Initialize the least common multiple computation. */
    mpz_set_si(den_lcm, 1);
    mpz_lcm(den_lcm, den_lcm, mpq_denref(rational_lb));
    mpz_lcm(den_lcm, den_lcm, mpq_denref(rational_ub));

    ppl_new_Linear_Expression_with_dimension(&ppl_le, dimension);
    ppl_assign_Coefficient_from_mpz_t(ppl_coeff, den_lcm);
    ppl_Linear_Expression_add_to_coefficient(ppl_le, column-1, ppl_coeff);

    type = glp_get_col_type(glpk_lp, column);
    add_constraints(ppl_le, type, rational_lb, rational_ub, den_lcm, ppl_cs);

    ppl_delete_Linear_Expression(ppl_le);
  }

  mpq_clear(rational_ub);
  mpq_clear(rational_lb);

  /* Deal with the objective function. */
  objective = (mpq_t*) malloc((dimension+1)*sizeof(mpq_t));

  /* Initialize the least common multiple computation. */
  mpz_set_si(den_lcm, 1);

  mpq_init(objective[0]);
  set_mpq_t_from_double(objective[0], glp_get_obj_coef(glpk_lp, 0));
  for (i = 1; i <= dimension; ++i) {
    mpq_init(objective[i]);
    set_mpq_t_from_double(objective[i], glp_get_obj_coef(glpk_lp, i));
    /* Update den_lcm. */
    mpz_lcm(den_lcm, den_lcm, mpq_denref(objective[i]));
  }

  /* Set the ppl_objective_le to be the objective function. */
  ppl_new_Linear_Expression_with_dimension(&ppl_objective_le, dimension);
  /* Set value for objective function's inhomogeneous term. */
  mpz_mul(tmp_z, den_lcm, mpq_numref(objective[0]));
  mpz_divexact(tmp_z, tmp_z, mpq_denref(objective[0]));
  ppl_assign_Coefficient_from_mpz_t(ppl_coeff, tmp_z);
  ppl_Linear_Expression_add_to_inhomogeneous(ppl_objective_le, ppl_coeff);
  /* Set values for objective function's variable coefficients. */
  for (i = 1; i <= dimension; ++i) {
    mpz_mul(tmp_z, den_lcm, mpq_numref(objective[i]));
    mpz_divexact(tmp_z, tmp_z, mpq_denref(objective[i]));
    ppl_assign_Coefficient_from_mpz_t(ppl_coeff, tmp_z);
    ppl_Linear_Expression_add_to_coefficient(ppl_objective_le, i-1, ppl_coeff);
  }

  if (verbosity >= 4) {
    fprintf(output_file, "Objective function:\n");
    if (mpz_cmp_si(den_lcm, 1) != 0)
      fprintf(output_file, "(");
    ppl_io_fprint_Linear_Expression(output_file, ppl_objective_le);
  }

  for (i = 0; i <= dimension; ++i)
    mpq_clear(objective[i]);
  free(objective);

  if (verbosity >= 4) {
    if (mpz_cmp_si(den_lcm, 1) != 0) {
      fprintf(output_file, ")/");
      mpz_out_str(output_file, 10, den_lcm);
    }
    fprintf(output_file, "\n%s\n",
            (maximize ? "Maximizing." : "Minimizing."));
  }

  ppl_new_Coefficient(&optimum_n);
  ppl_new_Coefficient(&optimum_d);
  ppl_new_Generator_zero_dim_point(&optimum_location);

  optimum_found = use_simplex
    ? solve_with_simplex(ppl_cs,
                         ppl_objective_le,
                         optimum_n,
                         optimum_d,
                         optimum_location)
    : solve_with_generators(ppl_cs,
                            ppl_objective_le,
                            optimum_n,
                            optimum_d,
                            optimum_location);

  ppl_delete_Linear_Expression(ppl_objective_le);

  if (glpk_lp_num_int > 0)
      free(integer_variables);

  if (optimum_found) {
    mpq_init(optimum);
    ppl_Coefficient_to_mpz_t(optimum_n, tmp_z);
    mpq_set_num(optimum, tmp_z);
    ppl_Coefficient_to_mpz_t(optimum_d, tmp_z);
    mpz_mul(tmp_z, tmp_z, den_lcm);
    mpq_set_den(optimum, tmp_z);
    if (verbosity == 1)
      fprintf(output_file, "Optimized problem.\n");
    if (verbosity >= 2)
      fprintf(output_file, "Optimum value: %.10g\n", mpq_get_d(optimum));
    if (verbosity >= 3) {
      fprintf(output_file, "Optimum location:\n");
      ppl_Generator_divisor(optimum_location, ppl_coeff);
      ppl_Coefficient_to_mpz_t(ppl_coeff, tmp_z);
      for (i = 0; i < dimension; ++i) {
        mpz_set(mpq_denref(tmp1_q), tmp_z);
        ppl_Generator_coefficient(optimum_location, i, ppl_coeff);
        ppl_Coefficient_to_mpz_t(ppl_coeff, mpq_numref(tmp1_q));
        ppl_io_fprint_variable(output_file, i);
        fprintf(output_file, " = %.10g\n", mpq_get_d(tmp1_q));
      }
    }
#ifndef NDEBUG
    {
      ppl_Polyhedron_t ph;
      unsigned int relation;
      ppl_new_C_Polyhedron_recycle_Constraint_System(&ph, ppl_cs_copy);
      ppl_delete_Constraint_System(ppl_cs_copy);
      relation = ppl_Polyhedron_relation_with_Generator(ph, optimum_location);
      ppl_delete_Polyhedron(ph);
      assert(relation == PPL_POLY_GEN_RELATION_SUBSUMES);
    }
#endif
    maybe_check_results(PPL_MIP_PROBLEM_STATUS_OPTIMIZED,
                        mpq_get_d(optimum));
    mpq_clear(optimum);
  }

  ppl_delete_Constraint_System(ppl_cs);
  ppl_delete_Coefficient(optimum_d);
  ppl_delete_Coefficient(optimum_n);
  ppl_delete_Generator(optimum_location);

  glp_delete_prob(glpk_lp);
}
예제 #7
0
파일: lp.c 프로젝트: kleptog/pyglpk
static PyObject* LPX_getnumint(LPXObject *self, void *closure) {
  return PyInt_FromLong(glp_get_num_int(LP)); }
예제 #8
0
int lpx_get_num_int(LPX *lp)
{     /* retrieve number of integer columns */
      return glp_get_num_int(lp);
}
예제 #9
0
int lpx_get_class(LPX *lp)
{     /* determine problem klass */
      return glp_get_num_int(lp) == 0 ? LPX_LP : LPX_MIP;
}
예제 #10
0
int glp_read_prob(glp_prob *P, int flags, const char *fname)
{     DMX _csa, *csa = &_csa;
      int mip, m, n, nnz, ne, i, j, k, type, kind, ret, *ln = NULL,
         *ia = NULL, *ja = NULL;
      double lb, ub, temp, *ar = NULL;
      char *rf = NULL, *cf = NULL;
      if (P == NULL || P->magic != GLP_PROB_MAGIC)
         xerror("glp_read_prob: P = %p; invalid problem object\n",
            P);
      if (flags != 0)
         xerror("glp_read_prob: flags = %d; invalid parameter\n",
            flags);
      if (fname == NULL)
         xerror("glp_read_prob: fname = %d; invalid parameter\n",
            fname);
      glp_erase_prob(P);
      if (setjmp(csa->jump))
      {  ret = 1;
         goto done;
      }
      csa->fname = fname;
      csa->fp = NULL;
      csa->count = 0;
      csa->c = '\n';
      csa->field[0] = '\0';
      csa->empty = csa->nonint = 0;
      xprintf("Reading problem data from '%s'...\n", fname);
      csa->fp = glp_open(fname, "r");
      if (csa->fp == NULL)
      {  xprintf("Unable to open '%s' - %s\n", fname, get_err_msg());
         longjmp(csa->jump, 1);
      }
      /* read problem line */
      read_designator(csa);
      if (strcmp(csa->field, "p") != 0)
         error(csa, "problem line missing or invalid");
      read_field(csa);
      if (strcmp(csa->field, "lp") == 0)
         mip = 0;
      else if (strcmp(csa->field, "mip") == 0)
         mip = 1;
      else
         error(csa, "wrong problem designator; 'lp' or 'mip' expected");
      read_field(csa);
      if (strcmp(csa->field, "min") == 0)
         glp_set_obj_dir(P, GLP_MIN);
      else if (strcmp(csa->field, "max") == 0)
         glp_set_obj_dir(P, GLP_MAX);
      else
         error(csa, "objective sense missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &m) == 0 && m >= 0))
         error(csa, "number of rows missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &n) == 0 && n >= 0))
         error(csa, "number of columns missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &nnz) == 0 && nnz >= 0))
         error(csa, "number of constraint coefficients missing or inval"
            "id");
      if (m > 0)
      {  glp_add_rows(P, m);
         for (i = 1; i <= m; i++)
            glp_set_row_bnds(P, i, GLP_FX, 0.0, 0.0);
      }
      if (n > 0)
      {  glp_add_cols(P, n);
         for (j = 1; j <= n; j++)
         {  if (!mip)
               glp_set_col_bnds(P, j, GLP_LO, 0.0, 0.0);
            else
               glp_set_col_kind(P, j, GLP_BV);
         }
      }
      end_of_line(csa);
      /* allocate working arrays */
      rf = xcalloc(1+m, sizeof(char));
      memset(rf, 0, 1+m);
      cf = xcalloc(1+n, sizeof(char));
      memset(cf, 0, 1+n);
      ln = xcalloc(1+nnz, sizeof(int));
      ia = xcalloc(1+nnz, sizeof(int));
      ja = xcalloc(1+nnz, sizeof(int));
      ar = xcalloc(1+nnz, sizeof(double));
      /* read descriptor lines */
      ne = 0;
      for (;;)
      {  read_designator(csa);
         if (strcmp(csa->field, "i") == 0)
         {  /* row descriptor */
            read_field(csa);
            if (str2int(csa->field, &i) != 0)
               error(csa, "row number missing or invalid");
            if (!(1 <= i && i <= m))
               error(csa, "row number out of range");
            read_field(csa);
            if (strcmp(csa->field, "f") == 0)
               type = GLP_FR;
            else if (strcmp(csa->field, "l") == 0)
               type = GLP_LO;
            else if (strcmp(csa->field, "u") == 0)
               type = GLP_UP;
            else if (strcmp(csa->field, "d") == 0)
               type = GLP_DB;
            else if (strcmp(csa->field, "s") == 0)
               type = GLP_FX;
            else
               error(csa, "row type missing or invalid");
            if (type == GLP_LO || type == GLP_DB || type == GLP_FX)
            {  read_field(csa);
               if (str2num(csa->field, &lb) != 0)
                  error(csa, "row lower bound/fixed value missing or in"
                     "valid");
            }
            else
               lb = 0.0;
            if (type == GLP_UP || type == GLP_DB)
            {  read_field(csa);
               if (str2num(csa->field, &ub) != 0)
                  error(csa, "row upper bound missing or invalid");
            }
            else
               ub = 0.0;
            if (rf[i] & 0x01)
               error(csa, "duplicate row descriptor");
            glp_set_row_bnds(P, i, type, lb, ub), rf[i] |= 0x01;
         }
         else if (strcmp(csa->field, "j") == 0)
         {  /* column descriptor */
            read_field(csa);
            if (str2int(csa->field, &j) != 0)
               error(csa, "column number missing or invalid");
            if (!(1 <= j && j <= n))
               error(csa, "column number out of range");
            if (!mip)
               kind = GLP_CV;
            else
            {  read_field(csa);
               if (strcmp(csa->field, "c") == 0)
                  kind = GLP_CV;
               else if (strcmp(csa->field, "i") == 0)
                  kind = GLP_IV;
               else if (strcmp(csa->field, "b") == 0)
               {  kind = GLP_IV;
                  type = GLP_DB, lb = 0.0, ub = 1.0;
                  goto skip;
               }
               else
                  error(csa, "column kind missing or invalid");
            }
            read_field(csa);
            if (strcmp(csa->field, "f") == 0)
               type = GLP_FR;
            else if (strcmp(csa->field, "l") == 0)
               type = GLP_LO;
            else if (strcmp(csa->field, "u") == 0)
               type = GLP_UP;
            else if (strcmp(csa->field, "d") == 0)
               type = GLP_DB;
            else if (strcmp(csa->field, "s") == 0)
               type = GLP_FX;
            else
               error(csa, "column type missing or invalid");
            if (type == GLP_LO || type == GLP_DB || type == GLP_FX)
            {  read_field(csa);
               if (str2num(csa->field, &lb) != 0)
                  error(csa, "column lower bound/fixed value missing or"
                     " invalid");
            }
            else
               lb = 0.0;
            if (type == GLP_UP || type == GLP_DB)
            {  read_field(csa);
               if (str2num(csa->field, &ub) != 0)
                  error(csa, "column upper bound missing or invalid");
            }
            else
               ub = 0.0;
skip:       if (cf[j] & 0x01)
               error(csa, "duplicate column descriptor");
            glp_set_col_kind(P, j, kind);
            glp_set_col_bnds(P, j, type, lb, ub), cf[j] |= 0x01;
         }
         else if (strcmp(csa->field, "a") == 0)
         {  /* coefficient descriptor */
            read_field(csa);
            if (str2int(csa->field, &i) != 0)
               error(csa, "row number missing or invalid");
            if (!(0 <= i && i <= m))
               error(csa, "row number out of range");
            read_field(csa);
            if (str2int(csa->field, &j) != 0)
               error(csa, "column number missing or invalid");
            if (!((i == 0 ? 0 : 1) <= j && j <= n))
               error(csa, "column number out of range");
            read_field(csa);
            if (i == 0)
            {  if (str2num(csa->field, &temp) != 0)
                  error(csa, "objective %s missing or invalid",
                     j == 0 ? "constant term" : "coefficient");
               if (cf[j] & 0x10)
                  error(csa, "duplicate objective %s",
                     j == 0 ? "constant term" : "coefficient");
               glp_set_obj_coef(P, j, temp), cf[j] |= 0x10;
            }
            else
            {  if (str2num(csa->field, &temp) != 0)
                  error(csa, "constraint coefficient missing or invalid"
                     );
               if (ne == nnz)
                  error(csa, "too many constraint coefficient descripto"
                     "rs");
               ln[++ne] = csa->count;
               ia[ne] = i, ja[ne] = j, ar[ne] = temp;
            }
         }
         else if (strcmp(csa->field, "n") == 0)
         {  /* symbolic name descriptor */
            read_field(csa);
            if (strcmp(csa->field, "p") == 0)
            {  /* problem name */
               read_field(csa);
               if (P->name != NULL)
                  error(csa, "duplicate problem name");
               glp_set_prob_name(P, csa->field);
            }
            else if (strcmp(csa->field, "z") == 0)
            {  /* objective name */
               read_field(csa);
               if (P->obj != NULL)
                  error(csa, "duplicate objective name");
               glp_set_obj_name(P, csa->field);
            }
            else if (strcmp(csa->field, "i") == 0)
            {  /* row name */
               read_field(csa);
               if (str2int(csa->field, &i) != 0)
                  error(csa, "row number missing or invalid");
               if (!(1 <= i && i <= m))
                  error(csa, "row number out of range");
               read_field(csa);
               if (P->row[i]->name != NULL)
                  error(csa, "duplicate row name");
               glp_set_row_name(P, i, csa->field);
            }
            else if (strcmp(csa->field, "j") == 0)
            {  /* column name */
               read_field(csa);
               if (str2int(csa->field, &j) != 0)
                  error(csa, "column number missing or invalid");
               if (!(1 <= j && j <= n))
                  error(csa, "column number out of range");
               read_field(csa);
               if (P->col[j]->name != NULL)
                  error(csa, "duplicate column name");
               glp_set_col_name(P, j, csa->field);
            }
            else
               error(csa, "object designator missing or invalid");
         }
         else if (strcmp(csa->field, "e") == 0)
            break;
         else
            error(csa, "line designator missing or invalid");
         end_of_line(csa);
      }
      if (ne < nnz)
         error(csa, "too few constraint coefficient descriptors");
      xassert(ne == nnz);
      k = glp_check_dup(m, n, ne, ia, ja);
      xassert(0 <= k && k <= nnz);
      if (k > 0)
      {  csa->count = ln[k];
         error(csa, "duplicate constraint coefficient");
      }
      glp_load_matrix(P, ne, ia, ja, ar);
      /* print some statistics */
      if (P->name != NULL)
         xprintf("Problem: %s\n", P->name);
      if (P->obj != NULL)
         xprintf("Objective: %s\n", P->obj);
      xprintf("%d row%s, %d column%s, %d non-zero%s\n",
         m, m == 1 ? "" : "s", n, n == 1 ? "" : "s", nnz, nnz == 1 ?
         "" : "s");
      if (glp_get_num_int(P) > 0)
      {  int ni = glp_get_num_int(P);
         int nb = glp_get_num_bin(P);
         if (ni == 1)
         {  if (nb == 0)
               xprintf("One variable is integer\n");
            else
               xprintf("One variable is binary\n");
         }
         else
         {  xprintf("%d integer variables, ", ni);
            if (nb == 0)
               xprintf("none");
            else if (nb == 1)
               xprintf("one");
            else if (nb == ni)
               xprintf("all");
            else
               xprintf("%d", nb);
            xprintf(" of which %s binary\n", nb == 1 ? "is" : "are");
         }
      }
      xprintf("%d lines were read\n", csa->count);
      /* problem data has been successfully read */
      glp_sort_matrix(P);
      ret = 0;
done: if (csa->fp != NULL) glp_close(csa->fp);
      if (rf != NULL) xfree(rf);
      if (cf != NULL) xfree(cf);
      if (ln != NULL) xfree(ln);
      if (ia != NULL) xfree(ia);
      if (ja != NULL) xfree(ja);
      if (ar != NULL) xfree(ar);
      if (ret) glp_erase_prob(P);
      return ret;
}
예제 #11
0
int glp_main(int argc, const char *argv[])
{     /* stand-alone LP/MIP solver */
      struct csa _csa, *csa = &_csa;
      int ret;
      xlong_t start;
      /* perform initialization */
      csa->prob = glp_create_prob();
      glp_get_bfcp(csa->prob, &csa->bfcp);
      glp_init_smcp(&csa->smcp);
      csa->smcp.presolve = GLP_ON;
      glp_init_iocp(&csa->iocp);
      csa->iocp.presolve = GLP_ON;
      csa->tran = NULL;
      csa->graph = NULL;
      csa->format = FMT_MPS_FILE;
      csa->in_file = NULL;
      csa->ndf = 0;
      csa->out_dpy = NULL;
      csa->solution = SOL_BASIC;
      csa->in_res = NULL;
      csa->dir = 0;
      csa->scale = 1;
      csa->out_sol = NULL;
      csa->out_res = NULL;
      csa->out_bnds = NULL;
      csa->check = 0;
      csa->new_name = NULL;
      csa->out_mps = NULL;
      csa->out_freemps = NULL;
      csa->out_cpxlp = NULL;
      csa->out_pb = NULL;
      csa->out_npb = NULL;
      csa->log_file = NULL;
      csa->crash = USE_ADV_BASIS;
      csa->exact = 0;
      csa->xcheck = 0;
      csa->nomip = 0;
      /* parse command-line parameters */
      ret = parse_cmdline(csa, argc, argv);
      if (ret < 0)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      if (ret > 0)
      {  ret = EXIT_FAILURE;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* remove all output files specified in the command line */
      if (csa->out_dpy != NULL) remove(csa->out_dpy);
      if (csa->out_sol != NULL) remove(csa->out_sol);
      if (csa->out_res != NULL) remove(csa->out_res);
      if (csa->out_bnds != NULL) remove(csa->out_bnds);
      if (csa->out_mps != NULL) remove(csa->out_mps);
      if (csa->out_freemps != NULL) remove(csa->out_freemps);
      if (csa->out_cpxlp != NULL) remove(csa->out_cpxlp);
      if (csa->out_pb != NULL) remove(csa->out_pb);
      if (csa->out_npb != NULL) remove(csa->out_npb);
      if (csa->log_file != NULL) remove(csa->log_file);
      /*--------------------------------------------------------------*/
      /* open log file, if required */
      if (csa->log_file != NULL)
      {  if (lib_open_log(csa->log_file))
         {  xprintf("Unable to create log file\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* read problem data from the input file */
      if (csa->in_file == NULL)
      {  xprintf("No input problem file specified; try %s --help\n",
            argv[0]);
         ret = EXIT_FAILURE;
         goto done;
      }
      if (csa->format == FMT_MPS_DECK)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->in_file);
         if (ret != 0)
err1:    {  xprintf("MPS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MPS_FILE)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->in_file);
         if (ret != 0) goto err1;
      }
      else if (csa->format == FMT_CPLEX_LP)
      {  ret = glp_read_lp(csa->prob, NULL, csa->in_file);
         if (ret != 0)
         {  xprintf("CPLEX LP file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MATHPROG)
      {  int k;
         /* allocate the translator workspace */
         csa->tran = glp_mpl_alloc_wksp();
         /* read model section and optional data section */
         if (glp_mpl_read_model(csa->tran, csa->in_file, csa->ndf > 0))
err2:    {  xprintf("MathProg model processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         /* read optional data section(s), if necessary */
         for (k = 1; k <= csa->ndf; k++)
         {  if (glp_mpl_read_data(csa->tran, csa->in_data[k]))
               goto err2;
         }
         /* generate the model */
         if (glp_mpl_generate(csa->tran, csa->out_dpy)) goto err2;
         /* build the problem instance from the model */
         glp_mpl_build_prob(csa->tran, csa->prob);
      }
      else if (csa->format == FMT_MIN_COST)
      {  csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_mincost(csa->graph, offsetof(v_data, rhs),
            offsetof(a_data, low), offsetof(a_data, cap),
            offsetof(a_data, cost), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_mincost_lp(csa->prob, csa->graph, GLP_ON,
            offsetof(v_data, rhs), offsetof(a_data, low),
            offsetof(a_data, cap), offsetof(a_data, cost));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else if (csa->format == FMT_MAX_FLOW)
      {  int s, t;
         csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_maxflow(csa->graph, &s, &t,
            offsetof(a_data, cap), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_maxflow_lp(csa->prob, csa->graph, GLP_ON, s, t,
            offsetof(a_data, cap));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* change problem name, if required */
      if (csa->new_name != NULL)
         glp_set_prob_name(csa->prob, csa->new_name);
      /* change optimization direction, if required */
      if (csa->dir != 0)
         glp_set_obj_dir(csa->prob, csa->dir);
      /* order rows and columns of the constraint matrix */
      lpx_order_matrix(csa->prob);
      /*--------------------------------------------------------------*/
      /* write problem data in fixed MPS format, if required */
      if (csa->out_mps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->out_mps);
         if (ret != 0)
         {  xprintf("Unable to write problem in fixed MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in free MPS format, if required */
      if (csa->out_freemps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->out_freemps);
         if (ret != 0)
         {  xprintf("Unable to write problem in free MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in CPLEX LP format, if required */
      if (csa->out_cpxlp != NULL)
      {  ret = glp_write_lp(csa->prob, NULL, csa->out_cpxlp);
         if (ret != 0)
         {  xprintf("Unable to write problem in CPLEX LP format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in OPB format, if required */
      if (csa->out_pb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_pb, 0, 0);
         if (ret != 0)
         {  xprintf("Unable to write problem in OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in normalized OPB format, if required */
      if (csa->out_npb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_npb, 1, 1);
         if (ret != 0)
         {  xprintf(
               "Unable to write problem in normalized OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* if only problem data check is required, skip computations */
      if (csa->check)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* determine the solution type */
      if (!csa->nomip &&
          glp_get_num_int(csa->prob) + glp_get_num_bin(csa->prob) > 0)
      {  if (csa->solution == SOL_INTERIOR)
         {  xprintf("Interior-point method is not able to solve MIP pro"
               "blem; use --simplex\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         csa->solution = SOL_INTEGER;
      }
      /*--------------------------------------------------------------*/
      /* if solution is provided, read it and skip computations */
      if (csa->in_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_read_sol(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_read_ipt(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_read_mip(csa->prob, csa->in_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to read problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         goto skip;
      }
      /*--------------------------------------------------------------*/
      /* scale the problem data, if required */
      if (csa->scale)
      {  if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
             csa->solution == SOL_INTERIOR ||
             csa->solution == SOL_INTEGER && !csa->iocp.presolve)
            glp_scale_prob(csa->prob, GLP_SF_AUTO);
      }
      /* construct starting LP basis */
      if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
          csa->solution == SOL_INTEGER && !csa->iocp.presolve)
      {  if (csa->crash == USE_STD_BASIS)
            glp_std_basis(csa->prob);
         else if (csa->crash == USE_ADV_BASIS)
            glp_adv_basis(csa->prob, 0);
         else if (csa->crash == USE_CPX_BASIS)
            glp_cpx_basis(csa->prob);
         else
            xassert(csa != csa);
      }
      /*--------------------------------------------------------------*/
      /* solve the problem */
      start = xtime();
      if (csa->solution == SOL_BASIC)
      {  if (!csa->exact)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
            if (csa->xcheck)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
                  xprintf("If you need to check final basis for non-opt"
                     "imal solution, use --nopresol\n");
               else
                  glp_exact(csa->prob, &csa->smcp);
            }
            if (csa->out_sol != NULL || csa->out_res != NULL)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
               xprintf("If you need actual output for non-optimal solut"
                  "ion, use --nopresol\n");
            }
         }
         else
            glp_exact(csa->prob, &csa->smcp);
      }
      else if (csa->solution == SOL_INTERIOR)
         glp_interior(csa->prob, NULL);
      else if (csa->solution == SOL_INTEGER)
      {  if (!csa->iocp.presolve)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
         }
         glp_intopt(csa->prob, &csa->iocp);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* display statistics */
      xprintf("Time used:   %.1f secs\n", xdifftime(xtime(), start));
      {  xlong_t tpeak;
         char buf[50];
         lib_mem_usage(NULL, NULL, NULL, &tpeak);
         xprintf("Memory used: %.1f Mb (%s bytes)\n",
            xltod(tpeak) / 1048576.0, xltoa(tpeak, buf));
      }
      /*--------------------------------------------------------------*/
skip: /* postsolve the model, if necessary */
      if (csa->tran != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_SOL);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_IPT);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_MIP);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Model postsolving error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* write problem solution in printable format, if required */
      if (csa->out_sol != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = lpx_print_sol(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTERIOR)
            ret = lpx_print_ips(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTEGER)
            ret = lpx_print_mip(csa->prob, csa->out_sol);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem solution in printable format, if required */
      if (csa->out_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_write_sol(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_write_ipt(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_write_mip(csa->prob, csa->out_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write sensitivity bounds information, if required */
      if (csa->out_bnds != NULL)
      {  if (csa->solution == SOL_BASIC)
         {  ret = lpx_print_sens_bnds(csa->prob, csa->out_bnds);
            if (ret != 0)
            {  xprintf("Unable to write sensitivity bounds information "
                  "\n");
               ret = EXIT_FAILURE;
               goto done;
            }
         }
         else
            xprintf("Cannot write sensitivity bounds information for in"
               "terior-point or MIP solution\n");
      }
      /*--------------------------------------------------------------*/
      /* all seems to be ok */
      ret = EXIT_SUCCESS;
      /*--------------------------------------------------------------*/
done: /* delete the LP/MIP problem object */
      if (csa->prob != NULL)
         glp_delete_prob(csa->prob);
      /* free the translator workspace, if necessary */
      if (csa->tran != NULL)
         glp_mpl_free_wksp(csa->tran);
      /* delete the network problem object, if necessary */
      if (csa->graph != NULL)
         glp_delete_graph(csa->graph);
      xassert(gmp_pool_count() == 0);
      gmp_free_mem();
      /* close log file, if necessary */
      if (csa->log_file != NULL) lib_close_log();
      /* check that no memory blocks are still allocated */
      {  int count;
         xlong_t total;
         lib_mem_usage(&count, NULL, &total, NULL);
         if (count != 0)
            xerror("Error: %d memory block(s) were lost\n", count);
         xassert(count == 0);
         xassert(total.lo == 0 && total.hi == 0);
      }
      /* free the library environment */
      lib_free_env();
      /* return to the control program */
      return ret;
}
예제 #12
0
파일: glpcpx.c 프로젝트: emersonxsu/glpk
int glp_read_lp(glp_prob *P, const glp_cpxcp *parm, const char *fname)
{     /* read problem data in CPLEX LP format */
      glp_cpxcp _parm;
      struct csa _csa, *csa = &_csa;
      int ret;
      xprintf("Reading problem data from '%s'...\n", fname);
      if (parm == NULL)
         glp_init_cpxcp(&_parm), parm = &_parm;
      /* check control parameters */
      check_parm("glp_read_lp", parm);
      /* initialize common storage area */
      csa->P = P;
      csa->parm = parm;
      csa->fname = fname;
      csa->fp = NULL;
      if (setjmp(csa->jump))
      {  ret = 1;
         goto done;
      }
      csa->count = 0;
      csa->c = '\n';
      csa->token = T_EOF;
      csa->image[0] = '\0';
      csa->imlen = 0;
      csa->value = 0.0;
      csa->n_max = 100;
      csa->ind = xcalloc(1+csa->n_max, sizeof(int));
      csa->val = xcalloc(1+csa->n_max, sizeof(double));
      csa->flag = xcalloc(1+csa->n_max, sizeof(char));
      memset(&csa->flag[1], 0, csa->n_max * sizeof(char));
      csa->lb = xcalloc(1+csa->n_max, sizeof(double));
      csa->ub = xcalloc(1+csa->n_max, sizeof(double));
#if 1 /* 27/VII-2013 */
      csa->lb_warn = csa->ub_warn = 0;
#endif
      /* erase problem object */
      glp_erase_prob(P);
      glp_create_index(P);
      /* open input CPLEX LP file */
      csa->fp = glp_open(fname, "r");
      if (csa->fp == NULL)
      {  xprintf("Unable to open '%s' - %s\n", fname, get_err_msg());
         ret = 1;
         goto done;
      }
      /* scan very first token */
      scan_token(csa);
      /* parse definition of the objective function */
      if (!(csa->token == T_MINIMIZE || csa->token == T_MAXIMIZE))
         error(csa, "'minimize' or 'maximize' keyword missing\n");
      parse_objective(csa);
      /* parse constraints section */
      if (csa->token != T_SUBJECT_TO)
         error(csa, "constraints section missing\n");
      parse_constraints(csa);
      /* parse optional bounds section */
      if (csa->token == T_BOUNDS) parse_bounds(csa);
      /* parse optional general, integer, and binary sections */
      while (csa->token == T_GENERAL ||
             csa->token == T_INTEGER ||
             csa->token == T_BINARY) parse_integer(csa);
      /* check for the keyword 'end' */
      if (csa->token == T_END)
         scan_token(csa);
      else if (csa->token == T_EOF)
         warning(csa, "keyword 'end' missing\n");
      else
         error(csa, "symbol '%s' in wrong position\n", csa->image);
      /* nothing must follow the keyword 'end' (except comments) */
      if (csa->token != T_EOF)
         error(csa, "extra symbol(s) detected beyond 'end'\n");
      /* set bounds of variables */
      {  int j, type;
         double lb, ub;
         for (j = 1; j <= P->n; j++)
         {  lb = csa->lb[j];
            ub = csa->ub[j];
            if (lb == +DBL_MAX) lb = 0.0;      /* default lb */
            if (ub == -DBL_MAX) ub = +DBL_MAX; /* default ub */
            if (lb == -DBL_MAX && ub == +DBL_MAX)
               type = GLP_FR;
            else if (ub == +DBL_MAX)
               type = GLP_LO;
            else if (lb == -DBL_MAX)
               type = GLP_UP;
            else if (lb != ub)
               type = GLP_DB;
            else
               type = GLP_FX;
            glp_set_col_bnds(csa->P, j, type, lb, ub);
         }
      }
      /* print some statistics */
      xprintf("%d row%s, %d column%s, %d non-zero%s\n",
         P->m, P->m == 1 ? "" : "s", P->n, P->n == 1 ? "" : "s",
         P->nnz, P->nnz == 1 ? "" : "s");
      if (glp_get_num_int(P) > 0)
      {  int ni = glp_get_num_int(P);
         int nb = glp_get_num_bin(P);
         if (ni == 1)
         {  if (nb == 0)
               xprintf("One variable is integer\n");
            else
               xprintf("One variable is binary\n");
         }
         else
         {  xprintf("%d integer variables, ", ni);
            if (nb == 0)
               xprintf("none");
            else if (nb == 1)
               xprintf("one");
            else if (nb == ni)
               xprintf("all");
            else
               xprintf("%d", nb);
            xprintf(" of which %s binary\n", nb == 1 ? "is" : "are");
         }
      }
      xprintf("%d lines were read\n", csa->count);
      /* problem data has been successfully read */
      glp_delete_index(P);
      glp_sort_matrix(P);
      ret = 0;
done: if (csa->fp != NULL) glp_close(csa->fp);
      xfree(csa->ind);
      xfree(csa->val);
      xfree(csa->flag);
      xfree(csa->lb);
      xfree(csa->ub);
      if (ret != 0) glp_erase_prob(P);
      return ret;
}
예제 #13
0
// read in all necessary elements for retrieving the LP/MILP
void Rglpk_read_file (char **file, int *type, 
		      int *lp_direction_of_optimization,
		      int *lp_n_constraints, int *lp_n_objective_vars,
		      int *lp_n_values_in_constraint_matrix,
		      int *lp_n_integer_vars, int *lp_n_binary_vars, 
		      char **lp_prob_name,
		      char **lp_obj_name,
		      int *lp_verbosity) {

  int status;
  extern glp_prob *lp;
  glp_tran *tran;
  const char *str; 
  
  // Turn on/off Terminal Output
  if (*lp_verbosity==1)
    glp_term_out(GLP_ON);
  else
    glp_term_out(GLP_OFF);

  // create problem object 
  if (lp)
    glp_delete_prob(lp);
  lp = glp_create_prob();

  // read file -> gets stored as an GLPK problem object 'lp'
  // which file type do we have?
  switch (*type){
  case 1: 
    // Fixed (ancient) MPS Format, param argument currently NULL
    status = glp_read_mps(lp, GLP_MPS_DECK, NULL, *file);
    break;
  case 2:
    // Free (modern) MPS format, param argument currently NULL
    status = glp_read_mps(lp, GLP_MPS_FILE, NULL, *file);
    break;
  case 3:
    // CPLEX LP Format
    status = glp_read_lp(lp, NULL, *file);
    break;
  case 4:
    // MATHPROG Format (based on lpx_read_model function)
    tran = glp_mpl_alloc_wksp();

    status = glp_mpl_read_model(tran, *file, 0);

    if (!status) {
        status = glp_mpl_generate(tran, NULL);
        if (!status) {
            glp_mpl_build_prob(tran, lp);
        }
    }
    glp_mpl_free_wksp(tran);
    break;    
  } 

  // if file read successfully glp_read_* returns zero
  if ( status != 0 ) {
    glp_delete_prob(lp);
    lp = NULL;
    error("Reading file %s failed", *file);
  }

  // retrieve problem name
  str = glp_get_prob_name(lp);
  if (str){
    *lp_prob_name = (char *) str;
  }

  // retrieve name of objective function
  str = glp_get_obj_name(lp);
  if (str){
    *lp_obj_name = (char *) str;
  }
  
  // retrieve optimization direction flag
  *lp_direction_of_optimization = glp_get_obj_dir(lp);  

  // retrieve number of constraints
  *lp_n_constraints = glp_get_num_rows(lp);  

  // retrieve number of objective variables
  *lp_n_objective_vars = glp_get_num_cols(lp);

  // retrieve number of non-zero elements in constraint matrix
  *lp_n_values_in_constraint_matrix = glp_get_num_nz(lp);

  // retrieve number of integer variables
  *lp_n_integer_vars = glp_get_num_int(lp);
  
  // retrieve number of binary variables
  *lp_n_binary_vars = glp_get_num_bin(lp);
}