Example #1
0
//*******************************************************************
CSolver:: ~CSolver() {
    FreeSolutionArrays();
    if ( m_bCreated ) {

         CPXflushstdchannels(m_env);
         CPXfreeprob(m_env,&m_lp);
         char buff[30];
         m_log.getTimeStamp(buff);
         CPXmsg(m_cpxlog, "\n%s : %s", "*** End Log ***", buff );
        
		 CPXfclose( m_cpxFile );

         CPXcloseCPLEX(&m_env);
         //m_log.write("In destructor");
   }
}
Example #2
0
//*******************************************************************
int CSolver:: Create(int estRows, int estCols, int estNonZeros,
					 int probsense,  char* probname, int namesize,
					 int nSerialnum,  char* licenvstring)
{
     int  i;
     char buff[100]; 

     setLogFile( (char*)probname); 

     memset( m_error, sizeof(m_error), 0 );
     m_debugLog = 0;

     m_probType    = PROBLEM_TYPE_LP;
     m_estRows     = estRows;
     m_estCols     = estCols;
     m_estNonZeros = estNonZeros;
     m_nObjSense   = probsense;
     m_nNameSize   = namesize;

	 m_nColCount   = 0;
	 m_nRowCount   = 0;

     // create arrays given problem size estimates
     // matrix
     m_pRowNdx    = new int[estNonZeros];
     m_pColNdx    = new int[estNonZeros];
     m_pCoef      = new double[estNonZeros];

     m_nRowItems  = 0;
     m_nColItems  = 0;
     m_nCoefItems = 0;

     // rim
     m_pObj       = new double[estCols];
     m_pRhs       = new double[estRows];
     m_pRhsSense  = new char[estRows];

     m_pCtype     = new char[estCols];  // column type
     m_pRstat     = new int[estRows];
     m_pCstat     = new int[estCols];

     m_nObjItems  = 0;
     m_nRhsItems  = 0;
     m_nRhsSense  = 0;

     // column bounds
     m_pBdl      = new double[estCols];
     m_pBdu      = new double[estCols];

     m_nBdItems   = 0;

     if (m_pBdl == NULL || m_pBdu == NULL ) return -1;

     for( i=0; i< estCols; i++ ) {
	      m_pBdl[i] = 0.0;
	      m_pBdu[i] = INFBOUND;
     }

     //---misc
     // build problem name string

     if( probname != NULL ) {
	 // user supplied a problem name on construction, so use that name
	 m_pszProbname = new char[strlen(probname)+1];

	 strcpy(m_pszProbname,probname);
     }
     else {
	     // no name given for problem
	     m_pszProbname = new char[strlen("NONAME")+1];
	     strcpy(m_pszProbname,"NONAME");
     }


     m_lp      = NULL;
     m_env     = NULL;
     m_obj     = 0;
     m_x       = NULL;
     m_pi      = NULL;
     m_slack   = NULL;
     m_dj      = NULL;

     m_nPosInCstore =0;
     m_cstore=NULL;
     m_nPosInCname  =0;
     m_cname=NULL;

     m_nPosInRstore =0;
     m_rstore=NULL;
     m_nPosInRname  =0;
     m_rname=NULL;

     m_RowMap.Create(estRows);
	 m_ColMap.Create(estCols);


     CreateNameSpace();

	 // check for memory allocation error
     if( m_pRowNdx == NULL  ||
	 m_pColNdx == NULL  ||
	 m_pCoef   == NULL  ||
	 m_pObj    == NULL  ||
	 m_pRhs    == NULL  ||
	 m_pRhsSense ==NULL ||
	 m_pBdl    == NULL  ||
	 m_pBdu    == NULL  ||
	 m_cstore  == NULL  ||
	 m_cname   == NULL  ||
	 m_rstore  == NULL  ||
	 m_rname   == NULL  ) {
	 Message("Not enough memory!");
		 return -1;  // failure error
	 }
	 sprintf(buff,"CPLEX Serial Number = %d", nSerialnum);
     
	 Message(buff);

//!     if ( nSerialnum == 0  )  
//!        // no serial number assume development license
//!    else
//!        // serial number provide assume runtime license
     m_env = CPXopenCPLEXruntime(&m_status, nSerialnum, licenvstring);

     if (m_env == NULL){
		  CPXgeterrorstring( m_env, m_status, m_error );
		  if (nSerialnum == 0 )
	          Message( "CPXopenCPLEXdevelop returned NULL !");
		  else
			  Message( "CPXopenCPLEXruntime returned NULL");
		  SetError("Failed to get a CPLEX environment");
          return -1;
     }

     CPXgetchannels(m_env, &m_cpxresults, &m_cpxwarning, &m_cpxerror, &m_cpxlog);

     char cpxbuff[80];

	 sprintf(cpxbuff, "%s.%s", probname, "cpx");

	 m_cpxFile = CPXfopen(cpxbuff,"w");

	 if (m_cpxFile == NULL ) {
         m_log.write("opening cplexlog.log failed");
	 }

	 CPXaddfuncdest(m_env, m_cpxresults, &m_cbData, channelsfunc);
	 CPXaddfuncdest(m_env, m_cpxwarning, &m_cbData, channelsfunc);
	 CPXaddfuncdest(m_env, m_cpxerror,   &m_cbData, channelsfunc);

     if ( CPXsetlogfile(m_env, m_cpxFile) != 0 ) {
          m_log.write("failed to set channels file");
      }

	 m_log.getTimeStamp(buff);

     m_bCreated    = 1;

     CPXmsg(m_cpxlog, "%s : %s\n\n","*** Begin Log ***", buff );

     return 0;
}
Example #3
0
int
main (void)
{
   CPXENVptr env;
   CPXLPptr lp = NULL;
   int *cone = NULL;
   int status;
   CPXCHANNELptr resc, warnc, errc, logc;
   int retval = -1;

   /* Initialize CPLEX and get a reference to the output channels.
    * If any of this fails immediately terminate the program.
    */
   env = CPXopenCPLEX (&status);
   if ( env == NULL || status != 0 )
      abort ();

   status = CPXgetchannels (env, &resc, &warnc, &errc, &logc);
   if ( status != 0 )
      abort ();

   /* CPLEX is fully setup. Enable output.
    */
   status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON);
   if ( status != 0 )
      goto TERMINATE;

   /* Create model. */
   lp = CPXcreateprob (env, &status, "xsocpex1");
   if ( lp == NULL || status != 0 )
      goto TERMINATE;
   if ( !createmodel (env, lp, &cone) )
      goto TERMINATE;

   /* Solve the problem to optimality. */
   CPXmsg (logc, "Optimizing ...\n");
   status = CPXsetdblparam (env, CPXPARAM_Barrier_QCPConvergeTol, CONVTOL);
   if ( status != 0 )
      goto TERMINATE;
   if ( (status = CPXhybbaropt (env, lp, CPX_ALG_NONE)) != 0 )
      goto TERMINATE;

   if ( CPXgetstat (env, lp) != CPX_STAT_OPTIMAL ) {
      CPXmsg (errc, "Cannot test KKT conditions on non-optimal solution.\n");
      goto TERMINATE;
   }

   /* Now test KKT conditions on the result. */
   if ( !checkkkt (env, lp, cone, TESTTOL) ) {
      CPXmsg (logc, "Testing of KKT conditions failed.\n");
      CPXmsg (errc, "Testing of KKT conditions failed.\n");
      goto TERMINATE;
   }

   CPXmsg (resc, "KKT conditions are satisfied.\n");
   retval = 0;
 TERMINATE:
   free (cone);
   if ( lp != NULL )
      CPXfreeprob (env, &lp);
   CPXcloseCPLEX (&env);

   return retval;
}
Example #4
0
/* This function creates the following model:
 *   Minimize
 *    obj: x1 + x2 + x3 + x4 + x5 + x6
 *   Subject To
 *    c1: x1 + x2      + x5      = 8
 *    c2:           x3 + x5 + x6 = 10
 *    q1: [ -x1^2 + x2^2 + x3^2 ] <= 0
 *    q2: [ -x4^2 + x5^2 ] <= 0
 *   Bounds
 *    x2 Free
 *    x3 Free
 *    x5 Free
 *   End
 * which is a second order cone program in standard form.
 * The function returns a true value on success and false on error.
 * The function also sets up *cone_p as follows:
 * (*cone_p)[j] >= 0              Column j is contained in a cone constraint
 *                                and is the cone head variable of that
 *                                constraint. The index of the respective
 *                                quadratic constraint is given by (*cone_p)[j].
 * (*cone_p)[j] = NOT_CONE_HEAD   Column j is contained in a cone constraint
 *                                but is not the cone head variable of that
 *                                constraint.
 * (*cone_p)[j] = NOT_IN_CONE     Column j is not contained in any cone
 *                                constraint.
 */
