示例#1
0
int main(int argc,char *argv[])
{
  MSKrescodee  r;
  MSKidxt i,j;
  double       c[]    = {3.0, 1.0, 5.0, 1.0};

  /* Below is the sparse representation of the A
     matrix stored by column. */
  MSKlidxt     aptrb[] = {0, 2, 5, 7};
  MSKlidxt     aptre[] = {2, 5, 7, 9};
  MSKidxt      asub[] = { 0, 1,
                          0, 1, 2,
                          0, 1,
                          1, 2};
  double       aval[] = { 3.0, 2.0,
                          1.0, 1.0, 2.0,
                          2.0, 3.0,
                          1.0, 3.0};

  /* Bounds on constraints. */
  MSKboundkeye bkc[]  = {MSK_BK_FX, MSK_BK_LO,     MSK_BK_UP    };
  double       blc[]  = {30.0,      15.0,          -MSK_INFINITY};
  double       buc[]  = {30.0,      +MSK_INFINITY, 25.0         };
  /* Bounds on variables. */
  MSKboundkeye bkx[]  = {MSK_BK_LO,     MSK_BK_RA, MSK_BK_LO,     MSK_BK_LO     };
  double       blx[]  = {0.0,           0.0,       0.0,           0.0           };
  double       bux[]  = {+MSK_INFINITY, 10.0,      +MSK_INFINITY, +MSK_INFINITY };
  double xx[NUMVAR];               
  MSKenv_t     env  = NULL;
  MSKtask_t    task = NULL; 
  
  /* Create the mosek environment. */
  r = MSK_makeenv(&env,NULL,NULL,NULL,NULL);
  
  /* Directs the env log stream to the 'printstr' function. */
  if ( r==MSK_RES_OK )
    MSK_linkfunctoenvstream(env,MSK_STREAM_LOG,NULL,printstr);
  
  /* Initialize the environment. */
  if ( r==MSK_RES_OK )
    r = MSK_initenv(env);
  
  if ( r==MSK_RES_OK )
  {
    /* Create the optimization task. */
    r = MSK_maketask(env,NUMCON,NUMVAR,&task);

    /* Directs the log task stream to the 'printstr' function. */
    if ( r==MSK_RES_OK )
      MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr);

    /* Give MOSEK an estimate of the size of the input data. 
     This is done to increase the speed of inputting data. 
     However, it is optional. */
    if (r == MSK_RES_OK)
      r = MSK_putmaxnumvar(task,NUMVAR);
  
    if (r == MSK_RES_OK)
      r = MSK_putmaxnumcon(task,NUMCON);
    
    if (r == MSK_RES_OK)
      r = MSK_putmaxnumanz(task,NUMANZ);

    /* Append 'NUMCON' empty constraints.
     The constraints will initially have no bounds. */
    if ( r == MSK_RES_OK )
      r = MSK_append(task,MSK_ACC_CON,NUMCON);

    /* Append 'NUMVAR' variables.
     The variables will initially be fixed at zero (x=0). */
    if ( r == MSK_RES_OK )
      r = MSK_append(task,MSK_ACC_VAR,NUMVAR);

    /* Optionally add a constant term to the objective. */
    if ( r ==MSK_RES_OK )
      r = MSK_putcfix(task,0.0);
    for(j=0; j<NUMVAR && r == MSK_RES_OK; ++j)
    {
      /* Set the linear term c_j in the objective.*/  
      if(r == MSK_RES_OK)
        r = MSK_putcj(task,j,c[j]);

      /* Set the bounds on variable j.
       blx[j] <= x_j <= bux[j] */
      if(r == MSK_RES_OK)
        r = MSK_putbound(task,
                         MSK_ACC_VAR, /* Put bounds on variables.*/
                         j,           /* Index of variable.*/
                         bkx[j],      /* Bound key.*/
                         blx[j],      /* Numerical value of lower bound.*/
                         bux[j]);     /* Numerical value of upper bound.*/

      /* Input column j of A */   
      if(r == MSK_RES_OK)
        r = MSK_putavec(task,
                        MSK_ACC_VAR,       /* Input columns of A.*/
                        j,                 /* Variable (column) index.*/
                        aptre[j]-aptrb[j], /* Number of non-zeros in column j.*/
                        asub+aptrb[j],     /* Pointer to row indexes of column j.*/
                        aval+aptrb[j]);    /* Pointer to Values of column j.*/
      
    }

    /* Set the bounds on constraints.
       for i=1, ...,NUMCON : blc[i] <= constraint i <= buc[i] */
    for(i=0; i<NUMCON && r==MSK_RES_OK; ++i)
      r = MSK_putbound(task,
                       MSK_ACC_CON, /* Put bounds on constraints.*/
                       i,           /* Index of constraint.*/
                       bkc[i],      /* Bound key.*/
                       blc[i],      /* Numerical value of lower bound.*/
                       buc[i]);     /* Numerical value of upper bound.*/

    /* Maximize objective function. */
    if (r == MSK_RES_OK)
      r = MSK_putobjsense(task,
                          MSK_OBJECTIVE_SENSE_MAXIMIZE);

    if ( r==MSK_RES_OK )
    {
      MSKrescodee trmcode;
    
      /* Run optimizer */
      r = MSK_optimizetrm(task,&trmcode);

      /* Print a summary containing information
       about the solution for debugging purposes. */
      MSK_solutionsummary (task,MSK_STREAM_LOG);
     
      if ( r==MSK_RES_OK )
      {
        MSKsolstae solsta;
        int j;
        MSK_getsolutionstatus (task,
                               MSK_SOL_BAS,
                               NULL,
                               &solsta);
        switch(solsta)
        {
          case MSK_SOL_STA_OPTIMAL:   
          case MSK_SOL_STA_NEAR_OPTIMAL:
            MSK_getsolutionslice(task,
                                 MSK_SOL_BAS,    /* Request the basic solution. */
                                 MSK_SOL_ITEM_XX,/* Which part of solution.     */
                                 0,              /* Index of first variable.    */
                                 NUMVAR,         /* Index of last variable+1.   */
                                 xx);
      
            printf("Optimal primal solution\n");
            for(j=0; j<NUMVAR; ++j)
              printf("x[%d]: %e\n",j,xx[j]);
          
            break;
          case MSK_SOL_STA_DUAL_INFEAS_CER:
          case MSK_SOL_STA_PRIM_INFEAS_CER:
          case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
          case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:  
            printf("Primal or dual infeasibility certificate found.\n");
            break;
            
          case MSK_SOL_STA_UNKNOWN:
            printf("The status of the solution could not be determined.\n");
            break;
          default:
            printf("Other solution status.");
            break;
        }
      }
      else
      {
        printf("Error while optimizing.\n");
      }
    }
    
    if (r != MSK_RES_OK)
    {
      /* In case of an error print error code and description. */      
      char symname[MSK_MAX_STR_LEN];
      char desc[MSK_MAX_STR_LEN];
      
      printf("An error occurred while optimizing.\n");     
      MSK_getcodedesc (r,
                       symname,
                       desc);
      printf("Error %s - '%s'\n",symname,desc);
    }
    
    MSK_deletetask(&task);
    
    MSK_deleteenv(&env);
  }
    
  return r;
}
示例#2
0
bool ConicSolver::Solve(VectorXd& sol)
{
    bool ret = false;
#ifdef _WIN32
    VectorXd solution;
	convertMatrixVectorFormat();
	MSKenv_t env;
	MSKtask_t task;
	MSKrescodee r;

	r = MSK_makeenv(&env, NULL, NULL, NULL, NULL);
	if (r == MSK_RES_OK)
	{
		r = MSK_linkfunctoenvstream(env, MSK_STREAM_LOG, NULL, printstr);
	}

	r = MSK_initenv(env);
	if (r == MSK_RES_OK)
	{
		r = MSK_maketask(env, mNumCon, mNumVar, &task);
		if (r == MSK_RES_OK)
		{
			r = MSK_linkfunctotaskstream(task, MSK_STREAM_LOG, NULL, printstr);
		}

		if (r == MSK_RES_OK)
			r = MSK_putmaxnumvar(task, mNumVar);
		if (r == MSK_RES_OK)
			r = MSK_putmaxnumcon(task, mNumCon);

		/* Append ¡¯NUMCON ¡¯ empty constraints .
		 The constraints will initially have no bounds . */
		if (r == MSK_RES_OK)
			r = MSK_append(task, MSK_ACC_CON, mNumCon);
		/* Append ¡¯NUMVAR ¡¯ variables .
		 The variables will initially be fixed at zero (x =0). */
		if (r == MSK_RES_OK)
			r = MSK_append(task, MSK_ACC_VAR, mNumVar);

		/* Optionally add a constant term to the objective . */
		if (r == MSK_RES_OK)
			r = MSK_putcfix(task, mConstant);

		for (int j = 0; j < mNumVar && r == MSK_RES_OK; ++j)
		{
			/* Set the linear term c_j in the objective .*/
			if (r == MSK_RES_OK)
				r = MSK_putcj(task, j, mc[j]);
			/* Set the bounds on variable j.*/
			if (r == MSK_RES_OK)
			{
				if (mbLowerBounded[j] && mbUpperBounded[j])
				{
					if (mlb[j] == mub[j])
						r = MSK_putbound(task, MSK_ACC_VAR, j, MSK_BK_FX, mlb[j], mub[j]);
					else
					{
						CHECK(mlb[j] < mub[j]);
						r = MSK_putbound(task, MSK_ACC_VAR, j, MSK_BK_RA, mlb[j], mub[j]);
					}
				}
				else if (mbLowerBounded[j])
				{
					r = MSK_putbound(task, MSK_ACC_VAR, j , MSK_BK_LO, mlb[j], +MSK_INFINITY);
				}
				else if (mbUpperBounded[j])
				{
					r = MSK_putbound(task, MSK_ACC_VAR, j, MSK_BK_UP, -MSK_INFINITY, mub[j]);
				}	
				else
				{
					r = MSK_putbound(task, MSK_ACC_VAR, j, MSK_BK_FR, -MSK_INFINITY, +MSK_INFINITY);
				}
			}
			/* Input column j of A */
			if (r == MSK_RES_OK && mNumCon)
			{
				int currentColumnIdx = mAColumnStartIdx[j];
				int nextColumnIdx = mAColumnStartIdx[j + 1];
                if (nextColumnIdx - currentColumnIdx > 0)
				    r = MSK_putavec(task, MSK_ACC_VAR, j, nextColumnIdx - currentColumnIdx, &(mARowIdx[currentColumnIdx]), &(mAValues[currentColumnIdx]));
			}
		}
		/* Set the bounds on constraints .
		 for i=1, ... , NUMCON : blc [i] <= constraint i <= buc [i] */
		for (int i = 0; i < mNumCon && r == MSK_RES_OK; ++i)
		{
			if (mbConstraintLowerBounded[i] && mbConstraintUpperBounded[i])
			{
				if (mlbc[i] == mubc[i])
				{
					r = MSK_putbound(task, MSK_ACC_CON, i, MSK_BK_FX, mlbc[i], mubc[i]);
				}
				else 
				{
					r = MSK_putbound(task, MSK_ACC_CON, i, MSK_BK_RA, mlbc[i], mubc[i]);
				}
			}
			else if (mbConstraintLowerBounded[i])
			{
				r = MSK_putbound(task, MSK_ACC_CON, i, MSK_BK_LO, mlbc[i], +MSK_INFINITY);
			}
			else if (mbConstraintUpperBounded[i])
			{
				r = MSK_putbound(task, MSK_ACC_CON, i, MSK_BK_UP, -MSK_INFINITY, mubc[i]);
			}
			else
			{
				LOG(WARNING) << "Every constraint should not be free.";
			}
		}
        for (int i = 0; i < mNumCone; ++i)
        {
            Cone& cone = mCones[i];
            r = MSK_appendcone(task, MSK_CT_RQUAD, 0.0, cone.mSubscripts.size(), cone.GetMosekConeSubId());
            //r = MSK_appendcone(task, MSK_CT_QUAD, 0.0, cone.mSubscripts.size(), cone.GetMosekConeSubId());
        }
		if (r == MSK_RES_OK)
		{
			MSKrescodee trmcode;

			r = MSK_optimizetrm(task, &trmcode);
			MSK_solutionsummary(task, MSK_STREAM_LOG);

			if (r == MSK_RES_OK)
			{
				MSKsolstae solsta;
				MSK_getsolutionstatus(task, MSK_SOL_ITR, NULL, &solsta);
				double* result = new double[mNumVar];
				switch (solsta)
				{
				case MSK_SOL_STA_OPTIMAL:
				case MSK_SOL_STA_NEAR_OPTIMAL:
					MSK_getsolutionslice(task, MSK_SOL_ITR, MSK_SOL_ITEM_XX, 0, mNumVar, result);
					LOG(INFO) << "Optimal primal solution";
                    ret = true;
					solution = VectorXd::Zero(mNumVar);
                    sol = VectorXd::Zero(mNumVar);
					for (int k = 0; k < mNumVar; ++k)
                    {
						solution[k] = result[k];
                        sol[k] = result[k];
                    }
					break;
				case MSK_SOL_STA_DUAL_INFEAS_CER:
				case MSK_SOL_STA_PRIM_INFEAS_CER:
				case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
				case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:
					LOG(WARNING) << "Primal or dual infeasibility certificate found.";
					break;
				case MSK_SOL_STA_UNKNOWN:
					LOG(WARNING) << "The status of the solution could not be determined.";
					break;
				default:
					LOG(WARNING) << "Other solution status.";
					break;

				}
				delete[] result;

			}
		}
		else
		{
			LOG(WARNING) << "Error while optimizing.";
		}
		if (r != MSK_RES_OK)
		{
			char symname[MSK_MAX_STR_LEN];
			char desc[MSK_MAX_STR_LEN];
			LOG(WARNING) << "An error occurred while optimizing.";
			MSK_getcodedesc(r, symname, desc);
			LOG(WARNING) << "Error " << symname << " - " << desc;
		
		}
       
	}
	MSK_deletetask(&task);
	MSK_deleteenv(&env);
#endif    
	return ret;
}
示例#3
0
文件: cqo1.c 项目: edljk/Mosek.jl
int main(int argc,char *argv[])
{
  MSKrescodee  r;
  
  const MSKint32t numvar = 6,
                  numcon = 1;
      
  MSKboundkeye bkc[] = { MSK_BK_FX };
  double       blc[] = { 1.0 };
  double       buc[] = { 1.0 };
  
  MSKboundkeye bkx[] = {MSK_BK_LO,
                        MSK_BK_LO,
                        MSK_BK_LO,
                        MSK_BK_FR,
                        MSK_BK_FR,
                        MSK_BK_FR};
  double       blx[] = {0.0,
                        0.0,
                        0.0,
                        -MSK_INFINITY,
                        -MSK_INFINITY,
                        -MSK_INFINITY};
  double       bux[] = {+MSK_INFINITY,
                        +MSK_INFINITY,
                        +MSK_INFINITY,
                        +MSK_INFINITY,
                        +MSK_INFINITY,
                        +MSK_INFINITY};
  
  double       c[]   = {0.0,
                        0.0,
                        0.0,
                        1.0,
                        1.0,
                        1.0};

  MSKint32t   aptrb[] = {0, 1, 2, 3, 3, 3},
              aptre[] = {1, 2, 3, 3, 3, 3},
              asub[]  = {0, 0, 0, 0};
  double      aval[]  = {1.0, 1.0, 2.0};
  
   
  MSKint32t   i,j,csub[3];

  MSKenv_t    env  = NULL;
  MSKtask_t   task = NULL;

  /* Create the mosek environment. */
  r = MSK_makeenv(&env,NULL);

  if ( r==MSK_RES_OK )
  {
    /* Create the optimization task. */
    r = MSK_maketask(env,numcon,numvar,&task);

    if ( r==MSK_RES_OK )
    {
      MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr);

      /* Append 'numcon' empty constraints.
     The constraints will initially have no bounds. */
      if ( r == MSK_RES_OK )
        r = MSK_appendcons(task,numcon);

      /* Append 'numvar' variables.
     The variables will initially be fixed at zero (x=0). */
      if ( r == MSK_RES_OK )
        r = MSK_appendvars(task,numvar);

      for(j=0; j<numvar && r == MSK_RES_OK; ++j)
      {
        /* Set the linear term c_j in the objective.*/  
        if(r == MSK_RES_OK)
          r = MSK_putcj(task,j,c[j]);

        /* Set the bounds on variable j.
       blx[j] <= x_j <= bux[j] */
        if(r == MSK_RES_OK)
          r = MSK_putvarbound(task,
                              j,           /* Index of variable.*/
                              bkx[j],      /* Bound key.*/
                              blx[j],      /* Numerical value of lower bound.*/
                              bux[j]);     /* Numerical value of upper bound.*/

        /* Input column j of A */   
        if(r == MSK_RES_OK)
          r = MSK_putacol(task,
                          j,                 /* Variable (column) index.*/
                          aptre[j]-aptrb[j], /* Number of non-zeros in column j.*/
                          asub+aptrb[j],     /* Pointer to row indexes of column j.*/
                          aval+aptrb[j]);    /* Pointer to Values of column j.*/
      
      }

      /* Set the bounds on constraints.
       for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
      for(i=0; i<numcon && r==MSK_RES_OK; ++i)
        r = MSK_putconbound(task,
                            i,           /* Index of constraint.*/
                            bkc[i],      /* Bound key.*/
                            blc[i],      /* Numerical value of lower bound.*/
                            buc[i]);     /* Numerical value of upper bound.*/
                 
      if ( r==MSK_RES_OK )
      {
        /* Append the first cone. */
        csub[0] = 3;
        csub[1] = 0;
        csub[2] = 1;
        r = MSK_appendcone(task,
                           MSK_CT_QUAD,
                           0.0, /* For future use only, can be set to 0.0 */
                           3,
                           csub);
      }

      if ( r==MSK_RES_OK )
      {
        /* Append the second cone. */
        csub[0] = 4;
        csub[1] = 5;
        csub[2] = 2;

        r = MSK_appendcone(task,
                           MSK_CT_RQUAD,
                           0.0,
                           3,
                           csub);
      }

      if ( r==MSK_RES_OK )
      {
        MSKrescodee trmcode;
        
        /* Run optimizer */
        r = MSK_optimizetrm(task,&trmcode);


        /* Print a summary containing information
           about the solution for debugging purposes*/
        MSK_solutionsummary (task,MSK_STREAM_MSG);
        
        if ( r==MSK_RES_OK )
        {
          MSKsolstae solsta;
          
          MSK_getsolsta (task,MSK_SOL_ITR,&solsta);
          
          switch(solsta)
          {
             case MSK_SOL_STA_OPTIMAL:   
             case MSK_SOL_STA_NEAR_OPTIMAL:
               {
                 double *xx = NULL;
                 
                 xx = calloc(numvar,sizeof(double));
                 if ( xx )
                 {                 
                   MSK_getxx (task,
                              MSK_SOL_ITR,    /* Request the interior solution. */
                              xx);

                   printf("Optimal primal solution\n");
                   for(j=0; j<numvar; ++j)
                     printf("x[%d]: %e\n",j,xx[j]);
                 }
                 else
                 {
                   r = MSK_RES_ERR_SPACE;
                 }
                 free(xx);
               }
               break;
             case MSK_SOL_STA_DUAL_INFEAS_CER:
             case MSK_SOL_STA_PRIM_INFEAS_CER:
             case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
             case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:  
               printf("Primal or dual infeasibility certificate found.\n");
               break;
             case MSK_SOL_STA_UNKNOWN:
               printf("The status of the solution could not be determined.\n");
               break;
             default:
               printf("Other solution status.");
               break;
          }
        }
        else
        {
          printf("Error while optimizing.\n");
        }
      }
    
      if (r != MSK_RES_OK)
      {
        /* In case of an error print error code and description. */      
        char symname[MSK_MAX_STR_LEN];
        char desc[MSK_MAX_STR_LEN];
        
        printf("An error occurred while optimizing.\n");     
        MSK_getcodedesc (r,
                         symname,
                         desc);
        printf("Error %s - '%s'\n",symname,desc);
      }
    }
    /* Delete the task and the associated data. */
    MSK_deletetask(&task);
  }
 
  /* Delete the environment and the associated data. */
  MSK_deleteenv(&env);

  return ( r );
} /* main */
示例#4
0
文件: myQCQP.cpp 项目: maoq1984/MTL
void MyQCQP::optimize()
{
	// resize alpha
	if(alpha != NULL)
		delete []alpha;
	alpha = new double[numvar];

	double *c_ = new double[numvar];
	for(int i = 0;i<numvar;i++) c_[i] = c[i];

	MSKboundkeye *bkc_ = new MSKboundkeye[numcon];
	double * blc_ = new double[numcon];
	double * buc_ = new double[numcon];
	for(int i = 0;i<numcon;i++)
	{
		bkc_[i] = bkc[i];
		blc_[i] = blc[i];
		buc_[i] = buc[i];
	}

	MSKboundkeye *bkx_ = new MSKboundkeye[numvar];
	double * blx_ = new double[numvar];
	double * bux_ = new double[numvar];
	for(int i = 0;i<numvar;i++)
	{
		bkx_[i] = bkx[i];
		blx_[i] = blx[i];
		bux_[i] = bux[i];
	}

	MSKlidxt *aptrb_ = new MSKlidxt[aptrb.size()];
	for(size_t i = 0;i<aptrb.size();i++) aptrb_[i] = aptrb[i];
	MSKlidxt * aptre_ = new MSKlidxt[aptre.size()];
	for(size_t i = 0;i<aptre.size();i++) aptre_[i] = aptre[i];
	MSKidxt * asub_ = new MSKidxt[asub.size()];
	for(size_t i = 0;i<asub.size();i++) asub_[i] = asub[i];
	double *aval_ = new double[aval.size()];
	for(size_t i = 0;i<aval.size();i++) aval_[i] = aval[i];

	MSKrescodee r;
	MSKenv_t env;
	MSKtask_t task;
	r = MSK_makeenv(&env,NULL,NULL,NULL,NULL);
	r = MSK_initenv(env);

	if(r == MSK_RES_OK)
	{
		r = MSK_maketask(env,numcon,numvar,&task);
		if(r == MSK_RES_OK)
			r = MSK_append(task,MSK_ACC_CON,numcon);

		if(r == MSK_RES_OK)
			r = MSK_append(task,MSK_ACC_VAR, numvar);

		for(int j = 0;j<numvar && r== MSK_RES_OK;j++)
		{
			if(r == MSK_RES_OK)
				r = MSK_putcj(task,j,c_[j]);

			if(r == MSK_RES_OK)
				r = MSK_putbound(task,MSK_ACC_VAR,j,bkx_[j],blx_[j],bux_[j]);

			if(r == MSK_RES_OK)
				r = MSK_putavec(task,MSK_ACC_VAR,j,aptre_[j] - aptrb_[j], asub_ + aptrb_[j],aval_+aptrb_[j]);
		}

		for(int i=0;i<numcon  && r== MSK_RES_OK;i++)
		{
			r = MSK_putbound(task,MSK_ACC_CON,i,bkc_[i],blc_[i],buc_[i]);
		}


		delete []c_;
		delete []bkx_;
		delete []blx_;
		delete []bux_;
		delete []aptrb_;
		delete []aptre_;
		delete []asub_;
		delete []aval_;
		delete []bkc_;
		delete []blc_;
		delete []buc_;


		for(int i=0;i<numcon-1 && r== MSK_RES_OK;i++) // numcon-1 quadratic constraints
		{
			int nzero = qsubi[i].size();
			MSKidxt * qsubi_ = new MSKidxt[nzero];
			MSKidxt * qsubj_ = new MSKidxt[nzero];
			double * qval_ = new double[nzero];
			for(int m = 0;m<nzero;m++)
			{
				qsubi_[m] = qsubi[i][m];
				qsubj_[m] = qsubj[i][m];
				qval_[m] = qval[i][m];
			}

			if(r == MSK_RES_OK)
				r = MSK_putqconk(task,i,nzero,qsubi_,qsubj_,qval_);

			delete []qsubi_;
			delete []qsubj_;
			delete []qval_;
		}


		if(r == MSK_RES_OK)
			r = MSK_putobjsense(task,MSK_OBJECTIVE_SENSE_MINIMIZE);

		if(r == MSK_RES_OK)
		{
			MSKrescodee trmcode;
			r = MSK_optimizetrm(task,&trmcode);

			MSK_getsolutionslice(task,MSK_SOL_ITR, MSK_SOL_ITEM_XX,0,numvar,alpha);

			MSK_getsolutionslice(task,MSK_SOL_ITR,MSK_SOL_ITEM_SUC,0,numcon,mu);
		}
		MSK_deletetask(&task);
	}
	MSK_deleteenv(&env);
}
示例#5
0
文件: milo1.c 项目: edljk/Mosek.jl
int main(int argc,char *argv[])
{
  const MSKint32t numvar = 2,
                  numcon = 2;

  double       c[]   = {  1.0, 0.64 };
  MSKboundkeye bkc[] = { MSK_BK_UP,    MSK_BK_LO };
  double       blc[] = { -MSK_INFINITY,-4.0 };
  double       buc[] = { 250.0,        MSK_INFINITY };

  MSKboundkeye bkx[] = { MSK_BK_LO,    MSK_BK_LO };
  double       blx[] = { 0.0,          0.0 };
  double       bux[] = { MSK_INFINITY, MSK_INFINITY };
  

  MSKint32t    aptrb[] = { 0, 2 },
               aptre[] = { 2, 4 },
               asub[] = { 0,    1,   0,    1 };
  double       aval[] = { 50.0, 3.0, 31.0, -2.0 };
  MSKint32t    i,j;

  MSKenv_t     env = NULL;
  MSKtask_t    task = NULL;
  MSKrescodee  r;

  /* Create the mosek environment. */
  r = MSK_makeenv(&env,NULL);

  /* Check if return code is ok. */
  if ( r==MSK_RES_OK )
  {
    /* Create the optimization task. */
    r = MSK_maketask(env,0,0,&task);

    if ( r==MSK_RES_OK )
      r = MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr);
    
    /* Append 'numcon' empty constraints.
     The constraints will initially have no bounds. */
    if ( r == MSK_RES_OK )
      r = MSK_appendcons(task,numcon);

    /* Append 'numvar' variables.
     The variables will initially be fixed at zero (x=0). */
    if ( r == MSK_RES_OK )
      r = MSK_appendvars(task,numvar);

    /* Optionally add a constant term to the objective. */
    if ( r ==MSK_RES_OK )
      r = MSK_putcfix(task,0.0);
    for(j=0; j<numvar && r == MSK_RES_OK; ++j)
    {
      /* Set the linear term c_j in the objective.*/  
      if(r == MSK_RES_OK)
        r = MSK_putcj(task,j,c[j]);

      /* Set the bounds on variable j.
       blx[j] <= x_j <= bux[j] */
      if(r == MSK_RES_OK)
        r = MSK_putvarbound(task,
                            j,           /* Index of variable.*/
                            bkx[j],      /* Bound key.*/
                            blx[j],      /* Numerical value of lower bound.*/
                            bux[j]);     /* Numerical value of upper bound.*/

      /* Input column j of A */   
      if(r == MSK_RES_OK)
        r = MSK_putacol(task,
                        j,                 /* Variable (column) index.*/
                        aptre[j]-aptrb[j], /* Number of non-zeros in column j.*/
                        asub+aptrb[j],     /* Pointer to row indexes of column j.*/
                        aval+aptrb[j]);    /* Pointer to Values of column j.*/
      
    }

    /* Set the bounds on constraints.
       for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
    for(i=0; i<numcon && r==MSK_RES_OK; ++i)
      r = MSK_putconbound(task,
                          i,           /* Index of constraint.*/
                          bkc[i],      /* Bound key.*/
                          blc[i],      /* Numerical value of lower bound.*/
                          buc[i]);     /* Numerical value of upper bound.*/
    
    /* Specify integer variables. */
    for(j=0; j<numvar && r == MSK_RES_OK; ++j)
      r = MSK_putvartype(task,j,MSK_VAR_TYPE_INT);
    
    if ( r==MSK_RES_OK )
      r =  MSK_putobjsense(task,
                           MSK_OBJECTIVE_SENSE_MAXIMIZE);
    
    if ( r==MSK_RES_OK )
    {
      MSKrescodee trmcode;

      /* Run optimizer */
      r = MSK_optimizetrm(task,&trmcode);

      /* Print a summary containing information
         about the solution for debugging purposes*/
      MSK_solutionsummary (task,MSK_STREAM_MSG);

      if ( r==MSK_RES_OK )
      {
        MSKint32t  j;
        MSKsolstae solsta;
        double     *xx = NULL; 

        MSK_getsolsta (task,MSK_SOL_ITG,&solsta);

        xx = calloc(numvar,sizeof(double));
        if ( xx ) 
        {        
          switch(solsta)
          {
             case MSK_SOL_STA_INTEGER_OPTIMAL:
             case MSK_SOL_STA_NEAR_INTEGER_OPTIMAL :             
               MSK_getxx(task,
                         MSK_SOL_ITG,    /* Request the integer solution. */
                         xx);
               
               printf("Optimal solution.\n");
               for(j=0; j<numvar; ++j)
                 printf("x[%d]: %e\n",j,xx[j]);                              
               break;
             case MSK_SOL_STA_PRIM_FEAS:
               /* A feasible but not necessarily optimal solution was located. */
               MSK_getxx(task,MSK_SOL_ITG,xx);
               
               printf("Feasible solution.\n");
               for(j=0; j<numvar; ++j)
                 printf("x[%d]: %e\n",j,xx[j]);               
               break;
             case MSK_SOL_STA_UNKNOWN:
               {
                 MSKprostae prosta; 
                 MSK_getprosta(task,MSK_SOL_ITG,&prosta); 
                 switch (prosta) 
                 {
                    case MSK_PRO_STA_PRIM_INFEAS_OR_UNBOUNDED:
                      printf("Problem status Infeasible or unbounded\n"); 
                      break; 
                    case MSK_PRO_STA_PRIM_INFEAS:
                      printf("Problem status Infeasible.\n"); 
                      break; 
                    case MSK_PRO_STA_UNKNOWN:
                      printf("Problem status unknown.\n"); 
                      break; 
                    default:
                      printf("Other problem status."); 
                      break;
                 }
               }
               break; 
             default:
               printf("Other solution status."); 
               break;               
          }
        }
        else
        {
          r = MSK_RES_ERR_SPACE;
        }
        free(xx);
      }
    }

    if (r != MSK_RES_OK)
    {
      /* In case of an error print error code and description. */
      char symname[MSK_MAX_STR_LEN];
      char desc[MSK_MAX_STR_LEN];

      printf("An error occurred while optimizing.\n");
      MSK_getcodedesc (r,
                       symname,
                       desc);
      printf("Error %s - '%s'\n",symname,desc);
    }

    MSK_deletetask(&task);
  }
  MSK_deleteenv(&env);

  printf("Return code: %d.\n",r);
  return ( r );
} /* main */
示例#6
0
int main (int argc, char * argv[])
{
  MSKtask_t   task = NULL;
  MSKenv_t    env  = NULL;
  MSKrescodee r  = MSK_RES_OK;

  if (argc <= 1)
  {
    printf ("Missing argument. The syntax is:\n");
    printf (" simple inputfile [ solutionfile ]\n");
  }
  else
  {    
    /* Create the mosek environment. 
       The `NULL' arguments here, are used to specify customized 
       memory allocators and a memory debug file. These can
       safely be ignored for now. */
    
    r = MSK_makeenv(&env, NULL, NULL, NULL, NULL);
      
    /* Initialize the environment */
    if ( r==MSK_RES_OK )
      MSK_initenv (env);

    /* Create a task object linked to the environment env.
       Initially we create it with 0 variables and 0 columns, 
       since we do not know the size of the problem. */ 
    if ( r==MSK_RES_OK )
      r = MSK_maketask (env, 0,0, &task);

    if (r == MSK_RES_OK)
      MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr);
      
    /* We assume that a problem file was given as the first command
       line argument (received in `argv'). */
    if ( r==MSK_RES_OK )   
      r = MSK_readdata (task, argv[1]);


    /* Solve the problem */
    if ( r==MSK_RES_OK )
    {
      MSKrescodee trmcode;
      
      MSK_optimizetrm(task,&trmcode);
    }

    /* Print a summary of the solution. */
    MSK_solutionsummary(task, MSK_STREAM_MSG);

    if (r == MSK_RES_OK)
    {
      MSKprostae prosta;
      MSKsolstae  solsta;
      MSKrealt primalobj,maxpbi,maxpcni,maxpeqi,maxinti,
        dualobj, maxdbi, maxdcni, maxdeqi;
      MSKintt isdef;
      MSKsoltypee whichsol = MSK_SOL_BAS;
      int accepted = 1;
      
        
      MSK_getsolutioninf (
                          task,
                          whichsol,
                          &prosta,
                          &solsta,
                          &primalobj,
                          &maxpbi,
                          &maxpcni,
                          &maxpeqi,
                          &maxinti,
                          &dualobj,
                          &maxdbi,
                          &maxdcni,
                          &maxdeqi);

        switch(solsta)
        {
          case MSK_SOL_STA_OPTIMAL:
          case MSK_SOL_STA_NEAR_OPTIMAL:
            {
              double max_primal_infeas = 0.0; /* maximal primal infeasibility */
              double max_dual_infeas   = 0.0; /* maximal dual infeasibility */
              double obj_gap = fabs(dualobj-primalobj);
           
            
              max_primal_infeas = double_max(max_primal_infeas,maxpbi);
              max_primal_infeas = double_max(max_primal_infeas,maxpcni);
              max_primal_infeas = double_max(max_primal_infeas,maxpeqi);
            
              max_dual_infeas = double_max(max_dual_infeas,maxdbi);
              max_dual_infeas = double_max(max_dual_infeas,maxdcni);
              max_dual_infeas = double_max(max_dual_infeas,maxdeqi);

              /* Assume the application needs the solution to be within
                 1e-6 ofoptimality in an absolute sense. Another approach
                 would be looking at the relative objective gap */
              printf("Objective gap: %e\n",obj_gap);
              if (obj_gap > 1e-6)
              {
                printf("Warning: The objective gap is too large.");
                accepted = 0;
              }            

              printf("Max primal infeasibility: %e\n", max_primal_infeas);
              printf("Max dual infeasibility: %e\n"  , max_dual_infeas);

              /* We will accept a primal infeasibility of 1e-8 and
                 dual infeasibility of 1e-6 */
            
              if (max_primal_infeas > 1e-8)
              {
                printf("Warning: Primal infeasibility is too large");
                accepted = 0;
              }

              if (max_dual_infeas > 1e-6)
              {
                printf("Warning: Dual infeasibility is too large");
                accepted = 0;
              }         
            }
            
            if (accepted && r == MSK_RES_OK)
            {
              MSKintt numvar,j;
              MSKrealt *xx = NULL;

              MSK_getnumvar(task,&numvar);
              
              xx = (double *) malloc(numvar*sizeof(MSKrealt));
              
              MSK_getsolutionslice(task,
                                   MSK_SOL_BAS,    /* Request the basic solution. */
                                   MSK_SOL_ITEM_XX,/* Which part of solution.     */
                                   0,              /* Index of first variable.    */
                                   numvar,         /* Index of last variable+1.   */
                                   xx);

      
              printf("Optimal primal solution\n");
              for(j=0; j<numvar; ++j)
                printf("x[%d]: %e\n",j,xx[j]);

              free(xx);
            }
            else
            {
              /* Print detailed information about the solution */
              if (r == MSK_RES_OK)
                r = MSK_analyzesolution(task,MSK_STREAM_LOG,whichsol);
            }
            break;
          case MSK_SOL_STA_DUAL_INFEAS_CER:
          case MSK_SOL_STA_PRIM_INFEAS_CER:
          case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
          case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:  
            printf("Primal or dual infeasibility certificate found.\n");
            break;
          case MSK_SOL_STA_UNKNOWN:
            printf("The status of the solution could not be determined.\n");
            break;
          default:
            printf("Other solution status");
            break;
        }
    }
    else
    {
      printf("Error while optimizing.\n");
    }

    MSK_deletetask(&task);
    MSK_deleteenv(&env);
  }
  return r;
}
int main(int argc,char *argv[])
{
  const MSKint32t numvar = 3, 
                  numcon = 3;
  MSKint32t       i,j;
  double          c[]    = {1.5, 2.5, 3.0};
  MSKint32t       ptrb[] = {0, 3, 6},
                  ptre[] = {3, 6, 9},
                  asub[] = { 0, 1, 2,
                             0, 1, 2,
                             0, 1, 2};
  
  double          aval[] = { 2.0, 3.0, 2.0,
                             4.0, 2.0, 3.0,
                             3.0, 3.0, 2.0};
 
  MSKboundkeye    bkc[]  = {MSK_BK_UP, MSK_BK_UP, MSK_BK_UP    };
  double          blc[]  = {-MSK_INFINITY, -MSK_INFINITY, -MSK_INFINITY};
  double          buc[]  = {100000, 50000, 60000};
  
  MSKboundkeye    bkx[]  = {MSK_BK_LO,     MSK_BK_LO,    MSK_BK_LO};
  double          blx[]  = {0.0,           0.0,          0.0,};
  double          bux[]  = {+MSK_INFINITY, +MSK_INFINITY,+MSK_INFINITY};
  
  double          *xx=NULL;               
  MSKenv_t        env;
  MSKtask_t       task;
  MSKint32t       varidx,conidx; 
  MSKrescodee     r;

  /* Create the mosek environment. */
  r = MSK_makeenv(&env,NULL);

  if ( r==MSK_RES_OK )
  {
    /* Create the optimization task. */
    r = MSK_maketask(env,numcon,numvar,&task);

    /* Directs the log task stream to the 
       'printstr' function. */

    MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr);
          
    /* Append the constraints. */
    if (r == MSK_RES_OK)
      r = MSK_appendcons(task,numcon);

    /* Append the variables. */
    if (r == MSK_RES_OK)
      r = MSK_appendvars(task,numvar);

    /* Put C. */
    if (r == MSK_RES_OK)
      r = MSK_putcfix(task, 0.0);

    if (r == MSK_RES_OK)
      for(j=0; j<numvar; ++j)
        r = MSK_putcj(task,j,c[j]);

    /* Put constraint bounds. */
    if (r == MSK_RES_OK)
      for(i=0; i<numcon; ++i)
        r = MSK_putconbound(task,i,bkc[i],blc[i],buc[i]);

    /* Put variable bounds. */
    if (r == MSK_RES_OK)
      for(j=0; j<numvar; ++j)
        r = MSK_putvarbound(task,j,bkx[j],blx[j],bux[j]);
                    
    /* Put A. */
    if (r == MSK_RES_OK)
      if ( numcon>0 )
        for(j=0; j<numvar; ++j)
          r = MSK_putacol(task,
                          j,
                          ptre[j]-ptrb[j],
                          asub+ptrb[j],
                          aval+ptrb[j]);
           
    if (r == MSK_RES_OK)
      r = MSK_putobjsense(task,
                          MSK_OBJECTIVE_SENSE_MAXIMIZE);

    if (r == MSK_RES_OK)
      r = MSK_optimizetrm(task,NULL);

    if (r == MSK_RES_OK)
    {
      xx = calloc(numvar,sizeof(double));
      if ( !xx )
        r = MSK_RES_ERR_SPACE;
    }

    if (r == MSK_RES_OK)
      r = MSK_getxx(task,
                    MSK_SOL_BAS,       /* Basic solution.       */
                    xx);
    
/* Make a change to the A matrix */
    if (r == MSK_RES_OK)
      r = MSK_putaij(task, 0, 0, 3.0);
    if (r == MSK_RES_OK)
      r = MSK_optimizetrm(task,NULL);

    /* Get index of new variable, this should be 3 */
    if (r == MSK_RES_OK)
      r = MSK_getnumvar(task,&varidx);

    /* Append a new variable x_3 to the problem */
    if (r == MSK_RES_OK)
      r = MSK_appendvars(task,1);
    
    /* Set bounds on new variable */
    if (r == MSK_RES_OK)
      r = MSK_putvarbound(task,
                          varidx,
                          MSK_BK_LO,
                          0,
                          +MSK_INFINITY);
    
    /* Change objective */
    if (r == MSK_RES_OK)
      r = MSK_putcj(task,varidx,1.0);
    
    /* Put new values in the A matrix */
    if (r == MSK_RES_OK)
    {
      MSKint32t acolsub[] = {0,   2};
      double    acolval[] =  {4.0, 1.0};
      
       r = MSK_putacol(task,
                       varidx, /* column index */
                       2, /* num nz in column*/
                       acolsub,
                       acolval);
    }
    
    /* Change optimizer to free simplex and reoptimize */
    if (r == MSK_RES_OK)
      r = MSK_putintparam(task,MSK_IPAR_OPTIMIZER,MSK_OPTIMIZER_FREE_SIMPLEX);
    
    if (r == MSK_RES_OK)
      r = MSK_optimizetrm(task,NULL);

    /* Get index of new constraint*/
    if (r == MSK_RES_OK)
      r = MSK_getnumcon(task,&conidx);

    /* Append a new constraint */
    if (r == MSK_RES_OK)
      r = MSK_appendcons(task,1);
    
    /* Set bounds on new constraint */
    if (r == MSK_RES_OK)
      r = MSK_putconbound(task,
                          conidx,
                          MSK_BK_UP,
                          -MSK_INFINITY,
                          30000);

    /* Put new values in the A matrix */
    if (r == MSK_RES_OK)
    {
      MSKidxt arowsub[] = {0,   1,   2,   3  };
      double arowval[] =  {1.0, 2.0, 1.0, 1.0};
      
      r = MSK_putarow(task,
                      conidx, /* row index */
                      4,      /* num nz in row*/
                      arowsub,
                      arowval);
    }
    if (r == MSK_RES_OK)
      r = MSK_optimizetrm(task,NULL);

    if ( xx )
      free(xx);
    
    MSK_deletetask(&task);
  }
  MSK_deleteenv(&env);

  printf("Return code: %d (0 means no error occured.)\n",r);

  return ( r );
} /* main */
示例#8
0
template <typename _Scalar> typename MosekOpt<_Scalar>::ReturnType
MosekOpt<_Scalar>::optimize( std::vector<_Scalar> *x_out, OBJ_SENSE objective_sense )
{
    if ( !this->_updated )
    {
        std::cerr << "[" << __func__ << "]: " << "Please call update() first!" << std::endl;
        return MSK_RES_ERR_UNKNOWN;
    }

    // cache problem size
    const int numvar = this->getVarCount();

    // determine problem type
    MSKobjsense_enum objsense = (objective_sense == OBJ_SENSE::MINIMIZE) ? MSK_OBJECTIVE_SENSE_MINIMIZE
                                                                         : MSK_OBJECTIVE_SENSE_MAXIMIZE;
    if ( MSK_RES_OK == _r )
        _r = MSK_putobjsense( _task, objsense );

    if ( MSK_RES_OK == _r  )
    {
        // set termination sensitivity
        MSKrescodee trmcode;
        if ( (_r == MSK_RES_OK) && (this->getTolRelGap() > Scalar(0)) )
        {
            _r = MSK_putdouparam( _task, MSK_DPAR_MIO_TOL_REL_GAP, this->getTolRelGap() /*1e-10f*/ );
            if ( _r != MSK_RES_OK )
            {
                std::cerr << "[" << __func__ << "]: " << "setting MSK_DPAR_MIO_DISABLE_TERM_TIME to " << this->getTimeLimit() << " did NOT work!" << std::endl;
            }
        }


        if ( (_r == MSK_RES_OK) && (this->getTimeLimit() > Scalar(0)) )
        {
            _r = MSK_putdouparam(_task, MSK_DPAR_MIO_DISABLE_TERM_TIME, this->getTimeLimit() );
            if ( _r != MSK_RES_OK )
            {
                std::cerr << "[" << __func__ << "]: " << "setting MSK_DPAR_MIO_DISABLE_TERM_TIME to " << this->getTimeLimit() << " did NOT work!" << std::endl;
            }
            _r = MSK_putdouparam(_task, MSK_DPAR_MIO_MAX_TIME, this->getTimeLimit()+Scalar(5) );
            if ( _r != MSK_RES_OK )
            {
                std::cerr << "[" << __func__ << "]: " << "setting MSK_DPAR_MIO_MAX_TIME to " << this->getTimeLimit()+Scalar(5) << " did NOT work!" << std::endl;
            }
        }

        if (_r == MSK_RES_OK)
        {
            //_r = MSK_putintparam(_task, MSK_IPAR_OPTIMIZER, MSK_OPTIMIZER_MIXED_INT_CONIC );
            if ( _r != MSK_RES_OK )
            {
                std::cerr << "[" << __func__ << "]: " << "setting MSK_OPTIMIZER_MIXED_INT_CONIC did not work!" << std::endl;
            }
        }

        if ( _r == MSK_RES_OK )
        {
            _r = MSK_putintparam( _task, MSK_IPAR_MIO_PRESOLVE_USE, MSK_ON );
            if ( _r != MSK_RES_OK )
            {
                std::cerr << "[" << __func__ << "]: " << "setting MSK_IPAR_MIO_PRESOLVE_USE did not work!" << std::endl;
            }
        }

        if ( _r == MSK_RES_OK )
        {
            _r = MSK_putintparam( _task, MSK_IPAR_MIO_HEURISTIC_LEVEL, 5 );
            if ( _r != MSK_RES_OK )
            {
                std::cerr << "[" << __func__ << "]: " << "setting MSK_IPAR_MIO_HEURISTIC_LEVEL did not work!" << std::endl;
            }
        }

        // Run optimizer
        _r = MSK_optimizetrm( _task, &trmcode );

        // Print a summary containing information about the solution for debugging purposes.
        MSK_solutionsummary( _task, MSK_STREAM_LOG );

        // save solution
        double *xx = (double*) calloc(numvar,sizeof(double));
        if ( _r == MSK_RES_OK )
        {
            MSKsolstae solsta;

            if ( _r == MSK_RES_OK )
            {
                _r = MSK_getsolsta( _task, MSK_SOL_ITR, &solsta );
                if ( _r != MSK_RES_OK )
                {
                    _r = MSK_getsolsta( _task, MSK_SOL_ITG, &solsta );
                }
                if ( _r != MSK_RES_OK )
                {
                    std::cerr << "[" << __func__ << "]: " << "neithter MSK_SOL_ITR, nor MSK_SOL_ITR worked" << std::endl;
                }
            }

            switch ( solsta )
            {
                case MSK_SOL_STA_OPTIMAL:
                case MSK_SOL_STA_NEAR_OPTIMAL:
                {
                    if ( xx )
                    {
                        MSK_getxx(_task,
                                  MSK_SOL_ITR,    /* Request the basic solution. */
                                  xx);

                        _storeSolution( xx, numvar );
                        printf("Optimal primal solution\n");
                    }
                    else
                    {
                        _r = MSK_RES_ERR_SPACE;
                    }
                    break;
                }

                case MSK_SOL_STA_DUAL_INFEAS_CER:
                case MSK_SOL_STA_PRIM_INFEAS_CER:
                case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
                case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:
                    printf("Primal or dual infeasibility certificate found.\n");
                    break;
                case MSK_SOL_STA_UNKNOWN:
                {
                    MSKprostae prosta;
                    MSK_getprosta(_task,MSK_SOL_ITG,&prosta);
                    switch (prosta)
                    {
                        case MSK_PRO_STA_PRIM_INFEAS_OR_UNBOUNDED:
                            printf("Problem status Infeasible or unbounded\n");
                            break;
                        case MSK_PRO_STA_PRIM_INFEAS:
                            printf("Problem status Infeasible.\n");
                            break;
                        case MSK_PRO_STA_UNKNOWN:
                            printf("Problem status unknown.\n");
                            break;
                        default:
                            printf("Other problem status.");
                            break;
                    }
                    char symname[MSK_MAX_STR_LEN];
                    char desc[MSK_MAX_STR_LEN];

                    /* If the solutions status is unknown, print the termination code
               indicating why the optimizer terminated prematurely. */

                    MSK_getcodedesc(trmcode,
                                    symname,
                                    desc);

                    printf("The solutuion status is unknown.\n");
                    printf("The optimizer terminitated with code: %s\n",symname);
                    break;
                }
                    // ITG
                    //asdf todo: consolidate this last part:
                case MSK_SOL_STA_INTEGER_OPTIMAL:
                case MSK_SOL_STA_NEAR_INTEGER_OPTIMAL :
                    MSK_getxx(_task,
                              MSK_SOL_ITG,    /* Request the integer solution. */
                              xx);
                    _storeSolution( xx, numvar );
                    printf("Optimal integer solution.\n");

                    break;

                case MSK_SOL_STA_PRIM_FEAS:
                    /* A feasible but not necessarily optimal solution was located. */
                    MSK_getxx(_task,MSK_SOL_ITG,xx);
                    _storeSolution( xx, numvar );
                    printf("Feasible solution.\n");
                    break;

                default:
                    std::cerr << "[" << __func__ << "]: " << "unknown code " << (int)solsta << std::endl;
                    break;
            }

            if ( xx ) { free(xx); xx = NULL; }
        }
    }

    if ( MSK_RES_OK != _r )
    {
        /* In case of an error print error code and description. */
        char symname[MSK_MAX_STR_LEN];
        char desc[MSK_MAX_STR_LEN];

        printf("An error occurred while optimizing.\n");
        MSK_getcodedesc( _r,
                         symname,
                         desc);
        printf("Error %s - '%s'\n",symname,desc);
    }
    else
    {
        // output
        if ( x_out )
        {
            x_out->clear();
            x_out->reserve( this->_x.size() );
            for ( int j=0; j < this->_x.size(); ++j )
            {
                x_out->push_back( this->_x[j] );
            }
        }
    }

    return _r;
} // ...MosekOpt::optimize()
示例#9
0
int do_thing()
{
   const MSKint32t numvar = 4,
   numcon = 3;
   
   double       c[]     = {3.0, 1.0, 5.0, 1.0};
   /* Below is the sparse representation of the A
    matrix stored by column. */
   MSKint32t    aptrb[] = {0, 2, 5, 7},
   aptre[] = {2, 5, 7, 9},
   asub[]  = { 0, 1,
      0, 1, 2,
      0, 1,
      1, 2};
   double       aval[]  = { 3.0, 2.0,
      1.0, 1.0, 2.0,
      2.0, 3.0,
      1.0, 3.0};
   
   /* Bounds on constraints. */
   MSKboundkeye bkc[]  = {MSK_BK_FX, MSK_BK_LO,     MSK_BK_UP    };
   double       blc[]  = {30.0,      15.0,          -MSK_INFINITY};
   double       buc[]  = {30.0,      +MSK_INFINITY, 25.0         };
   /* Bounds on variables. */
   MSKboundkeye bkx[]  = {MSK_BK_LO,     MSK_BK_RA, MSK_BK_LO,     MSK_BK_LO     };
   double       blx[]  = {0.0,           0.0,       0.0,           0.0           };
   double       bux[]  = {+MSK_INFINITY, 10.0,      +MSK_INFINITY, +MSK_INFINITY };
   MSKenv_t     env  = NULL;
   MSKtask_t    task = NULL;
   MSKrescodee  r;
   MSKint32t    i,j;
   
   /* Create the mosek environment. */
   r = MSK_makeenv(&env,NULL);
   
   if ( r==MSK_RES_OK )
   {
      /* Create the optimization task. */
      r = MSK_maketask(env,numcon,numvar,&task);
      
      /* Directs the log task stream to the 'printstr' function. */
      if ( r==MSK_RES_OK )
         r = MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr);
      
      /* Append 'numcon' empty constraints.
       The constraints will initially have no bounds. */
      if ( r == MSK_RES_OK )
         r = MSK_appendcons(task,numcon);
      
      /* Append 'numvar' variables.
       The variables will initially be fixed at zero (x=0). */
      if ( r == MSK_RES_OK )
         r = MSK_appendvars(task,numvar);
      
      for(j=0; j<numvar && r == MSK_RES_OK; ++j)
      {
         /* Set the linear term c_j in the objective.*/
         if(r == MSK_RES_OK)
            r = MSK_putcj(task,j,c[j]);
         
         /* Set the bounds on variable j.
          blx[j] <= x_j <= bux[j] */
         if(r == MSK_RES_OK)
            r = MSK_putvarbound(task,
                                j,           /* Index of variable.*/
                                bkx[j],      /* Bound key.*/
                                blx[j],      /* Numerical value of lower bound.*/
                                bux[j]);     /* Numerical value of upper bound.*/
         
         /* Input column j of A */
         if(r == MSK_RES_OK)
            r = MSK_putacol(task,
                            j,                 /* Variable (column) index.*/
                            aptre[j]-aptrb[j], /* Number of non-zeros in column j.*/
                            asub+aptrb[j],     /* Pointer to row indexes of column j.*/
                            aval+aptrb[j]);    /* Pointer to Values of column j.*/
      }
      
      /* Set the bounds on constraints.
       for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
      for(i=0; i<numcon && r==MSK_RES_OK; ++i)
         r = MSK_putconbound(task,
                             i,           /* Index of constraint.*/
                             bkc[i],      /* Bound key.*/
                             blc[i],      /* Numerical value of lower bound.*/
                             buc[i]);     /* Numerical value of upper bound.*/
      
      /* Maximize objective function. */
      if (r == MSK_RES_OK)
         r = MSK_putobjsense(task, MSK_OBJECTIVE_SENSE_MAXIMIZE);
      
      if ( r==MSK_RES_OK )
      {
         MSKrescodee trmcode;
         
         /* Run optimizer */
         r = MSK_optimizetrm(task,&trmcode);
         
         /* Print a summary containing information
          about the solution for debugging purposes. */
         MSK_solutionsummary (task,MSK_STREAM_LOG);
         
         if ( r==MSK_RES_OK )
         {
            MSKsolstae solsta;
            
            if ( r==MSK_RES_OK )
               r = MSK_getsolsta (task,
                                  MSK_SOL_BAS,
                                  &solsta);
            switch(solsta)
            {
               case MSK_SOL_STA_OPTIMAL:
               case MSK_SOL_STA_NEAR_OPTIMAL:
               {
                  double *xx = (double*) calloc(numvar,sizeof(double));
                  if ( xx )
                  {
                     MSK_getxx(task,
                               MSK_SOL_BAS,    /* Request the basic solution. */
                               xx);
                     
                     printf("Optimal primal solution\n");
                     for(j=0; j<numvar; ++j)
                        printf("x[%d]: %e\n",j,xx[j]);
                     
                     free(xx);
                  }
                  else
                     r = MSK_RES_ERR_SPACE;
                  
                  break;
               }
               case MSK_SOL_STA_DUAL_INFEAS_CER:
               case MSK_SOL_STA_PRIM_INFEAS_CER:
               case MSK_SOL_STA_NEAR_DUAL_INFEAS_CER:
               case MSK_SOL_STA_NEAR_PRIM_INFEAS_CER:
                  printf("Primal or dual infeasibility certificate found.\n");
                  break;
               case MSK_SOL_STA_UNKNOWN:
               {
                  char symname[MSK_MAX_STR_LEN];
                  char desc[MSK_MAX_STR_LEN];
                  
                  /* If the solutions status is unknown, print the termination code
                   indicating why the optimizer terminated prematurely. */
                  
                  MSK_getcodedesc(trmcode,
                                  symname,
                                  desc);
                  
                  printf("The solution status is unknown.\n");
                  printf("The optimizer terminitated with code: %s\n",symname);
                  break;
               }
               default:
                  printf("Other solution status.\n");
                  break;
            }
         }
      }
      
      if (r != MSK_RES_OK)
      {
         /* In case of an error print error code and description. */
         char symname[MSK_MAX_STR_LEN];
         char desc[MSK_MAX_STR_LEN];
         
         printf("An error occurred while optimizing.\n");     
         MSK_getcodedesc (r,
                          symname,
                          desc);
         printf("Error %s - '%s'\n",symname,desc);
      }
      
      /* Delete the task and the associated data. */
      MSK_deletetask(&task);
   }
   
   /* Delete the environment and the associated data. */
   MSK_deleteenv(&env);
   
   return r;
}