示例#1
0
文件: ip.cpp 项目: satoken/ractip
  double solve()
  {
    const int numcols = vars_.size();
    const int numrows = bnd_.size();

    int status;
    lp_ = CPXcreateprob(env_, &status, "PRactIP");
    if (lp_==NULL) 
      throw std::runtime_error("failed to create LP");
    
    unsigned int n_nonzero=0;
    for (unsigned int i=0; i!=m_.size(); ++i) 
      n_nonzero += m_[i].size();
    std::vector<int> matbeg(numcols, 0);
    std::vector<int> matcnt(numcols, 0);
    std::vector<int> matind(n_nonzero);
    std::vector<double> matval(n_nonzero);
    for (unsigned int i=0, k=0; i!=m_.size(); ++i) 
    {
      matbeg[i] = i==0 ? 0 : matbeg[i-1]+matcnt[i-1];
      matcnt[i] = m_[i].size();
      for (unsigned int j=0; j!=m_[i].size(); ++j, ++k)
      {
        matind[k] = m_[i][j].first;
        matval[k] = m_[i][j].second;
      }
    }
    m_.clear();

    status = CPXcopylp(env_, lp_, numcols, numrows,
                        dir_==IP::MIN ? CPX_MIN : CPX_MAX,
                        &coef_[0], &rhs_[0], &bnd_[0], 
                        &matbeg[0], &matcnt[0], &matind[0], &matval[0],
                        &vlb_[0], &vub_[0], &rngval_[0] );
    vlb_.clear();
    vub_.clear();

    status = CPXcopyctype(env_, lp_, &vars_[0]);
    vars_.clear();

    CPXsetintparam(env_, CPXPARAM_MIP_Display, 0);
    CPXsetintparam(env_, CPXPARAM_Barrier_Display, 0);
    CPXsetintparam(env_, CPXPARAM_Tune_Display, 0);
    CPXsetintparam(env_, CPXPARAM_Network_Display, 0);
    CPXsetintparam(env_, CPXPARAM_Sifting_Display, 0);
    CPXsetintparam(env_, CPXPARAM_Simplex_Display, 0);

    status = CPXmipopt(env_, lp_);
    double objval;
    status = CPXgetobjval(env_, lp_, &objval);
    res_cols_.resize(CPXgetnumcols(env_, lp_));
    status = CPXgetx(env_, lp_, &res_cols_[0], 0, res_cols_.size()-1);

    return objval;
  }
示例#2
0
文件: lpex8.c 项目: renvieir/ioc
int
main (void)
{
   /* Declare pointers for the variables and arrays that will contain
      the data which define the LP problem.  The setproblemdata() routine
      allocates space for the problem data.  */

   char     *probname = NULL;  
   int      numcols;
   int      numrows;
   int      objsen;
   double   *obj = NULL;
   double   *rhs = NULL;
   char     *sense = NULL;
   int      *matbeg = NULL;
   int      *matcnt = NULL;
   int      *matind = NULL;
   double   *matval = NULL;
   double   *lb = NULL;
   double   *ub = NULL;

   /* 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;

   /* 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.  */

   if ( env == NULL ) {
      char  errmsg[CPXMESSAGEBUFSIZE];
      fprintf (stderr, "Could not open CPLEX environment.\n");
      CPXgeterrorstring (env, status, errmsg);
      fprintf (stderr, "%s", errmsg);
      goto TERMINATE;
   }

   /* Turn on output to the screen */

   status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON);
   if ( status ) {
      fprintf (stderr, 
               "Failure to turn on screen indicator, error %d.\n", status);
      goto TERMINATE;
   }

   /* Allocate memory and fill in the data for the problem.  */

   status = setproblemdata (&probname, &numcols, &numrows, &objsen, 
                            &obj, &rhs, &sense, &matbeg, &matcnt, 
                            &matind, &matval, &lb, &ub);
   if ( status ) {
      fprintf (stderr, "Failed to build problem data arrays.\n");
      goto TERMINATE;
   }

   /* Create the problem. */

   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 ) {
      fprintf (stderr, "Failed to create LP.\n");
      goto TERMINATE;
   }

   /* Now copy the problem data into the lp */

   status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, rhs, 
                       sense, matbeg, matcnt, matind, matval,
                       lb, ub, NULL);

   if ( status ) {
      fprintf (stderr, "Failed to copy problem data.\n");
      goto TERMINATE;
   }


   /* Optimize the problem and obtain solution. */

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

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


   /* Write the output to the screen. */

   printf ("\nSolution status = %d\n", solstat);
   printf ("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 what was passed to CPXcopylp.
      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++) {
      printf ("Row %d:  Slack = %10f  Pi = %10f\n", i, slack[i], pi[i]);
   }

   for (j = 0; j < cur_numcols; j++) {
      printf ("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, "lpex1.lp", NULL);
   if ( status ) {
      fprintf (stderr, "Failed to write LP to disk.\n");
      goto TERMINATE;
   }
   
   
TERMINATE:

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

   if ( lp != NULL ) {
      status = CPXfreeprob (env, &lp);
      if ( status ) {
         fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status);
      }
   }

   /* 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 ) {
         char  errmsg[CPXMESSAGEBUFSIZE];
         fprintf (stderr, "Could not close CPLEX environment.\n");
         CPXgeterrorstring (env, status, errmsg);
         fprintf (stderr, "%s", errmsg);
      }
   }

   /* Free up the problem data arrays, if necessary. */

   free_and_null ((char **) &probname);
   free_and_null ((char **) &obj);
   free_and_null ((char **) &rhs);
   free_and_null ((char **) &sense);
   free_and_null ((char **) &matbeg);
   free_and_null ((char **) &matcnt);
   free_and_null ((char **) &matind);
   free_and_null ((char **) &matval);
   free_and_null ((char **) &lb);
   free_and_null ((char **) &ub);
        
   return (status);

}  /* END main */
示例#3
0
文件: lp_gen.c 项目: ratschlab/MiTie
void mexFunction(
    int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[]
)
{
    int i, j;
    double *c=NULL, *b=NULL, *A=NULL,
            *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ;
    int *iA=NULL, *kA=NULL, *nzA=NULL, neq=0, m=0, n=0, display=0;
    long *lpenv=NULL, *p_lp=NULL;
    char *Sense=NULL ;
#ifndef MX_COMPAT_32
    long *iA_=NULL, *kA_=NULL ;
#endif

    if (nrhs > 8 || nrhs < 1) {
        mexErrMsgTxt("Usage: [p_lp,how] "
                     "= lp_gen(lpenv,c,A,b,l,u,neq,disp)");
        return;
    }
    switch (nrhs) {
    case 8:
        if (mxGetM(prhs[7]) != 0 || mxGetN(prhs[7]) != 0) {
            if (!mxIsNumeric(prhs[7]) || mxIsComplex(prhs[7])
                    ||  mxIsSparse(prhs[7])
                    || !(mxGetM(prhs[7])==1 && mxGetN(prhs[7])==1)) {
                mexErrMsgTxt("8th argument (display) must be "
                             "an integer scalar.");
                return;
            }
            display = *mxGetPr(prhs[7]);
        }
    case 7:
        if (mxGetM(prhs[6]) != 0 || mxGetN(prhs[6]) != 0) {
            if (!mxIsNumeric(prhs[6]) || mxIsComplex(prhs[6])
                    ||  mxIsSparse(prhs[6])
                    || !(mxGetM(prhs[6])==1 && mxGetN(prhs[6])==1)) {
                mexErrMsgTxt("7th argument (neq) must be "
                             "an integer scalar.");
                return;
            }
            neq = *mxGetPr(prhs[6]);
        }
    case 6:
        if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) {
            if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5])
                    ||  mxIsSparse(prhs[5])
                    || !mxIsDouble(prhs[5])
                    ||  mxGetN(prhs[5])!=1 ) {
                mexErrMsgTxt("6th argument (u) must be "
                             "a column vector.");
                return;
            }
            u = mxGetPr(prhs[5]);
            n = mxGetM(prhs[5]);
        }
    case 5:
        if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) {
            if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4])
                    ||  mxIsSparse(prhs[4])
                    || !mxIsDouble(prhs[4])
                    ||  mxGetN(prhs[4])!=1 ) {
                mexErrMsgTxt("5th argument (l) must be "
                             "a column vector.");
                return;
            }
            if (n != 0 && n != mxGetM(prhs[4])) {
                mexErrMsgTxt("Dimension error (arg 5 and later).");
                return;
            }
            l = mxGetPr(prhs[4]);
            n = mxGetM(prhs[4]);
        }
    case 4:
        if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) {
            if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3])
                    ||  mxIsSparse(prhs[3])
                    || !mxIsDouble(prhs[3])
                    ||  mxGetN(prhs[3])!=1 ) {
                mexErrMsgTxt("4rd argument (b) must be "
                             "a column vector.");
                return;
            }
            if (m != 0 && m != mxGetM(prhs[3])) {
                mexErrMsgTxt("Dimension error (arg 4 and later).");
                return;
            }
            b = mxGetPr(prhs[3]);
            m = mxGetM(prhs[3]);
        }
    case 3:
        if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) {
            if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2])
                    || !mxIsSparse(prhs[2]) ) {
                mexErrMsgTxt("3n argument (A) must be "
                             "a sparse matrix.");
                return;
            }
            if (m != 0 && m != mxGetM(prhs[2])) {
                mexErrMsgTxt("Dimension error (arg 3 and later).");
                return;
            }
            if (n != 0 && n != mxGetN(prhs[2])) {
                mexErrMsgTxt("Dimension error (arg 3 and later).");
                return;
            }
            m = mxGetM(prhs[2]);
            n = mxGetN(prhs[2]);

            A = mxGetPr(prhs[2]);
