Esempio n. 1
0
static void parse_constraints(struct csa *csa)
{     int i, len, type;
      double s;
      /* parse the keyword 'subject to' */
      xassert(csa->token == T_SUBJECT_TO);
      scan_token(csa);
loop: /* create new row (constraint) */
      i = glp_add_rows(csa->P, 1);
      /* parse row name */
      if (csa->token == T_NAME && csa->c == ':')
      {  /* row name is followed by a colon */
         if (glp_find_row(csa->P, csa->image) != 0)
            error(csa, "constraint '%s' multiply defined\n",
               csa->image);
         glp_set_row_name(csa->P, i, csa->image);
         scan_token(csa);
         xassert(csa->token == T_COLON);
         scan_token(csa);
      }
      else
      {  /* row name is not specified; use default */
         char name[50];
         sprintf(name, "r.%d", csa->count);
         glp_set_row_name(csa->P, i, name);
      }
      /* parse linear form */
      len = parse_linear_form(csa);
      glp_set_mat_row(csa->P, i, len, csa->ind, csa->val);
      /* parse constraint sense */
      if (csa->token == T_LE)
         type = GLP_UP, scan_token(csa);
      else if (csa->token == T_GE)
         type = GLP_LO, scan_token(csa);
      else if (csa->token == T_EQ)
         type = GLP_FX, scan_token(csa);
      else
         error(csa, "missing constraint sense\n");
      /* parse right-hand side */
      if (csa->token == T_PLUS)
         s = +1.0, scan_token(csa);
      else if (csa->token == T_MINUS)
         s = -1.0, scan_token(csa);
      else
         s = +1.0;
      if (csa->token != T_NUMBER)
         error(csa, "missing right-hand side\n");
      glp_set_row_bnds(csa->P, i, type, s * csa->value, s * csa->value);
      /* the rest of the current line must be empty */
      if (!(csa->c == '\n' || csa->c == EOF))
         error(csa, "invalid symbol(s) beyond right-hand side\n");
      scan_token(csa);
      /* if the next token is a sign, numeric constant, or a symbolic
         name, here is another constraint */
      if (csa->token == T_PLUS || csa->token == T_MINUS ||
          csa->token == T_NUMBER || csa->token == T_NAME) goto loop;
      return;
}
Esempio n. 2
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;
}
int main(void) {

	glp_prob *lp;
	int ia[1+1000], ja[1+1000];
	double ar[1+1000], z, x1, x2, x3;

	s1: lp = glp_create_prob();
	s2: glp_set_prob_name(lp, "sample");
	s3: glp_set_obj_dir(lp, GLP_MAX);
	s4: glp_add_rows(lp, 3);
	s5: glp_set_row_name(lp, 1, "p");
	s6: glp_set_row_bnds(lp, 1, GLP_UP, 0.0, 100.0);
	s7: glp_set_row_name(lp, 2, "q");
	s8: glp_set_row_bnds(lp, 2, GLP_UP, 0.0, 600.0);
	s9: glp_set_row_name(lp, 3, "r");
	s10: glp_set_row_bnds(lp, 3, GLP_UP, 0.0, 300.0);
	s11: glp_add_cols(lp, 3);
	s12: glp_set_col_name(lp, 1, "x1");
	s13: glp_set_col_bnds(lp, 1, GLP_LO, 0.0, 0.0);
	s14: glp_set_obj_coef(lp, 1, 10.0);
	s15: glp_set_col_name(lp, 2, "x2");
	s16: glp_set_col_bnds(lp, 2, GLP_LO, 0.0, 0.0);
	s17: glp_set_obj_coef(lp, 2, 6.0);
	s18: glp_set_col_name(lp, 3, "x3");
	s19: glp_set_col_bnds(lp, 3, GLP_LO, 0.0, 0.0);
	s20: glp_set_obj_coef(lp, 3, 4.0);

	s21: ia[1] = 1, ja[1] = 1, ar[1] = 1.0; /* a[1,1] = 1 */
	s22: ia[2] = 1, ja[2] = 2, ar[2] = 1.0; /* a[1,2] = 1 */
	s23: ia[3] = 1, ja[3] = 3, ar[3] = 1.0; /* a[1,3] = 1 */
	s24: ia[4] = 2, ja[4] = 1, ar[4] = 10.0; /* a[2,1] = 10 */
	s25: ia[5] = 3, ja[5] = 1, ar[5] = 2.0; /* a[3,1] = 2 */
	s26: ia[6] = 2, ja[6] = 2, ar[6] = 4.0; /* a[2,2] = 4 */
	s27: ia[7] = 3, ja[7] = 2, ar[7] = 2.0; /* a[3,2] = 2 */
	s28: ia[8] = 2, ja[8] = 3, ar[8] = 5.0; /* a[2,3] = 5 */
	s29: ia[9] = 3, ja[9] = 3, ar[9] = 6.0; /* a[3,3] = 6 */

	s30: glp_load_matrix(lp, 9, ia, ja, ar);
	s31: glp_simplex(lp, NULL);
	s32: z = glp_get_obj_val(lp);

	s33: x1 = glp_get_col_prim(lp, 1);
	s34: x2 = glp_get_col_prim(lp, 2);
	s35: x3 = glp_get_col_prim(lp, 3);

	s36: printf("\nz = %g; x1 = %g; x2 = %g; x3 = %g\n", z, x1, x2, x3);

	s37: glp_delete_prob(lp);
	
return 0;
}
Esempio n. 4
0
int glp_asnprob_lp(glp_prob *P, int form, glp_graph *G, int names,
                   int v_set, int a_cost)
{   glp_vertex *v;
    glp_arc *a;
    int i, j, ret, ind[1+2];
    double cost, val[1+2];
    if (!(form == GLP_ASN_MIN || form == GLP_ASN_MAX ||
            form == GLP_ASN_MMP))
        xerror("glp_asnprob_lp: form = %d; invalid parameter\n",
               form);
    if (!(names == GLP_ON || names == GLP_OFF))
        xerror("glp_asnprob_lp: names = %d; invalid parameter\n",
               names);
    if (v_set >= 0 && v_set > G->v_size - (int)sizeof(int))
        xerror("glp_asnprob_lp: v_set = %d; invalid offset\n",
               v_set);
    if (a_cost >= 0 && a_cost > G->a_size - (int)sizeof(double))
        xerror("glp_asnprob_lp: a_cost = %d; invalid offset\n",
               a_cost);
    ret = glp_check_asnprob(G, v_set);
    if (ret != 0) goto done;
    glp_erase_prob(P);
    if (names) glp_set_prob_name(P, G->name);
    glp_set_obj_dir(P, form == GLP_ASN_MIN ? GLP_MIN : GLP_MAX);
    if (G->nv > 0) glp_add_rows(P, G->nv);
    for (i = 1; i <= G->nv; i++)
    {   v = G->v[i];
        if (names) glp_set_row_name(P, i, v->name);
        glp_set_row_bnds(P, i, form == GLP_ASN_MMP ? GLP_UP : GLP_FX,
                         1.0, 1.0);
    }
    if (G->na > 0) glp_add_cols(P, G->na);
    for (i = 1, j = 0; i <= G->nv; i++)
    {   v = G->v[i];
        for (a = v->out; a != NULL; a = a->t_next)
        {   j++;
            if (names)
            {   char name[50+1];
                sprintf(name, "x[%d,%d]", a->tail->i, a->head->i);
                xassert(strlen(name) < sizeof(name));
                glp_set_col_name(P, j, name);
            }
            ind[1] = a->tail->i, val[1] = +1.0;
            ind[2] = a->head->i, val[2] = +1.0;
            glp_set_mat_col(P, j, 2, ind, val);
            glp_set_col_bnds(P, j, GLP_DB, 0.0, 1.0);
            if (a_cost >= 0)
                memcpy(&cost, (char *)a->data + a_cost, sizeof(double));
            else
                cost = 1.0;
            glp_set_obj_coef(P, j, cost);
        }
    }
    xassert(j == G->na);
done:
    return ret;
}
Esempio n. 5
0
void glp_del_rows(glp_prob *lp, int nrs, const int num[])
{     glp_tree *tree = lp->tree;
      GLPROW *row;
      int i, k, m_new;
      /* mark rows to be deleted */
      if (!(1 <= nrs && nrs <= lp->m))
         xerror("glp_del_rows: nrs = %d; invalid number of rows\n",
            nrs);
      for (k = 1; k <= nrs; k++)
      {  /* take the number of row to be deleted */
         i = num[k];
         /* obtain pointer to i-th row */
         if (!(1 <= i && i <= lp->m))
            xerror("glp_del_rows: num[%d] = %d; row number out of range"
               "\n", k, i);
         row = lp->row[i];
         if (tree != NULL && tree->reason != 0)
         {  xassert(tree->curr != NULL);
            xassert(row->level == tree->curr->level);
         }
         /* check that the row is not marked yet */
         if (row->i == 0)
            xerror("glp_del_rows: num[%d] = %d; duplicate row numbers n"
               "ot allowed\n", k, i);
         /* erase symbolic name assigned to the row */
         glp_set_row_name(lp, i, NULL);
         xassert(row->node == NULL);
         /* erase corresponding row of the constraint matrix */
         glp_set_mat_row(lp, i, 0, NULL, NULL);
         xassert(row->ptr == NULL);
         /* mark the row to be deleted */
         row->i = 0;
      }
      /* delete all marked rows from the row list */
      m_new = 0;
      for (i = 1; i <= lp->m; i++)
      {  /* obtain pointer to i-th row */
         row = lp->row[i];
         /* check if the row is marked */
         if (row->i == 0)
         {  /* it is marked, delete it */
            dmp_free_atom(lp->pool, row, sizeof(GLPROW));
         }
         else
         {  /* it is not marked; keep it */
            row->i = ++m_new;
            lp->row[row->i] = row;
         }
      }
      /* set new number of rows */
      lp->m = m_new;
      /* invalidate the basis factorization */
      lp->valid = 0;
      return;
}
Esempio n. 6
0
void glpk_wrapper::set_constraint(int index, Enode * const e) {
    DREAL_LOG_INFO << "glpk_wrapper::set_constraint  " << e << " with " << e->getPolarity();
    assert(is_linear(e));
    changed = true;
    LAExpression la(e);
    auto vars = e->get_vars();
    auto s = vars.size();
    auto indices = new int[s + 1];
    auto values = new double[s + 1];
    int i = 1;
    for (auto it = la.begin(); it != la.end(); ++it) {
        auto v = it->first;
        double c = it->second;
        if (v != nullptr && c != 0.0) {
            DREAL_LOG_INFO << "glpk_wrapper::set_constraint " << c << " * " << v;
            indices[i] = get_index(v) + 1;
            values[i] = c;
            i += 1;
        } else {
            if (e->isEq()) {
                assert(!e->hasPolarity() || e->getPolarity() != l_False);
                DREAL_LOG_INFO << "glpk_wrapper::set_constraint == " << c;
                glp_set_row_bnds(lp, index, GLP_FX, -c, -c);
            } else {
                if (!e->hasPolarity() || e->getPolarity() != l_False) {
                    DREAL_LOG_INFO << "glpk_wrapper::set_constraint <= " << (-c);
                    glp_set_row_bnds(lp, index, GLP_UP, 0, -c);
                } else {
                    DREAL_LOG_INFO << "glpk_wrapper::set_constraint >= " << (-c);
                    glp_set_row_bnds(lp, index, GLP_LO, -c, 0);
                }
            }
        }
    }
    glp_set_mat_row(lp, index, i-1, indices, values);
    delete[] indices;
    delete[] values;
    // name the constraints (helps debugging)
    if (DREAL_LOG_INFO_IS_ON) {
        std::ostringstream stream;
        if (e->getPolarity() == l_False) {
            stream << "¬";
        }
        stream << e;
        glp_set_row_name(lp, index, stream.str().c_str());
    }
}
Esempio n. 7
0
void B2GlpkHasher::add_str_constraints()
{
	std::vector<ConstraintBounds> constraint_bounds_vec;
	std::vector<ConstraintCoeff> constraint_coeffs_vec;
	unsigned int constraint_idx = 0;
	for(B2StrSet::const_iterator str_it = _str_set.begin(); str_it != _str_set.end(); ++str_it)
	{
		const std::string &str = str_it->first;
		const char *first_even_trace = str.c_str();
		const char *first_odd_trace = (str.c_str() + 1);
		const char *trace_limit = (str.c_str() + str.size() - 2);
		unsigned int even_upper_bound = add_single_constraint(++constraint_idx, first_even_trace, trace_limit, constraint_coeffs_vec);
		constraint_bounds_vec.push_back(ConstraintBounds(constraint_idx, std::string("E") + str, even_upper_bound));
		unsigned int odd_upper_bound = add_single_constraint(++constraint_idx, first_odd_trace, trace_limit, constraint_coeffs_vec);
		constraint_bounds_vec.push_back(ConstraintBounds(constraint_idx, std::string("O") + str, odd_upper_bound));
	};

	glp_add_rows(_lp, constraint_bounds_vec.size());
	for(std::vector<ConstraintBounds>::const_iterator bounds_it = constraint_bounds_vec.begin(); bounds_it != constraint_bounds_vec.end(); ++bounds_it)
	{
		const ConstraintBounds &bounds = *bounds_it;
		glp_set_row_name(_lp, bounds._constraint_idx, bounds._str.c_str());
		if(bounds._upper_bound > 1)
		{
			glp_set_row_bnds(_lp, bounds._constraint_idx, GLP_DB, 1, bounds._upper_bound);
		}
		else
		{
			glp_set_row_bnds(_lp, bounds._constraint_idx, GLP_FX, 1, 1);
		};
	};

	int *ia = new int[1 + constraint_coeffs_vec.size()];
	int *ja = new int[1 + constraint_coeffs_vec.size()];
	double *ar = new double[1 + constraint_coeffs_vec.size()];
	unsigned int coeff_count = 0;
	for(std::vector<ConstraintCoeff>::const_iterator coeffs_it = constraint_coeffs_vec.begin(); coeffs_it != constraint_coeffs_vec.end(); ++coeffs_it)
	{
		const ConstraintCoeff &coeff = *coeffs_it;
		++coeff_count;
		ia[coeff_count] = coeff._constraint_idx, ja[coeff_count] = coeff._trace_var_idx, ar[coeff_count] = coeff._coeff; /* a[constraint_idx,trace_var_idx] = coeff */
	};
	glp_load_matrix(_lp, coeff_count, ia, ja, ar);
	delete [] ia;
	delete [] ja;
	delete [] ar;
};
Esempio n. 8
0
/* Restriction xj - xi >= Sij */
void addSeparationConstraint(glp_prob * Prob, int plane1, int plane2) {
    int cardinal, constr[3], i = plane1, j = plane2;
	double cValues[3];
	char buf[AUXSIZE];
	
    cardinal = glp_add_rows(Prob, 1);
    
	sprintf(buf,"S%i,%i",i,j);
	glp_set_row_name(Prob, cardinal, buf);
	glp_set_row_bnds(Prob, cardinal, GLP_LO, planes[i].sep[j], 0);
	
	sprintf(buf,"x%i",j);
	constr[1] = glp_find_col(Prob, buf);
	
	sprintf(buf,"x%i",i);
	constr[2] = glp_find_col(Prob, buf);
	
	cValues[1] = 1;
	cValues[2] = -1;
	
	glp_set_mat_row(Prob, cardinal, 2, constr, cValues);
}
Esempio n. 9
0
/* Restriction bci = ai - bi + xi = Ti and z += ai*Ei + bi*Li */
void addBasicRestriction(glp_prob * Prob, int plane) {
    int cardinal, constr[4], i = plane, cardRow;
	double cValues[4];
	char buf[AUXSIZE];

	cardinal = glp_add_cols(Prob, 3);
	
	sprintf(buf,"a%i",i);
	glp_set_col_name(Prob, cardinal, buf);
	glp_set_col_bnds(Prob, cardinal, GLP_LO, 0, 0);
	glp_set_obj_coef(Prob, cardinal, planes[i].costE);
	
	sprintf(buf,"b%i",i);
	glp_set_col_name(Prob, cardinal+1, buf);
	glp_set_col_bnds(Prob, cardinal+1, GLP_LO, 0, 0);
	glp_set_obj_coef(Prob, cardinal+1, planes[i].costL);
	
	sprintf(buf,"x%i",i);
	glp_set_col_name(Prob, cardinal+2, buf);
	if( planes[i].earliest == planes[i].latest )
	    glp_set_col_bnds(Prob, cardinal+2, GLP_FX, planes[i].earliest, 0);
	else
		glp_set_col_bnds(Prob, cardinal+2, GLP_DB, planes[i].earliest, planes[i].latest);
	
    cardRow = glp_add_rows(Prob, 1);
    
	sprintf(buf,"bc%i",i);
	glp_set_row_name(Prob, cardRow, buf);
	glp_set_row_bnds(Prob, cardRow, GLP_FX, planes[i].ideal, 0);
	
	constr[3] = 1 + (constr[2] = 1 + (constr[1] = cardinal));
	cValues[3] = cValues[1] = 1;
	cValues[2] = -1;
	
	glp_set_mat_row(Prob, cardRow, 3, constr, cValues);
}
/**
 * Add constraints that are iterating over "forall addresses"
 * and collects all existing peers for "forall peers" constraints
 *
 * @param cls GAS_MLP_Handle
 * @param key Hashcode
 * @param value ATS_Address
 *
 * @return GNUNET_OK to continue
 */