static int
createmodel (CPXENVptr env, CPXLPptr lp, int **cone_p)
{
   /* Column data. */
   static double const obj[]        = {  1.0,  1.0,  1.0,  1.0,  1.0,  1.0 };
   static double const lb[]         = {  0.0, -INF, -INF,  0.0, -INF,  0.0 };
   static double const ub[]         = {  INF,  INF,  INF,  INF,  INF,  INF };
   static char const *const cname[] = { "x1", "x2", "x3", "x4", "x5", "x6" };

   /* Row data. */
   static double const rval[]       = { 1.0, 1.0, 1.0,    1.0, 1.0, 1.0 };
   static int const rind[]          = {   0,   1,   4,      2,   4,   5 };
   static int const rbeg[]          = {   0,                3           };
   static double const rhs[]        = { 8.0,             10.0           };
   static char const sense[]        = { 'E',              'E'           };
   static char const *const rname[] = { "c1",             "c2"          };

   /* Data for second order cone constraints. */
   static double const qval[]  = { -1.0, 1.0, 1.0 }; /* Same for all Q cons. */
   static double const qrhs    = 0.0;                /* Same for all Q cons. */
   static char const qsense    = 'L';                /* Same for all Q cons. */
   static int const qind1[] = { 0, 1, 2 };
   static int const qind2[] = { 3, 4 };

   int status;
   int ok = 0;
   int *cone = NULL;

   CPXCHANNELptr errc;

   /* Get the channel for printing error messages. */
   if ( (status = CPXgetchannels (env, NULL, NULL, &errc, NULL)) != 0 )
      goto TERMINATE;

   cone = malloc ((sizeof (obj) / sizeof (obj[0])) * sizeof (*cone));
   if ( cone == NULL ) {
      CPXmsg (errc, "Out of memory!\n");
      goto TERMINATE;
   }

   status = CPXchgobjsen (env, lp, CPX_MIN);
   if ( status != 0 )
      goto TERMINATE;

   status = CPXnewcols (env, lp, sizeof (obj) / sizeof (obj[0]),
                        obj, lb, ub, NULL, (char **)cname);
   if ( status != 0 )
      goto TERMINATE;

   status = CPXaddrows (env, lp, 0, sizeof (rhs) / sizeof (rhs[0]),
                        sizeof (rval) / sizeof (rval[0]), rhs, sense,
                        rbeg, rind, rval, NULL, (char **)rname);
   if ( status != 0 )
      goto TERMINATE;

   status = CPXaddqconstr (env, lp, 0, sizeof (qind1) / sizeof (qind1[0]),
                           qrhs, qsense, NULL, NULL,
                           qind1, qind1, qval, "q1");
   if ( status != 0 )
      goto TERMINATE;
   cone[0] = 0;
   cone[1] = NOT_CONE_HEAD;
   cone[2] = NOT_CONE_HEAD;
   status = CPXaddqconstr (env, lp, 0, sizeof (qind2) / sizeof (qind2[0]),
                           qrhs, qsense, NULL, NULL,
                           qind2, qind2, qval, "q2");
   if ( status != 0 )
      goto TERMINATE;
   cone[3] = 1;
   cone[4] = NOT_CONE_HEAD;

   cone[5] = NOT_IN_CONE;

   ok = 1;
 TERMINATE:
   if ( !ok )
      free (cone);

   *cone_p = cone;

   return ok;
}
Example #5
0
/*
 * The function returns a true value if the tested KKT conditions are
 * satisfied and false otherwise.
 */