#ifdef MX_COMPAT_32
            iA = mxGetIr(prhs[2]);
            kA = mxGetJc(prhs[2]);
#else
            iA_ = mxGetIr(prhs[2]);
            kA_ = mxGetJc(prhs[2]);

            iA = myMalloc(mxGetNzmax(prhs[2])*sizeof(int)) ;
            for (i=0; i<mxGetNzmax(prhs[2]); i++)
                iA[i]=iA_[i] ;

            kA = myMalloc((n+1)*sizeof(int)) ;
            for (i=0; i<n+1; i++)
                kA[i]=kA_[i] ;
#endif
            nzA=myMalloc(n*sizeof(int)) ;
            for (i=0; i<n; i++)
                nzA[i]=kA[i+1]-kA[i] ;

            Sense=myMalloc((m+1)*sizeof(char)) ;
            for (i=0; i<m; i++)
                if (i<neq) Sense[i]='E' ;
                else Sense[i]='L' ;
            Sense[m]=0 ;
        }
    case 2:
        if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) {
            if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1])
                    ||  mxIsSparse(prhs[1])
                    || !mxIsDouble(prhs[1])
                    ||  mxGetN(prhs[1])!=1 ) {
                mexErrMsgTxt("2st argument (c) must be "
                             "a column vector.");
                return;
            }
            if (n != 0 && n != mxGetM(prhs[1])) {
                mexErrMsgTxt("Dimension error (arg 2 and later).");
                return;
            }
            c = mxGetPr(prhs[1]);
            n = mxGetM(prhs[1]);
        }
    case 1:
        if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) {
            if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0])
                    ||  mxIsSparse(prhs[0])
                    || !mxIsDouble(prhs[0])
                    ||  mxGetN(prhs[0])!=1 ) {
                mexErrMsgTxt("1st argument (lpenv) must be "
                             "a column vector.");
                return;
            }
            if (1 != mxGetM(prhs[0])) {
                mexErrMsgTxt("Dimension error (arg 1).");
                return;
            }
            lpenv = (long*) mxGetPr(prhs[0]);
        }
    }

    if (nlhs > 2 || nlhs < 1) {
        mexErrMsgTxt("Usage: [p_lp,how] "
                     "= lp_gen(lpenv,c,A,b,l,u,neq,disp)");
        return;
    }
    if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i) \n", m, n, neq) ;

    switch (nlhs) {
    case 2:
    case 1:
        plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
        p_lp = (long*) mxGetPr(plhs[0]);
    }
    if (display>2) fprintf(STD_OUT, "argument processing finished\n") ;
    {
        CPXENVptr     env = NULL;
        CPXLPptr      lp = NULL;

        int           status, lpstat;
        double        objval;

        /* Initialize the CPLEX environment */
        env = (CPXENVptr) lpenv[0] ;

        /* Create the problem */
        if (display>2) fprintf(STD_OUT, "calling CPXcreateprob \n") ;
        lp = CPXcreateprob (env, &status, "xxx");
        if ( lp == NULL ) {
            fprintf (STD_OUT,"Failed to create subproblem\n");
            status = 1;
            goto TERMINATE;
        }
        if (p_lp) *p_lp=(long) lp ;

        if (display>2)
            fprintf(STD_OUT, "calling CPXcopylp (m=%i, n=%i) \n", m, n) ;
        status = CPXcopylp(env, lp, n, m, CPX_MIN, c, b,
                           Sense, kA, nzA, iA, A,
                           l, u, NULL);
        if ( status ) {
            fprintf (STD_OUT, "CPXcopylp failed.\n");
            goto TERMINATE;
        }

TERMINATE:
        if (status) {
            char  errmsg[1024];
            CPXgeterrorstring (env, status, errmsg);
            fprintf (STD_OUT, "%s", errmsg);
            if (nlhs >= 2)
                plhs[1] = mxCreateString(errmsg) ;
        } else if (nlhs >= 2)
            plhs[1] = mxCreateString("OK") ;
        ;
        if (nzA) myFree(nzA) ;
#ifndef MX_COMPAT_32
        if (iA) myFree(iA) ;
        if (kA) myFree(kA) ;
#endif
        /*if (Sense) myFree(Sense) ;*/
        if (!p_lp)
        {
            if ( lp != NULL ) {
                if (display>2)
                    fprintf(STD_OUT, "calling CPXfreeprob\n") ;
                status = CPXfreeprob (env, &lp);
                if ( status ) {
                    fprintf (STD_OUT, "CPXfreeprob failed, error code %d.\n", status);
                }
            }
        }
        return ;
    }
}
示例#4
0
int
main (void)
{
    /* Declare pointers for the variables and arrays that will contain
       the data which define the LP problem.  The setproblemdata() routine
       allocates space for the problem data.  */

    char     *probname = NULL;
    int      numcols;
    int      numrows;
    int      objsen;
    double   *obj = NULL;
    double   *rhs = NULL;
    char     *sense = NULL;
    int      *matbeg = NULL;
    int      *matcnt = NULL;
    int      *matind = NULL;
    double   *matval = NULL;
    double   *lb = NULL;
    double   *ub = NULL;
    int      *qmatbeg = NULL;
    int      *qmatcnt = NULL;
    int      *qmatind = NULL;
    double   *qmatval = NULL;

    /* Declare pointers for the variables that will contain the data
       for the constraint that cuts off certain local optima. */

    int      numrows_extra;
    int      numnnz_extra;
    double   *rhs_extra = NULL;
    char     *sense_extra = NULL;
    int      *rmatbeg = NULL;
    int      *rmatind = NULL;
    double   *rmatval = NULL;
    int      rowind[1];

    /* 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;

    CPXENVptr     env = NULL;
    CPXLPptr      lp = NULL;
    int           status;

    /* 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.  */

    if ( env == NULL ) {
        char  errmsg[CPXMESSAGEBUFSIZE];
        fprintf (stderr, "Could not open CPLEX environment.\n");
        CPXgeterrorstring (env, status, errmsg);
        fprintf (stderr, "%s", errmsg);
        goto TERMINATE;
    }

    /* Turn on output to the screen */

    status = CPXsetintparam (env, CPXPARAM_ScreenOutput, CPX_ON);
    if ( status ) {
        fprintf (stderr,
                 "Failure to turn on screen indicator, error %d.\n", status);
        goto TERMINATE;
    }

    /* Fill in the data for the problem.  */

    status = setproblemdata (&probname, &numcols, &numrows, &objsen, &obj,
                             &rhs, &sense, &matbeg, &matcnt, &matind,
                             &matval, &lb, &ub, &qmatbeg, &qmatcnt,
                             &qmatind, &qmatval,
                             &numrows_extra, &numnnz_extra,
                             &rhs_extra, &sense_extra,
                             &rmatbeg, &rmatind, &rmatval);
    if ( status ) {
        fprintf (stderr, "Failed to build problem data arrays.\n");
        goto TERMINATE;
    }

    /* Create the problem. */

    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 ) {
        fprintf (stderr, "Failed to create problem.\n");
        goto TERMINATE;
    }

    /* Now copy the LP part of the problem data into the lp */

    status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, rhs,
                        sense, matbeg, matcnt, matind, matval,
                        lb, ub, NULL);

    if ( status ) {
        fprintf (stderr, "Failed to copy problem data.\n");
        goto TERMINATE;
    }

    status = CPXcopyquad (env, lp, qmatbeg, qmatcnt, qmatind, qmatval);
    if ( status ) {
        fprintf (stderr, "Failed to copy quadratic matrix.\n");
        goto TERMINATE;
    }


    /* When a non-convex objective function is present, CPLEX will
       return error CPXERR_Q_NOT_POS_DEF unless the parameter
       CPXPARAM_OptimalityTarget is set to accept first-order optimal
       solutions.  */
    status = CPXsetintparam (env, CPXPARAM_OptimalityTarget,
                             CPX_OPTIMALITYTARGET_FIRSTORDER);
    if ( status ) goto TERMINATE;

    /* Optimize the problem and obtain solution. */

    status = optimize_and_report(env, lp, &solstat, &objval);
    if ( status ) goto TERMINATE;


    /* Add a constraint to cut off the solution at (-1, 1) */

    status = CPXaddrows (env, lp, 0, numrows_extra, numnnz_extra,
                         rhs_extra, sense_extra,
                         rmatbeg, rmatind, rmatval,
                         NULL, NULL);
    if ( status ) goto TERMINATE;

    status = optimize_and_report(env, lp, &solstat, &objval);
    if ( status ) goto TERMINATE;


    /* Reverse the sense of the new constraint to cut off the solution at (1, 1) */

    rowind[0] = CPXgetnumrows (env, lp) - 1;
    status    = CPXchgsense (env, lp, 1, rowind, "L");
    if ( status ) goto TERMINATE;

    status = optimize_and_report(env, lp, &solstat, &objval);
    if ( status ) goto TERMINATE;

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

    status = CPXwriteprob (env, lp, "indefqpex1.lp", NULL);
    if ( status ) {
        fprintf (stderr, "Failed to write LP to disk.\n");
        goto TERMINATE;
    }


