Ejemplo n.º 1
0
Archivo: glpk.c Proyecto: ugonj/cvxopt
/* Initialisation of iocp object */
static int
iocp_init(pyiocp *self, PyObject *args, PyObject *kwds)
{
    /*static char *kwlist[] = {"number", NULL};*/
    static char *kwlist[] = { "msg_lev", "br_tech", "bt_tech", "tol_int", "tol_obj", "tm_lim", "out_frq", "out_dly", "cb_size", "pp_tech", "mip_gap", "mir_cuts", "gmi_cuts", "cov_cuts", "clq_cuts", "presolve", "binarize", "fp_heur", "ps_heur", "ps_tm_lim", "use_sol", "save_sol", "alien",NULL};
    glp_init_iocp(&self->obj);

    if (! PyArg_ParseTupleAndKeywords(args, kwds, "|iiiddiiiiidiiiiiiiiiisi", kwlist,
                &self->obj.msg_lev,
                &self->obj.br_tech,
                &self->obj.bt_tech,
                &self->obj.tol_int,
                &self->obj.tol_obj,
                &self->obj.tm_lim,
                &self->obj.out_frq,
                &self->obj.out_dly,
                &self->obj.cb_size,
                &self->obj.pp_tech,
                &self->obj.mip_gap,
                &self->obj.mir_cuts,
                &self->obj.gmi_cuts,
                &self->obj.cov_cuts,
                &self->obj.clq_cuts,
                &self->obj.presolve,
                &self->obj.binarize,
                &self->obj.fp_heur,
                &self->obj.ps_heur,
                &self->obj.ps_tm_lim,
                &self->obj.use_sol,
                &self->obj.save_sol,
                &self->obj.alien))
                    return -1;

    return 0;
}
Ejemplo n.º 2
0
void B2GlpkHasher::build_hash()
{
	glp_simplex(_lp, NULL);
	glp_iocp parm;
	glp_init_iocp(&parm);
	parm.presolve = GLP_ON;
	parm.binarize = GLP_ON;
	glp_intopt(_lp, &parm);
	double motif_count = glp_mip_obj_val(_lp);
	if((motif_count > 0) && (motif_count <= (_str_set.size() * 2)))
	{
		_motif_set = _trace_set;
		B2HashMap<B2Trace, unsigned int> &trace_vals = _motif_set.trace_vals();
		for(B2HashMap<B2Trace, unsigned int>::iterator trace_it = trace_vals.begin(); trace_it != trace_vals.end(); )
		{
			double is_motif = glp_mip_col_val(_lp, trace_it->second);
			if(is_motif == 0)
			{
				_motif_set.erase(trace_it->first);
				B2_HASH_MAP_ERASE(trace_vals, trace_it);
			}
			else
			{
				++trace_it;
			};
		};
	}
	else
	{
		b2_preproc_error_inc(B2_PREPROC_ERROR_BAD_MOTIF_SET, 1);
	};
};
Ejemplo n.º 3
0
int CMyProblem::SolveMIP()
{
	//инициализация параметров MIP-решателя
	glp_iocp params;
	glp_init_iocp(&params);
	params.presolve=GLP_ON;
	params.tm_lim=360000;
	return glp_intopt(lp, &params);	
}
Ejemplo n.º 4
0
int main(void)
{
  glp_prob *mip = glp_create_prob();
  glp_set_prob_name(mip, "sample");
  glp_set_obj_dir(mip, GLP_MAX);

  // 拘束条件
  // 具体的な関数は後で
  glp_add_rows(mip, 3); // 拘束条件の数
  glp_set_row_name(mip, 1, "c1"); glp_set_row_bnds(mip, 1, GLP_DB, 0.0, 20.0);
  glp_set_row_name(mip, 2, "c2"); glp_set_row_bnds(mip, 2, GLP_DB, 0.0, 30.0);
  glp_set_row_name(mip, 3, "c3"); glp_set_row_bnds(mip, 3, GLP_FX, 0.0, 0);

  // 変数
  // 変数そのものにかかる拘束は、拘束条件ではなくてこちらで管理
  glp_add_cols(mip, 4); // 変数の数
  glp_set_col_name(mip, 1, "x1");
  glp_set_col_bnds(mip, 1, GLP_DB, 0.0, 40.0); glp_set_obj_coef(mip, 1, 1.0);
  glp_set_col_name(mip, 2, "x2");
  glp_set_col_bnds(mip, 2, GLP_LO, 0.0, 0.0); glp_set_obj_coef(mip, 2, 2.0);
  glp_set_col_name(mip, 3, "x3");
  glp_set_col_bnds(mip, 3, GLP_LO, 0.0, 0.0); glp_set_obj_coef(mip, 3, 3.0);
  glp_set_col_kind(mip, 3, GLP_IV); // 整数値としての宣言
  glp_set_col_name(mip, 4, "x4");
  glp_set_col_bnds(mip, 4, GLP_DB, 2.0, 3.0); glp_set_obj_coef(mip, 4, 1.0);
  glp_set_col_kind(mip, 4, GLP_IV); // 整数値としての宣言

  int ia[1+9], ja[1+9];
  double ar[1+9];
  ia[1]=1,ja[1]=1,ar[1]=-1;   // a[1,1] = -1
  ia[2]=1,ja[2]=2,ar[2]=1;    // a[1,2] = 1
  ia[3]=1,ja[3]=3,ar[3]=1;    // a[1,3] = 1
  ia[4]=1,ja[4]=4,ar[4]=10;   // a[1,4] = 10
  ia[5]=2,ja[5]=1,ar[5]=1;    // a[2,1] = 1
  ia[6]=2,ja[6]=2,ar[6]=-3;   // a[2,2] = -3
  ia[7]=2,ja[7]=3,ar[7]=1;    // a[2,3] = 1
  ia[8]=3,ja[8]=2,ar[8]=1;    // a[3,2] = 1
  ia[9]=3,ja[9]=4,ar[9]=-3.5; // a[3,4] = -3.5
  glp_load_matrix(mip, 9, ia, ja, ar);

  glp_iocp parm;
  glp_init_iocp(&parm);
  parm.presolve = GLP_ON;
  int err = glp_intopt(mip, &parm);

  double z = glp_mip_obj_val(mip);
  double x1 = glp_mip_col_val(mip, 1);
  double x2 = glp_mip_col_val(mip, 2);
  double x3 = glp_mip_col_val(mip, 3);
  double x4 = glp_mip_col_val(mip, 4);
  printf("\nz = %g; x1 = %g; x2 = %g; x3 = %g, x4 = %g\n", z, x1, x2, x3, x4);
  // z = 122.5; x1 = 40; x2 = 10.5; x3 = 19.5, x4 = 3

  glp_delete_prob(mip);
  return 0;
}
Ejemplo n.º 5
0
 double solve()
 {
   glp_smcp smcp;
   glp_iocp iocp;
   glp_init_smcp(&smcp); smcp.msg_lev = GLP_MSG_ERR;
   glp_init_iocp(&iocp); iocp.msg_lev = GLP_MSG_ERR;
   glp_load_matrix(ip_, ia_.size()-1, &ia_[0], &ja_[0], &ar_[0]);
   glp_simplex(ip_, &smcp);
   glp_intopt(ip_, &iocp);
   return glp_mip_obj_val(ip_);
 }
Ejemplo n.º 6
0
/* Different cases :
 *     - if the created node is root, then father is NULL, the problem version in the node is the one gave as parameter.
 *     - else we copy the problem, and had the constraint "x_{y} = valy"
 */