static int
create_constraint_it (void *cls, const GNUNET_HashCode * key, void *value)
{
  struct GAS_MLP_Handle *mlp = cls;
  struct ATS_Address *address = value;
  struct MLP_information *mlpi;
  unsigned int row_index;
  char *name;

  GNUNET_assert (address->mlp_information != NULL);
  mlpi = (struct MLP_information *) address->mlp_information;

  /* c 1) bandwidth capping
   * b_t  + (-M) * n_t <= 0
   */
  row_index = glp_add_rows (mlp->prob, 1);
  mlpi->r_c1 = row_index;
  /* set row name */
  GNUNET_asprintf(&name, "c1_%s_%s", GNUNET_i2s(&address->peer), address->plugin);
  glp_set_row_name (mlp->prob, row_index, name);
  GNUNET_free (name);
  /* set row bounds: <= 0 */
  glp_set_row_bnds (mlp->prob, row_index, GLP_UP, 0.0, 0.0);
  mlp->ia[mlp->ci] = row_index;
  mlp->ja[mlp->ci] = mlpi->c_b;
  mlp->ar[mlp->ci] = 1;
  mlp->ci++;

  mlp->ia[mlp->ci] = row_index;
  mlp->ja[mlp->ci] = mlpi->c_n;
  mlp->ar[mlp->ci] = -mlp->BIG_M;
  mlp->ci++;

  /* c 3) minimum bandwidth
   * b_t + (-n_t * b_min) >= 0
   */

  row_index = glp_add_rows (mlp->prob, 1);
  /* set row name */
  GNUNET_asprintf(&name, "c3_%s_%s", GNUNET_i2s(&address->peer), address->plugin);
  glp_set_row_name (mlp->prob, row_index, name);
  GNUNET_free (name);
  mlpi->r_c3 = row_index;
  /* set row bounds: >= 0 */
  glp_set_row_bnds (mlp->prob, row_index, GLP_LO, 0.0, 0.0);

  mlp->ia[mlp->ci] = row_index;
  mlp->ja[mlp->ci] = mlpi->c_b;
  mlp->ar[mlp->ci] = 1;
  mlp->ci++;

  mlp->ia[mlp->ci] = row_index;
  mlp->ja[mlp->ci] = mlpi->c_n;
  mlp->ar[mlp->ci] = - (double) mlp->b_min;
  mlp->ci++;

  /* c 4) minimum connections
   * (1)*n_1 + ... + (1)*n_m >= n_min
   */
  mlp->ia[mlp->ci] = mlp->r_c4;
  mlp->ja[mlp->ci] = mlpi->c_n;
  mlp->ar[mlp->ci] = 1;
  mlp->ci++;

  /* c 6) maximize diversity
   * (1)*n_1 + ... + (1)*n_m - d == 0
   */
  mlp->ia[mlp->ci] = mlp->r_c6;
  mlp->ja[mlp->ci] = mlpi->c_n;
  mlp->ar[mlp->ci] = 1;
  mlp->ci++;

  /* c 10) obey network specific quotas
   * (1)*b_1 + ... + (1)*b_m <= quota_n
   */

  int cur_row = 0;
  int c;
  for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
    {
    if (mlp->quota_index[c] == address->atsp_network_type)
    {
      cur_row = mlp->r_quota[c];
      break;
    }
  }

  if (cur_row != 0)
  {
    mlp->ia[mlp->ci] = cur_row;
    mlp->ja[mlp->ci] = mlpi->c_b;
    mlp->ar[mlp->ci] = 1;
    mlp->ci++;
  }
  else
  {
    GNUNET_break (0);
  }

  return GNUNET_OK;
}
Esempio n. 11
0
File: tp3.c Progetto: dennisman/L3
int main(int argc, char *argv[])
{	
	/* structures de données propres à GLPK */
	
	glp_prob *prob; // déclaration d'un pointeur sur le problème
	int ia[1 + NBCREUX];
	int ja[1 + NBCREUX];
	double ar[1 + NBCREUX]; // déclaration des 3 tableaux servant à définir la partie creuse de la matrice des contraintes
	int p[N+1];
	p[1] = 34;
	  p[2] = 6; p[3] = 8; p[4] = 17; p[5] = 16; p[6] = 5; p[7] = 13; p[8] = 21; p[9] = 25; p[10] = 31; p[11] = 14; p[12] = 13; p[13] = 33; p[14] = 9; p[15] = 25; p[16] = 25;

	/* variables récupérant les résultats de la résolution du problème (fonction objectif et valeur des variables) */

	int i,j,pos;
	double z;
	double x[NBVAR];
	
	/* Les déclarations suivantes sont optionnelles, leur but est de donner des noms aux variables et aux contraintes.
	   Cela permet de lire plus facilement le modèle saisi si on en demande un affichage à GLPK, ce qui est souvent utile pour détecter une erreur! */
	
	char nomcontr[NBCONTR][8]; /* ici, les contraintes seront nommées "caisse1", "caisse2",... */
	char numero[NBCONTR][3]; /* pour un nombre à deux chiffres */	
	char nomvar[NBVAR][3]; /* "xA", "xB", ... */
	
	/* Création d'un problème (initialement vide) */
	
	prob = glp_create_prob(); /* allocation mémoire pour le problème */ 
	glp_set_prob_name(prob, "wagons"); /* affectation d'un nom (on pourrait mettre NULL) */
	glp_set_obj_dir(prob, GLP_MIN); /* Il s'agit d'un problème de minimisation, on utiliserait la constante GLP_MAX dans le cas contraire */
	
	/* Déclaration du nombre de contraintes (nombre de lignes de la matrice des contraintes) : NBCONTR */
	
	glp_add_rows(prob, NBCONTR); 

	/* On commence par préciser les bornes sur les constrainte, les indices des contraintes commencent à 1 (!) dans GLPK */

	for(i = 1;i <= N;i++)
	{
		/* partie optionnelle : donner un nom aux contraintes */
		strcpy(nomcontr[i-1], "caisse");
		sprintf(numero[i-1], "%d", i);
		strcat(nomcontr[i-1], numero[i-1]); /* Les contraintes sont nommés "salle1", "salle2"... */		
		glp_set_row_name(prob, i, nomcontr[i-1]); /* Affectation du nom à la contrainte i */
		
		/* partie indispensable : les bornes sur les contraintes */
		glp_set_row_bnds(prob, i, GLP_FX, 1.0, 1.0);
	}	
for(i = N+1;i <= NBCONTR;i++)
	{
	/* partie optionnelle : donner un nom aux contraintes */
		strcpy(nomcontr[i-1], "chaMax");
		sprintf(numero[i-1], "%d", i);
		strcat(nomcontr[i-1], numero[i-1]); /* Les contraintes sont nommés "chargemax", "chargemax2"... */		
		glp_set_row_name(prob, i, nomcontr[i-1]); /* Affectation du nom à la contrainte i */
		// il doit manquer un bout ici
		glp_set_row_bnds(prob, i, GLP_UP, 0.0, 0.0);
		//<=0
		// on met cmax a gauche car c'est une variable
		// il aura le coeff -1 dans la mat creuse
	}

	/* Déclaration du nombre de variables : NBVAR */
	
	glp_add_cols(prob, NBVAR); 
	
	/* On précise le type des variables, les indices commencent à 1 également pour les variables! */
	
	for(i = 1;i <= NBVAR;i++)
	{
		if(i==NBVAR){
			sprintf(nomvar[i-1],"Cm");
			glp_set_col_name(prob, i , nomvar[i-1]);
			glp_set_col_bnds(prob, i, GLP_LO, 0.0, 0.0);
		}else{
			/* partie optionnelle : donner un nom aux variables */
			sprintf(nomvar[i-1],"x%d",i-1);
			glp_set_col_name(prob, i , nomvar[i-1]); /* Les variables sont nommées "xA", "xB"... afin de respecter les noms de variables de l'exercice 2.2 */
		
			/* partie obligatoire : bornes éventuelles sur les variables, et type */
			glp_set_col_bnds(prob, i, GLP_DB, 0.0, 1.0); /* bornes sur les variables, comme sur les contraintes */
			glp_set_col_kind(prob, i, GLP_BV);	/* les variables sont par défaut continues, nous précisons ici qu'elles sont binaires avec la constante GLP_BV, on utiliserait GLP_IV pour des variables entières */	
		}
	} 

	/* définition des coefficients des variables dans la fonction objectif */

	for(i = 1;i <= N*M;i++) glp_set_obj_coef(prob,i,0.0); // Tous les coûts sont ici à 0! Mais on doit specifier quand meme
	glp_set_obj_coef(prob,N*M+1,1.0); // 1 fois cmax
	
	/* Définition des coefficients non-nuls dans la matrice des contraintes, autrement dit les coefficients de la matrice creuse */
	/* Les indices commencent également à 1 ! */



// pour i de 1 a n
//pour i de 1 a m
 /* xij intervient dans la ligne i avec un coeff 1 et dans la ligne 
 n+j avec un coeff pi
 
 ia -> i et n+j
 ar -> 1 et pi
 ja -> xij -> (i-1)*m+j
*/

	pos = 1;
	for(i=1; i<=N; i++){
		for(j=1; j<=M; j++){
			ia[pos] = i;
			ja[pos] = (i-1)*M+j;		ar[pos] = 1;
			pos++; 
			
			ia[pos] = N+j;
			ja[pos] = (i-1)*M+j;	ar[pos] = p[i];
			pos++;
		}
	}
	
//Cmax a -1 !!!
for(i=N+1; i<=N+M;i++){
	ia[pos] = i;
	ja[pos] = N*M+1;				ar[pos] = -1;
	pos++; 	
}
	

	
	/* chargement de la matrice dans le problème */
	
	glp_load_matrix(prob,NBCREUX,ia,ja,ar); 
	
	/* Optionnel : écriture de la modélisation dans un fichier (TRES utile pour debugger!) */

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

	/* Résolution, puis lecture des résultats */
	
	glp_simplex(prob,NULL);	glp_intopt(prob,NULL); /* Résolution */
	z = glp_mip_obj_val(prob); /* Récupération de la valeur optimale. Dans le cas d'un problème en variables continues, l'appel est différent : z = glp_get_obj_val(prob); */
	for(i = 0;i < NBVAR; i++) x[i] = glp_mip_col_val(prob,i+1); /* Récupération de la valeur des variables, Appel différent dans le cas d'un problème en variables continues : for(i = 0;i < p.nbvar;i++) x[i] = glp_get_col_prim(prob,i+1); */

	printf("z = %lf\n",z);
	for(i = 0;i < NBVAR;i++) printf("x%d = %d, ",i,(int)(x[i] + 0.5)); /* un cast est ajouté, x[i] pourrait être égal à 0.99999... */ 
	puts("");

	/* libération mémoire */
	glp_delete_prob(prob); 

	/* J'adore qu'un plan se déroule sans accroc! */
	return 0;
}
Esempio n. 12
0
void npp_build_prob(NPP *npp, glp_prob *prob)
{     /* build resultant (preprocessed) problem */
      NPPROW *row;
      NPPCOL *col;
      NPPAIJ *aij;
      int i, j, type, len, *ind;
      double dir, *val;
      glp_erase_prob(prob);
      glp_set_prob_name(prob, npp->name);
      glp_set_obj_name(prob, npp->obj);
      glp_set_obj_dir(prob, npp->orig_dir);
      if (npp->orig_dir == GLP_MIN)
         dir = +1.0;
      else if (npp->orig_dir == GLP_MAX)
         dir = -1.0;
      else
         xassert(npp != npp);
      glp_set_obj_coef(prob, 0, dir * npp->c0);
      /* build rows */
      for (row = npp->r_head; row != NULL; row = row->next)
      {  row->temp = i = glp_add_rows(prob, 1);
         glp_set_row_name(prob, i, row->name);
         if (row->lb == -DBL_MAX && row->ub == +DBL_MAX)
            type = GLP_FR;
         else if (row->ub == +DBL_MAX)
            type = GLP_LO;
         else if (row->lb == -DBL_MAX)
            type = GLP_UP;
         else if (row->lb != row->ub)
            type = GLP_DB;
         else
            type = GLP_FX;
         glp_set_row_bnds(prob, i, type, row->lb, row->ub);
      }
      /* build columns and the constraint matrix */
      ind = xcalloc(1+prob->m, sizeof(int));
      val = xcalloc(1+prob->m, sizeof(double));
      for (col = npp->c_head; col != NULL; col = col->next)
      {  j = glp_add_cols(prob, 1);
         glp_set_col_name(prob, j, col->name);
#if 0
         glp_set_col_kind(prob, j, col->kind);
#else
         glp_set_col_kind(prob, j, col->is_int ? GLP_IV : GLP_CV);
#endif
         if (col->lb == -DBL_MAX && col->ub == +DBL_MAX)
            type = GLP_FR;
         else if (col->ub == +DBL_MAX)
            type = GLP_LO;
         else if (col->lb == -DBL_MAX)
            type = GLP_UP;
         else if (col->lb != col->ub)
            type = GLP_DB;
         else
            type = GLP_FX;
         glp_set_col_bnds(prob, j, type, col->lb, col->ub);
         glp_set_obj_coef(prob, j, dir * col->coef);
         len = 0;
         for (aij = col->ptr; aij != NULL; aij = aij->c_next)
         {  len++;
            ind[len] = aij->row->temp;
            val[len] = aij->val;
         }
         glp_set_mat_col(prob, j, len, ind, val);
      }
      xfree(ind);
      xfree(val);
      /* resultant problem has been built */
      npp->m = prob->m;
      npp->n = prob->n;
      npp->nnz = prob->nnz;
      npp->row_ref = xcalloc(1+npp->m, sizeof(int));
      npp->col_ref = xcalloc(1+npp->n, sizeof(int));
      for (row = npp->r_head, i = 0; row != NULL; row = row->next)
         npp->row_ref[++i] = row->i;
      for (col = npp->c_head, j = 0; col != NULL; col = col->next)
         npp->col_ref[++j] = col->j;
      /* transformed problem segment is no longer needed */
      dmp_delete_pool(npp->pool), npp->pool = NULL;
      npp->name = npp->obj = NULL;
      npp->c0 = 0.0;
      npp->r_head = npp->r_tail = NULL;
      npp->c_head = npp->c_tail = NULL;
      return;
}
Esempio n. 13
0
void glp_copy_prob(glp_prob *dest, glp_prob *prob, int names)
{     glp_tree *tree = dest->tree;
      glp_bfcp bfcp;
      int i, j, len, *ind;
      double *val;
      if (tree != NULL && tree->reason != 0)
         xerror("glp_copy_prob: operation not allowed\n");
      if (dest == prob)
         xerror("glp_copy_prob: copying problem object to itself not al"
            "lowed\n");
      if (!(names == GLP_ON || names == GLP_OFF))
         xerror("glp_copy_prob: names = %d; invalid parameter\n",
            names);
      glp_erase_prob(dest);
      if (names && prob->name != NULL)
         glp_set_prob_name(dest, prob->name);
      if (names && prob->obj != NULL)
         glp_set_obj_name(dest, prob->obj);
      dest->dir = prob->dir;
      dest->c0 = prob->c0;
      if (prob->m > 0)
         glp_add_rows(dest, prob->m);
      if (prob->n > 0)
         glp_add_cols(dest, prob->n);
      glp_get_bfcp(prob, &bfcp);
      glp_set_bfcp(dest, &bfcp);
      dest->pbs_stat = prob->pbs_stat;
      dest->dbs_stat = prob->dbs_stat;
      dest->obj_val = prob->obj_val;
      dest->some = prob->some;
      dest->ipt_stat = prob->ipt_stat;
      dest->ipt_obj = prob->ipt_obj;
      dest->mip_stat = prob->mip_stat;
      dest->mip_obj = prob->mip_obj;
      for (i = 1; i <= prob->m; i++)
      {  GLPROW *to = dest->row[i];
         GLPROW *from = prob->row[i];
         if (names && from->name != NULL)
            glp_set_row_name(dest, i, from->name);
         to->type = from->type;
         to->lb = from->lb;
         to->ub = from->ub;
         to->rii = from->rii;
         to->stat = from->stat;
         to->prim = from->prim;
         to->dual = from->dual;
         to->pval = from->pval;
         to->dval = from->dval;
         to->mipx = from->mipx;
      }
      ind = xcalloc(1+prob->m, sizeof(int));
      val = xcalloc(1+prob->m, sizeof(double));
      for (j = 1; j <= prob->n; j++)
      {  GLPCOL *to = dest->col[j];
         GLPCOL *from = prob->col[j];
         if (names && from->name != NULL)
            glp_set_col_name(dest, j, from->name);
         to->kind = from->kind;
         to->type = from->type;
         to->lb = from->lb;
         to->ub = from->ub;
         to->coef = from->coef;
         len = glp_get_mat_col(prob, j, ind, val);
         glp_set_mat_col(dest, j, len, ind, val);
         to->sjj = from->sjj;
         to->stat = from->stat;
         to->prim = from->prim;
         to->dual = from->dual;
         to->pval = from->pval;
         to->dval = from->dval;
         to->mipx = from->mipx;
      }
      xfree(ind);
      xfree(val);
      return;
}
Esempio n. 14
0
void glp_maxflow_lp(glp_prob *lp, glp_graph *G, int names, int s,
      int t, int a_cap)
{     glp_vertex *v;
      glp_arc *a;
      int i, j, type, ind[1+2];
      double cap, val[1+2];
      if (!(names == GLP_ON || names == GLP_OFF))
         xerror("glp_maxflow_lp: names = %d; invalid parameter\n",
            names);
      if (!(1 <= s && s <= G->nv))
         xerror("glp_maxflow_lp: s = %d; source node number out of rang"
            "e\n", s);
      if (!(1 <= t && t <= G->nv))
         xerror("glp_maxflow_lp: t = %d: sink node number out of range "
            "\n", t);
      if (s == t)
         xerror("glp_maxflow_lp: s = t = %d; source and sink nodes must"
            " be distinct\n", s);
      if (a_cap >= 0 && a_cap > G->a_size - (int)sizeof(double))
         xerror("glp_maxflow_lp: a_cap = %d; invalid offset\n", a_cap);
      glp_erase_prob(lp);
      if (names) glp_set_prob_name(lp, G->name);
      glp_set_obj_dir(lp, GLP_MAX);
      glp_add_rows(lp, G->nv);
      for (i = 1; i <= G->nv; i++)
      {  v = G->v[i];
         if (names) glp_set_row_name(lp, i, v->name);
         if (i == s)
            type = GLP_LO;
         else if (i == t)
            type = GLP_UP;
         else
            type = GLP_FX;
         glp_set_row_bnds(lp, i, type, 0.0, 0.0);
      }
      if (G->na > 0) glp_add_cols(lp, G->na);
      for (i = 1, j = 0; i <= G->nv; i++)
      {  v = G->v[i];
         for (a = v->out; a != NULL; a = a->t_next)
         {  j++;
            if (names)
            {  char name[50+1];
               sprintf(name, "x[%d,%d]", a->tail->i, a->head->i);
               xassert(strlen(name) < sizeof(name));
               glp_set_col_name(lp, j, name);
            }
            if (a->tail->i != a->head->i)
            {  ind[1] = a->tail->i, val[1] = +1.0;
               ind[2] = a->head->i, val[2] = -1.0;
               glp_set_mat_col(lp, j, 2, ind, val);
            }
            if (a_cap >= 0)
               memcpy(&cap, (char *)a->data + a_cap, sizeof(double));
            else
               cap = 1.0;
            if (cap == DBL_MAX)
               type = GLP_LO;
            else if (cap != 0.0)
               type = GLP_DB;
            else
               type = GLP_FX;
            glp_set_col_bnds(lp, j, type, 0.0, cap);
            if (a->tail->i == s)
               glp_set_obj_coef(lp, j, +1.0);
            else if (a->head->i == s)
               glp_set_obj_coef(lp, j, -1.0);
         }
      }
      xassert(j == G->na);
      return;
}
Esempio n. 15
0
void c_glp_set_row_name(glp_prob *lp, int i, const char * name){
  	glp_set_row_name(lp, i, name);
}
Esempio n. 16
0
/*
    R is the random contraint data in row major memory layout
    ridx is an N array of integers 
    soln is an array of length (n+1) soln[n] is t (objective value)
    active_constr is an N-length 0-1 array
*/
void solve_lp(int N, int n, double* R, int* ridx, double* soln, int* active_constr)
{
    double tol = 1.0e-14;
    int size = (N+1)*(n+1) + 1; // We add one because GLPK indexes arrays
                                // starting at 1 instead of 0.

    glp_prob *lp;
    int* ia = malloc(size * sizeof(int));
    int* ja = malloc(size * sizeof(int));
    double* ar = malloc(size * sizeof(double));

    int i, j;
  
    lp = glp_create_prob();
    glp_set_prob_name(lp, "portfolio");
    glp_set_obj_dir(lp, GLP_MAX);

    glp_add_rows(lp, N+1);

    // Sampled constraints are ">= 0"
    for (i = 1; i <= N; i++) {
        glp_set_row_bnds(lp, i, GLP_LO, 0.0, 0.0);
    }
  
    // Sum = 1 constraint
    glp_set_row_name(lp, N+1, "sum");
    glp_set_row_bnds(lp, N+1, GLP_FX, 1.0, 1.0);
  
    glp_add_cols(lp, n+1);
  
    // Nonnegative variables y
    for (i = 1; i <= n; i++) {
        glp_set_col_bnds(lp, i, GLP_LO, 0.0, 0.0);
        glp_set_obj_coef(lp, i, 0.0);
    }
  
    // Free variable t
    glp_set_col_name(lp, n+1, "t");
    glp_set_col_bnds(lp, n+1, GLP_FR, 0.0, 0.0);
    glp_set_obj_coef(lp, n+1, 1.0);
    
    // for (i = 0; i < N*(n-1); i++) {
    //     printf("%d: %g\n", i, R[i]);
    // }

    int idx = 1;
    // Sampled constraints
    for (i = 1; i <= N; i++) {
        // Uncertain assets
        for (j = 1; j < n; j++) {
            ia[idx] = i;
            ja[idx] = j;
            ar[idx] = R[ ridx[(i-1)] * (n-1) + (j-1) ];
            idx += 1;
        }

        // Fixed return asset
        ia[idx] = i;
        ja[idx] = n;
        ar[idx] = 1.05;
        idx += 1;

        // t
        ia[idx] = i;
        ja[idx] = n+1;
        ar[idx] = -1.0;
        idx += 1;
    }

    // Sum = 1 constraint
    for (i = 1; i <= n; i++) {
        ia[idx] = N+1;
        ja[idx] = i;
        ar[idx] = 1.0;
        idx += 1;
    }
    // t
    ia[idx] = N+1;
    ja[idx] = n+1;
    ar[idx] = 0.0;
    idx += 1;

    // for (i = 1; i < size; i++) {
    //     printf("%d %d %g\n", ia[i], ja[i], ar[i]);
    // }

    glp_load_matrix(lp, size-1, ia, ja, ar);

    // glp_scale_prob(lp, GLP_SF_AUTO);

    glp_smcp param;
    glp_init_smcp(&param);
    param.meth = GLP_PRIMAL;
    //glp_std_basis(lp);
    glp_simplex(lp, &param);
  
    double z = glp_get_obj_val(lp);
    // printf("z = %g\n", z);
    if (soln) {
        for (i = 0; i < n; i++) {
            double y = glp_get_col_prim(lp, i+1);
            soln[i] = y;
            // printf("y%d = %g\n", i, y);
        }
        double t = glp_get_col_prim(lp, n+1);
        soln[n] = t;
        // printf("t = %g\n", glp_get_col_prim(lp, n+1));
    }
  

    for (i = 1; i <= N; i++) {
        double slack = glp_get_row_prim(lp, i);
        active_constr[i-1] = fabs(slack) < tol ? 1 : 0;
        // printf("constr%d %d\n", i, active_constr[i-1]);
    }


    glp_delete_prob(lp);
    // glp_free_env();
    free(ia);
    free(ja);
    free(ar);
}
Esempio n. 17
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
}
Esempio n. 18
0
int glp_read_prob(glp_prob *P, int flags, const char *fname)
{     DMX _csa, *csa = &_csa;
      int mip, m, n, nnz, ne, i, j, k, type, kind, ret, *ln = NULL,
         *ia = NULL, *ja = NULL;
      double lb, ub, temp, *ar = NULL;
      char *rf = NULL, *cf = NULL;
      if (P == NULL || P->magic != GLP_PROB_MAGIC)
         xerror("glp_read_prob: P = %p; invalid problem object\n",
            P);
      if (flags != 0)
         xerror("glp_read_prob: flags = %d; invalid parameter\n",
            flags);
      if (fname == NULL)
         xerror("glp_read_prob: fname = %d; invalid parameter\n",
            fname);
      glp_erase_prob(P);
      if (setjmp(csa->jump))
      {  ret = 1;
         goto done;
      }
      csa->fname = fname;
      csa->fp = NULL;
      csa->count = 0;
      csa->c = '\n';
      csa->field[0] = '\0';
      csa->empty = csa->nonint = 0;
      xprintf("Reading problem data from '%s'...\n", fname);
      csa->fp = glp_open(fname, "r");
      if (csa->fp == NULL)
      {  xprintf("Unable to open '%s' - %s\n", fname, get_err_msg());
         longjmp(csa->jump, 1);
      }
      /* read problem line */
      read_designator(csa);
      if (strcmp(csa->field, "p") != 0)
         error(csa, "problem line missing or invalid");
      read_field(csa);
      if (strcmp(csa->field, "lp") == 0)
         mip = 0;
      else if (strcmp(csa->field, "mip") == 0)
         mip = 1;
      else
         error(csa, "wrong problem designator; 'lp' or 'mip' expected");
      read_field(csa);
      if (strcmp(csa->field, "min") == 0)
         glp_set_obj_dir(P, GLP_MIN);
      else if (strcmp(csa->field, "max") == 0)
         glp_set_obj_dir(P, GLP_MAX);
      else
         error(csa, "objective sense missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &m) == 0 && m >= 0))
         error(csa, "number of rows missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &n) == 0 && n >= 0))
         error(csa, "number of columns missing or invalid");
      read_field(csa);
      if (!(str2int(csa->field, &nnz) == 0 && nnz >= 0))
         error(csa, "number of constraint coefficients missing or inval"
            "id");
      if (m > 0)
      {  glp_add_rows(P, m);
         for (i = 1; i <= m; i++)
            glp_set_row_bnds(P, i, GLP_FX, 0.0, 0.0);
      }
      if (n > 0)
      {  glp_add_cols(P, n);
         for (j = 1; j <= n; j++)
         {  if (!mip)
               glp_set_col_bnds(P, j, GLP_LO, 0.0, 0.0);
            else
               glp_set_col_kind(P, j, GLP_BV);
         }
      }
      end_of_line(csa);
      /* allocate working arrays */
      rf = xcalloc(1+m, sizeof(char));
      memset(rf, 0, 1+m);
      cf = xcalloc(1+n, sizeof(char));
      memset(cf, 0, 1+n);
      ln = xcalloc(1+nnz, sizeof(int));
      ia = xcalloc(1+nnz, sizeof(int));
      ja = xcalloc(1+nnz, sizeof(int));
      ar = xcalloc(1+nnz, sizeof(double));
      /* read descriptor lines */
      ne = 0;
      for (;;)
      {  read_designator(csa);
         if (strcmp(csa->field, "i") == 0)
         {  /* row descriptor */
            read_field(csa);
            if (str2int(csa->field, &i) != 0)
               error(csa, "row number missing or invalid");
            if (!(1 <= i && i <= m))
               error(csa, "row number out of range");
            read_field(csa);
            if (strcmp(csa->field, "f") == 0)
               type = GLP_FR;
            else if (strcmp(csa->field, "l") == 0)
               type = GLP_LO;
            else if (strcmp(csa->field, "u") == 0)
               type = GLP_UP;
            else if (strcmp(csa->field, "d") == 0)
               type = GLP_DB;
            else if (strcmp(csa->field, "s") == 0)
               type = GLP_FX;
            else
               error(csa, "row type missing or invalid");
            if (type == GLP_LO || type == GLP_DB || type == GLP_FX)
            {  read_field(csa);
               if (str2num(csa->field, &lb) != 0)
                  error(csa, "row lower bound/fixed value missing or in"
                     "valid");
            }
            else
               lb = 0.0;
            if (type == GLP_UP || type == GLP_DB)
            {  read_field(csa);
               if (str2num(csa->field, &ub) != 0)
                  error(csa, "row upper bound missing or invalid");
            }
            else
               ub = 0.0;
            if (rf[i] & 0x01)
               error(csa, "duplicate row descriptor");
            glp_set_row_bnds(P, i, type, lb, ub), rf[i] |= 0x01;
         }
         else if (strcmp(csa->field, "j") == 0)
         {  /* column descriptor */
            read_field(csa);
            if (str2int(csa->field, &j) != 0)
               error(csa, "column number missing or invalid");
            if (!(1 <= j && j <= n))
               error(csa, "column number out of range");
            if (!mip)
               kind = GLP_CV;
            else
            {  read_field(csa);
               if (strcmp(csa->field, "c") == 0)
                  kind = GLP_CV;
               else if (strcmp(csa->field, "i") == 0)
                  kind = GLP_IV;
               else if (strcmp(csa->field, "b") == 0)
               {  kind = GLP_IV;
                  type = GLP_DB, lb = 0.0, ub = 1.0;
                  goto skip;
               }
               else
                  error(csa, "column kind missing or invalid");
            }
            read_field(csa);
            if (strcmp(csa->field, "f") == 0)
               type = GLP_FR;
            else if (strcmp(csa->field, "l") == 0)
               type = GLP_LO;
            else if (strcmp(csa->field, "u") == 0)
               type = GLP_UP;
            else if (strcmp(csa->field, "d") == 0)
               type = GLP_DB;
            else if (strcmp(csa->field, "s") == 0)
               type = GLP_FX;
            else
               error(csa, "column type missing or invalid");
            if (type == GLP_LO || type == GLP_DB || type == GLP_FX)
            {  read_field(csa);
               if (str2num(csa->field, &lb) != 0)
                  error(csa, "column lower bound/fixed value missing or"
                     " invalid");
            }
            else
               lb = 0.0;
            if (type == GLP_UP || type == GLP_DB)
            {  read_field(csa);
               if (str2num(csa->field, &ub) != 0)
                  error(csa, "column upper bound missing or invalid");
            }
            else
               ub = 0.0;
skip:       if (cf[j] & 0x01)
               error(csa, "duplicate column descriptor");
            glp_set_col_kind(P, j, kind);
            glp_set_col_bnds(P, j, type, lb, ub), cf[j] |= 0x01;
         }
         else if (strcmp(csa->field, "a") == 0)
         {  /* coefficient descriptor */
            read_field(csa);
            if (str2int(csa->field, &i) != 0)
               error(csa, "row number missing or invalid");
            if (!(0 <= i && i <= m))
               error(csa, "row number out of range");
            read_field(csa);
            if (str2int(csa->field, &j) != 0)
               error(csa, "column number missing or invalid");
            if (!((i == 0 ? 0 : 1) <= j && j <= n))
               error(csa, "column number out of range");
            read_field(csa);
            if (i == 0)
            {  if (str2num(csa->field, &temp) != 0)
                  error(csa, "objective %s missing or invalid",
                     j == 0 ? "constant term" : "coefficient");
               if (cf[j] & 0x10)
                  error(csa, "duplicate objective %s",
                     j == 0 ? "constant term" : "coefficient");
               glp_set_obj_coef(P, j, temp), cf[j] |= 0x10;
            }
            else
            {  if (str2num(csa->field, &temp) != 0)
                  error(csa, "constraint coefficient missing or invalid"
                     );
               if (ne == nnz)
                  error(csa, "too many constraint coefficient descripto"
                     "rs");
               ln[++ne] = csa->count;
               ia[ne] = i, ja[ne] = j, ar[ne] = temp;
            }
         }
         else if (strcmp(csa->field, "n") == 0)
         {  /* symbolic name descriptor */
            read_field(csa);
            if (strcmp(csa->field, "p") == 0)
            {  /* problem name */
               read_field(csa);
               if (P->name != NULL)
                  error(csa, "duplicate problem name");
               glp_set_prob_name(P, csa->field);
            }
            else if (strcmp(csa->field, "z") == 0)
            {  /* objective name */
               read_field(csa);
               if (P->obj != NULL)
                  error(csa, "duplicate objective name");
               glp_set_obj_name(P, csa->field);
            }
            else if (strcmp(csa->field, "i") == 0)
            {  /* row name */
               read_field(csa);
               if (str2int(csa->field, &i) != 0)
                  error(csa, "row number missing or invalid");
               if (!(1 <= i && i <= m))
                  error(csa, "row number out of range");
               read_field(csa);
               if (P->row[i]->name != NULL)
                  error(csa, "duplicate row name");
               glp_set_row_name(P, i, csa->field);
            }
            else if (strcmp(csa->field, "j") == 0)
            {  /* column name */
               read_field(csa);
               if (str2int(csa->field, &j) != 0)
                  error(csa, "column number missing or invalid");
               if (!(1 <= j && j <= n))
                  error(csa, "column number out of range");
               read_field(csa);
               if (P->col[j]->name != NULL)
                  error(csa, "duplicate column name");
               glp_set_col_name(P, j, csa->field);
            }
            else
               error(csa, "object designator missing or invalid");
         }
         else if (strcmp(csa->field, "e") == 0)
            break;
         else
            error(csa, "line designator missing or invalid");
         end_of_line(csa);
      }
      if (ne < nnz)
         error(csa, "too few constraint coefficient descriptors");
      xassert(ne == nnz);
      k = glp_check_dup(m, n, ne, ia, ja);
      xassert(0 <= k && k <= nnz);
      if (k > 0)
      {  csa->count = ln[k];
         error(csa, "duplicate constraint coefficient");
      }
      glp_load_matrix(P, ne, ia, ja, ar);
      /* print some statistics */
      if (P->name != NULL)
         xprintf("Problem: %s\n", P->name);
      if (P->obj != NULL)
         xprintf("Objective: %s\n", P->obj);
      xprintf("%d row%s, %d column%s, %d non-zero%s\n",
         m, m == 1 ? "" : "s", n, n == 1 ? "" : "s", nnz, nnz == 1 ?
         "" : "s");
      if (glp_get_num_int(P) > 0)
      {  int ni = glp_get_num_int(P);
         int nb = glp_get_num_bin(P);
         if (ni == 1)
         {  if (nb == 0)
               xprintf("One variable is integer\n");
            else
               xprintf("One variable is binary\n");
         }
         else
         {  xprintf("%d integer variables, ", ni);
            if (nb == 0)
               xprintf("none");
            else if (nb == 1)
               xprintf("one");
            else if (nb == ni)
               xprintf("all");
            else
               xprintf("%d", nb);
            xprintf(" of which %s binary\n", nb == 1 ? "is" : "are");
         }
      }
      xprintf("%d lines were read\n", csa->count);
      /* problem data has been successfully read */
      glp_sort_matrix(P);
      ret = 0;
done: if (csa->fp != NULL) glp_close(csa->fp);
      if (rf != NULL) xfree(rf);
      if (cf != NULL) xfree(cf);
      if (ln != NULL) xfree(ln);
      if (ia != NULL) xfree(ia);
      if (ja != NULL) xfree(ja);
      if (ar != NULL) xfree(ar);
      if (ret) glp_erase_prob(P);
      return ret;
}
Esempio n. 19
0
/* Restrictions xj - xi >= Sij&ij + (Li - Ej)&ji and
                xi - xj >= Sji&ji + (Lj - Ei)&ij and
				&ij + &ji = 1*/
void addOrderConstraint(glp_prob * Prob, int plane1, int plane2) {
    int cardinal, constr[3], i = plane1, j = plane2;
	double cValues[3];
	char buf[AUXSIZE];
	int xi, xj, uij;
	
	sprintf(buf,"x%i",i);
	xi = glp_find_col(Prob, buf);
    sprintf(buf,"x%i",j);
	xj = glp_find_col(Prob, buf);
	
	uij = glp_add_cols(Prob, 2);
	
	sprintf(buf,"u%i,%i",i,j);
	glp_set_col_name(Prob, uij, buf);
    glp_set_col_kind(Prob, uij, GLP_BV);
    
	sprintf(buf,"u%i,%i",j,i);
	glp_set_col_name(Prob, uij+1, buf);
    glp_set_col_kind(Prob, uij+1, GLP_BV);
    
	cardinal = glp_add_rows(Prob, 2);
	
	sprintf(buf,"S%i,%i",i,j);
	glp_set_row_name(Prob, cardinal, buf);
	glp_set_row_bnds(Prob, cardinal, GLP_LO, 0, 0);
	
	constr[1] = xj;
	constr[2] = xi;
	constr[3] = uij;
	constr[4] = uij+1;
	cValues[1] = 1;
	cValues[2] = -1;
	cValues[3] = -planes[i].sep[j];
	cValues[4] = planes[i].latest - planes[j].earliest;
	
	glp_set_mat_row(Prob, cardinal, 4, constr, cValues);
	
	sprintf(buf,"S%i,%i",j,i);
	glp_set_row_name(Prob, cardinal+1, buf);
	glp_set_row_bnds(Prob, cardinal+1, GLP_LO, 0, 0);
	
	constr[1] = xi;
	constr[2] = xj;
	constr[3] = uij+1;
	constr[4] = uij;
	cValues[1] = 1;
	cValues[2] = -1;
	cValues[3] = -planes[j].sep[i];
	cValues[4] = planes[j].latest - planes[i].earliest;
	
	glp_set_mat_row(Prob, cardinal+1, 4, constr, cValues);
	
	cardinal = glp_add_rows(Prob, 1);

	sprintf(buf,"E%i,%i",i,j);
	glp_set_row_name(Prob, cardinal, buf);
	glp_set_row_bnds(Prob, cardinal, GLP_FX, 1, 0);
	
	constr[1] = uij;
	constr[2] = uij+1;
	cValues[1] = 1;
	cValues[2] = 1;
	
	glp_set_mat_row(Prob, cardinal, 2, constr, cValues);
}
static void
mlp_add_constraints_all_addresses (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses)
{
  unsigned int n_addresses;
  int c;
  char *name;

  /* Problem matrix*/
  n_addresses = GNUNET_CONTAINER_multihashmap_size(addresses);

  /* Required indices in the constrain matrix
   *
   * feasibility constraints:
   *
   * c 1) bandwidth capping
   * #rows: |n_addresses|
   * #indices: 2 * |n_addresses|
   *
   * c 2) one active address per peer
   * #rows: |peers|
   * #indices: |n_addresses|
   *
   * c 3) minium bandwidth assigned
   * #rows: |n_addresses|
   * #indices: 2 * |n_addresses|
   *
   * c 4) minimum number of active connections
   * #rows: 1
   * #indices: |n_addresses|
   *
   * c 5) maximum ressource consumption
   * #rows: |ressources|
   * #indices: |n_addresses|
   *
   * c 10) obey network specific quota
   * #rows: |network types
   * #indices: |n_addresses|
   *
   * Sum for feasibility constraints:
   * #rows: 3 * |n_addresses| +  |ressources| + |peers| + 1
   * #indices: 7 * |n_addresses|
   *
   * optimality constraints:
   *
   * c 6) diversity
   * #rows: 1
   * #indices: |n_addresses| + 1
   *
   * c 7) quality
   * #rows: |quality properties|
   * #indices: |n_addresses| + |quality properties|
   *
   * c 8) utilization
   * #rows: 1
   * #indices: |n_addresses| + 1
   *
   * c 9) relativity
   * #rows: |peers|
   * #indices: |n_addresses| + |peers|
   * */

  /* last +1 caused by glpk index starting with one: [1..pi]*/
  int pi = ((7 * n_addresses) + (5 * n_addresses +  mlp->m_q + mlp->c_p + 2) + 1);
  mlp->cm_size = pi;
  mlp->ci = 1;

  /* row index */
  int *ia = GNUNET_malloc (pi * sizeof (int));
  mlp->ia = ia;

  /* column index */
  int *ja = GNUNET_malloc (pi * sizeof (int));
  mlp->ja = ja;

  /* coefficient */
  double *ar= GNUNET_malloc (pi * sizeof (double));
  mlp->ar = ar;

  /* Adding constraint rows
   * This constraints are kind of "for all addresses"
   * Feasibility constraints:
   *
   * c 1) bandwidth capping
   * c 3) minimum bandwidth
   * c 4) minimum number of connections
   * c 6) maximize diversity
   * c 10) obey network specific quota
   */

  /* Row for c4) minimum connection */
  int min = mlp->n_min;
  /* Number of minimum connections is min(|Peers|, n_min) */
  if (mlp->n_min > mlp->c_p)
    min = mlp->c_p;

  mlp->r_c4 = glp_add_rows (mlp->prob, 1);
  glp_set_row_name (mlp->prob, mlp->r_c4, "c4");
  glp_set_row_bnds (mlp->prob, mlp->r_c4, GLP_LO, min, min);

  /* Add row for c6) */

  mlp->r_c6 = glp_add_rows (mlp->prob, 1);
  /* Set type type to fix */
  glp_set_row_bnds (mlp->prob, mlp->r_c6, GLP_FX, 0.0, 0.0);
  /* Setting -D */
  ia[mlp->ci] = mlp->r_c6 ;
  ja[mlp->ci] = mlp->c_d;
  ar[mlp->ci] = -1;
  mlp->ci++;

  /* Add rows for c 10) */
  for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
  {
    mlp->r_quota[c] = glp_add_rows (mlp->prob, 1);
    char * text;
    GNUNET_asprintf(&text, "quota_ats_%i", mlp->quota_index[c]);
    glp_set_row_name (mlp->prob, mlp->r_quota[c], text);
    GNUNET_free (text);
    /* Set bounds to 0 <= x <= quota_out */
    glp_set_row_bnds (mlp->prob, mlp->r_quota[c], GLP_UP, 0.0, mlp->quota_out[c]);
  }

  GNUNET_CONTAINER_multihashmap_iterate (addresses, create_constraint_it, mlp);

  /* Adding constraint rows
   * This constraints are kind of "for all peers"
   * Feasibility constraints:
   *
   * c 2) 1 address per peer
   * sum (n_p1_1 + ... + n_p1_n) = 1
   *
   * c 8) utilization
   * sum (f_p * b_p1_1 + ... + f_p * b_p1_n) - u = 0
   *
   * c 9) relativity
   * V p : sum (bt_1 + ... +bt_n) - f_p * r = 0
   * */

  /* Adding rows for c 8) */
  mlp->r_c8 = glp_add_rows (mlp->prob, mlp->c_p);
  glp_set_row_name (mlp->prob, mlp->r_c8, "c8");
  /* Set row bound == 0 */
  glp_set_row_bnds (mlp->prob, mlp->r_c8, GLP_FX, 0.0, 0.0);
  /* -u */

  ia[mlp->ci] = mlp->r_c8;
  ja[mlp->ci] = mlp->c_u;
  ar[mlp->ci] = -1;
  mlp->ci++;

  struct ATS_Peer * peer = mlp->peer_head;
  /* For all peers */
  while (peer != NULL)
  {
    struct ATS_Address *addr = peer->head;
    struct MLP_information *mlpi = NULL;

    /* Adding rows for c 2) */
    peer->r_c2 = glp_add_rows (mlp->prob, 1);
    GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&peer->id));
    glp_set_row_name (mlp->prob, peer->r_c2, name);
    GNUNET_free (name);
    /* Set row bound == 1 */
    glp_set_row_bnds (mlp->prob, peer->r_c2, GLP_FX, 1.0, 1.0);

    /* Adding rows for c 9) */
#if ENABLE_C9
    peer->r_c9 = glp_add_rows (mlp->prob, 1);
    GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&peer->id));
    glp_set_row_name (mlp->prob, peer->r_c9, name);
    GNUNET_free (name);
    /* Set row bound == 0 */
    glp_set_row_bnds (mlp->prob, peer->r_c9, GLP_LO, 0.0, 0.0);

    /* Set -r */
    ia[mlp->ci] = peer->r_c9;
    ja[mlp->ci] = mlp->c_r;
    ar[mlp->ci] = -peer->f;
    mlp->ci++;