TERMINATE:

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

    if ( lp != NULL ) {
        status = CPXfreeprob (env, &lp);
        if ( status ) {
            fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status);
        }
    }

    /* 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 ) {
            char  errmsg[CPXMESSAGEBUFSIZE];
            fprintf (stderr, "Could not close CPLEX environment.\n");
            CPXgeterrorstring (env, status, errmsg);
            fprintf (stderr, "%s", errmsg);
        }
    }

    /* Free up the problem data arrays, if necessary. */

    free_and_null ((char **) &probname);
    free_and_null ((char **) &obj);
    free_and_null ((char **) &rhs);
    free_and_null ((char **) &sense);
    free_and_null ((char **) &matbeg);
    free_and_null ((char **) &matcnt);
    free_and_null ((char **) &matind);
    free_and_null ((char **) &matval);
    free_and_null ((char **) &lb);
    free_and_null ((char **) &ub);
    free_and_null ((char **) &qmatbeg);
    free_and_null ((char **) &qmatcnt);
    free_and_null ((char **) &qmatind);
    free_and_null ((char **) &qmatval);
    free_and_null ((char **) &rhs_extra);
    free_and_null ((char **) &sense_extra);
    free_and_null ((char **) &rmatbeg);
    free_and_null ((char **) &rmatind);
    free_and_null ((char **) &rmatval);

    return (status);

}  /* END main */
示例#5
0
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  /* MATLAB memory structures */
  const mxArray *c,*A,*b,*l,*u,*le,*ge,*maxIterPtr;

  /* Return arguments */
  double   *matlpstat,*objval,*x,*pi,*cstat,*itcnt;

  /* Other declarations */
  char *sense,errorMsg[255];
  int rows,cols,maxIter,*matbeg,*matcnt,*matind;
  double *c_ptr,*b_ptr,*matval,*l_ptr,*u_ptr,*slack,*dj;
  int matrixSize,status,i,j,le_size,ge_size,m,n;
  double *le_ptr = NULL,*ge_ptr = NULL;
  int *istat,lpstat;
  //CPXENVptr env;
  //CPXLPptr lp = NULL;

  /* Assign pointers to MATLAB memory stuctures */
  c = prhs[C_IN];
  A = prhs[A_IN];
  b = prhs[B_IN];
  l = prhs[L_IN];
  u = prhs[U_IN];

  c_ptr = mxGetPr(c); 
  b_ptr = mxGetPr(b); 
  l_ptr = mxGetPr(l);
  u_ptr = mxGetPr(u);
  rows  = mxGetM(b);  
  cols  = mxGetM(c);  

  /* Build the matrix of coefficients, taking sparsity into account. */
  if (mxIsSparse(A)){
    /* Sparse */
    matbeg = mxGetJc(A);   /* beginnings of each column */
    matcnt = (int*)mxCalloc(cols,sizeof(int)); /* # of entries in each col */
    for (i = 0; i < cols; i++)
      matcnt[i] = matbeg[i+1] - matbeg[i];
    matind = mxGetIr(A);   /* row locations */
    matval = mxGetPr(A);   /* actual coefficients */

  } else {
    /* Dense */
    m = mxGetM(A);
    n = mxGetN(A);
    matbeg = (int*)mxCalloc(n,sizeof(int));
    matcnt = (int*)mxCalloc(n,sizeof(int));
    matind = (int*)mxCalloc(m*n,sizeof(int));
    matval = mxGetPr(A);
    for (j = 0; j < n; j++) {
      matbeg[j] = j*m;
      for (i = 0; i < m; i++)
	matind[j*m + i] = i; 
      matcnt[j] = m;
    }
  }

  /* Initialize all constraints to be equality constraints (default). */
  sense = (char*)mxCalloc(rows,sizeof(char));
  for(i = 0; i < rows; i++)
    sense[i] = 'E';

  /* If "<=" constraints given, set them up. */
  if(nrhs > MANDATORY_ARGS){
    le = prhs[LE_IN];
    le_ptr = mxGetPr(le);
    le_size = mxGetM(le);
    for(i = 0; i < le_size; i++)
      sense[(int)(le_ptr[i]-1)] = 'L';
  }

  /* If ">=" constraints given, set them up. */
  if(nrhs > MANDATORY_ARGS + 1){
    ge = prhs[GE_IN];
    ge_ptr = mxGetPr(ge);
    ge_size = mxGetM(ge);
    for(i = 0; i < ge_size; i++)
      sense[(int)(ge_ptr[i]-1)] = 'G';
  }

  /* Set up maximum number of iterations */
  if (nrhs > MANDATORY_ARGS + 2) {
    maxIterPtr = prhs[MI_IN];
    maxIter = (int)mxGetScalar(maxIterPtr);
  } else
    maxIter = MAX_ITER_DEFAULT;

  /* Output to MATLAB */
  plhs[OBJ_OUT]    = mxCreateDoubleMatrix(1,1,mxREAL);
  plhs[X_OUT]      = mxCreateDoubleMatrix(cols,1,mxREAL);
  plhs[PI_OUT]     = mxCreateDoubleMatrix(rows,1,mxREAL);
  plhs[STAT_OUT]   = mxCreateDoubleMatrix(1,1,mxREAL);
  plhs[CSTAT_OUT]  = mxCreateDoubleMatrix(cols,1,mxREAL);
  plhs[ITER_OUT]   = mxCreateDoubleMatrix(1,1,mxREAL);

  objval    = mxGetPr(plhs[OBJ_OUT]);
  x         = mxGetPr(plhs[X_OUT]);
  pi        = mxGetPr(plhs[PI_OUT]);
  matlpstat = mxGetPr(plhs[STAT_OUT]);
  cstat     = mxGetPr(plhs[CSTAT_OUT]);
  istat     = (int*)mxCalloc(cols,sizeof(int));
  itcnt     = mxGetPr(plhs[ITER_OUT]);
  
  if (!initialized)
  {
      mexPrintf("MEX-file: lp_cplex_mex opening cplex environment\n");
      /* Open CPLEX environment */
      env = CPXopenCPLEXdevelop(&status);
      if (!env) {
        printf(CPXgeterrorstring(env,status,errorMsg));
        mexErrMsgTxt("\nCould not open CPLEX environment.");
      }
      /* Create CPLEX problem space */
      lp = CPXcreateprob(env, &status, "matlab");
      if (!lp) {
        printf(CPXgeterrorstring(env,status,errorMsg));
        CPXcloseCPLEX(&env);
        mexErrMsgTxt("\nCould not create CPLEX problem.");
      }
      mexAtExit(cleanup);
      initialized = 1;
  }
  
	
  /* Copy LP into CPLEX environment */
  status = CPXcopylp(env, lp, cols, rows, MINIMIZE, c_ptr, b_ptr, sense,
		     matbeg, matcnt, matind, matval, l_ptr, u_ptr, NULL);
  
  if (status) {
    printf(CPXgeterrorstring(env,status,errorMsg));
    //CPXfreeprob(env,&lp); 
    //CPXcloseCPLEX(&env);
    mexErrMsgTxt("\nCould not copy CPLEX problem.");
  }
  
  /* Set iteration limit. */
  status = CPXsetintparam(env, CPX_PARAM_ITLIM, maxIter);
  if (status) {
    printf(CPXgeterrorstring(env,status,errorMsg));
    //CPXfreeprob(env,&lp); 
    //CPXcloseCPLEX(&env);
    mexErrMsgTxt("\nCould not set number of iterations.");
  }
  
  /* Perform optimization */
  status = CPXprimopt(env,lp);
  if (status) {
    printf(CPXgeterrorstring(env,status,errorMsg));
    //CPXfreeprob(env,&lp); 
    //CPXcloseCPLEX(&env);
    mexErrMsgTxt("\nOptimization error.");
  }
  
  /* Obtain solution */
  status = CPXsolution(env, lp, &lpstat, objval, x, pi, NULL, NULL);
  *matlpstat = lpstat;
  if (status) {
    printf(CPXgeterrorstring(env,status,errorMsg));
    //CPXfreeprob(env,&lp); 
    //CPXcloseCPLEX(&env);
    mexErrMsgTxt("\nFailure when retrieving solution.");
  }
  
  /* Get status of columns */
  status = CPXgetbase(env, lp, istat, NULL);
  if (status) {
    printf(CPXgeterrorstring(env,status,errorMsg));
    //CPXfreeprob(env,&lp); 
    //CPXcloseCPLEX(&env);
    mexErrMsgTxt("\nUnable to get basis status.");
  }
 
  /* Copy int column values to double column values */
  for (i=0; i < cols; i++)
    cstat[i] = istat[i];
  
  /* Get iteration count */
  *itcnt = (double)CPXgetitcnt(env,lp);
  
  /* Clean up problem  */
  //CPXfreeprob(env,&lp); 
  //CPXcloseCPLEX(&env);
  
}
示例#6
0
文件: reducemex.c 项目: pcasau/FITBOX
reducemex(double M[], double costs[], double stats[], double ikeep[],
          double m[],
		  int matbeg[], int matcnt[], int matind[], double matval[],
          char sense[], int objsen, double lb[], double ub[],
          int numrows, int numcols, double tol)