static int
checkkkt (CPXCENVptr env, CPXLPptr lp, int const *cone, double tol)
{
   int cols = CPXgetnumcols (env, lp);
   int rows = CPXgetnumrows (env, lp);
   int qcons = CPXgetnumqconstrs (env, lp);
   double *dslack = NULL, *pi = NULL, *socppi = NULL;
   double *val = NULL, *rhs = NULL;
   int *ind = NULL;
   char *sense = NULL;
   double *x = NULL, *slack = NULL, *qslack = NULL;
   double *sum = NULL;
   qbuf_type qbuf;
   CPXCHANNELptr resc, warnc, errc, logc;
   int ok = 0, skip = 0;
   int status;
   int i, j, q;

   qbuf_init (&qbuf);

   /* Get the channels on which we may report. */
   if ( (status = CPXgetchannels (env, &resc, &warnc, &errc, &logc)) != 0 )
      goto TERMINATE;

   /* Fetch results and problem data that we need to check the KKT
    * conditions.
    */
   CPXmsg (logc, "Fetching results ... ");
   if ( (cols  > 0 && (dslack = malloc (cols *  sizeof (*dslack))) == NULL) ||
        (rows  > 0 && (pi =     malloc (rows *  sizeof (*pi)))     == NULL) ||
        (qcons > 0 && (socppi = malloc (qcons * sizeof (*socppi))) == NULL) ||
        (cols  > 0 && (x =      malloc (cols *  sizeof (*x)))      == NULL) ||
        (rows  > 0 && (sense =  malloc (rows *  sizeof (*sense)))  == NULL ) ||
        (rows  > 0 && (slack =  malloc (rows *  sizeof (*slack)))  == NULL ) ||
        (qcons > 0 && (qslack = malloc (qcons * sizeof (*qslack))) == NULL) ||
        (cols  > 0 && (sum =    malloc (cols *  sizeof (*sum)))    == NULL) ||
        (cols  > 0 && (val =    malloc (cols *  sizeof (*val)))    == NULL) ||
        (cols  > 0 && (ind =    malloc (cols *  sizeof (*ind)))    == NULL) ||
        (rows  > 0 && (rhs =    malloc (rows *  sizeof (*rhs)))    == NULL) )
   {
      CPXmsg (errc, "Out of memory!\n");
      goto TERMINATE;
   }

   /* Fetch problem data. */
   if ( (status = CPXgetsense (env, lp, sense, 0, rows - 1)) != 0 )
      goto TERMINATE;
   if ( (status = CPXgetrhs (env, lp, rhs, 0, rows - 1)) != 0 )
      goto TERMINATE;

   /* Fetch solution information. */
   if ( (status = CPXgetx (env, lp, x, 0, cols - 1)) != 0 )
      goto TERMINATE;
   if ( (status = CPXgetpi (env, lp, pi, 0, rows - 1)) != 0 )
      goto TERMINATE;
   if ( (status = getsocpconstrmultipliers (env, lp, dslack, socppi)) != 0 )
      goto TERMINATE;
   if ( (status = CPXgetslack (env, lp, slack, 0, rows - 1)) != 0 )
      goto TERMINATE;
   if ( (status = CPXgetqconstrslack (env, lp, qslack, 0, qcons - 1)) != 0 )
      goto TERMINATE;
   CPXmsg (logc, "ok.\n");

   /* Print out the solution data we just fetched. */
   CPXmsg (resc, "x      = [");
   for (j = 0; j < cols; ++j)
      CPXmsg (resc, " %+7.3f", x[j]);
   CPXmsg (resc, " ]\n");
   CPXmsg (resc, "dslack = [");
   for (j = 0; j < cols; ++j)
      CPXmsg (resc, " %+7.3f", dslack[j]);
   CPXmsg (resc, " ]\n");
   CPXmsg (resc, "pi     = [");
   for (i = 0; i < rows; ++i)
      CPXmsg (resc, " %+7.3f", pi[i]);
   CPXmsg (resc, " ]\n");
   CPXmsg (resc, "slack  = [");
   for (i = 0; i < rows; ++i)
      CPXmsg (resc, " %+7.3f", slack[i]);
   CPXmsg (resc, " ]\n");
   CPXmsg (resc, "socppi = [");
   for (q = 0; q < qcons; ++q)
      CPXmsg (resc, " %+7.3f", socppi[q]);
   CPXmsg (resc, " ]\n");
   CPXmsg (resc, "qslack = [");
   for (q = 0; q < qcons; ++q)
      CPXmsg (resc, " %+7.3f", qslack[q]);
   CPXmsg (resc, " ]\n");

   /* Test primal feasibility. */
   CPXmsg (logc, "Testing primal feasibility ... ");
   /* This example illustrates the use of dual vectors returned by CPLEX
    * to verify dual feasibility, so we do not test primal feasibility
    * here. */
   CPXmsg (logc, "ok.\n");

   /* Test dual feasibility.
    * We must have
    * - for all <= constraints the respective pi value is non-negative,
    * - for all >= constraints the respective pi value is non-positive,
    * - since all quadratic constraints are <= constraints the socppi
    *   value must be non-negative for all quadratic constraints,
    * - the dslack value for all non-cone variables must be non-negative.
    * Note that we do not support ranged constraints here.
    */
   CPXmsg (logc, "Testing dual feasibility ... ");
   for (i = 0; i < rows; ++i) {
      switch (sense[i]) {
      case 'L':
         if ( pi[i] < -tol ) {
            CPXmsg (errc, "<= row %d has invalid dual multiplier %f.\n",
                    i, pi[i]);
            goto TERMINATE;
         }
         break;
      case 'G':
         if ( pi[i] > tol ) {
            CPXmsg (errc, ">= row %d has invalid dual multiplier %f.\n",
                    i, pi[i]);
            goto TERMINATE;
         }
         break;
      case 'E':
         /* Nothing to check here. */
         break;
      }
   }
   for (q = 0; q < qcons; ++q) {
      if ( socppi[q] < -tol ) {
         CPXmsg (errc, "Quadratic constraint %d has invalid dual multiplier %f.\n",
                 q, socppi[q]);
         goto TERMINATE;
      }
   }
   for (j = 0; j < cols; ++j) {
      if ( cone[j] == NOT_IN_CONE && dslack[j] < -tol ) {
         CPXmsg (errc, "dslack value for column %d is invalid: %f\n", j, dslack[j]);
         goto TERMINATE;
      }
   }
   CPXmsg (logc, "ok.\n");

   /* Test complementary slackness.
    * For each constraint either the constraint must have zero slack or
    * the dual multiplier for the constraint must be 0. Again, we must
    * consider the special case in which a variable is not explicitly
    * contained in a second order cone constraint (conestat[j] == 0).
    */
   CPXmsg (logc, "Testing complementary slackness ... ");
   for (i = 0; i < rows; ++i) {
      if ( fabs (slack[i]) > tol && fabs (pi[i]) > tol ) {
         CPXmsg (errc, "Complementary slackness not satisfied for row %d (%f, %f)\n",
                 i, slack[i], pi[i]);
         goto TERMINATE;
      }
   }
   for (q = 0; q < qcons; ++q) {
      if ( fabs (qslack[q]) > tol && fabs (socppi[q]) > tol ) {
         CPXmsg (errc, "Complementary slackness not satisfied for cone %d (%f, %f).\n",
                 q, qslack[q], socppi[q]);
         goto TERMINATE;
      }
   }
   for (j = 0; j < cols; ++j) {
      if ( cone[j] == NOT_IN_CONE ) {
         if ( fabs (x[j]) > tol && fabs (dslack[j]) > tol ) {
            CPXmsg (errc, "Complementary slackness not satisfied for non-cone variable %f (%f, %f).\n",
                    j, x[j], dslack[j]);
            goto TERMINATE;
         }
      }
   }
   CPXmsg (logc, "ok.\n");

   /* Test stationarity.
    * We must have
    *  c - g[i]'(X)*pi[i] = 0
    * where c is the objective function, g[i] is the i-th constraint of the
    * problem, g[i]'(x) is the derivate of g[i] with respect to x and X is the
    * optimal solution.
    * We need to distinguish the following cases:
    * - linear constraints g(x) = ax - b. The derivative of such a
    *   constraint is g'(x) = a.
    * - second order constraints g(x[1],...,x[n]) = -x[1] + |(x[2],...,x[n])|
    *   the derivative of such a constraint is
    *     g'(x) = (-1, x[2]/|(x[2],...,x[n])|, ..., x[n]/|(x[2],...,x[n])|
    *   (here |.| denotes the Euclidean norm).
    * - bound constraints g(x) = -x for variables that are not explicitly
    *   contained in any second order cone constraint. The derivative for
    *   such a constraint is g'(x) = -1.
    * Note that it may happen that the derivative of a second order cone
    * constraint is not defined at the optimal solution X (this happens if
    * X=0). In this case we just skip the stationarity test.
    */
   CPXmsg (logc, "Testing stationarity ... ");
   /* Initialize sum = c. */
   if ( (status = CPXgetobj (env, lp, sum, 0, cols - 1)) != 0 )
      goto TERMINATE;

   /* Handle linear constraints. */
   for (i = 0; i < rows; ++i) {
      int nz, surplus, beg;
      int n;

      status = CPXgetrows (env, lp, &nz, &beg, ind, val, cols, &surplus,
                           i, i);
      if ( status != 0 )
         goto TERMINATE;
      for (n = 0; n < nz; ++n) {
         sum[ind[n]] -= pi[i] * val[n];
      }
   }
   /* Handle second order cone constraints. */
   for (q = 0; q < qcons; ++q) {
      double norm = 0.0;
      int n;

      if ( !getqconstr (env, lp, q, &qbuf) )
         goto TERMINATE;

      for (n = 0; n < qbuf.qnz; ++n) {
         if ( qbuf.qval[n] > 0 )
            norm += x[qbuf.qcol[n]] * x[qbuf.qcol[n]];
      }
      norm = sqrt (norm);
      if ( fabs (norm) <= tol ) {
         CPXmsg (warnc, "WARNING: Cannot test stationarity at non-differentiable point.\n");
         skip = 1;
         break;
      }

      for (n = 0; n < qbuf.qnz; ++n) {
         if ( qbuf.qval[n] < 0 )
            sum[qbuf.qcol[n]] -= socppi[q];
         else
            sum[qbuf.qcol[n]] += socppi[q] * x[qbuf.qcol[n]] / norm;
      }
   }
   /* Handle variables that do not appear in any second order cone constraint.
    */
   for (j = 0; !skip && j < cols; ++j) {
      if ( cone[j] == NOT_IN_CONE ) {
         sum[j] -= dslack[j];
      }
   }

   /* Now test that all the entries in sum[] are 0.
    */
   for (j = 0; !skip && j < cols; ++j) {
      if ( fabs (sum[j]) > tol ) {
         CPXmsg (errc, "Stationarity not satisfied at index %d: %f\n",
                 j, sum[j]);
         goto TERMINATE;
      }
   }
   CPXmsg (logc, "ok.\n");

   CPXmsg (logc, "KKT conditions are satisfied.\n");

   ok = 1;
 TERMINATE:
   if ( !ok )
      CPXmsg (logc, "failed.\n");
   qbuf_clear (&qbuf);
   free (rhs);
   free (ind);
   free (val);
   free (sum);
   free (qslack);
   free (slack);
   free (sense);
   free (x);
   free (socppi);
   free (pi);
   free (dslack);

   return ok;
}
Example #6
0
/* Read quadratic constraint number Q from LP and store it in qbuf.
 * The buffers in qbuf are expanded if they do not provide enough room
 * to store the constraint.
 * The function returns a true value on success and false if it fails.
 */