#endif
    /* For all addresses of this peer */
    while (addr != NULL)
    {
      mlpi = (struct MLP_information *) addr->mlp_information;

      /* coefficient for c 2) */
      ia[mlp->ci] = peer->r_c2;
      ja[mlp->ci] = mlpi->c_n;
      ar[mlp->ci] = 1;
      mlp->ci++;

      /* coefficient for c 8) */
      ia[mlp->ci] = mlp->r_c8;
      ja[mlp->ci] = mlpi->c_b;
      ar[mlp->ci] = peer->f;
      mlp->ci++;

#if ENABLE_C9
      /* coefficient for c 9) */
      ia[mlp->ci] = peer->r_c9;
      ja[mlp->ci] = mlpi->c_b;
      ar[mlp->ci] = 1;
      mlp->ci++;
#endif

      addr = addr->next;
    }
    peer = peer->next;
  }

  /* c 7) For all quality metrics */
  for (c = 0; c < mlp->m_q; c++)
  {
    struct ATS_Peer *tp;
    struct ATS_Address *ta;
    struct MLP_information * mlpi;
    double value = 1.0;

    /* Adding rows for c 7) */
    mlp->r_q[c] = glp_add_rows (mlp->prob, 1);
    GNUNET_asprintf(&name, "c7_q%i_%s", c, mlp_ats_to_string(mlp->q[c]));
    glp_set_row_name (mlp->prob, mlp->r_q[c], name);
    GNUNET_free (name);
    /* Set row bound == 0 */
    glp_set_row_bnds (mlp->prob, mlp->r_q[c], GLP_FX, 0.0, 0.0);

    ia[mlp->ci] = mlp->r_q[c];
    ja[mlp->ci] = mlp->c_q[c];
    ar[mlp->ci] = -1;
    mlp->ci++;

    for (tp = mlp->peer_head; tp != NULL; tp = tp->next)
      for (ta = tp->head; ta != NULL; ta = ta->next)
        {
          mlpi = ta->mlp_information;
          value = mlpi->q_averaged[c];

          mlpi->r_q[c] = mlp->r_q[c];

          ia[mlp->ci] = mlp->r_q[c];
          ja[mlp->ci] = mlpi->c_b;
          ar[mlp->ci] = tp->f_q[c] * value;
          mlp->ci++;
        }
  }
}
Esempio n. 21
0
void lpx_set_row_name(LPX *lp, int i, const char *name)
{     /* assign (change) row name */
      glp_set_row_name(lp, i, name);
      return;
}
Esempio n. 22
0
void glp_mincost_lp(glp_prob *lp, glp_graph *G, int names, int v_rhs,
      int a_low, int a_cap, int a_cost)
{     glp_vertex *v;
      glp_arc *a;
      int i, j, type, ind[1+2];
      double rhs, low, cap, cost, val[1+2];
      if (!(names == GLP_ON || names == GLP_OFF))
         xerror("glp_mincost_lp: names = %d; invalid parameter\n",
            names);
      if (v_rhs >= 0 && v_rhs > G->v_size - (int)sizeof(double))
         xerror("glp_mincost_lp: v_rhs = %d; invalid offset\n", v_rhs);
      if (a_low >= 0 && a_low > G->a_size - (int)sizeof(double))
         xerror("glp_mincost_lp: a_low = %d; invalid offset\n", a_low);
      if (a_cap >= 0 && a_cap > G->a_size - (int)sizeof(double))
         xerror("glp_mincost_lp: a_cap = %d; invalid offset\n", a_cap);
      if (a_cost >= 0 && a_cost > G->a_size - (int)sizeof(double))
         xerror("glp_mincost_lp: a_cost = %d; invalid offset\n", a_cost)
            ;
      glp_erase_prob(lp);
      if (names) glp_set_prob_name(lp, G->name);
      if (G->nv > 0) glp_add_rows(lp, G->nv);
      for (i = 1; i <= G->nv; i++)
      {  v = G->v[i];
         if (names) glp_set_row_name(lp, i, v->name);
         if (v_rhs >= 0)
            memcpy(&rhs, (char *)v->data + v_rhs, sizeof(double));
         else
            rhs = 0.0;
         glp_set_row_bnds(lp, i, GLP_FX, rhs, rhs);
      }
      if (G->na > 0) glp_add_cols(lp, G->na);
      for (i = 1, j = 0; i <= G->nv; i++)
      {  v = G->v[i];
         for (a = v->out; a != NULL; a = a->t_next)
         {  j++;
            if (names)
            {  char name[50+1];
               sprintf(name, "x[%d,%d]", a->tail->i, a->head->i);
               xassert(strlen(name) < sizeof(name));
               glp_set_col_name(lp, j, name);
            }
            if (a->tail->i != a->head->i)
            {  ind[1] = a->tail->i, val[1] = +1.0;
               ind[2] = a->head->i, val[2] = -1.0;
               glp_set_mat_col(lp, j, 2, ind, val);
            }
            if (a_low >= 0)
               memcpy(&low, (char *)a->data + a_low, sizeof(double));
            else
               low = 0.0;
            if (a_cap >= 0)
               memcpy(&cap, (char *)a->data + a_cap, sizeof(double));
            else
               cap = 1.0;
            if (cap == DBL_MAX)
               type = GLP_LO;
            else if (low != cap)
               type = GLP_DB;
            else
               type = GLP_FX;
            glp_set_col_bnds(lp, j, type, low, cap);
            if (a_cost >= 0)
               memcpy(&cost, (char *)a->data + a_cost, sizeof(double));
            else
               cost = 0.0;
            glp_set_obj_coef(lp, j, cost);
         }
      }
      xassert(j == G->na);
      return;
}
Esempio n. 23
0
void inline fence_insertert::mip_set_cst(ilpt& ilp, unsigned& i)
{
#ifdef HAVE_GLPK
  glp_add_rows(ilp.lp, constraints_number);
  i=1;

  /* first the powr: for all C_j */
  for(
    std::list<std::set<unsigned> >::const_iterator c_wr_it =
      powr_constraints.begin();
    c_wr_it != powr_constraints.end();
    ++c_wr_it)
  {
    /* for all e */
    for(unsigned j=1; j<=c_wr_it->size(); ++j)
    {
      std::string name="C_"+i2string(i)+"_c_wr_"+i2string(j);
      glp_set_row_name(ilp.lp, i, name.c_str());
      glp_set_row_bnds(ilp.lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
      ++i;
    }
  }

  /* then the poww: for all C_j */
  for(
    std::list<std::set<unsigned> >::const_iterator c_ww_it =
      poww_constraints.begin();
    c_ww_it != poww_constraints.end();
    ++c_ww_it)
  {
    /* for all e */
    for(unsigned j=1; j<=c_ww_it->size(); ++j)
    {
      std::string name="C_"+i2string(i)+"_c_ww_"+i2string(j);
      glp_set_row_name(ilp.lp, i, name.c_str());
      glp_set_row_bnds(ilp.lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
      ++i;
    }
  }

  /* then the porw: for all C_j */
  for(
    std::list<std::set<unsigned> >::const_iterator c_rw_it =
      porw_constraints.begin();
    c_rw_it != porw_constraints.end();
    ++c_rw_it)
  {
    /* for all e */
    for(unsigned j=1; j<=c_rw_it->size(); ++j)
    {
      std::string name="C_"+i2string(i)+"_c_rw_"+i2string(j);
      glp_set_row_name(ilp.lp, i, name.c_str());
      glp_set_row_bnds(ilp.lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
      ++i;
    }
  }

  /* and finally the porr: for all C_j */
  for(
    std::list<std::set<unsigned> >::const_iterator c_rr_it =
      porr_constraints.begin();
    c_rr_it != porr_constraints.end();
    ++c_rr_it)
  {
    /* for all e */
    for(unsigned j=1; j<=c_rr_it->size(); ++j)
    {
      std::string name="C_"+i2string(i)+"_c_rr_"+i2string(j);
      glp_set_row_name(ilp.lp, i, name.c_str());
      glp_set_row_bnds(ilp.lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
      ++i;
    }
  }

  if(model==Power || model==Unknown) {
    for(
      std::list<std::set<unsigned> >::const_iterator c_it =
        com_constraints.begin();
      c_it != com_constraints.end();
      ++c_it)
    {
      /* for all e */
      for(unsigned j=1; j<=c_it->size(); ++j)
      {
        std::string name="C_"+i2string(i)+"_c_"+i2string(j);
        glp_set_row_name(ilp.lp, i, name.c_str());
        glp_set_row_bnds(ilp.lp, i, GLP_LO, 1.0, 0.0); /* >= 1*/
        ++i;
      }
    }
  }
#else
  throw "Sorry, musketeer requires glpk; please recompile\
    musketeer with glpk.";
#endif
}
Esempio n. 24
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;
}
Esempio n. 25
0
void glp_mpl_build_prob(glp_tran *tran, glp_prob *prob)
{     /* build LP/MIP problem instance from the model */
      int m, n, i, j, t, kind, type, len, *ind;
      double lb, ub, *val;
      if (tran->phase != 3)
         xerror("glp_mpl_build_prob: invalid call sequence\n");
      /* erase the problem object */
      glp_erase_prob(prob);
      /* set problem name */
      glp_set_prob_name(prob, mpl_get_prob_name(tran));
      /* build rows (constraints) */
      m = mpl_get_num_rows(tran);
      if (m > 0)
         glp_add_rows(prob, m);
      for (i = 1; i <= m; i++)
      {  /* set row name */
         glp_set_row_name(prob, i, mpl_get_row_name(tran, i));
         /* set row bounds */
         type = mpl_get_row_bnds(tran, i, &lb, &ub);
         switch (type)
         {  case MPL_FR: type = GLP_FR; break;
            case MPL_LO: type = GLP_LO; break;
            case MPL_UP: type = GLP_UP; break;
            case MPL_DB: type = GLP_DB; break;
            case MPL_FX: type = GLP_FX; break;
            default: xassert(type != type);
         }
         if (type == GLP_DB && fabs(lb - ub) < 1e-9 * (1.0 + fabs(lb)))
         {  type = GLP_FX;
            if (fabs(lb) <= fabs(ub)) ub = lb; else lb = ub;
         }
         glp_set_row_bnds(prob, i, type, lb, ub);
         /* warn about non-zero constant term */
         if (mpl_get_row_c0(tran, i) != 0.0)
            xprintf("glp_mpl_build_prob: row %s; constant term %.12g ig"
               "nored\n",
               mpl_get_row_name(tran, i), mpl_get_row_c0(tran, i));
      }
      /* build columns (variables) */
      n = mpl_get_num_cols(tran);
      if (n > 0)
         glp_add_cols(prob, n);
      for (j = 1; j <= n; j++)
      {  /* set column name */
         glp_set_col_name(prob, j, mpl_get_col_name(tran, j));
         /* set column kind */
         kind = mpl_get_col_kind(tran, j);
         switch (kind)
         {  case MPL_NUM:
               break;
            case MPL_INT:
            case MPL_BIN:
               glp_set_col_kind(prob, j, GLP_IV);
               break;
            default:
               xassert(kind != kind);
         }
         /* set column bounds */
         type = mpl_get_col_bnds(tran, j, &lb, &ub);
         switch (type)
         {  case MPL_FR: type = GLP_FR; break;
            case MPL_LO: type = GLP_LO; break;
            case MPL_UP: type = GLP_UP; break;
            case MPL_DB: type = GLP_DB; break;
            case MPL_FX: type = GLP_FX; break;
            default: xassert(type != type);
         }
         if (kind == MPL_BIN)
         {  if (type == GLP_FR || type == GLP_UP || lb < 0.0) lb = 0.0;
            if (type == GLP_FR || type == GLP_LO || ub > 1.0) ub = 1.0;
            type = GLP_DB;
         }
         if (type == GLP_DB && fabs(lb - ub) < 1e-9 * (1.0 + fabs(lb)))
         {  type = GLP_FX;
            if (fabs(lb) <= fabs(ub)) ub = lb; else lb = ub;
         }
         glp_set_col_bnds(prob, j, type, lb, ub);
      }
      /* load the constraint matrix */
      ind = xcalloc(1+n, sizeof(int));
      val = xcalloc(1+n, sizeof(double));
      for (i = 1; i <= m; i++)
      {  len = mpl_get_mat_row(tran, i, ind, val);
         glp_set_mat_row(prob, i, len, ind, val);
      }
      /* build objective function (the first objective is used) */
      for (i = 1; i <= m; i++)
      {  kind = mpl_get_row_kind(tran, i);
         if (kind == MPL_MIN || kind == MPL_MAX)
         {  /* set objective name */
            glp_set_obj_name(prob, mpl_get_row_name(tran, i));
            /* set optimization direction */
            glp_set_obj_dir(prob, kind == MPL_MIN ? GLP_MIN : GLP_MAX);
            /* set constant term */
            glp_set_obj_coef(prob, 0, mpl_get_row_c0(tran, i));
            /* set objective coefficients */
            len = mpl_get_mat_row(tran, i, ind, val);
            for (t = 1; t <= len; t++)
               glp_set_obj_coef(prob, ind[t], val[t]);
            break;
         }
      }
      /* free working arrays */
      xfree(ind);
      xfree(val);
      return;
}
Esempio n. 26
0
void Constraint::set_name(const std::string& name) {
    glp_set_row_name(lp_, lineNumber_, name.c_str());
}
Esempio n. 27
0
int CConstraints::GLPK_lp(CModel* pmodel)
{
    glp_prob* lp = glp_create_prob();

    int iRow = (int) m_vWeights.size();
    //int iCol = (int) m_iWeightLength + m_iPatternNum;
    int iSize = iRow * ( m_iWeightLength + 1);
    int ia[10 + iSize], ja[1 + iSize];
    double ar[1 + iSize];
    glp_set_prob_name(lp, "StrLP");
    glp_set_obj_dir(lp, GLP_MIN);
    glp_add_rows(lp, (int) m_vWeights.size());
    // setup rows
    for (int i = 0; i < (int) m_vWeights.size(); i ++)
    {
        char tmp[200];
        sprintf(tmp, "cc_%d", i + 1);
        glp_set_row_name(lp, i + 1, tmp);
        glp_set_row_bnds(lp, i + 1, GLP_LO, m_fDistance - m_fEpsilon, 0);
    }
    glp_add_cols(lp, m_iWeightLength + m_iPatternNum);
    for (int i = 0; i < m_iWeightLength; i ++)
    {
        char tmp[200];
        sprintf(tmp, "w%d", i + 1);
        glp_set_col_name(lp, i + 1, tmp);
        glp_set_col_bnds(lp, i + 1, GLP_LO, 0, 0.0);
        glp_set_obj_coef(lp, i + 1, 1.0);
    }

    for (int i = 0; i < m_iPatternNum; i ++)
    {
        char tmp[200];
        sprintf(tmp, "e%d", i + 1);
        glp_set_col_name(lp, m_iWeightLength + i + 1, tmp);
        glp_set_col_bnds(lp, m_iWeightLength + i + 1, GLP_LO, 0, 0.0);
        glp_set_obj_coef(lp, m_iWeightLength + i + 1, m_fC / m_iPatternNum);
    }
    int iIndex = 1;
    for (int i = 0; i < (int)m_vWeights.size(); i ++)
    {
        double* pd = m_vWeights[i];
        for (int j = 0; j < (int) m_iWeightLength; j ++)
        {
            ia[iIndex] = i + 1, ja[iIndex] = j + 1;
            if (pmodel->m_vSign[j] <= 0)
            {
                ar[iIndex] = -pd[j];
            }
            else
            {
                ar[iIndex] = pd[j];
            }
            iIndex ++;
        }
        ia[iIndex] = i + 1;
        ja[iIndex] = m_iWeightLength + m_vPatternIndex[i] + 1;
        //ar[iIndex] = 1;
        ar[iIndex] = m_vLoss[i];
        iIndex ++;
    }
    glp_load_matrix(lp, iIndex - 1, ia, ja, ar);
    glp_simplex(lp, NULL);
    double z = glp_get_obj_val(lp);
    fprintf(stderr, "minimal value %f \n", z);
    for (int i = 0; i < m_iWeightLength; i ++)
    {
        double x = glp_get_col_prim(lp, i + 1);
        if (pmodel->m_vSign[i] <=0)
        {
            pmodel->m_vWeight[i] = -x;
        }
        else
        {
            pmodel->m_vWeight[i] = x;
        }

        if (x != 0) fprintf(stderr, "(w%d, %f)\t", i + 1, pmodel->m_vWeight[i]);
    }
    for (int i = 0; i < m_iPatternNum; i ++)
    {
        double x = glp_get_col_prim(lp, m_iWeightLength + i + 1);
        pmodel->m_vTheta[i] = x;
        if (x != 0)  fprintf(stderr, "(e%d, %f)\t", i + 1, pmodel->m_vTheta[i]);
    }
    glp_delete_prob(lp);
    return 1;
}