void create_node(node* n, glp_prob* prob, node* father, int y, double valy)
{
	n->father = father;
	n->leftSon = NULL;
	n->rightSon = NULL;
	n->check = 0;
	
	int i = 0;
	int ind[] = {0,y};
	double val[] = {0,1};
	
	if (n-> father == NULL)
	{
		n->prob = prob;
	}
	else
	{
		n->prob = glp_create_prob();
		glp_copy_prob(n->prob, n->father->prob, GLP_ON);
		i = glp_add_rows(n->prob, 1);
		glp_set_mat_row(n->prob, i, 1, ind, val);
		glp_set_row_bnds(n->prob, i, GLP_FX, valy, valy);
	}

	glp_smcp parm;
	glp_init_smcp(&parm);
	parm.msg_lev = GLP_MSG_OFF;

	glp_iocp parmip;
	glp_init_iocp(&parmip);
	parmip.msg_lev = GLP_MSG_OFF;

	glp_write_lp(prob, NULL, "ULS.lp");

	n->solveFlag = glp_simplex(n->prob, &parm); glp_intopt(n->prob, &parmip);

	n->z = glp_mip_obj_val(n->prob);
	n->x = (double *) malloc (glp_get_num_cols(n->prob) * sizeof(double));
	for (i = 0; i < glp_get_num_cols(n->prob); ++i) n->x[i] = glp_mip_col_val(n->prob, i+1);
}
Ejemplo n.º 7
0
int c_glp_mip_solve(glp_prob *lp, int msg_lev, int br_tech, int bt_tech, int pp_tech,
		     	int fp_heur, int tm_lim, int cuts, double mip_gap, int presolve){
  	glp_iocp iocp;
	glp_mem_limit(10000);
// 	printf ("%d %d %d time\n", msg_lev, br_tech, tm_lim);
	glp_init_iocp(&iocp);
	iocp.msg_lev = msg_lev;
	iocp.br_tech = br_tech;
	iocp.bt_tech = bt_tech;
	iocp.pp_tech = pp_tech;
	//	iocp.fp_heur = fp_heur ? GLP_ON : GLP_OFF;
// 	printf ("fp %d\n", iocp.fp_heur);
	iocp.gmi_cuts = cuts & 1 ? GLP_ON : GLP_OFF;
	iocp.mir_cuts = cuts & 2 ? GLP_ON : GLP_OFF;
	iocp.cov_cuts = cuts & 4 ? GLP_ON : GLP_OFF;
	iocp.clq_cuts = cuts & 8 ? GLP_ON : GLP_OFF;
	iocp.mip_gap = mip_gap;
	iocp.tm_lim = tm_lim;
// 	printf ("%d %d %d time\n", msg_lev, br_tech, tm_lim);
	iocp.presolve = presolve ? GLP_ON : GLP_OFF;
	return glp_intopt(lp, &iocp);
}
Ejemplo n.º 8
0
static void
maybe_check_results(const int ppl_status, const double ppl_optimum_value) {
  const char* ppl_status_string;
  const char* glpk_status_string;
  int glpk_status;
  int treat_as_lp = 0;
  glp_smcp glpk_smcp;

  if (!check_results)
    return;

  if (no_mip || glpk_lp_num_int == 0)
    treat_as_lp = 1;

  glp_set_obj_dir(glpk_lp, (maximize ? GLP_MAX : GLP_MIN));

  glp_init_smcp(&glpk_smcp);
  /* Disable GLPK output. */
  glpk_smcp.msg_lev = GLP_MSG_OFF;

  if (treat_as_lp) {
    /* Set the problem class to LP: MIP problems are thus treated as
       LP ones. */
    glp_exact(glpk_lp, &glpk_smcp);
    glpk_status = glp_get_status(glpk_lp);
  }
  else {
    /* MIP case. */
    glp_simplex(glpk_lp, &glpk_smcp);
    glpk_status = glp_get_status(glpk_lp);
    if (glpk_status != GLP_NOFEAS && glpk_status != GLP_UNBND) {
      glp_iocp glpk_iocp;
      glp_init_iocp(&glpk_iocp);
      /* Disable GLPK output. */
      glpk_iocp.msg_lev = GLP_MSG_OFF;
      glp_intopt(glpk_lp, &glpk_iocp);
      glpk_status = glp_mip_status(glpk_lp);
    }
  }
  /* If no_optimization is enabled, the second case is not possibile. */
  if (!((ppl_status == PPL_MIP_PROBLEM_STATUS_UNFEASIBLE
         && glpk_status == GLP_NOFEAS)
        || (ppl_status == PPL_MIP_PROBLEM_STATUS_UNBOUNDED
            && glpk_status == GLP_UNBND)
        || (ppl_status == PPL_MIP_PROBLEM_STATUS_OPTIMIZED
            && (glpk_status == GLP_OPT
                /* If no_optimization is enabled, check if the problem is
                   unbounded for GLPK.  */
                || (no_optimization && (glpk_status == GLP_UNBND
                                        || glpk_status == GLP_UNDEF))))))  {

    if (ppl_status == PPL_MIP_PROBLEM_STATUS_UNFEASIBLE)
      ppl_status_string = "unfeasible";
    else if (ppl_status == PPL_MIP_PROBLEM_STATUS_UNBOUNDED)
      ppl_status_string = "unbounded";
    else if (ppl_status == PPL_MIP_PROBLEM_STATUS_OPTIMIZED)
      ppl_status_string = "optimizable";
    else
      ppl_status_string = "<?>";

    switch (glpk_status) {
    case GLP_NOFEAS:
      glpk_status_string = "unfeasible";
      break;
    case GLP_UNBND:
      glpk_status_string = "unbounded";
      break;
    case GLP_OPT:
      glpk_status_string = "optimizable";
      break;
    case GLP_UNDEF:
      glpk_status_string = "undefined";
      break;
    default:
      glpk_status_string = "<?>";
      break;
    }

    error("check failed: for GLPK the problem is %s, not %s",
          glpk_status_string, ppl_status_string);

    check_results_failed = 1;
  }
  else if (!no_optimization
           && ppl_status == PPL_MIP_PROBLEM_STATUS_OPTIMIZED) {

    double glpk_optimum_value
      = (treat_as_lp ? glp_get_obj_val(glpk_lp) : glp_mip_obj_val(glpk_lp));

    if (fabs(ppl_optimum_value - glpk_optimum_value) > check_threshold) {
      error("check failed: for GLPK the problem's optimum is %.20g,"
            " not %.20g", glpk_optimum_value, ppl_optimum_value);
      check_results_failed = 1;
    }
  }
  return;
}
Ejemplo n.º 9
0
int main(int argc,char *argv[]){
  int q[] = {atoi(argv[1]),atoi(argv[2]),atoi(argv[3])};    //queue length
  int n[] = {atoi(argv[4]),atoi(argv[5]),atoi(argv[6])};    //different request number
  float cmax = atof(argv[7]);                                 //bandwidth limitation
  glp_prob *mip = glp_create_prob();
  glp_set_prob_name(mip, "sample");
  glp_set_obj_dir(mip, GLP_MAX);

  glp_add_rows(mip, 8);
  glp_set_row_name(mip, 1, "n1");
  if (n[0]==0)
    glp_set_row_bnds(mip, 1, GLP_FX, 0.0, n[0]);
  else
    glp_set_row_bnds(mip, 1, GLP_DB, 0.0, n[0]);
  glp_set_row_name(mip, 2, "n2");
  if (n[1]==0)
    glp_set_row_bnds(mip, 2, GLP_FX, 0.0, n[1]);
  else
    glp_set_row_bnds(mip, 2, GLP_DB, 0.0, n[1]);
  glp_set_row_name(mip, 3, "n3");
  if (n[2]==0)
    glp_set_row_bnds(mip, 3, GLP_FX, 0.0, n[2]);
  else
    glp_set_row_bnds(mip, 3, GLP_DB, 0.0, n[2]);
  glp_set_row_name(mip, 4, "c1");
  glp_set_row_bnds(mip, 4, GLP_DB, 0.0, cmax);
  glp_set_row_name(mip, 5, "c2");
  glp_set_row_bnds(mip, 5, GLP_DB, 0.0, cmax);
  glp_set_row_name(mip, 6, "c3");
  glp_set_row_bnds(mip, 6, GLP_DB, 0.0, cmax);
  glp_set_row_name(mip, 7, "c4");
  glp_set_row_bnds(mip, 7, GLP_DB, 0.0, cmax);
  glp_set_row_name(mip, 8, "c5");
  glp_set_row_bnds(mip, 8, GLP_DB, 0.0, cmax);

  glp_add_cols(mip, 15);
  glp_set_col_name(mip, 1, "x11");
  glp_set_col_bnds(mip, 1, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 1, q[0]);                           //queue length
  glp_set_col_kind(mip, 1, GLP_IV);

  glp_set_col_name(mip, 2, "x12");
  glp_set_col_bnds(mip, 2, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 2, q[1]);
  glp_set_col_kind(mip, 2, GLP_IV);

  glp_set_col_name(mip, 3, "x13");
  glp_set_col_bnds(mip, 3, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 3, q[2]);
  glp_set_col_kind(mip, 3, GLP_IV);

  glp_set_col_name(mip, 4, "x21");
  glp_set_col_bnds(mip, 4, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 4, q[0]);
  glp_set_col_kind(mip, 4, GLP_IV);

  glp_set_col_name(mip, 5, "x22");
  glp_set_col_bnds(mip, 5, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 5, q[1]);
  glp_set_col_kind(mip, 5, GLP_IV);

  glp_set_col_name(mip, 6, "x23");
  glp_set_col_bnds(mip, 6, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 6, q[2]);
  glp_set_col_kind(mip, 6, GLP_IV);

  glp_set_col_name(mip, 7, "x31");
  glp_set_col_bnds(mip, 7, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 7, q[0]);
  glp_set_col_kind(mip, 7, GLP_IV);

  glp_set_col_name(mip, 8, "x32");
  glp_set_col_bnds(mip, 8, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 8, q[1]);
  glp_set_col_kind(mip, 8, GLP_IV);

  glp_set_col_name(mip, 9, "x33");
  glp_set_col_bnds(mip, 9, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 9, q[2]);
  glp_set_col_kind(mip, 9, GLP_IV);

  glp_set_col_name(mip, 10, "x41");
  glp_set_col_bnds(mip, 10, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 10, q[0]);
  glp_set_col_kind(mip, 10, GLP_IV);

  glp_set_col_name(mip, 11, "x42");
  glp_set_col_bnds(mip, 11, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 11, q[1]);
  glp_set_col_kind(mip, 11, GLP_IV);

  glp_set_col_name(mip, 12, "x43");
  glp_set_col_bnds(mip, 12, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 12, q[2]);
  glp_set_col_kind(mip, 12, GLP_IV);

  glp_set_col_name(mip, 13, "x51");
  glp_set_col_bnds(mip, 13, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 13, q[0]);
  glp_set_col_kind(mip, 13, GLP_IV);

  glp_set_col_name(mip, 14, "x52");
  glp_set_col_bnds(mip, 14, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 14, q[1]);
  glp_set_col_kind(mip, 14, GLP_IV);

  glp_set_col_name(mip, 15, "x53");
  glp_set_col_bnds(mip, 15, GLP_LO, 0, 0);
  glp_set_obj_coef(mip, 15, q[2]);
  glp_set_col_kind(mip, 15, GLP_IV);

  int ia[1+30], ja[1+30];
  double ar[1+30];
  int i=1,j=1,k=1;
  for (i=1;i<4;i++)
    for (j=1;j<6;j++){
      ia[k]=i,ja[k]=(j-1)*3+i,ar[k]=1;
      k++;
    }
  ia[16]=4,ja[16]=1,ar[16]=10;
  ia[17]=4,ja[17]=2,ar[17]=1;
  ia[18]=4,ja[18]=3,ar[18]=0.1;
  ia[19]=5,ja[19]=4,ar[19]=10;
  ia[20]=5,ja[20]=5,ar[20]=1;
  ia[21]=5,ja[21]=6,ar[21]=0.1;
  ia[22]=6,ja[22]=7,ar[22]=10;
  ia[23]=6,ja[23]=8,ar[23]=1;
  ia[24]=6,ja[24]=9,ar[24]=0.1;
  ia[25]=7,ja[25]=10,ar[25]=10;
  ia[26]=7,ja[26]=11,ar[26]=1;
  ia[27]=7,ja[27]=12,ar[27]=0.1;
  ia[28]=8,ja[28]=13,ar[28]=10;
  ia[29]=8,ja[29]=14,ar[29]=1;
  ia[30]=8,ja[30]=15,ar[30]=0.1;
  /*
  for (i=1;i<31;i++){
    printf("%d,%d,%f\n",ia[i],ja[i],ar[i]);
  }
  */

  glp_load_matrix(mip, 30, ia, ja, ar);

  glp_iocp parm;
  glp_init_iocp(&parm);
  parm.presolve = GLP_ON;
  int err = glp_intopt(mip, &parm);


  //glp_simplex(mip, NULL);
  // double t = glp_mip_obj_val(mip);
  int result[15]={0};
  for (i=0;i<15;i++){
    result[i] = glp_mip_col_val(mip, i+1);
  }


  printf("\n");
  //display the result
  for (i=0;i<14;i++){
    printf("%d,",result[i]);
  }
  printf("%d\n",result[14]);

  glp_delete_prob(mip);
  return 0;
}
Ejemplo n.º 10
0
int glp_main(int argc, const char *argv[])
{     /* stand-alone LP/MIP solver */
      struct csa _csa, *csa = &_csa;
      int ret;
      xlong_t start;
      /* perform initialization */
      csa->prob = glp_create_prob();
      glp_get_bfcp(csa->prob, &csa->bfcp);
      glp_init_smcp(&csa->smcp);
      csa->smcp.presolve = GLP_ON;
      glp_init_iocp(&csa->iocp);
      csa->iocp.presolve = GLP_ON;
      csa->tran = NULL;
      csa->graph = NULL;
      csa->format = FMT_MPS_FILE;
      csa->in_file = NULL;
      csa->ndf = 0;
      csa->out_dpy = NULL;
      csa->solution = SOL_BASIC;
      csa->in_res = NULL;
      csa->dir = 0;
      csa->scale = 1;
      csa->out_sol = NULL;
      csa->out_res = NULL;
      csa->out_bnds = NULL;
      csa->check = 0;
      csa->new_name = NULL;
      csa->out_mps = NULL;
      csa->out_freemps = NULL;
      csa->out_cpxlp = NULL;
      csa->out_pb = NULL;
      csa->out_npb = NULL;
      csa->log_file = NULL;
      csa->crash = USE_ADV_BASIS;
      csa->exact = 0;
      csa->xcheck = 0;
      csa->nomip = 0;
      /* parse command-line parameters */
      ret = parse_cmdline(csa, argc, argv);
      if (ret < 0)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      if (ret > 0)
      {  ret = EXIT_FAILURE;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* remove all output files specified in the command line */
      if (csa->out_dpy != NULL) remove(csa->out_dpy);
      if (csa->out_sol != NULL) remove(csa->out_sol);
      if (csa->out_res != NULL) remove(csa->out_res);
      if (csa->out_bnds != NULL) remove(csa->out_bnds);
      if (csa->out_mps != NULL) remove(csa->out_mps);
      if (csa->out_freemps != NULL) remove(csa->out_freemps);
      if (csa->out_cpxlp != NULL) remove(csa->out_cpxlp);
      if (csa->out_pb != NULL) remove(csa->out_pb);
      if (csa->out_npb != NULL) remove(csa->out_npb);
      if (csa->log_file != NULL) remove(csa->log_file);
      /*--------------------------------------------------------------*/
      /* open log file, if required */
      if (csa->log_file != NULL)
      {  if (lib_open_log(csa->log_file))
         {  xprintf("Unable to create log file\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* read problem data from the input file */
      if (csa->in_file == NULL)
      {  xprintf("No input problem file specified; try %s --help\n",
            argv[0]);
         ret = EXIT_FAILURE;
         goto done;
      }
      if (csa->format == FMT_MPS_DECK)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->in_file);
         if (ret != 0)
err1:    {  xprintf("MPS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MPS_FILE)
      {  ret = glp_read_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->in_file);
         if (ret != 0) goto err1;
      }
      else if (csa->format == FMT_CPLEX_LP)
      {  ret = glp_read_lp(csa->prob, NULL, csa->in_file);
         if (ret != 0)
         {  xprintf("CPLEX LP file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      else if (csa->format == FMT_MATHPROG)
      {  int k;
         /* allocate the translator workspace */
         csa->tran = glp_mpl_alloc_wksp();
         /* read model section and optional data section */
         if (glp_mpl_read_model(csa->tran, csa->in_file, csa->ndf > 0))
err2:    {  xprintf("MathProg model processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         /* read optional data section(s), if necessary */
         for (k = 1; k <= csa->ndf; k++)
         {  if (glp_mpl_read_data(csa->tran, csa->in_data[k]))
               goto err2;
         }
         /* generate the model */
         if (glp_mpl_generate(csa->tran, csa->out_dpy)) goto err2;
         /* build the problem instance from the model */
         glp_mpl_build_prob(csa->tran, csa->prob);
      }
      else if (csa->format == FMT_MIN_COST)
      {  csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_mincost(csa->graph, offsetof(v_data, rhs),
            offsetof(a_data, low), offsetof(a_data, cap),
            offsetof(a_data, cost), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_mincost_lp(csa->prob, csa->graph, GLP_ON,
            offsetof(v_data, rhs), offsetof(a_data, low),
            offsetof(a_data, cap), offsetof(a_data, cost));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else if (csa->format == FMT_MAX_FLOW)
      {  int s, t;
         csa->graph = glp_create_graph(sizeof(v_data), sizeof(a_data));
         ret = glp_read_maxflow(csa->graph, &s, &t,
            offsetof(a_data, cap), csa->in_file);
         if (ret != 0)
         {  xprintf("DIMACS file processing error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         glp_maxflow_lp(csa->prob, csa->graph, GLP_ON, s, t,
            offsetof(a_data, cap));
         glp_set_prob_name(csa->prob, csa->in_file);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* change problem name, if required */
      if (csa->new_name != NULL)
         glp_set_prob_name(csa->prob, csa->new_name);
      /* change optimization direction, if required */
      if (csa->dir != 0)
         glp_set_obj_dir(csa->prob, csa->dir);
      /* order rows and columns of the constraint matrix */
      lpx_order_matrix(csa->prob);
      /*--------------------------------------------------------------*/
      /* write problem data in fixed MPS format, if required */
      if (csa->out_mps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_DECK, NULL,
            csa->out_mps);
         if (ret != 0)
         {  xprintf("Unable to write problem in fixed MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in free MPS format, if required */
      if (csa->out_freemps != NULL)
      {  ret = glp_write_mps(csa->prob, GLP_MPS_FILE, NULL,
            csa->out_freemps);
         if (ret != 0)
         {  xprintf("Unable to write problem in free MPS format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in CPLEX LP format, if required */
      if (csa->out_cpxlp != NULL)
      {  ret = glp_write_lp(csa->prob, NULL, csa->out_cpxlp);
         if (ret != 0)
         {  xprintf("Unable to write problem in CPLEX LP format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in OPB format, if required */
      if (csa->out_pb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_pb, 0, 0);
         if (ret != 0)
         {  xprintf("Unable to write problem in OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem data in normalized OPB format, if required */
      if (csa->out_npb != NULL)
      {  ret = lpx_write_pb(csa->prob, csa->out_npb, 1, 1);
         if (ret != 0)
         {  xprintf(
               "Unable to write problem in normalized OPB format\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* if only problem data check is required, skip computations */
      if (csa->check)
      {  ret = EXIT_SUCCESS;
         goto done;
      }
      /*--------------------------------------------------------------*/
      /* determine the solution type */
      if (!csa->nomip &&
          glp_get_num_int(csa->prob) + glp_get_num_bin(csa->prob) > 0)
      {  if (csa->solution == SOL_INTERIOR)
         {  xprintf("Interior-point method is not able to solve MIP pro"
               "blem; use --simplex\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         csa->solution = SOL_INTEGER;
      }
      /*--------------------------------------------------------------*/
      /* if solution is provided, read it and skip computations */
      if (csa->in_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_read_sol(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_read_ipt(csa->prob, csa->in_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_read_mip(csa->prob, csa->in_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to read problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
         goto skip;
      }
      /*--------------------------------------------------------------*/
      /* scale the problem data, if required */
      if (csa->scale)
      {  if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
             csa->solution == SOL_INTERIOR ||
             csa->solution == SOL_INTEGER && !csa->iocp.presolve)
            glp_scale_prob(csa->prob, GLP_SF_AUTO);
      }
      /* construct starting LP basis */
      if (csa->solution == SOL_BASIC && !csa->smcp.presolve ||
          csa->solution == SOL_INTEGER && !csa->iocp.presolve)
      {  if (csa->crash == USE_STD_BASIS)
            glp_std_basis(csa->prob);
         else if (csa->crash == USE_ADV_BASIS)
            glp_adv_basis(csa->prob, 0);
         else if (csa->crash == USE_CPX_BASIS)
            glp_cpx_basis(csa->prob);
         else
            xassert(csa != csa);
      }
      /*--------------------------------------------------------------*/
      /* solve the problem */
      start = xtime();
      if (csa->solution == SOL_BASIC)
      {  if (!csa->exact)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
            if (csa->xcheck)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
                  xprintf("If you need to check final basis for non-opt"
                     "imal solution, use --nopresol\n");
               else
                  glp_exact(csa->prob, &csa->smcp);
            }
            if (csa->out_sol != NULL || csa->out_res != NULL)
            {  if (csa->smcp.presolve &&
                   glp_get_status(csa->prob) != GLP_OPT)
               xprintf("If you need actual output for non-optimal solut"
                  "ion, use --nopresol\n");
            }
         }
         else
            glp_exact(csa->prob, &csa->smcp);
      }
      else if (csa->solution == SOL_INTERIOR)
         glp_interior(csa->prob, NULL);
      else if (csa->solution == SOL_INTEGER)
      {  if (!csa->iocp.presolve)
         {  glp_set_bfcp(csa->prob, &csa->bfcp);
            glp_simplex(csa->prob, &csa->smcp);
         }
         glp_intopt(csa->prob, &csa->iocp);
      }
      else
         xassert(csa != csa);
      /*--------------------------------------------------------------*/
      /* display statistics */
      xprintf("Time used:   %.1f secs\n", xdifftime(xtime(), start));
      {  xlong_t tpeak;
         char buf[50];
         lib_mem_usage(NULL, NULL, NULL, &tpeak);
         xprintf("Memory used: %.1f Mb (%s bytes)\n",
            xltod(tpeak) / 1048576.0, xltoa(tpeak, buf));
      }
      /*--------------------------------------------------------------*/
skip: /* postsolve the model, if necessary */
      if (csa->tran != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_SOL);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_IPT);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_mpl_postsolve(csa->tran, csa->prob, GLP_MIP);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Model postsolving error\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /*--------------------------------------------------------------*/
      /* write problem solution in printable format, if required */
      if (csa->out_sol != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = lpx_print_sol(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTERIOR)
            ret = lpx_print_ips(csa->prob, csa->out_sol);
         else if (csa->solution == SOL_INTEGER)
            ret = lpx_print_mip(csa->prob, csa->out_sol);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write problem solution in printable format, if required */
      if (csa->out_res != NULL)
      {  if (csa->solution == SOL_BASIC)
            ret = glp_write_sol(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTERIOR)
            ret = glp_write_ipt(csa->prob, csa->out_res);
         else if (csa->solution == SOL_INTEGER)
            ret = glp_write_mip(csa->prob, csa->out_res);
         else
            xassert(csa != csa);
         if (ret != 0)
         {  xprintf("Unable to write problem solution\n");
            ret = EXIT_FAILURE;
            goto done;
         }
      }
      /* write sensitivity bounds information, if required */
      if (csa->out_bnds != NULL)
      {  if (csa->solution == SOL_BASIC)
         {  ret = lpx_print_sens_bnds(csa->prob, csa->out_bnds);
            if (ret != 0)
            {  xprintf("Unable to write sensitivity bounds information "
                  "\n");
               ret = EXIT_FAILURE;
               goto done;
            }
         }
         else
            xprintf("Cannot write sensitivity bounds information for in"
               "terior-point or MIP solution\n");
      }
      /*--------------------------------------------------------------*/
      /* all seems to be ok */
      ret = EXIT_SUCCESS;
      /*--------------------------------------------------------------*/
done: /* delete the LP/MIP problem object */
      if (csa->prob != NULL)
         glp_delete_prob(csa->prob);
      /* free the translator workspace, if necessary */
      if (csa->tran != NULL)
         glp_mpl_free_wksp(csa->tran);
      /* delete the network problem object, if necessary */
      if (csa->graph != NULL)
         glp_delete_graph(csa->graph);
      xassert(gmp_pool_count() == 0);
      gmp_free_mem();
      /* close log file, if necessary */
      if (csa->log_file != NULL) lib_close_log();
      /* check that no memory blocks are still allocated */
      {  int count;
         xlong_t total;
         lib_mem_usage(&count, NULL, &total, NULL);
         if (count != 0)
            xerror("Error: %d memory block(s) were lost\n", count);
         xassert(count == 0);
         xassert(total.lo == 0 && total.hi == 0);
      }
      /* free the library environment */
      lib_free_env();
      /* return to the control program */
      return ret;
}
Ejemplo n.º 11
0
Archivo: lp.c Proyecto: kleptog/pyglpk
static PyObject* LPX_solver_integer(LPXObject *self, PyObject *args,
				    PyObject *keywds) {
#if GLPK_VERSION(4, 20)
  PyObject *callback=NULL;
  struct mip_callback_object*info=NULL;
  glp_iocp cp;
  glp_init_iocp(&cp);
  cp.msg_lev = GLP_MSG_OFF;
  // Map the keyword arguments to the appropriate entries.
  static char *kwlist[] = 
    {"msg_lev", "br_tech", "bt_tech",
#if GLPK_VERSION(4, 21)
     "pp_tech",
#endif // GLPK_VERSION(4, 21)
#if GLPK_VERSION(4, 24)
     "gmi_cuts",
#endif // GLPK_VERSION(4, 24)
#if GLPK_VERSION(4, 23)
     "mir_cuts",
     "mip_gap",
#endif // GLPK_VERSION(4, 23)
#if GLPK_VERSION(4, 32)
     "cov_cuts", "clq_cuts", "presolve", "binarize",
#endif // GLPK_VERSION(4, 32)
#if GLPK_VERSION(4, 37)
     "fp_heur",
#endif // GLPK_VERSION(4, 37)
     "tol_int", "tol_obj", "tm_lim", "out_frq", "out_dly", 
     "callback", //"cb_info", "cb_size",
     NULL};
  if (!PyArg_ParseTupleAndKeywords
      (args, keywds, "|iii"
#if GLPK_VERSION(4, 21)
       "i"
#endif // GLPK_VERSION(4, 21)
#if GLPK_VERSION(4, 24)
       "i"
#endif // GLPK_VERSION(4, 24)
#if GLPK_VERSION(4, 23)
       "ii"
#endif // GLPK_VERSION(4, 23)
#if GLPK_VERSION(4, 32)
       "iiii"
#endif // GLPK_VERSION(4, 32)
#if GLPK_VERSION(4, 37)
       "i"
#endif // GLPK_VERSION(4, 37)
       "ddiiiO", kwlist, &cp.msg_lev, &cp.br_tech, &cp.bt_tech,
#if GLPK_VERSION(4, 21)
       &cp.pp_tech,
#endif // GLPK_VERSION(4, 21)
#if GLPK_VERSION(4, 24)
       &cp.gmi_cuts,
#endif // GLPK_VERSION(4, 24)
#if GLPK_VERSION(4, 23)
       &cp.mir_cuts,
       &cp.mip_gap,
#endif // GLPK_VERSION(4, 23)
#if GLPK_VERSION(4, 32)
       &cp.cov_cuts, &cp.clq_cuts, &cp.presolve, &cp.binarize,
#endif // GLPK_VERSION(4, 32)
#if GLPK_VERSION(4, 37)
       &cp.fp_heur,
#endif // GLPK_VERSION(4, 37)
       &cp.tol_int, &cp.tol_obj, &cp.tm_lim, &cp.out_frq, &cp.out_dly,
       &callback)) {
    return NULL;
  }
#if GLPK_VERSION(4, 24)
  cp.gmi_cuts = cp.gmi_cuts ? GLP_ON : GLP_OFF;
#endif // GLPK_VERSION(4, 24)
#if GLPK_VERSION(4, 23)
  cp.mir_cuts = cp.mir_cuts ? GLP_ON : GLP_OFF;
#endif // GLPK_VERSION(4, 23)
#if GLPK_VERSION(4, 32)
  cp.cov_cuts = cp.cov_cuts ? GLP_ON : GLP_OFF;
  cp.clq_cuts = cp.clq_cuts ? GLP_ON : GLP_OFF;
  cp.presolve = cp.presolve ? GLP_ON : GLP_OFF;
  cp.binarize = cp.binarize ? GLP_ON : GLP_OFF;
#endif // GLPK_VERSION(4, 32)
#if GLPK_VERSION(4, 37)
  cp.fp_heur = cp.fp_heur ? GLP_ON : GLP_OFF;
#endif // GLPK_VERSION(4, 32)

  // Do checking on the various entries.
#if GLPK_VERSION(4, 32)
  if (!cp.presolve && glp_get_status(LP) != GLP_OPT) {
    PyErr_SetString(PyExc_RuntimeError, "integer solver requires "
                    "use of presolver or existing optimal basic solution");
    return NULL;
  }
#else
  if (glp_get_status(LP) != GLP_OPT) {
    PyErr_SetString(PyExc_RuntimeError, "integer solver requires "
		    "existing optimal basic solution");
    return NULL;
  }
#endif
  switch (cp.msg_lev) {
  case GLP_MSG_OFF: case GLP_MSG_ERR: case GLP_MSG_ON: case GLP_MSG_ALL: break;
  default:
    PyErr_SetString
      (PyExc_ValueError,
       "invalid value for msg_lev (LPX.MSG_* are valid values)");
    return NULL;
  }
  switch (cp.br_tech) {
  case GLP_BR_FFV: case GLP_BR_LFV: case GLP_BR_MFV: case GLP_BR_DTH: break;
  default:
    PyErr_SetString
      (PyExc_ValueError,
       "invalid value for br_tech (LPX.BR_* are valid values)");
    return NULL;
  }
  switch (cp.bt_tech) {
  case GLP_BT_DFS: case GLP_BT_BFS: case GLP_BT_BLB: case GLP_BT_BPH: break;
  default:
    PyErr_SetString
      (PyExc_ValueError,
       "invalid value for bt_tech (LPX.BT_* are valid values)");
    return NULL;
  }
#if GLPK_VERSION(4, 21)
  switch (cp.pp_tech) {
  case GLP_PP_NONE: case GLP_PP_ROOT: case GLP_PP_ALL: break;
  default:
    PyErr_SetString
      (PyExc_ValueError,
       "invalid value for pp_tech (LPX.PP_* are valid values)");
    return NULL;
  }
#endif // GLPK_VERSION(4, 21)
  if (cp.tol_int<=0 || cp.tol_int>=1) {
    PyErr_SetString(PyExc_ValueError, "tol_int must obey 0<tol_int<1");
    return NULL;
  }
  if (cp.tol_obj<=0 || cp.tol_obj>=1) {
    PyErr_SetString(PyExc_ValueError, "tol_obj must obey 0<tol_obj<1");
    return NULL;
  }
  if (cp.tm_lim<0) {
    PyErr_SetString(PyExc_ValueError, "tm_lim must be non-negative");
    return NULL;
  }
  if (cp.out_frq<=0) {
    PyErr_SetString(PyExc_ValueError, "out_frq must be positive");
    return NULL;
  }
  if (cp.out_dly<0) {
    PyErr_SetString(PyExc_ValueError, "out_dly must be non-negative");
    return NULL;
  }
#if GLPK_VERSION(4, 23)
  if (cp.mip_gap<0) {
    PyErr_SetString(PyExc_ValueError, "mip_gap must be non-negative");
    return NULL;
  }
#endif
  int retval;
  if (callback != NULL && callback != Py_None) {
    info = (struct mip_callback_object*)
      malloc(sizeof(struct mip_callback_object));
    info->callback = callback;
    info->py_lp = self;
    cp.cb_info = info;
    cp.cb_func = mip_callback;
  }
  retval = glp_intopt(LP, &cp);
  if (info) free(info);
  if (PyErr_Occurred()) {
    // This should happen only if there was a problem within the
    // callback function, or if the callback was not appropriate.
    return NULL;
  }
  if (retval!=GLP_EBADB && retval!=GLP_ESING && retval!=GLP_ECOND
      && retval!=GLP_EBOUND && retval!=GLP_EFAIL)
    self->last_solver = 2;
  return glpsolver_retval_to_message(retval);
#else
  int retval = lpx_integer(LP);
  if (retval!=LPX_E_FAULT) self->last_solver = 2;
  return solver_retval_to_message(retval);
#endif // GLPK_VERSION(4, 20)
}
Ejemplo n.º 12
0
static int solve_mip(LPX *lp, int presolve)
{     glp_iocp parm;
      int ret;
      glp_init_iocp(&parm);
      switch (lpx_get_int_parm(lp, LPX_K_MSGLEV))
      {  case 0:  parm.msg_lev = GLP_MSG_OFF;   break;
         case 1:  parm.msg_lev = GLP_MSG_ERR;   break;
         case 2:  parm.msg_lev = GLP_MSG_ON;    break;
         case 3:  parm.msg_lev = GLP_MSG_ALL;   break;
         default: xassert(lp != lp);
      }
      switch (lpx_get_int_parm(lp, LPX_K_BRANCH))
      {  case 0:  parm.br_tech = GLP_BR_FFV;    break;
         case 1:  parm.br_tech = GLP_BR_LFV;    break;
         case 2:  parm.br_tech = GLP_BR_DTH;    break;
         case 3:  parm.br_tech = GLP_BR_MFV;    break;
         default: xassert(lp != lp);
      }
      switch (lpx_get_int_parm(lp, LPX_K_BTRACK))
      {  case 0:  parm.bt_tech = GLP_BT_DFS;    break;
         case 1:  parm.bt_tech = GLP_BT_BFS;    break;
         case 2:  parm.bt_tech = GLP_BT_BPH;    break;
         case 3:  parm.bt_tech = GLP_BT_BLB;    break;
         default: xassert(lp != lp);
      }
      parm.tol_int = lpx_get_real_parm(lp, LPX_K_TOLINT);
      parm.tol_obj = lpx_get_real_parm(lp, LPX_K_TOLOBJ);
      if (lpx_get_real_parm(lp, LPX_K_TMLIM) < 0.0 ||
          lpx_get_real_parm(lp, LPX_K_TMLIM) > 1e6)
         parm.tm_lim = INT_MAX;
      else
         parm.tm_lim =
            (int)(1000.0 * lpx_get_real_parm(lp, LPX_K_TMLIM));
      parm.mip_gap = lpx_get_real_parm(lp, LPX_K_MIPGAP);
      if (lpx_get_int_parm(lp, LPX_K_USECUTS) & LPX_C_GOMORY)
         parm.gmi_cuts = GLP_ON;
      else
         parm.gmi_cuts = GLP_OFF;
      if (lpx_get_int_parm(lp, LPX_K_USECUTS) & LPX_C_MIR)
         parm.mir_cuts = GLP_ON;
      else
         parm.mir_cuts = GLP_OFF;
      if (lpx_get_int_parm(lp, LPX_K_USECUTS) & LPX_C_COVER)
         parm.cov_cuts = GLP_ON;
      else
         parm.cov_cuts = GLP_OFF;
      if (lpx_get_int_parm(lp, LPX_K_USECUTS) & LPX_C_CLIQUE)
         parm.clq_cuts = GLP_ON;
      else
         parm.clq_cuts = GLP_OFF;
      parm.presolve = presolve;
      if (lpx_get_int_parm(lp, LPX_K_BINARIZE))
         parm.binarize = GLP_ON;
      ret = glp_intopt(lp, &parm);
      switch (ret)
      {  case 0:           ret = LPX_E_OK;      break;
         case GLP_ENOPFS:  ret = LPX_E_NOPFS;   break;
         case GLP_ENODFS:  ret = LPX_E_NODFS;   break;
         case GLP_EBOUND:
         case GLP_EROOT:   ret = LPX_E_FAULT;   break;
         case GLP_EFAIL:   ret = LPX_E_SING;    break;
         case GLP_EMIPGAP: ret = LPX_E_MIPGAP;  break;
         case GLP_ETMLIM:  ret = LPX_E_TMLIM;   break;
         default:          xassert(ret != ret);
      }
      return ret;
}
Ejemplo n.º 13
0
Archivo: glpk.c Proyecto: ugonj/cvxopt
static PyObject *integer(PyObject *self, PyObject *args,
    PyObject *kwrds)
{
    matrix *c, *h, *b=NULL, *x=NULL;
    PyObject *G, *A=NULL, *IntSet=NULL, *BinSet = NULL;
    PyObject *t=NULL;
    pyiocp *iocpParm = NULL;;
    glp_iocp *options = NULL;
    glp_prob *lp;
    int m, n, p, i, j, k, nnz, nnzmax, *rn=NULL, *cn=NULL;
    double *a=NULL, val;
    char *kwlist[] = {"c", "G", "h", "A", "b", "I", "B","iocp", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "OOO|OOOOO!", kwlist, &c,
	    &G, &h, &A, &b, &IntSet, &BinSet,iocp_t,&iocpParm)) return NULL;

    if(!iocpParm) 
    {
      iocpParm = (pyiocp*)malloc(sizeof(*iocpParm));
      glp_init_iocp(&(iocpParm->obj));
    }
    if(iocpParm) 
    {
      Py_INCREF(iocpParm);
      options = &iocpParm->obj;
      options->presolve = 1;
    }

    if ((Matrix_Check(G) && MAT_ID(G) != DOUBLE) ||
        (SpMatrix_Check(G) && SP_ID(G) != DOUBLE) ||
        (!Matrix_Check(G) && !SpMatrix_Check(G))){
        PyErr_SetString(PyExc_TypeError, "G must be a 'd' matrix");
        return NULL;
    }
    if ((m = Matrix_Check(G) ? MAT_NROWS(G) : SP_NROWS(G)) <= 0)
        err_p_int("m");
    if ((n = Matrix_Check(G) ? MAT_NCOLS(G) : SP_NCOLS(G)) <= 0)
        err_p_int("n");

    if (!Matrix_Check(h) || h->id != DOUBLE) err_dbl_mtrx("h");
    if (h->nrows != m || h->ncols != 1){
        PyErr_SetString(PyExc_ValueError, "incompatible dimensions");
        return NULL;
    }

    if (A){
        if ((Matrix_Check(A) && MAT_ID(A) != DOUBLE) ||
            (SpMatrix_Check(A) && SP_ID(A) != DOUBLE) ||
            (!Matrix_Check(A) && !SpMatrix_Check(A))){
                PyErr_SetString(PyExc_ValueError, "A must be a dense "
                    "'d' matrix or a general sparse matrix");
                return NULL;
	}
        if ((p = Matrix_Check(A) ? MAT_NROWS(A) : SP_NROWS(A)) < 0)
            err_p_int("p");
        if ((Matrix_Check(A) ? MAT_NCOLS(A) : SP_NCOLS(A)) != n){
            PyErr_SetString(PyExc_ValueError, "incompatible "
                "dimensions");
            return NULL;
	}
    }
    else p = 0;

    if (b && (!Matrix_Check(b) || b->id != DOUBLE)) err_dbl_mtrx("b");
    if ((b && (b->nrows != p || b->ncols != 1)) || (!b && p !=0 )){
        PyErr_SetString(PyExc_ValueError, "incompatible dimensions");
        return NULL;
    }

    if ((IntSet) && (!PyAnySet_Check(IntSet)))
      PY_ERR_TYPE("invalid integer index set");

    if ((BinSet) && (!PyAnySet_Check(BinSet)))
      PY_ERR_TYPE("invalid binary index set");

    lp = glp_create_prob();
    glp_add_rows(lp, m+p);
    glp_add_cols(lp, n);

    for (i=0; i<n; i++){
        glp_set_obj_coef(lp, i+1, MAT_BUFD(c)[i]);
        glp_set_col_bnds(lp, i+1, GLP_FR, 0.0, 0.0);
    }
    for (i=0; i<m; i++)
        glp_set_row_bnds(lp, i+1, GLP_UP, 0.0, MAT_BUFD(h)[i]);
    for (i=0; i<p; i++)
        glp_set_row_bnds(lp, i+m+1, GLP_FX, MAT_BUFD(b)[i],
            MAT_BUFD(b)[i]);

    nnzmax = (SpMatrix_Check(G) ? SP_NNZ(G) : m*n ) +
        ((A && SpMatrix_Check(A)) ? SP_NNZ(A) : p*n);
    a = (double *) calloc(nnzmax+1, sizeof(double));
    rn = (int *) calloc(nnzmax+1, sizeof(int));
    cn = (int *) calloc(nnzmax+1, sizeof(int));
    if (!a || !rn || !cn){
        free(a);  free(rn);  free(cn);  glp_delete_prob(lp);
        return PyErr_NoMemory();
    }

    nnz = 0;
    if (SpMatrix_Check(G)) {
        for (j=0; j<n; j++) for (k=SP_COL(G)[j]; k<SP_COL(G)[j+1]; k++)
            if ((val = SP_VALD(G)[k]) != 0.0){
                a[1+nnz] = val;
                rn[1+nnz] = SP_ROW(G)[k]+1;
                cn[1+nnz] = j+1;
                nnz++;
            }
    }
    else for (j=0; j<n; j++) for (i=0; i<m; i++)
        if ((val = MAT_BUFD(G)[i+j*m]) != 0.0){
            a[1+nnz] = val;
            rn[1+nnz] = i+1;
            cn[1+nnz] = j+1;
            nnz++;
        }

    if (A && SpMatrix_Check(A)){
        for (j=0; j<n; j++) for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1]; k++)
            if ((val = SP_VALD(A)[k]) != 0.0){
                a[1+nnz] = val;
                rn[1+nnz] = m+SP_ROW(A)[k]+1;
                cn[1+nnz] = j+1;
                nnz++;
            }
    }
    else for (j=0; j<n; j++) for (i=0; i<p; i++)
        if ((val = MAT_BUFD(A)[i+j*p]) != 0.0){
            a[1+nnz] = val;
            rn[1+nnz] = m+i+1;
            cn[1+nnz] = j+1;
            nnz++;
        }

    glp_load_matrix(lp, nnz, rn, cn, a);
    free(rn);  free(cn);  free(a);

    if (!(t = PyTuple_New(2))) {
        glp_delete_prob(lp);
        return PyErr_NoMemory();
    }

    if (IntSet) {
      PyObject *iter = PySequence_Fast(IntSet, "Critical error: not sequence");

      for (i=0; i<PySet_GET_SIZE(IntSet); i++) {

	PyObject *tmp = PySequence_Fast_GET_ITEM(iter, i);
#if PY_MAJOR_VERSION >= 3
	if (!PyLong_Check(tmp)) {
#else
	if (!PyInt_Check(tmp)) {
#endif
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR_TYPE("non-integer element in I");
	}
#if PY_MAJOR_VERSION >= 3
	int k = PyLong_AS_LONG(tmp);
#else
	int k = PyInt_AS_LONG(tmp);
#endif
	if ((k < 0) || (k >= n)) {
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR(PyExc_IndexError, "index element out of range in I");
	}
	glp_set_col_kind(lp, k+1, GLP_IV);
      }

      Py_DECREF(iter);
    }

    if (BinSet) {
      PyObject *iter = PySequence_Fast(BinSet, "Critical error: not sequence");

      for (i=0; i<PySet_GET_SIZE(BinSet); i++) {

	PyObject *tmp = PySequence_Fast_GET_ITEM(iter, i);
#if PY_MAJOR_VERSION >= 3
	if (!PyLong_Check(tmp)) {
#else
	if (!PyInt_Check(tmp)) {
#endif
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR_TYPE("non-binary element in I");
	}
#if PY_MAJOR_VERSION >= 3
	int k = PyLong_AS_LONG(tmp);
#else
	int k = PyInt_AS_LONG(tmp);
#endif
	if ((k < 0) || (k >= n)) {
	  glp_delete_prob(lp);
	  Py_DECREF(iter);
	  PY_ERR(PyExc_IndexError, "index element out of range in B");
	}
	glp_set_col_kind(lp, k+1, GLP_BV);
      }

      Py_DECREF(iter);

    }


      switch (glp_intopt(lp,options)){

          case 0:

              x = (matrix *) Matrix_New(n,1,DOUBLE);
              if (!x) {
                  Py_XDECREF(iocpParm);
                  Py_XDECREF(t);
                  glp_delete_prob(lp);
                  return PyErr_NoMemory();
              }
              set_output_string(t,"optimal");
              set_output_string(t,"optimal");

              for (i=0; i<n; i++)
                  MAT_BUFD(x)[i] = glp_mip_col_val(lp, i+1);
              PyTuple_SET_ITEM(t, 1, (PyObject *) x);

              Py_XDECREF(iocpParm);
              glp_delete_prob(lp);
              return (PyObject *) t;

          case GLP_ETMLIM:

              x = (matrix *) Matrix_New(n,1,DOUBLE);
              if (!x) {
                  Py_XDECREF(t);
                  Py_XDECREF(iocpParm);
                  glp_delete_prob(lp);
                  return PyErr_NoMemory();
              }
              set_output_string(t,"time limit exceeded");

              for (i=0; i<n; i++)
                  MAT_BUFD(x)[i] = glp_mip_col_val(lp, i+1);
              PyTuple_SET_ITEM(t, 1, (PyObject *) x);

              Py_XDECREF(iocpParm);
              glp_delete_prob(lp);
              return (PyObject *) t;


          case GLP_EBOUND:
              set_output_string(t,"incorrect bounds");
              break;
          case GLP_EFAIL:
              set_output_string(t,"invalid MIP formulation");
              break;

          case GLP_ENOPFS:
              set_output_string(t,"primal infeasible");
              break;

          case GLP_ENODFS:
              set_output_string(t,"dual infeasible");
              break;

          case GLP_EMIPGAP:
              set_output_string(t,"Relative mip gap tolerance reached");
              break;

              /*case LPX_E_ITLIM:

                set_output_string(t,"maxiters exceeded");
                break;*/

              /*case LPX_E_SING:

                set_output_string(t,"singular or ill-conditioned basis");
                break;*/


          default:

              set_output_string(t,"unknown");
      }

      Py_XDECREF(iocpParm);
    glp_delete_prob(lp);

    PyTuple_SET_ITEM(t, 1, Py_BuildValue(""));
    return (PyObject *) t;
}


static PyMethodDef glpk_functions[] = {
    {"lp", (PyCFunction) simplex, METH_VARARGS|METH_KEYWORDS,
        doc_simplex},
    {"ilp", (PyCFunction) integer, METH_VARARGS|METH_KEYWORDS,
        doc_integer},
    {NULL}  /* Sentinel */
};

#if PY_MAJOR_VERSION >= 3

static PyModuleDef glpk_module_def = {
    PyModuleDef_HEAD_INIT,
    "glpk",
    glpk__doc__,
    -1,
    glpk_functions,
    NULL, NULL, NULL, NULL
};

void addglpkConstants (void)
{
  PyModule_AddIntMacro(glpk_module, GLP_ON);
  PyModule_AddIntMacro(glpk_module,GLP_OFF);

  /* reason codes: */
  PyModule_AddIntMacro(glpk_module,GLP_IROWGEN);
  PyModule_AddIntMacro(glpk_module,GLP_IBINGO);
  PyModule_AddIntMacro(glpk_module,GLP_IHEUR);
  PyModule_AddIntMacro(glpk_module,GLP_ICUTGEN);
  PyModule_AddIntMacro(glpk_module,GLP_IBRANCH);
  PyModule_AddIntMacro(glpk_module,GLP_ISELECT);
  PyModule_AddIntMacro(glpk_module,GLP_IPREPRO);

  /* branch selection indicator: */
  PyModule_AddIntMacro(glpk_module,GLP_NO_BRNCH);
  PyModule_AddIntMacro(glpk_module,GLP_DN_BRNCH);
  PyModule_AddIntMacro(glpk_module,GLP_UP_BRNCH);

  /* return codes: */
  PyModule_AddIntMacro(glpk_module,GLP_EBADB);
  PyModule_AddIntMacro(glpk_module,GLP_ESING);
  PyModule_AddIntMacro(glpk_module,GLP_ECOND);
  PyModule_AddIntMacro(glpk_module,GLP_EBOUND);
  PyModule_AddIntMacro(glpk_module,GLP_EFAIL);
  PyModule_AddIntMacro(glpk_module,GLP_EOBJLL);
  PyModule_AddIntMacro(glpk_module,GLP_EOBJUL);
  PyModule_AddIntMacro(glpk_module,GLP_EITLIM);
  PyModule_AddIntMacro(glpk_module,GLP_ETMLIM);
  PyModule_AddIntMacro(glpk_module,GLP_ENOPFS);
  PyModule_AddIntMacro(glpk_module,GLP_ENODFS);
  PyModule_AddIntMacro(glpk_module,GLP_EROOT);
  PyModule_AddIntMacro(glpk_module,GLP_ESTOP);
  PyModule_AddIntMacro(glpk_module,GLP_EMIPGAP);
  PyModule_AddIntMacro(glpk_module,GLP_ENOFEAS);
  PyModule_AddIntMacro(glpk_module,GLP_ENOCVG);
  PyModule_AddIntMacro(glpk_module,GLP_EINSTAB);
  PyModule_AddIntMacro(glpk_module,GLP_EDATA);
  PyModule_AddIntMacro(glpk_module,GLP_ERANGE);

  /* condition indicator: */
  PyModule_AddIntMacro(glpk_module,GLP_KKT_PE);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_PB);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_DE);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_DB);
  PyModule_AddIntMacro(glpk_module,GLP_KKT_CS);

  /* MPS file format: */
  PyModule_AddIntMacro(glpk_module,GLP_MPS_DECK);
  PyModule_AddIntMacro(glpk_module,GLP_MPS_FILE);

  /* simplex method control parameters */
  /* message level: */
  PyModule_AddIntMacro(glpk_module,GLP_MSG_OFF);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_ERR);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_ON);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_ALL);
  PyModule_AddIntMacro(glpk_module,GLP_MSG_DBG);
  /* simplex method option: */
  PyModule_AddIntMacro(glpk_module,GLP_PRIMAL);
  PyModule_AddIntMacro(glpk_module,GLP_DUALP);
  PyModule_AddIntMacro(glpk_module,GLP_DUAL);
  /* pricing technique: */
  PyModule_AddIntMacro(glpk_module,GLP_PT_STD);
  PyModule_AddIntMacro(glpk_module,GLP_PT_PSE);
  /* ratio test technique: */
  PyModule_AddIntMacro(glpk_module,GLP_RT_STD);
  PyModule_AddIntMacro(glpk_module,GLP_RT_HAR);

  /* interior-point solver control parameters */
  /* ordering algorithm: */
  PyModule_AddIntMacro(glpk_module,GLP_ORD_NONE);
  PyModule_AddIntMacro(glpk_module,GLP_ORD_QMD);
  PyModule_AddIntMacro(glpk_module,GLP_ORD_AMD);
  PyModule_AddIntMacro(glpk_module,GLP_ORD_SYMAMD);
}

PyMODINIT_FUNC PyInit_glpk(void)
{
  if (!(glpk_module = PyModule_Create(&glpk_module_def))) return NULL;
  if (PyType_Ready(&iocp_t) < 0 || (PyType_Ready(&smcp_t) < 0)) return NULL;
  /*  Adding macros */
  addglpkConstants();
  /* Adding  option lists as objects */
  Py_INCREF(&smcp_t);
  PyModule_AddObject(glpk_module,"smcp",(PyObject*)&smcp_t);
  Py_INCREF(&iocp_t);
  PyModule_AddObject(glpk_module,"iocp",(PyObject*)&iocp_t);
  if (import_cvxopt() < 0) return NULL;
  return glpk_module;
}

#else

PyMODINIT_FUNC initglpk(void)
{
    glpk_module = Py_InitModule3("cvxopt.glpk", glpk_functions, 
            glpk__doc__);
    if (PyType_Ready(&iocp_t) < 0 || (PyType_Ready(&smcp_t) < 0)) return NULL;
    addglpkConstants();
    Py_INCREF(&smcp_t);
    PyModule_AddObject(glpk_module,"smcp",(PyObject*)&smcp_t);
    Py_INCREF(&iocp_t);
    PyModule_AddObject(glpk_module,"iocp",(PyObject*)&iocp_t);
    if (import_cvxopt() < 0) return;
}
Ejemplo n.º 14
0
double solve_glp_grb(glp_prob *mip, wrapper_params *par){


	GLPK_out = par->glp_out;
	GRB_out = par->grb_out;
	double obj_val;



	/** GLPK: Generate Variable indexing **/
	glp_create_index(mip);

	/** GLPK: Generate LP **/
	glp_write_mps(mip, GLP_MPS_FILE, NULL, "tmp.mps");


	/************/
	/** GUROBI **/
	/************/

	retGRB = GRBloadenv(&env, NULL);
	if (retGRB || env == NULL)
	{
		fprintf(stderr, "Error: could not create environment\n");
		exit(1);
	}

	retGRB = GRBsetintparam(env, "OutputFlag", GRB_out?1:0);
	if (retGRB) freeMem();

	//retGRB = GRBsetintparam(env, "Sensitivity", 1);
	//if (retGRB) freeMem();

	/** GUROBI: Read model **/
	retGRB = GRBreadmodel(env, "tmp.mps", &model);
	if (retGRB) freeMem();

	/** Remove utility files from disk **/
	//remove("tmp.mps");

	/** GUROBI: Get environment **/
	mipenv = GRBgetenv(model);
	if (!mipenv) freeMem();

	/** GUROBI: Set parameters **/

	/** GUROBI: Ask for more precision **/
	retGRB = GRBsetdblparam(mipenv, "FeasibilityTol", 10E-6);
	if (retGRB) freeMem();
	retGRB = GRBsetdblparam(mipenv, "IntFeasTol", 10E-5);
	if (retGRB) freeMem();
	retGRB = GRBsetdblparam(mipenv, "MIPgap", 10E-6);
	if (retGRB) freeMem();

	/* * Playing with gurobi parameters and attr*/

	//gurobi_set_basis();
	retGRB = GRBsetintparam(mipenv, "Cuts", 3);
	if (retGRB) freeMem();

	retGRB = GRBsetintparam(mipenv, "RootMethod", 1);
	if (retGRB) freeMem();

	retGRB = GRBsetintparam(mipenv, "Symmetry", -1);
	if (retGRB) freeMem();

	

	/** GUROBI: get numvars and numrows **/
	retGRB = GRBgetintattr(model, "NumVars", &numvars);
	if (retGRB) freeMem();


	/** Test variable names */
	for(int j=0;j<numvars;j++){	
		retGRB = GRBgetstrattrelement(model, "VarName", j, &nameGRB);
		printf("GRB Var %d Name %s\n",j,nameGRB); 
	}
	/** GUROBI: get model type **/
	retGRB = GRBgetintattr(model, "IsMIP", &GRB_IsMIP);
	if (retGRB) freeMem();

	/** GUROBI: Optimize model **/
	retGRB = GRBoptimize(model);
	if (retGRB) freeMem();

	
	
	/** GUROBI: Retreive the optimization status **/
	GRBgetintattr(model, "Status", &retGRB);
	switch(retGRB){
	case GRB_OPTIMAL:
		break;
	case GRB_INFEASIBLE :
		fprintf(stderr, "Error GRB optimization failed with code GRB_INFEASIBLE\n");
	case GRB_INF_OR_UNBD :
		fprintf(stderr, "Error GRB optimization failed with code GRB_INF_OR_UNBD \n");
	case GRB_UNBOUNDED :
		fprintf(stderr, "Error GRB optimization failed with code GRB_UNBOUNDED \n");
	case GRB_CUTOFF :
		fprintf(stderr, "Error GRB optimization failed with code GRB_CUTOFF \n");
	case GRB_ITERATION_LIMIT :
		fprintf(stderr, "Error GRB optimization failed with code GRB_ITERATION_LIMIT \n");
	case GRB_NODE_LIMIT :
		fprintf(stderr, "Error GRB optimization failed with code GRB_NODE_LIMIT \n");
	case GRB_TIME_LIMIT :
		fprintf(stderr, "Error GRB optimization failed with code GRB_TIME_LIMIT \n");
	case GRB_SOLUTION_LIMIT :
		fprintf(stderr, "Error GRB optimization failed with code GRB_SOLUTION_LIMIT \n");
	case GRB_INTERRUPTED :
		fprintf(stderr, "Error GRB optimization failed with code GRB_INTERRUPTED \n");
	case GRB_SUBOPTIMAL :
		fprintf(stderr, "Error GRB optimization failed with code GRB_SUBOPTIMAL \n");
	case GRB_NUMERIC :
		fprintf(stderr, "Error GRB optimization failed with code GRB_NUMERIC \n");

		/** GUROBI: Quit in any case non optimal **/
		freeMem();
	}

	/** GUROBI: Get obj function value **/
	retGRB = GRBgetdblattr(model, "IntVio", &tmp);
	if (retGRB) freeMem();


	retGRB = GRBgetdblattr(model, "ObjBound", &bound);
	if (retGRB) freeMem();

	retGRB = GRBgetdblattr(model, "ObjVal", &tmp);
	if (retGRB) freeMem();

	/* ********************** */

	obj_val = tmp;


	/* ************ */
	if (verbose) printf ("Objective %lf\n", tmp);
	if (verbose) printf ("Best bound %lf\n", bound);
	if (verbose) printf ("Absolute gap %lf\n", fabs(tmp - bound));

	/** GUROBI: Get variable values **/
	for (j = 0; j < numvars; ++j){

		retGRB = GRBgetdblattrelement(model, "X", j, &tmp);
		if (retGRB) freeMem();

		retGRB = GRBgetstrattrelement(model, "VarName", j, &nameGRB);
		printf("GRB Var %d Name %s\n",j,nameGRB); 
		if (retGRB) freeMem();

		retGRB = GRBgetcharattrelement(model, "VType", j, &type);
		if (retGRB) freeMem();

		/** GLPK search variable index by name **/
		col_index = glp_find_col(mip, nameGRB);

		if (col_index != 0){
			/** GLPK set variable bounds **/
			if ((type == 'B') || (type == 'I')){
				if (verbose) printf ("Variable %s is of type %c value %lf fixed to %lf\n", nameGRB, type, tmp, round(tmp));
				glp_set_col_bnds(mip, col_index, GLP_FX, round(tmp), round(tmp));
			}
			else{
				if (verbose) printf ("Variable %s is of type %c value %lf fixed to %lf\n", nameGRB, type, tmp, tmp);
				glp_set_col_bnds(mip, col_index, GLP_FX, tmp, tmp);
			}
		}
	}

	if (GRB_IsMIP){

		/** GLPK initialize parameters **/
		iparm = (glp_iocp*) malloc(sizeof(glp_iocp));
		glp_init_iocp(iparm);
		iparm->presolve = GLP_ON;
		iparm->mip_gap = glpk_iparm_mip_gap;
		iparm->tol_int = glpk_iparm_tol_int;
		iparm->tol_obj = glpk_iparm_tol_obj;

		/** GLPK get the optimal integer solution **/
		ret = glp_intopt(mip, iparm);
		if (ret){
			fprintf(stderr, "glp_intopt, Error on optimizing the model : %d \n", ret);
			freeMem();
		}

		ret = glp_mip_status(mip);
		switch (ret){
		case GLP_OPT:
			break;
		case GLP_FEAS:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_FEAS, code %d\n", ret);
			freeMem();
		case GLP_NOFEAS:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_NOFEAS, code %d\n", ret);
			freeMem();
		case GLP_UNDEF:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_UNDEF, code %d\n", ret);
			freeMem();
		}
	}
	else{

		/*GLPK initialize parameters */
		parm = (glp_smcp*) malloc(sizeof(glp_smcp));
		glp_init_smcp(parm);
		parm->meth = GLP_DUALP;
		parm->tol_bnd = 10E-4;
		parm->tol_dj = 10E-4;

		/* GLPK get the optimal basis */
		//ret = glp_simplex(mip, parm);
		if (ret){
			fprintf(stderr, "glp_simplex, Error on optimizing the model : %d \n", ret);
			freeMem();
		}
		ret = glp_get_status(mip);
		switch (ret){
		case GLP_OPT:
			break;
		case GLP_FEAS:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_FEAS, code %d\n", ret);
			freeMem();
		case GLP_INFEAS:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_INFEAS, code %d\n", ret);
			freeMem();
		case GLP_NOFEAS:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_NOFEAS, code %d\n", ret);
			freeMem();
		case GLP_UNBND:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_UNBND, code %d\n", ret);
			freeMem();
		case GLP_UNDEF:
			fprintf(stderr, "Error GLPK simplex is not optimal, GLP_UNDEF, code %d\n", ret);
			freeMem();
		}


	}

	//GRBmodel *fmod = fixed_model(model);
	//gurobi_sens_output(fmod, "/tmp/sens.sol");
        GRBwrite(model, "/tmp/model.sol");






	/** GUROBI: free structures **/
	if (model) GRBfreemodel(model);
	if (env) GRBfreeenv(env);

	return obj_val;
}
Ejemplo n.º 15
0
int glp_intopt(glp_prob *P, const glp_iocp *parm)
{     /* solve MIP problem with the branch-and-bound method */
      glp_iocp _parm;
      int i, j, ret;
      /* check problem object */
      if (P == NULL || P->magic != GLP_PROB_MAGIC)
         xerror("glp_intopt: P = %p; invalid problem object\n", P);
      if (P->tree != NULL)
         xerror("glp_intopt: operation not allowed\n");
      /* check control parameters */
      if (parm == NULL)
         parm = &_parm, glp_init_iocp((glp_iocp *)parm);
      if (!(parm->msg_lev == GLP_MSG_OFF ||
            parm->msg_lev == GLP_MSG_ERR ||
            parm->msg_lev == GLP_MSG_ON  ||
            parm->msg_lev == GLP_MSG_ALL ||
            parm->msg_lev == GLP_MSG_DBG))
         xerror("glp_intopt: msg_lev = %d; invalid parameter\n",
            parm->msg_lev);
      if (!(parm->br_tech == GLP_BR_FFV ||
            parm->br_tech == GLP_BR_LFV ||
            parm->br_tech == GLP_BR_MFV ||
            parm->br_tech == GLP_BR_DTH ||
            parm->br_tech == GLP_BR_PCH))
         xerror("glp_intopt: br_tech = %d; invalid parameter\n",
            parm->br_tech);
      if (!(parm->bt_tech == GLP_BT_DFS ||
            parm->bt_tech == GLP_BT_BFS ||
            parm->bt_tech == GLP_BT_BLB ||
            parm->bt_tech == GLP_BT_BPH))
         xerror("glp_intopt: bt_tech = %d; invalid parameter\n",
            parm->bt_tech);
      if (!(0.0 < parm->tol_int && parm->tol_int < 1.0))
         xerror("glp_intopt: tol_int = %g; invalid parameter\n",
            parm->tol_int);
      if (!(0.0 < parm->tol_obj && parm->tol_obj < 1.0))
         xerror("glp_intopt: tol_obj = %g; invalid parameter\n",
            parm->tol_obj);
      if (parm->tm_lim < 0)
         xerror("glp_intopt: tm_lim = %d; invalid parameter\n",
            parm->tm_lim);
      if (parm->out_frq < 0)
         xerror("glp_intopt: out_frq = %d; invalid parameter\n",
            parm->out_frq);
      if (parm->out_dly < 0)
         xerror("glp_intopt: out_dly = %d; invalid parameter\n",
            parm->out_dly);
      if (!(0 <= parm->cb_size && parm->cb_size <= 256))
         xerror("glp_intopt: cb_size = %d; invalid parameter\n",
            parm->cb_size);
      if (!(parm->pp_tech == GLP_PP_NONE ||
            parm->pp_tech == GLP_PP_ROOT ||
            parm->pp_tech == GLP_PP_ALL))
         xerror("glp_intopt: pp_tech = %d; invalid parameter\n",
            parm->pp_tech);
      if (parm->mip_gap < 0.0)
         xerror("glp_intopt: mip_gap = %g; invalid parameter\n",
            parm->mip_gap);
      if (!(parm->mir_cuts == GLP_ON || parm->mir_cuts == GLP_OFF))
         xerror("glp_intopt: mir_cuts = %d; invalid parameter\n",
            parm->mir_cuts);
      if (!(parm->gmi_cuts == GLP_ON || parm->gmi_cuts == GLP_OFF))
         xerror("glp_intopt: gmi_cuts = %d; invalid parameter\n",
            parm->gmi_cuts);
      if (!(parm->cov_cuts == GLP_ON || parm->cov_cuts == GLP_OFF))
         xerror("glp_intopt: cov_cuts = %d; invalid parameter\n",
            parm->cov_cuts);
      if (!(parm->clq_cuts == GLP_ON || parm->clq_cuts == GLP_OFF))
         xerror("glp_intopt: clq_cuts = %d; invalid parameter\n",
            parm->clq_cuts);
      if (!(parm->presolve == GLP_ON || parm->presolve == GLP_OFF))
         xerror("glp_intopt: presolve = %d; invalid parameter\n",
            parm->presolve);
      if (!(parm->binarize == GLP_ON || parm->binarize == GLP_OFF))
         xerror("glp_intopt: binarize = %d; invalid parameter\n",
            parm->binarize);
      if (!(parm->fp_heur == GLP_ON || parm->fp_heur == GLP_OFF))
         xerror("glp_intopt: fp_heur = %d; invalid parameter\n",
            parm->fp_heur);
#if 1 /* 28/V-2010 */
      if (!(parm->alien == GLP_ON || parm->alien == GLP_OFF))
         xerror("glp_intopt: alien = %d; invalid parameter\n",
            parm->alien);
#endif
#if 0 /* 11/VII-2013 */
      /* integer solution is currently undefined */
      P->mip_stat = GLP_UNDEF;
      P->mip_obj = 0.0;
#else
      if (!parm->use_sol)
         P->mip_stat = GLP_UNDEF;
      if (P->mip_stat == GLP_NOFEAS)
         P->mip_stat = GLP_UNDEF;
      if (P->mip_stat == GLP_UNDEF)
         P->mip_obj = 0.0;
      else if (P->mip_stat == GLP_OPT)
         P->mip_stat = GLP_FEAS;
#endif
      /* check bounds of double-bounded variables */
      for (i = 1; i <= P->m; i++)
      {  GLPROW *row = P->row[i];
         if (row->type == GLP_DB && row->lb >= row->ub)
         {  if (parm->msg_lev >= GLP_MSG_ERR)
               xprintf("glp_intopt: row %d: lb = %g, ub = %g; incorrect"
                  " bounds\n", i, row->lb, row->ub);
            ret = GLP_EBOUND;
            goto done;
         }
      }
      for (j = 1; j <= P->n; j++)
      {  GLPCOL *col = P->col[j];
         if (col->type == GLP_DB && col->lb >= col->ub)
         {  if (parm->msg_lev >= GLP_MSG_ERR)
               xprintf("glp_intopt: column %d: lb = %g, ub = %g; incorr"
                  "ect bounds\n", j, col->lb, col->ub);
            ret = GLP_EBOUND;
            goto done;
         }
      }
      /* bounds of all integer variables must be integral */
      for (j = 1; j <= P->n; j++)
      {  GLPCOL *col = P->col[j];
         if (col->kind != GLP_IV) continue;
         if (col->type == GLP_LO || col->type == GLP_DB)
         {  if (col->lb != floor(col->lb))
            {  if (parm->msg_lev >= GLP_MSG_ERR)
                  xprintf("glp_intopt: integer column %d has non-intege"
                     "r lower bound %g\n", j, col->lb);
               ret = GLP_EBOUND;
               goto done;
            }
         }
         if (col->type == GLP_UP || col->type == GLP_DB)
         {  if (col->ub != floor(col->ub))
            {  if (parm->msg_lev >= GLP_MSG_ERR)
                  xprintf("glp_intopt: integer column %d has non-intege"
                     "r upper bound %g\n", j, col->ub);
               ret = GLP_EBOUND;
               goto done;
            }
         }
         if (col->type == GLP_FX)
         {  if (col->lb != floor(col->lb))
            {  if (parm->msg_lev >= GLP_MSG_ERR)
                  xprintf("glp_intopt: integer column %d has non-intege"
                     "r fixed value %g\n", j, col->lb);
               ret = GLP_EBOUND;
               goto done;
            }
         }
      }
      /* solve MIP problem */
      if (parm->msg_lev >= GLP_MSG_ALL)
      {  int ni = glp_get_num_int(P);
         int nb = glp_get_num_bin(P);
         char s[50];
         xprintf("GLPK Integer Optimizer, v%s\n", glp_version());
         xprintf("%d row%s, %d column%s, %d non-zero%s\n",
            P->m, P->m == 1 ? "" : "s", P->n, P->n == 1 ? "" : "s",
            P->nnz, P->nnz == 1 ? "" : "s");
         if (nb == 0)
            strcpy(s, "none of");
         else if (ni == 1 && nb == 1)
            strcpy(s, "");
         else if (nb == 1)
            strcpy(s, "one of");
         else if (nb == ni)
            strcpy(s, "all of");
         else
            sprintf(s, "%d of", nb);
         xprintf("%d integer variable%s, %s which %s binary\n",
            ni, ni == 1 ? "" : "s", s, nb == 1 ? "is" : "are");
      }
#if 1 /* 28/V-2010 */
      if (parm->alien)
      {  /* use alien integer optimizer */
         ret = _glp_intopt1(P, parm);
         goto done;
      }
#endif
      if (!parm->presolve)
#if 0 /* 11/VII-2013 */
         ret = solve_mip(P, parm);
#else
         ret = solve_mip(P, parm, P, NULL);
#endif
      else
/**
 * Init the MLP problem solving component
 *
 * @param cfg the GNUNET_CONFIGURATION_Handle handle
 * @param stats the GNUNET_STATISTICS handle
 * @param max_duration maximum numbers of iterations for the LP/MLP Solver
 * @param max_iterations maximum time limit for the LP/MLP Solver
 * @return struct GAS_MLP_Handle * on success, NULL on fail
 */
struct GAS_MLP_Handle *
GAS_mlp_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
              const struct GNUNET_STATISTICS_Handle *stats,
              struct GNUNET_TIME_Relative max_duration,
              unsigned int max_iterations)
{
  struct GAS_MLP_Handle * mlp = GNUNET_malloc (sizeof (struct GAS_MLP_Handle));

  double D;
  double R;
  double U;
  unsigned long long tmp;
  unsigned int b_min;
  unsigned int n_min;
  struct GNUNET_TIME_Relative i_exec;
  int c;
  char * quota_out_str;
  char * quota_in_str;

  /* Init GLPK environment */
  int res = glp_init_env();
  switch (res) {
    case 0:
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
          "initialization successful");
      break;
    case 1:
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
          "environment is already initialized");
      break;
    case 2:
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
          "initialization failed (insufficient memory)");
      GNUNET_free(mlp);
      return NULL;
      break;
    case 3:
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
          "initialization failed (unsupported programming model)");
      GNUNET_free(mlp);
      return NULL;
      break;
    default:
      break;
  }

  /* Create initial MLP problem */
  mlp->prob = glp_create_prob();
  GNUNET_assert (mlp->prob != NULL);

  mlp->BIG_M = (double) BIG_M_VALUE;

  /* Get diversity coefficient from configuration */
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "COEFFICIENT_D",
                                                      &tmp))
    D = (double) tmp / 100;
  else
    D = 1.0;

  /* Get proportionality coefficient from configuration */
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "COEFFICIENT_R",
                                                      &tmp))
    R = (double) tmp / 100;
  else
    R = 1.0;

  /* Get utilization coefficient from configuration */
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "COEFFICIENT_U",
                                                      &tmp))
    U = (double) tmp / 100;
  else
    U = 1.0;

  /* Get quality metric coefficients from configuration */
  int i_delay = -1;
  int i_distance = -1;
  int q[GNUNET_ATS_QualityPropertiesCount] = GNUNET_ATS_QualityProperties;
  for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
  {
    /* initialize quality coefficients with default value 1.0 */
    mlp->co_Q[c] = 1.0;

    mlp->q[c] = q[c];
    if (q[c] == GNUNET_ATS_QUALITY_NET_DELAY)
      i_delay = c;
    if (q[c] == GNUNET_ATS_QUALITY_NET_DISTANCE)
      i_distance = c;
  }

  if ((i_delay != -1) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "COEFFICIENT_QUALITY_DELAY",
                                                      &tmp)))

    mlp->co_Q[i_delay] = (double) tmp / 100;
  else
    mlp->co_Q[i_delay] = 1.0;

  if ((i_distance != -1) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "COEFFICIENT_QUALITY_DISTANCE",
                                                      &tmp)))
    mlp->co_Q[i_distance] = (double) tmp / 100;
  else
    mlp->co_Q[i_distance] = 1.0;

  /* Get minimum bandwidth per used address from configuration */
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "MIN_BANDWIDTH",
                                                      &tmp))
    b_min = tmp;
  else
  {
    b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
  }

  /* Get minimum number of connections from configuration */
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
                                                      "MIN_CONNECTIONS",
                                                      &tmp))
    n_min = tmp;
  else
    n_min = 4;

  /* Init network quotas */
  int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
  for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
  {
    mlp->quota_index[c] = quotas[c];
    static char * entry_in = NULL;
    static char * entry_out = NULL;
    unsigned long long quota_in = 0;
    unsigned long long quota_out = 0;

    switch (quotas[c]) {
      case GNUNET_ATS_NET_UNSPECIFIED:
        entry_out = "UNSPECIFIED_QUOTA_OUT";
        entry_in = "UNSPECIFIED_QUOTA_IN";
        break;
      case GNUNET_ATS_NET_LOOPBACK:
        entry_out = "LOOPBACK_QUOTA_OUT";
        entry_in = "LOOPBACK_QUOTA_IN";
        break;
      case GNUNET_ATS_NET_LAN:
        entry_out = "LAN_QUOTA_OUT";
        entry_in = "LAN_QUOTA_IN";
        break;
      case GNUNET_ATS_NET_WAN:
        entry_out = "WAN_QUOTA_OUT";
        entry_in = "WAN_QUOTA_IN";
        break;
      case GNUNET_ATS_NET_WLAN:
        entry_out = "WLAN_QUOTA_OUT";
        entry_in = "WLAN_QUOTA_IN";
        break;
      default:
        break;
    }

    if ((entry_in == NULL) || (entry_out == NULL))
      continue;

    if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
    {
      if (0 == strcmp(quota_out_str, BIG_M_STRING) ||
          (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &quota_out)))
        quota_out = mlp->BIG_M;

      GNUNET_free (quota_out_str);
      quota_out_str = NULL;
    }
    else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
    {
      quota_out = mlp->BIG_M;
    }
    else
    {
      quota_out = mlp->BIG_M;
    }

    if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
    {
      if (0 == strcmp(quota_in_str, BIG_M_STRING) ||
          (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &quota_in)))
        quota_in = mlp->BIG_M;

      GNUNET_free (quota_in_str);
      quota_in_str = NULL;
    }
    else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
    {
      quota_in = mlp->BIG_M;
    }
    else
    {
      quota_in = mlp->BIG_M;
    }

    /* Check if defined quota could make problem unsolvable */
    if (((n_min * b_min) > quota_out) && (GNUNET_ATS_NET_UNSPECIFIED != quotas[c]))
    {
      GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Inconsistent quota configuration value `%s': " 
		  "outbound quota (%u Bps) too small for combination of minimum connections and minimum bandwidth per peer (%u * %u Bps = %u)\n", entry_out, quota_out, n_min, b_min, n_min * b_min);

      GAS_mlp_done(mlp);
      mlp = NULL;
      return NULL;
    }

    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found `%s' quota %llu and `%s' quota %llu\n",
                entry_out, quota_out, entry_in, quota_in);
    GNUNET_STATISTICS_update ((struct GNUNET_STATISTICS_Handle *) stats, entry_out, quota_out, GNUNET_NO);
    GNUNET_STATISTICS_update ((struct GNUNET_STATISTICS_Handle *) stats, entry_in, quota_in, GNUNET_NO);
    mlp->quota_out[c] = quota_out;
    mlp->quota_in[c] = quota_in;
  }

  /* Get minimum number of connections from configuration */
  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_time (cfg, "ats",
                                                        "ATS_EXEC_INTERVAL",
                                                        &i_exec))
    mlp->exec_interval = i_exec;
  else
    mlp->exec_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30);

  mlp->stats = (struct GNUNET_STATISTICS_Handle *) stats;
  mlp->max_iterations = max_iterations;
  mlp->max_exec_duration = max_duration;
  mlp->auto_solve = GNUNET_YES;

  /* Redirect GLPK output to GNUnet logging */
  glp_error_hook((void *) mlp, &mlp_term_hook);

  /* Init LP solving parameters */
  glp_init_smcp(&mlp->control_param_lp);

  mlp->control_param_lp.msg_lev = GLP_MSG_OFF;