{
CPXENVptr     env = NULL;
CPXLPptr      lp = NULL;
int           status;
char          probname[16];
double        *pi;
double        *slack;
double        *dj;


double        *obj;
int           solstat;
double        objval;
double        *x;

double        newval;
int           *indices;

int kc, i;

obj = mxCalloc(numcols,sizeof(double));
x   = mxCalloc(numcols,sizeof(double));

indices = mxCalloc(numcols,sizeof(int));

pi = mxCalloc(numrows,sizeof(double));
slack = mxCalloc(numrows,sizeof(double));
dj = mxCalloc(numcols,sizeof(double));

   /* Initialize the CPLEX environment */

   env = CPXopenCPLEX (&status);

   if ( env == NULL ) {
   char  errmsg[1024];
      fprintf (stderr, "Could not open CPLEX environment.\n");
      CPXgeterrorstring (env, status, errmsg);
      fprintf (stderr, "%s", errmsg);
      goto TERMINATE;
   }

   /* Turn off output to the screen */

   status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF);
   if ( status ) {
      fprintf (stderr,
               "Failure to turn on screen indicator, error %d.\n", status);
      goto TERMINATE;
   }

   /* Turn off pre-processor

   status = CPXsetintparam (env, CPX_PARAM_PREIND, CPX_OFF);
   if ( status ) {
      fprintf (stderr,
               "Failure to turn off pre-processor, error %d.\n", status);
      goto TERMINATE;
   }

   /* Turn off aggregator

   status = CPXsetintparam (env, CPX_PARAM_AGGIND, CPX_OFF);
   if ( status ) {
      fprintf (stderr,
               "Failure to turn of aggregator, error %d.\n", status);
      goto TERMINATE;
   }*/

   /* Create the problem. */

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

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

   /* Initialize data */
   for (kc = 0; kc <= numcols-1; kc++)
     {
       indices[kc] = kc;
     }

   /* Now copy the problem data into the lp */

   status = CPXcopylp (env, lp, numcols, numrows, objsen, obj, m,
                       sense, matbeg, matcnt, matind, matval,
                       lb, ub, NULL);

   if ( status ) {
      fprintf (stderr, "Failed to copy problem data.\n");
      goto TERMINATE;
   }

/**********MAIN LOOP************/

   for(i = 0; i <= numrows-1; i++)
   {
   for (kc = 0; kc <= numcols-1; kc++)
     {
       obj[kc] = M[i+kc*numrows];
     }

   CPXchgobj(env, lp, numcols, indices, obj);

 
   newval = m[i] + 10;
   CPXchgrhs(env, lp, 1, &i, &newval);
 
   /* Optimize the problem and obtain solution. */

   status = CPXlpopt (env, lp);   /*status = CPX[prim/dual]opt (env, lp);*/
   if ( status ) {
      fprintf (stderr, "Failed to optimize LP.\n");
      goto TERMINATE;
   }

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

   ikeep[i] = 0;
   if (objval > m[i] + tol)  /* keep row */
     {
       ikeep[i] = 1;
       newval = m[i];
       CPXchgrhs(env, lp, 1, &i, &newval);
     }


/*   Write the output to the screen.  */
/*
   printf ("\nSolution status = %d\n", solstat);
   printf ("Solution value  = %f\n\n", objval);
*/

   costs[i] = objval;
   stats[i] = solstat;

}