static int
getqconstr (CPXCENVptr env, CPXCLPptr lp, int q, qbuf_type *qbuf)
{
   int ok = 0;
   int status;
   int linnz, linsurplus;
   int qnz, qsurplus;
   CPXCHANNELptr errc;

   /* Get the channel for printing error messages. */
   if ( (status = CPXgetchannels (env, NULL, NULL, &errc, NULL)) != 0 )
      goto TERMINATE;

   /* Call CPXgetqconstr() a first time with zero-length buffers to figure
    * how long the buffers must be.
    */
   status = CPXgetqconstr (env, lp, &linnz, &qnz, NULL, NULL,
                           NULL, NULL, 0, &linsurplus,
                           NULL, NULL, NULL, 0, &qsurplus, q);
   if ( status != CPXERR_NEGATIVE_SURPLUS )
      goto TERMINATE;

   /* Adjust buffers for linear coefficients if necessary.
    */
   if ( linsurplus < 0 && -linsurplus >= qbuf->lcap ) {
      int newcap = -linsurplus;

      if ( (qbuf->lind = realloc (qbuf->lind, newcap * sizeof (*qbuf->lind))) == NULL ||
           (qbuf->lval = realloc (qbuf->lval, newcap * sizeof (*qbuf->lval))) == NULL )
      {
         CPXmsg (errc, "Out of memory!\n");
         goto TERMINATE;
      }
      qbuf->lcap = newcap;
   }

   /* Adjust buffers for quadratic coefficients if necessary.
    */
   if ( qsurplus < 0 && -qsurplus >= qbuf->qcap ) {
      int newcap = -qsurplus;

      if ( (qbuf->qcol = realloc (qbuf->qcol, newcap * sizeof (*qbuf->qcol))) == NULL ||
           (qbuf->qrow = realloc (qbuf->qrow, newcap * sizeof (*qbuf->qrow))) == NULL ||
           (qbuf->qval = realloc (qbuf->qval, newcap * sizeof (*qbuf->qval))) == NULL )
      {
         CPXmsg (errc, "Out of memory!\n");
         goto TERMINATE;
      }
      qbuf->qcap = newcap;
   }

   /* Now all buffers in QBUF are long enough to store the constraint we
    * want to query. Copy the constraint into QBUF.
    */
   status = CPXgetqconstr (env, lp, &qbuf->lnz, &qbuf->qnz, &qbuf->rhs,
                           &qbuf->sense,
                           qbuf->lind, qbuf->lval, qbuf->lcap, &linsurplus,
                           qbuf->qrow, qbuf->qcol, qbuf->qval, qbuf->qcap,
                           &qsurplus, q);
   if ( status != 0 )
      goto TERMINATE;

   ok = 1;
 TERMINATE:
   return ok;
}
Example #7
0
File: lpex5.c Project: renvieir/ioc
int
main (void)
{
   char     probname[16];  /* Problem name is max 16 characters */

   /* Declare and allocate space for the variables and arrays where we
      will store the optimization results including the status, objective
      value, variable values, dual values, row slacks and variable
      reduced costs. */

   int      solstat;
   double   objval;
   double   x[NUMCOLS];
   double   pi[NUMROWS];
   double   slack[NUMROWS];
   double   dj[NUMCOLS];


   CPXENVptr     env = NULL;
   CPXLPptr      lp = NULL;
   int           status;
   int           i, j;
   int           cur_numrows, cur_numcols;
   char          errmsg[CPXMESSAGEBUFSIZE];

   CPXCHANNELptr  cpxerror   = NULL;
   CPXCHANNELptr  cpxwarning = NULL;
   CPXCHANNELptr  cpxresults = NULL;
   CPXCHANNELptr  ourchannel = NULL;

   char errorlabel[] = "cpxerror";
   char warnlabel[]  = "cpxwarning";
   char reslabel[]   = "cpxresults";
   char ourlabel[]   = "Our Channel";
   char ourmessage[] = "Our Message";

   CPXFILEptr fpout  = NULL;


   /* Initialize the CPLEX environment */

   env = CPXopenCPLEX (&status);

   /* If an error occurs, the status value indicates the reason for
      failure.  A call to CPXgeterrorstring will produce the text of
      the error message.  Note that CPXopenCPLEX produces no output,
      so the only way to see the cause of the error is to use
      CPXgeterrorstring.  For other CPLEX routines, the errors will
      be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON.  */

   /* Since the message handler is yet to be set up, we'll call our
      messaging function directly to print out any errors  */

   if ( env == NULL ) {
      ourmsgfunc (ourmessage, "Could not open CPLEX environment.\n");
      goto TERMINATE;
   }

   /* Now get the standard channels.  If an error, just call our
      message function directly. */

   status = CPXgetchannels (env, &cpxresults, &cpxwarning, &cpxerror, NULL);
   if ( status ) {
      ourmsgfunc (ourmessage, "Could not get standard channels.\n");
      CPXgeterrorstring (env, status, errmsg);
      ourmsgfunc (ourmessage, errmsg);
      goto TERMINATE;
   }

   /* Now set up the error channel first.  The label will be "cpxerror" */

   status = CPXaddfuncdest (env, cpxerror, errorlabel, ourmsgfunc);
   if ( status ) {
      ourmsgfunc (ourmessage, "Could not set up error message handler.\n");
      CPXgeterrorstring (env, status, errmsg);
      ourmsgfunc (ourmessage, errmsg);
   }

   /* Now that we have the error message handler set up, all CPLEX
      generated errors will go through ourmsgfunc.  So we don't have
      to use CPXgeterrorstring to determine the text of the message.
      We can also use CPXmsg to do any other printing.  */

   status = CPXaddfuncdest (env, cpxwarning, warnlabel, ourmsgfunc);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to set up handler for cpxwarning.\n");
      goto TERMINATE;
   }

   status = CPXaddfuncdest (env, cpxresults, reslabel, ourmsgfunc);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to set up handler for cpxresults.\n");
      goto TERMINATE;
   }
   
   /* Now turn on the iteration display. */

   status = CPXsetintparam (env, CPXPARAM_Simplex_Display, 2);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to turn on simplex display level.\n");
      goto TERMINATE;
   }

   /* Create the problem. */

   strcpy (probname, "example");
   lp = CPXcreateprob (env, &status, probname);

   /* A returned pointer of NULL may mean that not enough memory
      was available or there was some other problem.  In the case of 
      failure, an error message will have been written to the error 
      channel from inside CPLEX.  In this example, the setting of
      the parameter CPXPARAM_ScreenOutput causes the error message to
      appear on stdout.  */

   if ( lp == NULL ) {
      CPXmsg (cpxerror, "Failed to create LP.\n");
      goto TERMINATE;
   }

   /* Now populate the problem with the data. */

   status = populatebycolumn (env, lp);

   if ( status ) {
      CPXmsg (cpxerror, "Failed to populate problem data.\n");
      goto TERMINATE;
   }


   /* Optimize the problem and obtain solution. */

   status = CPXlpopt (env, lp);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to optimize LP.\n");
      goto TERMINATE;
   }

   status = CPXsolution (env, lp, &solstat, &objval, x, pi, slack, dj);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to obtain solution.\n");
      goto TERMINATE;
   }


   /* Write the output to the screen.  We will also write it to a
      file as well by setting up a file destination and a function
      destination. */

   ourchannel = CPXaddchannel (env);
   if ( ourchannel == NULL ) {
      CPXmsg (cpxerror, "Failed to set up our private channel.\n");
      goto TERMINATE;
   }

   fpout = CPXfopen ("lpex5.msg", "w");
   if ( fpout == NULL ) {
      CPXmsg (cpxerror, "Failed to open lpex5.msg file for output.\n");
      goto TERMINATE;
   }
   status = CPXaddfpdest (env, ourchannel, fpout);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to set up output file destination.\n");
      goto TERMINATE;
   }

   status = CPXaddfuncdest (env, ourchannel, ourlabel, ourmsgfunc);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to set up our output function.\n");
      goto TERMINATE;
   }

   /* Now any message to channel ourchannel will go into the file 
      and into the file opened above. */

   CPXmsg (ourchannel, "\nSolution status = %d\n", solstat);
   CPXmsg (ourchannel, "Solution value  = %f\n\n", objval);

   /* The size of the problem should be obtained by asking CPLEX what
      the actual size is, rather than using sizes from when the problem
      was built.  cur_numrows and cur_numcols store the current number 
      of rows and columns, respectively.  */

   cur_numrows = CPXgetnumrows (env, lp);
   cur_numcols = CPXgetnumcols (env, lp);
   for (i = 0; i < cur_numrows; i++) {
      CPXmsg (ourchannel, "Row %d:  Slack = %10f  Pi = %10f\n", 
              i, slack[i], pi[i]);
   }

   for (j = 0; j < cur_numcols; j++) {
      CPXmsg (ourchannel, "Column %d:  Value = %10f  Reduced cost = %10f\n",
              j, x[j], dj[j]);
   }

   /* Finally, write a copy of the problem to a file. */

   status = CPXwriteprob (env, lp, "lpex5.lp", NULL);
   if ( status ) {
      CPXmsg (cpxerror, "Failed to write LP to disk.\n");
      goto TERMINATE;
   }
   
   