#if VERBOSE_GLPK
  mlp->control_param_lp.msg_lev = GLP_MSG_ALL;
#endif

  mlp->control_param_lp.it_lim = max_iterations;
  mlp->control_param_lp.tm_lim = max_duration.rel_value;

  /* Init MLP solving parameters */
  glp_init_iocp(&mlp->control_param_mlp);

  mlp->control_param_mlp.msg_lev = GLP_MSG_OFF;
#if VERBOSE_GLPK
  mlp->control_param_mlp.msg_lev = GLP_MSG_ALL;
#endif
  mlp->control_param_mlp.tm_lim = max_duration.rel_value;

  mlp->last_execution = GNUNET_TIME_UNIT_FOREVER_ABS;

  mlp->co_D = D;
  mlp->co_R = R;
  mlp->co_U = U;
  mlp->b_min = b_min;
  mlp->n_min = n_min;
  mlp->m_q = GNUNET_ATS_QualityPropertiesCount;
  mlp->semaphore = GNUNET_NO;
  return mlp;
}
Ejemplo n.º 17
0
int main(int argc, char** argv)
{
	/*==================================================*/
	/* Variables */
	data d;
	int* M;

	/* GLPK */
	int *ia, *ja;
	double *ar;
	double z;
	double *x;
	int notZeroCount;

	/* Misc */
	int i, pos;

	/* Check up */
	if(argc != 2)
	{
		printf("ERROR : no data file !\n");
		exit(1);		
	}
	
	/* Initialization */
	filereader(argv[1], &d);

	if(d.nbjour < 1)
	{
		printf("Obvious...\n");
		return 0;	
	}
	
	M = (int*) malloc ((d.nbjour +1)* sizeof(int));
	M[d.nbjour] = d.d[d.nbjour];
	for (i = d.nbjour-1; i >=0; --i)
	{
		M[i] = d.d[i] + M[i+1];
	}

	/* Problem creation*/
	glp_prob *prob;
	prob = glp_create_prob();
	glp_set_prob_name(prob, "ULS");
	glp_set_obj_dir(prob, GLP_MIN);

	glp_smcp parm;
	glp_init_smcp(&parm);
	parm.msg_lev = GLP_MSG_OFF;

	glp_iocp parmip;
	glp_init_iocp(&parmip);
	parmip.msg_lev = GLP_MSG_OFF;

	/* Number of constraints : 2 * nbjour +2 */
	glp_add_rows(prob, 2*d.nbjour +2);
	for (i = 1; i <= d.nbjour; ++i)
	{
		glp_set_row_bnds(prob, i, GLP_FX, d.d[i], d.d[i]);
	}
	for (i = d.nbjour+1; i <= 2*d.nbjour; ++i)
	{
		glp_set_row_bnds(prob, i, GLP_LO, 0, 0);
	}	
	glp_set_row_bnds(prob, 2*d.nbjour+1, GLP_FX, 0.0, 0.0);
	glp_set_row_bnds(prob, 2*d.nbjour+2, GLP_FX, 0.0, 0.0);

	/* Number of variables : 3*(nbjour +1)*/
	glp_add_cols(prob, 3*(d.nbjour+1));
	for (i = 0; i < d.nbjour +1; ++i)
	{
		glp_set_col_bnds(prob, i*3 +1, GLP_LO, 0.0, 0.0);
		glp_set_col_bnds(prob, i*3 +2, GLP_LO, 0.0, 0.0);
		glp_set_col_bnds(prob, i*3 +3, GLP_DB, 0.0, 1.0);
	}
	for (i = 1; i <= 3*(d.nbjour+1); ++i)
	{
		glp_set_col_kind(prob, i, GLP_CV);
	}

	/* Coefficients of the economic function */
	glp_set_obj_coef(prob, 1, 0);
	glp_set_obj_coef(prob, 2, 0);
	glp_set_obj_coef(prob, 3, 0);
	for (i = 1; i <=d.nbjour; ++i)
	{
		glp_set_obj_coef(prob, 3*i+1, d.p[i]);
		glp_set_obj_coef(prob, 3*i+2, d.h[i]);
		glp_set_obj_coef(prob, 3*i+3, d.f[i]);
	}

	/* Matrix */
	notZeroCount = 5 * d.nbjour + 2;

	ia = (int *) malloc ((1+notZeroCount) * sizeof(int));
	ja = (int *) malloc ((1+notZeroCount) * sizeof(int));	
	ar = (double *) malloc ((1+notZeroCount) * sizeof(double));

	pos = 1;
	for (i = 1; i <= d.nbjour; ++i)
	{
		ia[pos] = i;
		ia[pos+1] = i;
		ia[pos+2] = i;

		ja[pos] = i*3-1;
		ja[pos+1] = i*3+1;
		ja[pos+2] = i*3+2;

		ar[pos] = 1.0;
		ar[pos+1] = 1.0;
		ar[pos+2] = -1.0;
			
		pos += 3;
	}

	for (i = 1; i <= d.nbjour; ++i)
	{
		ia[pos] = i + d.nbjour;
		ia[pos+1] = i + d.nbjour;

		ja[pos] = i*3+1;
		ja[pos+1] = i*3+3;

		ar[pos] = -1.0;
		ar[pos+1] = M[i];
			
		pos += 2;
	}
	
	ia[pos] = 2*d.nbjour +1;
	ia[pos+1] = 2 * d.nbjour+2;

	ja[pos] = 3*(d.nbjour+1)-1;
	ja[pos+1] = 2;

	ar[pos] = 1.0;
	ar[pos+1] = 1.0;

	pos += 2;

	glp_load_matrix(prob, notZeroCount, ia, ja , ar);

	/* Writing in a file */
	glp_write_lp(prob, NULL, "ULS.lp");

	/* Branch and bound */
	node* res = branchAndBound(prob);
	displayNode(res);
}
Ejemplo n.º 18
0
int glpk (int sense, int n, int m, double *c, int nz, int *rn, int *cn,
      	 double *a, double *b, char *ctype, int *freeLB, double *lb,
      	 int *freeUB, double *ub, int *vartype, int isMIP, int lpsolver,
      	 int save_pb, char *save_filename, char *filetype,
         double *xmin, double *fmin, double *status,
      	 double *lambda, double *redcosts, double *time, double *mem)
{
  int typx = 0;
  int method;

  clock_t t_start = clock();

  //Redirect standard output
  if (glpIntParam[0] > 1) glp_term_hook (glpk_print_hook, NULL);
  else glp_term_hook (NULL, NULL);

  //-- Create an empty LP/MILP object
  LPX *lp = lpx_create_prob ();

  //-- Set the sense of optimization
  if (sense == 1)
    glp_set_obj_dir (lp, GLP_MIN);
  else
    glp_set_obj_dir (lp, GLP_MAX);

  //-- Define the number of unknowns and their domains.
  glp_add_cols (lp, n);
  for (int i = 0; i < n; i++)
  {
    //-- Define type of the structural variables
    if (! freeLB[i] && ! freeUB[i]) {
      if ( lb[i] == ub[i] )
        glp_set_col_bnds (lp, i+1, GLP_FX, lb[i], ub[i]);
      else
        glp_set_col_bnds (lp, i+1, GLP_DB, lb[i], ub[i]);
    }
    else
	  {
      if (! freeLB[i] && freeUB[i])
        glp_set_col_bnds (lp, i+1, GLP_LO, lb[i], ub[i]);
      else
      {
        if (freeLB[i] && ! freeUB[i])
		      glp_set_col_bnds (lp, i+1, GLP_UP, lb[i], ub[i]);
	      else
		      glp_set_col_bnds (lp, i+1, GLP_FR, lb[i], ub[i]);
	    }
	  }

  // -- Set the objective coefficient of the corresponding
  // -- structural variable. No constant term is assumed.
  glp_set_obj_coef(lp,i+1,c[i]);

  if (isMIP)
    glp_set_col_kind (lp, i+1, vartype[i]);
  }

  glp_add_rows (lp, m);

  for (int i = 0; i < m; i++)
  {
    /*  If the i-th row has no lower bound (types F,U), the
        corrispondent parameter will be ignored.
        If the i-th row has no upper bound (types F,L), the corrispondent
        parameter will be ignored.
        If the i-th row is of S type, the i-th LB is used, but
        the i-th UB is ignored.
    */

    switch (ctype[i])
    {
      case 'F': typx = GLP_FR; break;
      // upper bound
	  case 'U': typx = GLP_UP; break;
      // lower bound
	  case 'L': typx = GLP_LO; break;
      // fixed constraint
	  case 'S': typx = GLP_FX; break;
      // double-bounded variable
      case 'D': typx = GLP_DB; break;
	}

    if ( typx == GLP_DB && -b[i] < b[i]) {
        glp_set_row_bnds (lp, i+1, typx, -b[i], b[i]);
    }
    else if(typx == GLP_DB && -b[i] == b[i]) {
        glp_set_row_bnds (lp, i+1, GLP_FX, b[i], b[i]);
    }
    else {
    // this should be glp_set_row_bnds (lp, i+1, typx, -b[i], b[i]);
        glp_set_row_bnds (lp, i+1, typx, b[i], b[i]);
    }

  }
  // Load constraint matrix A
  glp_load_matrix (lp, nz, rn, cn, a);

  // Save problem
  if (save_pb) {
    if (!strcmp(filetype,"cplex")){
      if (glp_write_lp (lp, NULL, save_filename) != 0) {
	        mexErrMsgTxt("glpk: unable to write the problem");
	        longjmp (mark, -1);
      }
    }else{
      if (!strcmp(filetype,"fixedmps")){
        if (glp_write_mps (lp, GLP_MPS_DECK, NULL, save_filename) != 0) {
            mexErrMsgTxt("glpk: unable to write the problem");
	        longjmp (mark, -1);
        }
      }else{
        if (!strcmp(filetype,"freemps")){
          if (glp_write_mps (lp, GLP_MPS_FILE, NULL, save_filename) != 0) {
              mexErrMsgTxt("glpk: unable to write the problem");
	          longjmp (mark, -1);
          }
        }else{// plain text
          if (lpx_print_prob (lp, save_filename) != 0) {
              mexErrMsgTxt("glpk: unable to write the problem");
	          longjmp (mark, -1);
          }
        }
      }
    }
  }
  //-- scale the problem data (if required)
  if (! glpIntParam[16] || lpsolver != 1) {
    switch ( glpIntParam[1] ) {
        case ( 0 ): glp_scale_prob( lp, GLP_SF_SKIP ); break;
        case ( 1 ): glp_scale_prob( lp, GLP_SF_GM ); break;
        case ( 2 ): glp_scale_prob( lp, GLP_SF_EQ ); break;
        case ( 3 ): glp_scale_prob( lp, GLP_SF_AUTO  ); break;
        case ( 4 ): glp_scale_prob( lp, GLP_SF_2N ); break;
        default :
            mexErrMsgTxt("glpk: unrecognized scaling option");
            longjmp (mark, -1);
    }
  }
  else {
    /* do nothing? or unscale?
        glp_unscale_prob( lp );
    */
  }

  //-- build advanced initial basis (if required)
  if (lpsolver == 1 && ! glpIntParam[16])
    glp_adv_basis (lp, 0);

  glp_smcp sParam;
  glp_init_smcp(&sParam);

  //-- set control parameters for simplex/exact method
  if (lpsolver == 1 || lpsolver == 3){
    //remap of control parameters for simplex method
    sParam.msg_lev=glpIntParam[0];	// message level

    // simplex method: primal/dual
    switch ( glpIntParam[2] ) {
        case 0: sParam.meth=GLP_PRIMAL; break;
        case 1: sParam.meth=GLP_DUAL;   break;
        case 2: sParam.meth=GLP_DUALP;  break;
        default:
            mexErrMsgTxt("glpk: unrecognized primal/dual method");
            longjmp (mark, -1);
    }

    // pricing technique
    if (glpIntParam[3]==0) sParam.pricing=GLP_PT_STD;
    else sParam.pricing=GLP_PT_PSE;

    // ratio test
    if (glpIntParam[20]==0) sParam.r_test = GLP_RT_STD;
    else sParam.r_test=GLP_RT_HAR;

    //tollerances
    sParam.tol_bnd=glpRealParam[1];	// primal feasible tollerance
    sParam.tol_dj=glpRealParam[2];	// dual feasible tollerance
    sParam.tol_piv=glpRealParam[3];	// pivot tollerance
    sParam.obj_ll=glpRealParam[4];	// lower limit
    sParam.obj_ul=glpRealParam[5];	// upper limit

    // iteration limit
    if (glpIntParam[5]==-1) sParam.it_lim=INT_MAX;
    else sParam.it_lim=glpIntParam[5];

    // time limit
    if (glpRealParam[6]==-1) sParam.tm_lim=INT_MAX;
    else sParam.tm_lim=(int) glpRealParam[6];
    sParam.out_frq=glpIntParam[7];	// output frequency
    sParam.out_dly=(int) glpRealParam[7];	// output delay
    // presolver
    if (glpIntParam[16]) sParam.presolve=GLP_ON;
    else sParam.presolve=GLP_OFF;
  }else{
	for(int i = 0; i < NIntP; i++) {
        // skip assinging ratio test or
        if ( i == 18 || i == 20) continue;
		lpx_set_int_parm (lp, IParam[i], glpIntParam[i]);
    }

	for (int i = 0; i < NRealP; i++) {
		lpx_set_real_parm (lp, RParam[i], glpRealParam[i]);
    }
  }

  //set MIP params if MIP....
  glp_iocp iParam;
  glp_init_iocp(&iParam);

  if ( isMIP ){
    method = 'I';

    switch (glpIntParam[0]) { //message level
         case 0:  iParam.msg_lev = GLP_MSG_OFF;   break;
         case 1:  iParam.msg_lev = GLP_MSG_ERR;   break;
         case 2:  iParam.msg_lev = GLP_MSG_ON;    break;
         case 3:  iParam.msg_lev = GLP_MSG_ALL;   break;
         default:  mexErrMsgTxt("glpk: msg_lev bad param");
    }
    switch (glpIntParam[14]) { //branching param
         case 0:  iParam.br_tech = GLP_BR_FFV;    break;
         case 1:  iParam.br_tech = GLP_BR_LFV;    break;
         case 2:  iParam.br_tech = GLP_BR_MFV;    break;
         case 3:  iParam.br_tech = GLP_BR_DTH;    break;
         default: mexErrMsgTxt("glpk: branch bad param");
    }
    switch (glpIntParam[15]) { //backtracking heuristic
        case 0:  iParam.bt_tech = GLP_BT_DFS;    break;
        case 1:  iParam.bt_tech = GLP_BT_BFS;    break;
        case 2:  iParam.bt_tech = GLP_BT_BLB;    break;
        case 3:  iParam.bt_tech = GLP_BT_BPH;    break;
        default: mexErrMsgTxt("glpk: backtrack bad param");
    }

    if (  glpRealParam[8] > 0.0 && glpRealParam[8] < 1.0 )
        iParam.tol_int = glpRealParam[8];  // absolute tolorence
    else
        mexErrMsgTxt("glpk: tolint must be between 0 and 1");

    iParam.tol_obj = glpRealParam[9];  // relative tolarence
    iParam.mip_gap = glpRealParam[10]; // realative gap tolerance

    // set time limit for mip
    if ( glpRealParam[6] < 0.0 || glpRealParam[6] > 1e6 )
       iParam.tm_lim = INT_MAX;
    else
       iParam.tm_lim = (int)(1000.0 * glpRealParam[6] );

    // Choose Cutsets for mip
    // shut all cuts off, then start over....
    iParam.gmi_cuts = GLP_OFF;
    iParam.mir_cuts = GLP_OFF;
    iParam.cov_cuts = GLP_OFF;
    iParam.clq_cuts = GLP_OFF;

    switch( glpIntParam[17] ) {
        case 0: break;
        case 1: iParam.gmi_cuts = GLP_ON; break;
        case 2: iParam.mir_cuts = GLP_ON; break;
        case 3: iParam.cov_cuts = GLP_ON; break;
        case 4: iParam.clq_cuts = GLP_ON; break;
        case 5: iParam.clq_cuts = GLP_ON;
                iParam.gmi_cuts = GLP_ON;
                iParam.mir_cuts = GLP_ON;
                iParam.cov_cuts = GLP_ON;
                iParam.clq_cuts = GLP_ON; break;
        default: mexErrMsgTxt("glpk: cutset bad param");
    }

    switch( glpIntParam[18] ) { // pre-processing for mip
        case 0: iParam.pp_tech = GLP_PP_NONE; break;
        case 1: iParam.pp_tech = GLP_PP_ROOT; break;
        case 2: iParam.pp_tech = GLP_PP_ALL;  break;
        default:  mexErrMsgTxt("glpk: pprocess bad param");
    }

    if (glpIntParam[16])  iParam.presolve=GLP_ON;
    else                  iParam.presolve=GLP_OFF;

    if (glpIntParam[19])  iParam.binarize = GLP_ON;
    else                  iParam.binarize = GLP_OFF;

  }
  else {
     /* Choose simplex method ('S')
     or interior point method ('T')
     or Exact method          ('E')
     to solve the problem  */
    switch (lpsolver) {
      case 1: method = 'S'; break;
      case 2: method = 'T'; break;
      case 3: method = 'E'; break;
      default:
            mexErrMsgTxt("glpk:  lpsolver != lpsolver");
            longjmp (mark, -1);
    }
  }

	// now run the problem...
	int errnum = 0;

	switch (method) {
	case 'I':
		errnum = glp_intopt( lp, &iParam );
		errnum += 200; //this is to avoid ambiguity in the return codes.
		break;

	case 'S':
		errnum = glp_simplex(lp, &sParam);
		errnum += 100; //this is to avoid ambiguity in the return codes.
		break;

	case 'T':
		errnum = glp_interior(lp, NULL );
		errnum += 300; //this is to avoid ambiguity in the return codes.
		break;

	case 'E':
		errnum = glp_exact(lp, &sParam);
		errnum += 100; //this is to avoid ambiguity in the return codes.
		break;

	default:  /*xassert (method != method); */
		mexErrMsgTxt("glpk: method != method");
		longjmp (mark, -1);
	}

    if (errnum==100 || errnum==200 || errnum==300 || errnum==106 || errnum==107 || errnum==108 || errnum==109 || errnum==209 || errnum==214 || errnum==308) {

    // Get status and object value
    if (isMIP) {
      *status = glp_mip_status (lp);
      *fmin = glp_mip_obj_val (lp);
    }
    else {

      if (lpsolver == 1 || lpsolver == 3) {
        *status = glp_get_status (lp);
        *fmin = glp_get_obj_val (lp);
	  }
      else {
        *status = glp_ipt_status (lp);
        *fmin = glp_ipt_obj_val (lp);
	  }
    }

    // Get optimal solution (if exists)
    if (isMIP) {

      for (int i = 0; i < n; i++)
        xmin[i] = glp_mip_col_val (lp, i+1);
    }
    else {

      /* Primal values */
      for (int i = 0; i < n; i++) {

        if (lpsolver == 1 || lpsolver == 3)
              xmin[i] = glp_get_col_prim (lp, i+1);
        else
		      xmin[i] = glp_ipt_col_prim (lp, i+1);
      }

      /* Dual values */
      for (int i = 0; i < m; i++) {

        if (lpsolver == 1 || lpsolver == 3)
            lambda[i] = glp_get_row_dual (lp, i+1);
	    else
            lambda[i] = glp_ipt_row_dual (lp, i+1);
      }

      /* Reduced costs */
      for (int i = 0; i < glp_get_num_cols (lp); i++) {

        if (lpsolver == 1 || lpsolver == 3)
            redcosts[i] = glp_get_col_dual (lp, i+1);
        else
            redcosts[i] = glp_ipt_col_dual (lp, i+1);
      }

    }

    *time = (clock () - t_start) / CLOCKS_PER_SEC;

    size_t tpeak;
    glp_mem_usage(NULL, NULL, NULL, &tpeak);
    *mem=((double) tpeak) / (1024);

	lpx_delete_prob(lp);

    return 0;
  }
  else {
   // printf("errnum is %d\n", errnum);
  }

  lpx_delete_prob(lp);

  /* this shouldn't be nessiary with glp_deleted_prob, but try it
  if we have weird behavior again... */
  glp_free_env();


  *status = errnum;

  return errnum;
}
Ejemplo n.º 19
0
int main()
{
   // Variáveis auxiliares
   int i, j, constraintNumber, *constraintIndices;
   double *constraintCoefficients;

   // Aloca os vetores utilizados para criar as restrições do problema
   // ***********************************************************************************************
   // ATENÇÃO ===> É importante dizer que estes vetores serão utilizados da posição 1 em diante
   //              Ou seja, no GLPK você aloca uma posição a mais e descarta a posição 0 dos vetores.
   // ***********************************************************************************************
   constraintIndices = (int*)malloc((n+1)*sizeof(int));
   constraintCoefficients = (double*)malloc((n+1)*sizeof(double));

   // Cria um modelo com nenhuma variável e nenhuma restrição
   glp_prob *model = glp_create_prob();

   // Define o sentido da otimização que, para este problema, é minimização
   glp_set_obj_dir(model, GLP_MIN);

   // Cria as variáveis (colunas) no modelo
   // Para este problema são necessárias n*n variáveis
   // Estas n*n variáveis são definidas pelo GLPK através dos indices que vão de 1 até n*n (x1, x2, ..., x(n*n))
   // Portanto, neste momento é importante determinar qual variável no GLPK (índice) representará qual variável x[i,j]
   // Para tanto, fazemos o mapeamento das variáveis x[i,j] utilizando a fórmula (i-1)*n + j
   // Isto é, a variável x[i,j] será representada pela variável de índice (i-1)*n + j no modelo do GLPK
   // Note que é imprescindível que cada índice (variável do GLPK) seja associado a no máximo uma variável x[i,j]
   // Caso contrário, uma variável do GLPK pode representar duas variáveis x[i,j] diferentes que assumem valores distintos nas soluções ótimas
   // Neste caso, o modelo estará incorreto
   glp_add_cols(model, n*n);
   
   // Ajuste dos tipos, limitantes e coeficientes da função objetivo das variáveis do modelo
   
   for (i = 1; i <= n; i++)
      for (j = 1; j <= n; j++)
      {
         // Define o tipo da variável como sendo binária (em outros modelos poderia ser contínua (GLP_CV) ou inteira (GLP_IV))
         glp_set_col_kind(model, (i-1)*n + j, GLP_BV);
         
         // Define o limitante inferior (0) e superior (1) da variável
         // Consultem no manual as outras forma para definir apenas o limitante inferior ou superior
         glp_set_col_bnds(model, (i-1)*n + j, GLP_DB, 0.0, 1.0);

         // Define o coeficiente da variável na função objetivo
         glp_set_obj_coef(model, (i-1)*n + j, c[i-1][j-1]);
      }
      
   // Cria no modelo 2n restrições (linhas) nulas (com os coeficientes e limitantes zerados)
   // Ou seja, neste momento é criada uma matriz de zeros que correspondem aos coeficientes das restrições do modelo
   // O próximo passo será modificar esta matriz de tal forma que ela represente as restrições do problema descrito
   glp_add_rows(model, 2*n);

   // Esta variável define qual das restrições (qual linha da matriz de coeficientes) estamos modificando
   // ************************************************************************************************************
   // ATENÇÃO: perceba que as restrições (linhas), assim como as variáveis (colunas), são indexadas a partir de 1.
   // ************************************************************************************************************
   constraintNumber = 1;
   
   // Preenchimento das restrições limitando a soma das linhas:  
   // sum{j in 1..n} w[i,j]*x[i,j] <= u[i] para i in 1..n

   for (i = 1; i <= n; i++)
   {
      // Define o limite superior (RHS) da restrição      
      glp_set_row_bnds(model, constraintNumber, GLP_UP, 0.0, u[i-1]);

      for (j = 1; j <= n; j++)
      {
         // Ajusta o índice da variável que será informado à rotina do GLPK
         constraintIndices[j] = (i-1)*n + j;
         
         // Ajusta o coeficiente da variável cujo índice foi definido na linha anterior para ser informado ao GLPK
         // ******************************************************************************************************
         // ATENÇÃO: perceba que na matriz w os índices e colunas são indexados a partir de ZERO !
         // ******************************************************************************************************
         constraintCoefficients[j] = w[i-1][j-1];
      }

      // Passa ao GLPK a restrição que acabou de ser definida nos vetores constraintIndices e constraintCoefficients
      glp_set_mat_row(model, constraintNumber, n, constraintIndices, constraintCoefficients);
      
      // atualiza o indice da próxima restrição a ser inserida
      constraintNumber++;
   }
 
   // Preenchimento das restrições limitando a soma das colunas: 
   //    sum{i in 1..n} w[i,j]*x[i,j] >= l[i] para j in 1..n   
   for (j = 1; j <= n; j++)
   {
      // Define o limite inferior (RHS)  da restrição      
      glp_set_row_bnds(model, constraintNumber, GLP_LO, l[j-1], 0.0);

      for (i = 1; i <= n; i++)
      {
         // Ajusta o índice da variável que será informado a rotina do GLPK
         constraintIndices[i] = (i-1)*n + j;
         
         // Ajusta o coeficiente da variável cujo índice foi definido na linha anterior para ser informado ao GLPK
         constraintCoefficients[i] = w[i-1][j-1];
      }

      // Passa ao GLPK a restrição que acabou de ser definida nos vetores constraintIndices e constraintCoefficients
      glp_set_mat_row(model, constraintNumber, n, constraintIndices, constraintCoefficients);
      
      // atualiza o indice da próxima restrição a ser inserida
      constraintNumber++;
   } 
 
   // Define os parâmetros que serão passados ao resolvedor   
   glp_iocp param;
   glp_init_iocp(&param);
   
   // Ativa o presolver
   param.presolve = GLP_ON;

   // Resolve o modelo
   int status = glp_intopt(model, &param);

   // Verifica se houve algum erro durante a otimização
   if (status)
   {
      printf("Ocorreu um erro durante o processo de otimizacao.\n");
   }
   else
   {
      // Verifica se o método encontrou uma solução
      
      status = glp_mip_status(model);
      
      if ((status == GLP_OPT) || (status == GLP_FEAS))
      {
         // Imprime a solução encontrada
         
         if (status == GLP_OPT)
            printf("Solucao otima encontrada!\n");
         else
            printf("A solucao encontrada pode nao ser otima!\n");
      
         printf("Custo da solucao: %f\n", glp_mip_obj_val(model));

         for (i = 1; i <= n; i++)
         {
            for (j = 1; j <= n; j++)
               printf("%f ", glp_mip_col_val(model, (i-1)*n + j));
         
            printf("\n");
         }
      }
      else
      {
         printf("Nenhuma solucao foi encontrada!\n");
      }
   }


   // Desaloca os vetores
   free(constraintIndices);
   free(constraintCoefficients);

   return 0;
}
Ejemplo n.º 20
0
extern void* jl_glpkw__iocp_init()
{
    glp_iocp * iocp = calloc(1, sizeof(glp_iocp));
    glp_init_iocp(iocp);
    return (void*) iocp;
}
Ejemplo n.º 21
0
void inline instrumentert::instrument_minimum_interference_inserter(
  const std::set<event_grapht::critical_cyclet>& set_of_cycles)
{
  /* Idea:
     We solve this by a linear programming approach,
     using for instance glpk lib.

     Input: the edges to instrument E, the cycles C_j
     Pb: min sum_{e_i in E} d(e_i).x_i
         s.t. for all j, sum_{e_i in C_j} >= 1,
       where e_i is a pair to potentially instrument,
       x_i is a Boolean stating whether we instrument
       e_i, and d() is the cost of an instrumentation.
     Output: the x_i, saying which pairs to instrument

     For this instrumentation, we propose:
     d(poW*)=1
     d(poRW)=d(rfe)=2
     d(poRR)=3

     This function can be refined with the actual times
     we get in experimenting the different pairs in a
     single IRIW.
  */

#ifdef HAVE_GLPK
  /* first, identify all the unsafe pairs */
  std::set<event_grapht::critical_cyclet::delayt> edges;
  for(std::set<event_grapht::critical_cyclet>::iterator
    C_j=set_of_cycles.begin();
    C_j!=set_of_cycles.end();
    ++C_j)
    for(std::set<event_grapht::critical_cyclet::delayt>::const_iterator e_i=
      C_j->unsafe_pairs.begin();
      e_i!=C_j->unsafe_pairs.end();
      ++e_i)
      edges.insert(*e_i);

  glp_prob* lp;
  glp_iocp parm;
  glp_init_iocp(&parm);
  parm.msg_lev=GLP_MSG_OFF;
  parm.presolve=GLP_ON;

  lp=glp_create_prob();
  glp_set_prob_name(lp, "instrumentation optimisation");
  glp_set_obj_dir(lp, GLP_MIN);

  message.debug() << "edges: "<<edges.size()<<" cycles:"<<set_of_cycles.size()
    << messaget::eom;

  /* sets the variables and coefficients */
  glp_add_cols(lp, edges.size());
  unsigned i=0;
  for(std::set<event_grapht::critical_cyclet::delayt>::iterator
    e_i=edges.begin();
    e_i!=edges.end();
    ++e_i)
  {
    ++i;
    std::string name="e_"+i2string(i);
    glp_set_col_name(lp, i, name.c_str());
    glp_set_col_bnds(lp, i, GLP_LO, 0.0, 0.0);
    glp_set_obj_coef(lp, i, cost(*e_i));
    glp_set_col_kind(lp, i, GLP_BV);
  }

  /* sets the constraints (soundness): one per cycle */
  glp_add_rows(lp, set_of_cycles.size());
  i=0;
  for(std::set<event_grapht::critical_cyclet>::iterator
    C_j=set_of_cycles.begin();
    C_j!=set_of_cycles.end();
    ++C_j)
  {
    ++i;
    std::string name="C_"+i2string(i);
    glp_set_row_name(lp, i, name.c_str());
    glp_set_row_bnds(lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
  }

  const unsigned mat_size=set_of_cycles.size()*edges.size();
  message.debug() << "size of the system: " << mat_size
    << messaget::eom;
  int* imat=(int*)malloc(sizeof(int)*(mat_size+1));
  int* jmat=(int*)malloc(sizeof(int)*(mat_size+1));
  double* vmat=(double*)malloc(sizeof(double)*(mat_size+1));

  /* fills the constraints coeff */
  /* tables read from 1 in glpk -- first row/column ignored */
  unsigned col=1;
  unsigned row=1;
  i=1;
  for(std::set<event_grapht::critical_cyclet::delayt>::iterator
    e_i=edges.begin();
    e_i!=edges.end();
    ++e_i)
  {
    row=1;
    for(std::set<event_grapht::critical_cyclet>::iterator
      C_j=set_of_cycles.begin();
      C_j!=set_of_cycles.end();
      ++C_j)
    {
      imat[i]=row;
      jmat[i]=col;
      if(C_j->unsafe_pairs.find(*e_i)!=C_j->unsafe_pairs.end())
        vmat[i]=1.0;
      else
        vmat[i]=0.0;
      ++i;
      ++row;
    }
    ++col;
  }

#ifdef DEBUG
  for(i=1; i<=mat_size; ++i)
    message.statistics() <<i<<"["<<imat[i]<<","<<jmat[i]<<"]="<<vmat[i]
      << messaget::eom;
#endif

  /* solves MIP by branch-and-cut */
  glp_load_matrix(lp, mat_size, imat, jmat, vmat);
  glp_intopt(lp, &parm);

  /* loads results (x_i) */
  message.statistics() << "minimal cost: " << glp_mip_obj_val(lp)
    << messaget::eom;
  i=0;
  for(std::set<event_grapht::critical_cyclet::delayt>::iterator
    e_i=edges.begin();
    e_i!=edges.end();
    ++e_i)
  {
    ++i;
    if(glp_mip_col_val(lp, i)>=1)
    {
      const abstract_eventt& first_ev=egraph[e_i->first];
      var_to_instr.insert(first_ev.variable);
      id2loc.insert(
        std::pair<irep_idt,source_locationt>(first_ev.variable,first_ev.source_location));
      if(!e_i->is_po)
      {
        const abstract_eventt& second_ev=egraph[e_i->second];
        var_to_instr.insert(second_ev.variable);
        id2loc.insert(
          std::pair<irep_idt,source_locationt>(second_ev.variable,second_ev.source_location));
      }
    }
  }

  glp_delete_prob(lp);
  free(imat);
  free(jmat);
  free(vmat);
#else
  throw "Sorry, minimum interference option requires glpk; "
        "please recompile goto-instrument with glpk.";
#endif
}
Ejemplo n.º 22
0
void ILP::sample() {
    
    PPReader& reader = handler->get_reader();
    
    
    // Read in all the data to this->data
    point *p;
    while ((p = reader.get())) {
        data.push_back(*p);
    }
    delete p;
    
    
    // Encode the problem into ILP
    uint N = data.size();
    
    glp_prob *lp = glp_create_prob();
    glp_set_obj_dir(lp, GLP_MIN);
    
    glp_add_rows(lp, 1 + 3*N*(N-1)/2);
    glp_add_cols(lp, N + N*(N-1)/2);
    
    vector<int> ia(1, 0);
    vector<int> ja(1, 0);
    vector<double> ar(1, 0.0);
    
    for (uint i = 1; i <= N; i++) {
        glp_set_obj_coef(lp, i, 0);
        glp_set_col_bnds(lp, i, GLP_DB, 0.0, 1.0);
        glp_set_col_kind(lp, i, GLP_BV);
    }
    
    for (uint i = 1; i <= N; i++) {
        ia.push_back(1);
        ja.push_back(i);
        ar.push_back(1.0);
    }
    glp_set_row_bnds(lp, 1, GLP_FX, K, K);
    
    // Set:
    // 1. coefficient for objective
    // 2. row bounds
    // 3. column bounds
    // 4. coefficient matrix for constraints
    uint k = 1;
    for (uint i = 1; i <= N-1; i++) {
        for (uint j = i+1; j <= N; j++) {
            point a = data[i-1];
            point b = data[j-1];
            
            // object coefficient and column bounds
            double l = handler->loss(handler->dist(a, b));
            glp_set_obj_coef(lp, N+k, l);
            glp_set_col_bnds(lp, N+k, GLP_DB, 0.0, 1.0);
            glp_set_col_kind(lp, N+k, GLP_BV);
            
            // row bounds
            glp_set_row_bnds(lp, 1 + (k-1)*3 + 1, GLP_LO, 0.0, 1.0);
            glp_set_row_bnds(lp, 1 + (k-1)*3 + 2, GLP_LO, 0.0, 1.0);
            glp_set_row_bnds(lp, 1 + (k-1)*3 + 3, GLP_LO, -1.0, 1.0);
            
            // coefficient matrix
            ia.push_back(1 + (k-1)*3 + 1);
            ja.push_back(i);
            ar.push_back(1.0);
            
            ia.push_back(1 + (k-1)*3 + 1);
            ja.push_back(N+k);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 2);
            ja.push_back(j);
            ar.push_back(1.0);
            
            ia.push_back(1 + (k-1)*3 + 2);
            ja.push_back(N+k);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 3);
            ja.push_back(i);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 3);
            ja.push_back(j);
            ar.push_back(-1.0);
            
            ia.push_back(1 + (k-1)*3 + 3);
            ja.push_back(N+k);
            ar.push_back(1.0);
            
            k++;
        }             
    }
    
    int* ia_a = &ia[0];
    int* ja_a = &ja[0];
    double* ar_a = &ar[0];
        
    glp_load_matrix(lp, ia.size()-1, ia_a, ja_a, ar_a);
    
    glp_iocp parm;
    glp_init_iocp(&parm);
    parm.presolve = GLP_ON;
    parm.msg_lev = GLP_MSG_OFF;
    
    int ret = glp_intopt(lp, &parm);
    
//    cout << "program returned: " << ret << endl;
    
    
    // Collect processed results
    for (uint i = 1; i <= N; i++) {
        double x = glp_mip_col_val(lp, i);
        if (x == 1.0) {
            sampled.push_back(data[i-1]);
        }
    }
}