TERMINATE:

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

   if ( lp != NULL ) {
      status = CPXfreeprob (env, &lp);
      if ( status ) {
         fprintf (stderr, "CPXfreeprob failed, error code %d.\n", status);
      }
   }

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

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

      if ( status ) {
      char  errmsg[1024];
         fprintf (stderr, "Could not close CPLEX environment.\n");
         CPXgeterrorstring (env, status, errmsg);
         fprintf (stderr, "%s", errmsg);
      }
   }

}
示例#7
0
/* This routine initializes the cplex enviorement, sets screen as an output for cplex errors and notifications, 
   and sets parameters for cplex. It calls for a mixed integer program solution and frees the environment.
   To Do:
   Declare the parameters for the problem and fill them accordingly. After creating the program thus, copy it into cplex. 
   Define any integer or binary variables as needed, and change their type before the call to CPXmipopt to solve problem. 
   Use CPXwriteprob to output the problem in lp format, in the name of cluster_editing.lp.
   Read solution (both objective function value and variables assignment). 
   Communicate to pass the problem and the solution between the modules in the best way you see. 
 */
int cluster()
{
	/* Declare and allocate space for the variables and arrays where we
      will store the optimization results including the status, objective
      value and variable values. */

	CPXENVptr p_env              = NULL;
	CPXLPptr  p_lp               = NULL;
	int       status;

	/* Initialize the CPLEX environment */
	p_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 CPX_PARAM_SCRIND indicator is set to CPX_ON.  */

	if ( p_env == NULL ) {
		char  errmsg[1024];
		fprintf (stderr, "Error: Could not open CPLEX environment.\n");
		CPXgeterrorstring (p_env, status, errmsg);
		fprintf (stderr, "%s", errmsg);
		goto TERMINATE;
	}

	/* Turn on output to the screen */
	status = CPXsetintparam (p_env, CPX_PARAM_SCRIND, CPX_ON);
	if ( status ) {
		fprintf (stderr,
				"Error: Failure to turn on screen indicator, error %d.\n", status);
		goto TERMINATE;
	}

	/* Create the problem. */
	p_lp = CPXcreateprob (p_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. The setting of
      the parameter CPX_PARAM_SCRIND causes the error message to
      appear on stdout.  */

	if ( p_lp == NULL ) {
		fprintf (stderr, "Error: Failed to create problem.\n");
		goto TERMINATE;
	}

	/* Use CPXcopylp to transfer the ILP part of the problem data into the cplex pointer lp */
	CPXcopylp (p_env, p_lp, numcols, numrows, objsen, obj, rhs, sense, matbeg, matcnt, matind, matval, lb, ub, 0);
	CPXchgctype(p_env, p_lp, cnt, indices, ctype);

	/* Optimize the problem. */
	status = CPXmipopt (p_env, p_lp);
	if ( status ) {
		fprintf (stderr, "Error: Failed to optimize problem.\n");
		goto TERMINATE;
	}

	status = CPXsolution(p_env, p_lp, &solstat, &objval, x, NULL, NULL, NULL);
	if ( status ) {
			fprintf (stderr, "Error: Failed to get solution variables.\n");
			goto TERMINATE;
		}

	/* Write a copy of the problem to a file.
      Please put into probname the following string: Output Directory + "clustering_solution.lp" to create clustering_solution.lp in your output directory */
	status = CPXwriteprob (p_env, p_lp, probname, NULL);
	if ( status ) {
		fprintf (stderr, "Error: Failed to write LP to disk.\n");
		goto TERMINATE;
	}


	TERMINATE:

	/* Free up the problem as allocated by CPXcreateprob, if necessary */
	if ( p_lp != NULL ) {
		status = CPXfreeprob (p_env, &p_lp);
		if ( status ) {
			fprintf (stderr, "Error: CPXfreeprob failed, error code %d.\n", status);
		}
	}

	/* Free up the CPLEX environment, if necessary */
	if ( p_env != NULL ) {
		status = CPXcloseCPLEX (&p_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 CPX_PARAM_SCRIND indicator is set to CPX_ON. */

		if ( status ) {
			char  errmsg[1024];
			fprintf (stderr, "Could not close CPLEX environment.\n");
			CPXgeterrorstring (p_env, status, errmsg);
			fprintf (stderr, "%s", errmsg);
		}
	}
	return (status);
}  
示例#8
0
void mexFunction(
    int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[]
)
{
  int i, j;
  double *c=NULL, *b=NULL, *A=NULL, *H=NULL,
    *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ;
  int *nzA=NULL, *nzH=NULL ;
  int *iA=NULL, *kA=NULL ;
  int *iH=NULL, *kH=NULL ;
#ifndef MX_COMPAT_32
  long *iA_=NULL, *kA_=NULL ;
  long *iH_=NULL, *kH_=NULL ;
#endif 
  int neq=0, m=0, n=0, display=0;
  long *cpenv=NULL, *p_qp=NULL;
  char *Sense=NULL ;
  CPXENVptr     env = NULL;
  CPXLPptr      qp = NULL;
  int           status, qpstat;
  double        objval;
  double * p_qpstat ;
  char          opt_method[128]="auto" ;
  
  if (nrhs > 10 || nrhs < 1) {
    mexErrMsgTxt("Usage: [x,lambda,how,p_qp] "
		 "= qp_solve(cpenv,Q,c,A,b,l,u,neq,disp,method)");
    return;
  }
  switch (nrhs) {
  case 10:
	  if (mxGetM(prhs[9]) != 0 || mxGetN(prhs[9]) != 0) {
		  if (mxIsNumeric(prhs[9]) || mxIsComplex(prhs[9]) || !mxIsChar(prhs[9]) 
			  ||  mxIsSparse(prhs[9])
			  || !(mxGetM(prhs[9])==1 && mxGetN(prhs[9])>=1)) {
			  mexErrMsgTxt("10th argument (method) must be "
						   "a string.");
			  return;
		  }
		  mxGetString(prhs[9], opt_method, 128) ;
	  }
  case 9:
    if (mxGetM(prhs[8]) != 0 || mxGetN(prhs[8]) != 0) {
      if (!mxIsNumeric(prhs[8]) || mxIsComplex(prhs[8]) 
	  ||  mxIsSparse(prhs[8])
	  || !(mxGetM(prhs[8])==1 && mxGetN(prhs[8])==1)) {
	mexErrMsgTxt("9th argument (display) must be "
		     "an integer scalar.");
	return;
      }
      display = *mxGetPr(prhs[8]);
    }
  case 8:
    if (mxGetM(prhs[7]) != 0 || mxGetN(prhs[7]) != 0) {
      if (!mxIsNumeric(prhs[7]) || mxIsComplex(prhs[7]) 
	  ||  mxIsSparse(prhs[7])
	  || !(mxGetM(prhs[7])==1 && mxGetN(prhs[7])==1)) {
	mexErrMsgTxt("8th argument (neqcstr) must be "
		     "an integer scalar.");
	return;
      }
      neq = *mxGetPr(prhs[7]);
    }
  case 7:
    if (mxGetM(prhs[6]) != 0 || mxGetN(prhs[6]) != 0) {
      if (!mxIsNumeric(prhs[6]) || mxIsComplex(prhs[6]) 
	  ||  mxIsSparse(prhs[6])
	  || !mxIsDouble(prhs[6]) 
	  ||  mxGetN(prhs[6])!=1 ) {
	mexErrMsgTxt("7th argument (u) must be "
		     "a column vector.");
	return;
      }
      u = mxGetPr(prhs[6]);
      n = mxGetM(prhs[6]);
    }
  case 6:
    if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) {
      if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5]) 
	  ||  mxIsSparse(prhs[5])
	  || !mxIsDouble(prhs[5]) 
	  ||  mxGetN(prhs[5])!=1 ) {
	mexErrMsgTxt("6th argument (l) must be "
		     "a column vector.");
	return;
      }
      if (n != 0 && n != mxGetM(prhs[5])) {
	mexErrMsgTxt("Dimension error (arg 6 and later).");
	return;
      }
      l = mxGetPr(prhs[5]);
      n = mxGetM(prhs[5]);
    }
  case 5:
    if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) {
      if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) 
	  ||  mxIsSparse(prhs[4])
	  || !mxIsDouble(prhs[4]) 
	  ||  mxGetN(prhs[4])!=1 ) {
	mexErrMsgTxt("5th argument (b) must be "
		     "a column vector.");
	return;
      }
      if (m != 0 && m != mxGetM(prhs[4])) {
	mexErrMsgTxt("Dimension error (arg 5 and later).");
	return;
      }
      b = mxGetPr(prhs[4]);
      m = mxGetM(prhs[4]);
    }
  case 4:
    if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) {
      if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) 
	  || !mxIsSparse(prhs[3]) ) {
	mexErrMsgTxt("4th argument (A) must be "
		     "a sparse matrix.");
	return;
      }
      if (m != 0 && m != mxGetM(prhs[3])) {
	mexErrMsgTxt("Dimension error (arg 4 and later).");
	return;
      }
      if (n != 0 && n != mxGetN(prhs[3])) {
	mexErrMsgTxt("Dimension error (arg 4 and later).");
	return;
      }
      m = mxGetM(prhs[3]);
      n = mxGetN(prhs[3]);
      
      A = mxGetPr(prhs[3]);