TERMINATE:

   /* First check if ourchannel is open */

   if ( ourchannel != NULL ) {
      int  chanstat;
      chanstat = CPXdelfuncdest (env, ourchannel, ourlabel, ourmsgfunc);
      if ( chanstat ) {
         strcpy (errmsg, "CPXdelfuncdest failed.\n");
         ourmsgfunc (ourmessage, errmsg); 
         if (!status)  status = chanstat;
      }
      if ( fpout != NULL ) {
         chanstat = CPXdelfpdest (env, ourchannel, fpout);
         if ( chanstat ) {
            strcpy (errmsg, "CPXdelfpdest failed.\n");
            ourmsgfunc (ourmessage, errmsg);
            if (!status)  status = chanstat;
         }
         CPXfclose (fpout);
      }

      chanstat = CPXdelchannel (env, &ourchannel);
      if ( chanstat ) {
         strcpy (errmsg, "CPXdelchannel failed.\n");
         ourmsgfunc (ourmessage, errmsg); 
         if (!status)  status = chanstat;
      }
   }

   /* Free up the problem as allocated by CPXcreateprob, if necessary */

   if ( lp != NULL ) {
      status = CPXfreeprob (env, &lp);
      if ( status ) {
         strcpy (errmsg, "CPXfreeprob failed.\n");
         ourmsgfunc (ourmessage, errmsg);
      }
   }

   /* Now delete our function destinations from the 3 CPLEX channels. */
   if ( cpxresults != NULL ) {
      int  chanstat;
      chanstat = CPXdelfuncdest (env, cpxresults, reslabel, ourmsgfunc);
      if ( chanstat && !status ) {
         status = chanstat;
         strcpy (errmsg, "Failed to delete cpxresults function.\n");
         ourmsgfunc (ourmessage, errmsg);
      }
   }

   if ( cpxwarning != NULL ) {
      int  chanstat;
      chanstat = CPXdelfuncdest (env, cpxwarning, warnlabel, ourmsgfunc);
      if ( chanstat && !status ) {
         status = chanstat;
         strcpy (errmsg, "Failed to delete cpxwarning function.\n");
         ourmsgfunc (ourmessage, errmsg);
      }
   }

   if ( cpxerror != NULL ) {
      int  chanstat;
      chanstat = CPXdelfuncdest (env, cpxerror, errorlabel, ourmsgfunc);
      if ( chanstat && !status ) {
         status = chanstat;
         strcpy (errmsg, "Failed to delete cpxerror function.\n");
         ourmsgfunc (ourmessage, errmsg);
      }
   }

   /* Free up the CPLEX environment, if necessary */

   if ( env != NULL ) {
      status = CPXcloseCPLEX (&env);

      /* Note that CPXcloseCPLEX produces no output,
         so the only way to see the cause of the error is to use
         CPXgeterrorstring.  For other CPLEX routines, the errors will
         be seen if the CPXPARAM_ScreenOutput indicator is set to CPX_ON. */

      if ( status ) {
         strcpy (errmsg, "Could not close CPLEX environment.\n");
         ourmsgfunc (ourmessage, errmsg);
         CPXgeterrorstring (env, status, errmsg);
         ourmsgfunc (ourmessage, errmsg);
      }
   }
     
   return (status);

}  /* END main */