static int LPX_setname(LPXObject *self, PyObject *value, void *closure) { char *name; if (value==NULL || value==Py_None) { glp_set_prob_name(LP, NULL); return 0; } name = PyString_AsString(value); if (name==NULL) return -1; if (PyString_Size(value) > 255) { PyErr_SetString(PyExc_ValueError, "name may be at most 255 chars"); return -1; } glp_set_prob_name(LP, name); return 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; }
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; }
B2GlpkHasher::B2GlpkHasher(const B2TraceCoeffs &trace_coeffs, const B2StrSet &str_set) : B2HasherBase(str_set) { _lp = glp_create_prob(); glp_set_prob_name(_lp, "Bouma2-GLPK"); glp_set_obj_dir(_lp, GLP_MIN); add_trace_vars(trace_coeffs); add_str_constraints(); #ifdef B2_GLPK_DEBUG glp_write_prob(_lp, 0, b2_preproc_config(B2_CFG_GLPK_DEBUG_FILE).c_str()); #endif //B2_GLPK_DEBUG build_hash(); _motif_set.remove_duplicates(trace_coeffs); };
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; }
int CMyProblem::ConstructLP(const char* model_file) { //надо проверить чего-нибудь glp_erase_prob(lp); glp_tran *tran; int ret; tran = glp_mpl_alloc_wksp(); try{ ret = glp_mpl_read_model(tran, model_file, 1); if (ret != 0) { cerr << "Error on translating model\n"; throw MyException(); } string data_file = name; data_file+=".dat"; WriteMathProg(data_file.c_str()); ret = glp_mpl_read_data(tran, data_file.c_str()); if (ret != 0) { cerr << "Error on translating data\n"; throw MyException(); } ret = glp_mpl_generate(tran, NULL); if (ret != 0) { cerr << "Error on generating model\n"; throw MyException(); } glp_mpl_build_prob(tran, lp); glp_set_prob_name(lp, name.c_str()); //вот тут я разрушаю транслятор, что делать с postsolve непонятно, но пока оно не надо glp_mpl_free_wksp(tran); } catch(MyException){ glp_mpl_free_wksp(tran); glp_erase_prob(lp); return ret; } return 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; }
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; }
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; }
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; }
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); }
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 /* Variables récupérant les résultats de la résolution du problème (fonction objectif et valeur des variables) */ int i, j; double z; double x[NBVAR]; // Autres variables int * p = (int*)malloc(n * sizeof(int)); 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; /* Transfert de ces données dans les structures utilisées par la bibliothèque GLPK */ prob = glp_create_prob(); /* allocation mémoire pour le problème */ glp_set_prob_name(prob, "wagons"); /* affectation d'un nom */ glp_set_obj_dir(prob, GLP_MIN); /* Il s'agit d'un problème de minimisation */ /* Déclaration du nombre de contraintes (nombre de lignes de la matrice des contraintes) */ glp_add_rows(prob, NBCONTR); /* On commence par préciser les bornes sur les contraintes, les indices commencent à 1 (!) dans GLPK */ /* Premier ensemble de contraintes ( c = 1 ) */ for(i = 1; i <= n; i++) { glp_set_row_bnds(prob, i, GLP_FX, 1.0, 1.0); } /* Second ensembles de contraintes (c <= 0 ) */ for(i = n + 1; i <= NBCONTR; i++) { glp_set_row_bnds(prob, i, GLP_UP, 0.0, 0.0); } /* Déclaration du nombre de variables */ 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 - 1; i++) { glp_set_col_bnds(prob, i, GLP_DB, 0.0, 1.0); glp_set_col_kind(prob, i, GLP_BV); /* les variables sont binaires */ } glp_set_col_bnds(prob, NBVAR, GLP_LO, 0.0, 0.0); /* La dernière variables est continue (par défaut) non négative */ /* 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 à 0 (sauf le dernier) } /* Dernier coût (qui vaut 1) */ glp_set_obj_coef(prob,n*m + 1,1.0); /* Définition des coefficients non-nuls dans la matrice des contraintes, autrement dit les coefficients de la matrice creuse */ int pos = 1; for(i = 1; i <= n; i++) { for(j = 1; j <= m; j++) { // Première moitié de la matrice ja[pos] = (i - 1)*m + j; ia[pos] = i; ar[pos] = 1; pos++; // Deuxième moitié de la matrice ja[pos] = (i - 1)*m + j; ia[pos] = n + j; ar[pos] = p[i]; pos++; } } // ajout des -1 dans la dernière colonne for(i = n + 1; i <= n + m; i++) { ja[pos] = n*m + 1; ia[pos] = i; ar[pos] = -1; pos++; } /* Chargement de la matrice dans le problème */ glp_load_matrix(prob,NBCREUX,ia,ja,ar); /* Ecriture de la modélisation dans un fichier */ 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%c = %d, ",'B'+i,(int)(x[i] + 0.5)); /* un cast est ajouté, x[i] pourrait être égal à 0.99999... */ puts(""); /* Libération de la mémoire */ glp_delete_prob(prob); free(p); return 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(¶m); param.meth = GLP_PRIMAL; //glp_std_basis(lp); glp_simplex(lp, ¶m); 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); }
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 }
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; }
int main(int argc, char * argv[]) { int i,j; time(&initial); srand(SEED); /* Default values */ outFile = stdout; maxAlpha = 2; maxIter = 100; maxTime = 30; randomSeed = SEED; simpleOutput = 0; /* Read arguments */ if( argc > 7 ) argc = 7; switch(argc) { case 7: simpleOutput = atoi(argv[6]); case 6: if( !(randomSeed = atoi(argv[5])) ) leave(argv[0]); case 5: if( !(maxTime = atoi(argv[4])) ) leave(argv[0]); case 4: if( !(maxIter = atoi(argv[3])) ) leave(argv[0]); case 3: if( !(maxAlpha = atoi(argv[2])) ) leave(argv[0]); case 2: if( simpleOutput ) { if( !(outFile = fopen(argv[1],"a")) ) leave(argv[0]); break; } if( !(outFile = fopen(argv[1],"w")) ) leave(argv[0]); } readInput(stdin); /* Initiate positions */ for( i = 0 ; i < n ; ++i ) { pOrd[i].ideal = planes[i].ideal; pOrd[i].pos = i; } qsort (pOrd, n, sizeof(struct planeOrder), compIdealT); for( i = 0 ; i < n ; ++i ) { planes[pOrd[i].pos].pos = i; } /* Create lp instance */ glp_prob * Prob; Prob = glp_create_prob(); glp_set_prob_name(Prob, "Airplane Landing Problem"); glp_set_obj_name(Prob, "Cost"); /* Create basic constraints */ for( i = 0 ; i < n ; ++i ) { addBasicRestriction(Prob,i); } glp_create_index(Prob); /* Create separation constraints and order variables (&ij) if necessary */ for( i = 0 ; i < n ; ++i ) { for( j = i+1 ; j < n ; ++j ) { if( planes[i].latest >= planes[j].earliest && planes[j].latest >= planes[i].earliest ) { addOrderConstraint(Prob,i,j); } else if ( planes[i].latest < planes[j].earliest && planes[i].latest + planes[i].sep[j] >= planes[j].earliest ) { addSeparationConstraint(Prob, i, j); } else if ( planes[j].latest < planes[i].earliest && planes[j].latest + planes[j].sep[i] >= planes[i].earliest ) { addSeparationConstraint(Prob, j, i); } } } /* Write problem in MPS format so glpsol can (try to) solve it */ glp_write_mps(Prob, GLP_MPS_FILE, NULL,"mpsProblem.txt"); glp_delete_index(Prob); glp_create_index(Prob); /* GRASP */ /* Data to handle glp solving, time checking and solution generating */ glp_smcp * param = malloc(sizeof(glp_smcp)); glp_init_smcp(param); param->msg_lev = GLP_MSG_ERR; int solution[MAXSIZE], timeAux[MAXSIZE], t; double currResult = DBL_MAX, bestResult = DBL_MAX; alpha = 0; time_t start, curr; time(&start); for( t = 0 ; t < maxIter ; ++t ) { /* Greedy solution generation */ while(createSolution(solution,timeAux,0)) alpha = n; /* Building the right constraints */ mapSolution(Prob,solution); /* Solving with glpsol */ param->presolve = GLP_ON; glp_simplex(Prob,param); param->presolve = GLP_OFF; currResult = glp_get_obj_val(Prob); /* Local search using the first increase */ for( i = 0 ; i < n-1 ; ++i ) { /* Swap two adjacent planes */ swapConstraint(Prob,i,solution,0); glp_simplex(Prob,param); /* Check for improvements */ if( GLP_OPT == glp_get_status(Prob) && glp_get_obj_val(Prob) < currResult ) { currResult = glp_get_obj_val(Prob); /* Changing the solution */ int swp; swp = solution[i]; solution[i] = solution[i+1]; solution[i+1] = swp; /* Restarting */ i = -1; } else swapConstraint(Prob,i,solution,1); } /* Checking improvements */ if( bestResult > currResult ) { bestResult = currResult; for( i = 0 ; i < n ; ++i ) planes[solution[i]].pos = i; } /* Choosing alpha */ alpha = rand()%(maxAlpha+1); /* Is our time up? */ time(&curr); if( difftime(curr,start) > maxTime ) break; } /* Print Answer */ printResult(Prob, stdout); if( outFile ) { printResult(Prob, outFile); fclose(outFile); } return 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; }
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; }
/** * Create the MLP problem * * @param mlp the MLP handle * @param addresses the hashmap containing all adresses * @return GNUNET_OK or GNUNET_SYSERR */ static int mlp_create_problem (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses) { int res = GNUNET_OK; int col; int c; char *name; GNUNET_assert (mlp->prob == NULL); /* create the glpk problem */ mlp->prob = glp_create_prob (); /* Set a problem name */ glp_set_prob_name (mlp->prob, "gnunet ats bandwidth distribution"); /* Set optimization direction to maximize */ glp_set_obj_dir (mlp->prob, GLP_MAX); /* Adding invariant columns */ /* Diversity d column */ col = glp_add_cols (mlp->prob, 1); mlp->c_d = col; /* Column name */ glp_set_col_name (mlp->prob, col, "d"); /* Column objective function coefficient */ glp_set_obj_coef (mlp->prob, col, mlp->co_D); /* Column lower bound = 0.0 */ glp_set_col_bnds (mlp->prob, col, GLP_LO, 0.0, 0.0); /* Utilization u column */ col = glp_add_cols (mlp->prob, 1); mlp->c_u = col; /* Column name */ glp_set_col_name (mlp->prob, col, "u"); /* Column objective function coefficient */ glp_set_obj_coef (mlp->prob, col, mlp->co_U); /* Column lower bound = 0.0 */ glp_set_col_bnds (mlp->prob, col, GLP_LO, 0.0, 0.0); #if ENABLE_C9 /* Relativity r column */ col = glp_add_cols (mlp->prob, 1); mlp->c_r = col; /* Column name */ glp_set_col_name (mlp->prob, col, "r"); /* Column objective function coefficient */ glp_set_obj_coef (mlp->prob, col, mlp->co_R); /* Column lower bound = 0.0 */ glp_set_col_bnds (mlp->prob, col, GLP_LO, 0.0, 0.0); #endif /* Quality metric columns */ col = glp_add_cols(mlp->prob, mlp->m_q); for (c = 0; c < mlp->m_q; c++) { mlp->c_q[c] = col + c; GNUNET_asprintf (&name, "q_%u", mlp->q[c]); glp_set_col_name (mlp->prob, col + c, name); /* Column lower bound = 0.0 */ glp_set_col_bnds (mlp->prob, col + c, GLP_LO, 0.0, 0.0); GNUNET_free (name); /* Coefficient == Qm */ glp_set_obj_coef (mlp->prob, col + c, mlp->co_Q[c]); } /* Add columns for addresses */ GNUNET_CONTAINER_multihashmap_iterate (addresses, create_columns_it, mlp); /* Add constraints */ mlp_add_constraints_all_addresses (mlp, addresses); /* Load the matrix */ glp_load_matrix(mlp->prob, (mlp->ci-1), mlp->ia, mlp->ja, mlp->ar); return res; }
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; }
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; }
void lpx_set_prob_name(LPX *lp, const char *name) { /* assign (change) problem name */ glp_set_prob_name(lp, name); return; }
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; }
static bool Graph_solve(Graph& graph, size_t loops, PositionList* position_tbl) { glp_prob* lp = glp_create_prob(); glp_set_prob_name(lp, "scaffold"); glp_set_obj_dir(lp, GLP_MIN); size_t rows = 0, cols = 0, vals = 0; for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) { ++cols; // var x_i for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) { rows += 3; cols += 2; // var e_i_j; var E_i_j; vals += 7; } } glp_add_rows(lp, rows); glp_add_cols(lp, cols); std::map< std::pair< size_t, size_t >, size_t > mapping; { size_t row = 1, col = 1; for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) { mapping[std::make_pair(i->first, -1)] = col; glp_set_col_bnds(lp, col++, GLP_LO, 0.0, 0.0); // x_i >= 0 for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) { glp_set_row_bnds(lp, row++, GLP_FX, j->second, j->second); glp_set_row_bnds(lp, row++, GLP_LO, 0.0, 0.0); glp_set_row_bnds(lp, row++, GLP_LO, 0.0, 0.0); mapping[std::make_pair(i->first, j->first)] = col; ++col; // var e_i glp_set_obj_coef(lp, col++, 1.0); } } } LOG4CXX_TRACE(logger, boost::format(" rows = %d, cols = %d, vals = %d") % rows % cols % vals); int* ia = new int[vals + 1]; int* ja = new int[vals + 1]; double* ra = new double[vals + 1]; { size_t l = 1, row = 1, col = 1; for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) { for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) { // x_j - x_i + e_i_j = d_i_j ia[l] = row; ja[l] = mapping[std::make_pair(j->first, -1)]; ra[l] = 1.0; ++l; ia[l] = row; ja[l] = mapping[std::make_pair(i->first, -1)]; ra[l] = -1.0; ++l; ia[l] = row; ja[l] = mapping[std::make_pair(i->first, j->first)] + 0; ra[l] = 1.0; ++l; ++row; // E_i_j + e_i_j >= 0 ia[l] = row; ja[l] = mapping[std::make_pair(i->first, j->first)] + 1; ra[l] = 1.0; ++l; ia[l] = row; ja[l] = mapping[std::make_pair(i->first, j->first)] + 0; ra[l] = 1.0; ++l; ++row; // E_i_j - e_i_j >= 0 ia[l] = row; ja[l] = mapping[std::make_pair(i->first, j->first)] + 1; ra[l] = 1.0; ++l; ia[l] = row; ja[l] = mapping[std::make_pair(i->first, j->first)] + 0; ra[l] = -1.0; ++l; ++row; } } } glp_load_matrix(lp, vals, ia, ja, ra); glp_smcp parm; glp_init_smcp(&parm); parm.it_lim = loops; //parm.pricing = GLP_PT_PSE; //parm.presolve = GLP_ON; parm.msg_lev = GLP_MSG_ERR; glp_simplex(lp, &parm); double z = glp_get_obj_val(lp); LOG4CXX_TRACE(logger, boost::format("z = %f") % z); for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) { size_t val = glp_get_col_prim(lp, mapping[std::make_pair(i->first, -1)]); if (position_tbl != NULL) { (*position_tbl)[i->first] = val; } LOG4CXX_TRACE(logger, boost::format("x\t%d\t%d") % i->first % val); } delete[] ra; delete[] ja; delete[] ia; glp_delete_prob(lp); return true; }