#ifdef MX_COMPAT_32
      iA = mxGetIr(prhs[3]);
      kA = mxGetJc(prhs[3]);
#else
      iA_ = mxGetIr(prhs[3]);
      kA_ = mxGetJc(prhs[3]);

	  iA = (int*)malloc(mxGetNzmax(prhs[3])*sizeof(int)) ;
	  for (i=0; i<mxGetNzmax(prhs[3]); i++)
		  iA[i]=iA_[i] ;

	  kA = (int*)malloc((n+1)*sizeof(int)) ;
	  for (i=0; i<n+1; i++)
		  kA[i]=kA_[i] ;
#endif
	  
      nzA=myMalloc(n*sizeof(int)) ;
      for (i=0; i<n; i++)
		  nzA[i]=kA[i+1]-kA[i] ;
	  
      Sense=myMalloc((m+1)*sizeof(char)) ;
      for (i=0; i<m; i++)
		  if (i<neq) Sense[i]='E' ;
		  else Sense[i]='L' ;
      Sense[m]=0 ;
    }
  case 3:
    if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) {
      if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2]) 
	  ||  mxIsSparse(prhs[2])
	  || !mxIsDouble(prhs[2]) 
	  ||  mxGetN(prhs[2])!=1 ) {
	mexErrMsgTxt("3rd argument (c) must be "
		     "a column vector.");
	return;
      }
      if (n != 0 && n != mxGetM(prhs[2])) {
	mexErrMsgTxt("Dimension error (arg 3 and later).");
	return;
      }
      c = mxGetPr(prhs[2]);
      n = mxGetM(prhs[2]);
    }
  case 2:
    if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) {
      if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) 
	  || !mxIsSparse(prhs[1]) ) {
	mexErrMsgTxt("2nd argument (H) must be "
		     "a sparse matrix.");
	return;
      }
      if (n != 0 && n != mxGetM(prhs[1])) {
	mexErrMsgTxt("Dimension error (arg 2 and later).");
	return;
      }
      if (n != 0 && n != mxGetN(prhs[1])) {
		  mexErrMsgTxt("Dimension error (arg 2 and later).");
		  return;
      }
      n = mxGetN(prhs[1]);
      
      H = mxGetPr(prhs[1]);

#ifdef MX_COMPAT_32
      iH = mxGetIr(prhs[1]);
      kH = mxGetJc(prhs[1]);
#else
      iH_ = mxGetIr(prhs[1]);
      kH_ = mxGetJc(prhs[1]);

	  iH = (int*)malloc(mxGetNzmax(prhs[1])*sizeof(int)) ;
	  for (i=0; i<mxGetNzmax(prhs[1]); i++)
		  iH[i]=iH_[i] ;

	  kH = (int*)malloc((n+1)*sizeof(int)) ;
	  for (i=0; i<n+1; i++)
		  kH[i]=kH_[i] ;
#endif
	  
      nzH=myMalloc(n*sizeof(int)) ;
      for (i=0; i<n; i++)
		  nzH[i]=kH[i+1]-kH[i] ;
    }
  case 1:
	  if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) {
		  if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) 
			  ||  mxIsSparse(prhs[0])
	  || !mxIsDouble(prhs[0]) 
			  ||  mxGetN(prhs[0])!=1 ) {
			  mexErrMsgTxt("1st argument (cpenv) must be "
						   "a column vector.");
			  return;
      }
		  if (1 != mxGetM(prhs[0])) {
			  mexErrMsgTxt("Dimension error (arg 1).");
			  return;
		  }
		  cpenv = (long*) mxGetPr(prhs[0]);
	  }
  }
  /*if (display>3) */
	  fprintf(STD_OUT,"argument processing finished") ;
  
  /* Initialize the CPLEX environment */
  env = (CPXENVptr) cpenv[0] ;
  
  /* Turn on output to the screen */
  if (display>0)
	  status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_ON);
  else
	  status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF);
  if ( status ) {
	  fprintf (STD_OUT, 
			   "Failure to turn on screen indicator, error %d.\n", status);
	  goto TERMINATE;
  }
  status = CPXsetintparam (env, CPX_PARAM_SIMDISPLAY, display);
  if ( status ) {
	  fprintf (STD_OUT,"Failed to turn up simplex display level.\n");
	  goto TERMINATE;
  }
  
  if (nlhs > 4 || nlhs < 1) {
	  mexErrMsgTxt("Usage: [x,lambda,how,p_qp] "
				   "= qp_solve(cpenv,H,c,A,b,l,u,neqcstr)");
	  return;
  }
  if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i) \n", m, n, neq) ;
  
  switch (nlhs) {
  case 4:
	  plhs[3] = mxCreateDoubleMatrix(1, 1, mxREAL);
	  p_qp = (long*) mxGetPr(plhs[3]);
  case 3:
	  /*    plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
			p_qpstat = mxGetPr(plhs[2]);*/
  case 2:
	  plhs[1] = mxCreateDoubleMatrix(m, 1, mxREAL);
	  lambda = mxGetPr(plhs[1]);
  case 1:
	  plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL);
	  x = mxGetPr(plhs[0]);
	  break;
  }
  if (display>2) fprintf(STD_OUT, "argument processing finished\n") ;
  
  if (strcmp(opt_method, "primal") &&  
	  strcmp(opt_method, "dual") &&
      strcmp(opt_method, "net") && 
	  strcmp(opt_method, "bar") &&
	  strcmp(opt_method, "sift") &&
	  strcmp(opt_method, "con") &&
	  strcmp(opt_method, "auto"))
	  mexErrMsgTxt("method \\in " 
				  "{'auto','primal','dual','bar','net','sift','con'}\n") ;

  if (strcmp(opt_method, "primal")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 1);
  else if (strcmp(opt_method, "dual")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 2);
  else if (strcmp(opt_method, "net")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 3);
  else if (strcmp(opt_method, "bar")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 4);
  else if (strcmp(opt_method, "sift")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 5);
  else if (strcmp(opt_method, "con")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 6);
  else if (strcmp(opt_method, "auto")==0)
	  status = CPXsetintparam (env, CPX_PARAM_QPMETHOD, 0);
  else 
	  status = 1 ;
  
  if ( status ) {
    fprintf (STD_OUT,"Failed to set QP method.\n");
    goto TERMINATE;
  }

  /* Create the problem */    
  if (display>2) fprintf(STD_OUT, "calling CPXcreateprob \n") ;
  qp = CPXcreateprob (env, &status, "xxx");
  if ( qp == NULL ) {
    fprintf (STD_OUT,"Failed to create subproblem\n");
    status = 1;
    goto TERMINATE;
  } 
  if (p_qp) *p_qp=(long) qp ;
  
  /* Copy network part of problem.  */    
  /*if (display>2) */
    fprintf(STD_OUT, "calling CPXcopylp (m=%i, n=%i) \n", m, n) ;
  status = CPXcopylp(env, qp, n, m, CPX_MIN, c, b, 
		     Sense, kA, nzA, iA, A, 
		     l, u, NULL);
  if ( status ) {
    fprintf (STD_OUT, "CPXcopylp failed.\n");
    goto TERMINATE;
  }
  
  /*if (display>2) */
    fprintf(STD_OUT, "calling CPXcopyquad \n") ;
  status = CPXcopyquad (env, qp, kH, nzH, iH, H);    
  
  if ( status ) {
    fprintf (STD_OUT, "CPXcopyquad failed.\n");
    goto TERMINATE;
  }
  
  /*if (display>2) */
    fprintf(STD_OUT, "calling optimizer 'bar'\n") ;
  status = CPXqpopt (env, qp);
  if (display>3)
    fprintf(STD_OUT, "CPXbaropt=%i\n", status) ;
  if ( status ) {
    fprintf (STD_OUT,"CPXbaropt failed.\n");
    goto TERMINATE;
  }
  
  if (display>2)
    fprintf(STD_OUT, "calling CPXsolution\n") ;
  status = CPXsolution (env, qp, &qpstat, &objval, x, lambda, NULL, NULL);
  if ( status ) {
    fprintf (STD_OUT,"CPXsolution failed.\n");
    goto TERMINATE;
  }
  
  if (display>1)
    fprintf (STD_OUT, "Solution status: %i,%s\n", qpstat, err_str[qpstat]);
  if (display>2)
    fprintf (STD_OUT, "Objective value %g\n", objval);
  
  if (nlhs >= 3) 
    if (qpstat==1)
      plhs[2] = mxCreateString(err_str[0]) ;
    else
      plhs[2] = mxCreateString(err_str[qpstat]) ;

  /*  if (nlhs >= 3) 
    if (qpstat==1)
      *p_qpstat = 0 ;
    else
    *p_qpstat = qpstat ;*/
  
 TERMINATE:
  if (status) {
    char  errmsg[1024];
    CPXgeterrorstring (env, status, errmsg);
    fprintf (STD_OUT, "%s", errmsg);
    if (nlhs >= 3) 
      plhs[2] = mxCreateString(errmsg) ;
    } ;
  if (nzA) myFree(nzA) ;
  if (nzH) myFree(nzH) ;
  if (Sense) myFree(Sense) ;

#ifndef MX_COMPAT_32
  if (iA) myFree(iA) ;
  if (kA) myFree(kA) ;
  if (iH) myFree(iH) ;
  if (kH) myFree(kH) ;
#endif
  
  if (!p_qp)
      {
	if ( qp != NULL ) {
	  if (display>2)
	    fprintf(STD_OUT, "calling CPXfreeprob\n") ;
	  status = CPXfreeprob (env, &qp);
	  if ( status ) {
	    fprintf (STD_OUT, "CPXfreeprob failed, error code %d.\n", status);
	  }
	}
      }
  return ;
}     
示例#9
0
EXPORT int fit(const double * X_p, const double * Yl_p, double* w, int postags, int numSamples, int numFeatures, double C, double epsilon,
        int numBoxConstraints, const double * boxValues, const int64_t * boxIndices, const double * boxMatrix)
{
  int i,j,k;
  CPXENVptr     env = NULL;
  CPXLPptr      lp = NULL;
  int status;
  char probname[] = "Testproblem";

  int numrows = postags + numSamples;
  int numcols = numFeatures + 1 + numrows;
  int nnzcol = numFeatures + 2;
  int numEntries = nnzcol * numrows;

  char *sense = (char*) malloc((numrows) * sizeof(char));
  double *lb = (double*) malloc(numcols * sizeof(double));
  double *ub = (double*) malloc(numcols * sizeof(double));
  double *obj = (double*) malloc(numcols * sizeof(double));
  double *rhs = (double*) malloc(numrows * sizeof(double));
  double *tagarray = (double*) malloc(numrows * sizeof(double));

  int      *matbeg = (int*) malloc(numcols * sizeof(int));
  int      *matcnt = (int*) malloc(numcols * sizeof(int));
  int      *matind = (int*) malloc(numEntries * sizeof(int));
  double   *matval = (double* ) malloc(numEntries * sizeof(double));
  double   *qsepvec = (double*) malloc((numcols + 2 * numBoxConstraints) * sizeof(double));

  int       numBoxSamples = 0;
  double   *dens = NULL;
  double   *boxConstraints = NULL;
  int      *boxrmatbeg = NULL;
  int      *boxrmatind = NULL;
  char     *boxSense = NULL;
  int      *hmatbeg = NULL;
  int      *hmatind = NULL;
  double   *hmatval = NULL;
  char     *hSense = NULL;
  env = CPXopenCPLEX (&status);
  lp = CPXcreateprob (env, &status, probname);
  status = CPXsetintparam (env, CPX_PARAM_SCRIND, CPX_OFF);
  status = CPXsetintparam (env, CPX_PARAM_BARCOLNZ, 2);
  if ( status ) {
    fprintf (stderr,
             "Failure to create CPLEX environment, error %d.\n", status);
    goto TERMINATE;
  }

  if (sense == NULL || lb == NULL || ub == NULL || obj == NULL
      || rhs == NULL || tagarray == NULL || qsepvec == NULL) {
    status = 1;
    goto TERMINATE;
  }


  for (i = 0; i < postags; ++i) {
    tagarray[i] = 1;
    sense[i] = 'G';
  }
  for (i = postags; i < numrows; ++i) {
    tagarray[i] = -1;
    sense[i] = 'L';
  }
  for (i = 0; i < postags; ++i) {
    rhs[i] = Yl_p[i] - tagarray[i] * epsilon ;
  }
  for (i = postags; i < numrows; ++i) {
    rhs[i] = Yl_p[i - postags] - tagarray[i] * epsilon ;
  }
  for (i = 0; i < numFeatures + 1; ++i) {
    lb[i] = -CPX_INFBOUND;
    ub[i] = CPX_INFBOUND;
    matbeg[i] = i * (numrows);
    matcnt[i] = numrows;
  }
  for (i = numFeatures + 1; i < numcols; ++i) {
    lb[i] = 0;
    ub[i] = CPX_INFBOUND;
    matbeg[i] = (numFeatures + 1) * numrows + (i - numFeatures - 1);
    matcnt[i] = 1;
  }

  for (j = 0; j < numFeatures; ++j) {
    for (i = 0; i < postags; ++i) {
      matind[j * numrows + i] = i;
      matval[j * (numrows) + i] = X_p[i * numFeatures + j];
    }
    for (i = postags; i < numrows; ++i) {
      matind[j * numrows + i] = i;
      matval[j * (numrows) + i] = X_p[(i - postags) * numFeatures + j];
    }
  }

  /* printf("Status ok\n");*/
  for (i = 0; i < numrows; ++i) {
    matind[numFeatures * numrows + i] = i;
    matval[numFeatures * numrows + i] = 1;
  }

  for (i = 0; i < numrows; ++i) {
    matind[(numFeatures + 1) * numrows + i] = i;
    matval[(numFeatures + 1) * numrows + i] = tagarray[i];
  }

  for (i = 0; i < numFeatures; ++i){
    qsepvec[i] = 1;
    obj[i] = 0;
  }
  obj[numFeatures] = 0;
  qsepvec[numFeatures] = 0;
  for (i = numFeatures + 1; i < numcols; ++i){
    qsepvec[i] = 2 * C;
    obj[i] = 0;
  }

  /*printf("Status ok\n");*/
  status = CPXcopylp (env, lp, numcols, numrows, 1, obj, rhs,
                      sense, matbeg, matcnt, matind, matval,
                      lb, ub, NULL);

  status = CPXcopyqpsep (env, lp, qsepvec);
  status = CPXwriteprob (env, lp, "qpex1.lp", NULL);
  status = CPXqpopt (env, lp);
  status = CPXgetx (env, lp, w, 0, numFeatures);

  if (numBoxConstraints > 0) {
    numBoxSamples = (int) boxIndices[numBoxConstraints];

    dens = (double*) malloc(numBoxSamples * sizeof(double));
    boxConstraints = (double*) calloc(numBoxConstraints * (numFeatures + 2), sizeof(double));
    boxrmatbeg = (int*) malloc(numBoxConstraints * sizeof(int));
    boxrmatind = (int*) malloc(numBoxConstraints * (numFeatures + 2) * sizeof(int));
    boxSense = (char*) malloc(numBoxConstraints * sizeof(char));

    hmatbeg = (int*) malloc(numBoxSamples * sizeof(int));
    hmatind = (int*) malloc(numBoxSamples * (numFeatures + 1) * sizeof(int));
    hmatval = (double* ) malloc(numBoxSamples * (numFeatures + 1) * sizeof(double));
    hSense = (char* ) malloc(numBoxSamples * sizeof(char));

    if (dens == NULL || boxConstraints == NULL || boxrmatbeg == NULL || boxrmatind == NULL
        || boxSense == NULL) {
      status = 1;
      goto TERMINATE;
    }
    if (hmatbeg == NULL || hmatind == NULL || hmatval == NULL || hSense == NULL) {
      status = 1;
      goto TERMINATE;
    }

    /*for every entry in the box features, check if it's background or
    foreground
    double   *boxrmatval = (double* ) malloc( * sizeof(double));*/
    
    for (i = 0; i < numBoxSamples; ++i) {
      dens[i] = w[numFeatures];
      for (j = 0; j < numFeatures; ++j) {
        dens[i] += boxMatrix[i * numFeatures + j] * w[j];
      }
    }
    for (i = 0; i < numBoxSamples; ++i) {
      if (dens[i] > 0){
        dens[i] = 1;
      }
      else {
        dens[i] = 0;
      }
      /* printf("Density: %f\n", dens[i]); */
    }

    /*printfarray(boxConstraints, numBoxConstraints, numFeatures + 2, "boxConstraints"); */

    for (k = 0; k < numBoxConstraints; ++k) {
      boxrmatbeg[k] = k * (numFeatures + 2);
      for (i = (int) boxIndices[k]; i < boxIndices[k + 1]; ++i){
        for (j = 0; j < numFeatures; ++j){
          boxConstraints[k * (numFeatures + 2) + j]  += dens[i] * boxMatrix[i * numFeatures + j];
        }
        boxConstraints[k * (numFeatures + 2) + numFeatures] += dens[i];
      }
    }
    for (i = 0; i < numBoxConstraints; ++i) {
      for (j = 0; j < numFeatures + 1; ++j) {
        boxrmatind[i * (numFeatures + 2) + j] = j;
      }
      boxrmatind[i * (numFeatures + 2) + numFeatures + 1] = numcols + i;
    }

    for (i = 0; i < numBoxConstraints; ++i) {
      boxSense[i] = 'L';
    }
    for (i = 0; i < numBoxConstraints; ++i) {
      boxConstraints[i * (numFeatures + 2) + numFeatures+1] = - 1;
    }
    status = CPXaddrows(env, lp, numBoxConstraints, numBoxConstraints, numBoxConstraints * (numFeatures + 2), boxValues,
                        boxSense, boxrmatbeg, boxrmatind, boxConstraints, NULL, NULL);
    for (i = 0; i < numBoxConstraints; ++i) {
      boxrmatind[i * (numFeatures + 2) + numFeatures + 1] = numcols + numBoxConstraints + i;
    }

    for (i = 0; i < numBoxConstraints; ++i) {
      boxSense[i] = 'G';
    }
    for (i = 0; i < numBoxConstraints; ++i) {
      boxConstraints[i * (numFeatures + 2) + numFeatures+1] = + 1;
    }
    status = CPXaddrows(env, lp, numBoxConstraints, numBoxConstraints, numBoxConstraints * (numFeatures + 2), boxValues,
                        boxSense, boxrmatbeg, boxrmatind, boxConstraints, NULL, NULL);

    for (i = 0; i < numBoxConstraints; ++i) {
      qsepvec[numcols + i] = 2 * C / (boxIndices[i + 1] - boxIndices[i]);
      qsepvec[numcols + i + numBoxConstraints] = 2 * C / (boxIndices[i + 1] - boxIndices[i]);
    /*  printf("%d, %d\n",boxIndices[i], boxIndices[i + 1]);
      printf("%f, %f\n", qsepvec[numcols+i], qsepvec[numcols + i + numBoxConstraints]);
      */
    }

    /*adding hard constraints:*/



    for (i = 0; i < numBoxSamples; ++i) {
      hmatbeg[i] = i * (numFeatures + 1);
      for (j = 0; j < numFeatures; ++j) {
        hmatind[i * (numFeatures + 1) + j] = j;
        hmatval[i * (numFeatures + 1) + j] = boxMatrix[i * numFeatures + j];
      }
      hmatind[i * (numFeatures + 1) + numFeatures] = numFeatures;
      hmatval[i * (numFeatures + 1) + numFeatures] = 1;

      if (dens[i] == 0){
        hSense[i]  = 'L';
      }
      else {
        hSense[i] = 'G';
      }
    }
    /* printf("Density: %f\n", dens[i]);
        printf("Close, but no cigar\n");
    printiarray(hmatind, backgroundcount, numFeatures + 1, "");
        printf("Close, but no cigar\n"); */

    status = CPXaddrows(env, lp, 0, numBoxSamples, numBoxSamples* (numFeatures + 1), NULL,
                        hSense, hmatbeg, hmatind, hmatval, NULL, NULL);
    /*    printf("WHY IS NOTHING HAPPENING\n") */
    printf ("Number of Columns in Problem: %d\n", CPXgetnumcols(env, lp));
    printf("%d\n", numcols + (2 * numBoxConstraints));
    status = CPXcopyqpsep (env, lp, qsepvec);
    status = CPXwriteprob (env, lp, "qpex1.lp", NULL);
    status = CPXqpopt (env, lp);
    status = CPXgetx (env, lp, w, 0, numFeatures);

    /*for (i = 0; i < numBoxSamples; ++i) {
      density[i] = w[numFeatures];
      for (j = 0; j < numFeatures; ++j) {
      density[i] += boxMatrix[i * numFeatures + j] * w[j];
      }
      } */
  }

  /*printf("Objective value: %f\n", sol);
    double * slack = malloc((numcols + 2 * numBoxConstraints) * sizeof(double));
    status = CPXgetx (env, lp, slack, 0, numcols + 2 * numBoxConstraints - 1);
    printfarray(slack, numcols + 2 * numBoxConstraints, 1, "Slack");
    */
TERMINATE:;

  free_and_null ((char **) &obj);
  free_and_null ((char **) &rhs);
  free_and_null ((char **) &sense);
  free_and_null ((char **) &tagarray);
  free_and_null ((char **) &lb);
  free_and_null ((char **) &ub);
  free_and_null ((char **) &matbeg);
  free_and_null ((char **) &matcnt);
  free_and_null ((char **) &matind);
  free_and_null ((char **) &matval);
  free_and_null ((char **) &qsepvec);

  free_and_null ((char **) &dens);
  free_and_null ((char **) &boxConstraints);
  free_and_null ((char **) &boxrmatbeg);
  free_and_null ((char **) &boxrmatind);

  free_and_null ((char **) &hmatbeg);
  free_and_null ((char **) &hmatind);
  free_and_null ((char **) &hmatval);
  free_and_null ((char **) &hSense);
  /*free_and_null ((char **) &slack); */
  return (status);

}