dense_c.c


dense_c.c


/ * 2021年版权,Gurobi优狗万app足彩化,LLC * / / *本例制定和解决以下简单的QP模型:最小化x + y + x ^ 2 + x * y + y ^ 2 + y * z + z ^ 2受x + 2 + 3 z > = 4 x + y > = 1 x, y, z的示例展示了使用非负密度矩阵来存储和Q(和密集的其他相关数据的向量)。我们不建议您使用密集矩阵,但是如果您已经有了这种格式的数据,这个示例可能会有所帮助。*/ #include  #include  #include "gurobi_c.h" /*用密集矩阵表示LP/QP/MILP/MIQP。这个例程假设A和Q都是按行主顺序存储的。如果优化成功,则返回1。当成功时,它将返回'objvalP'中的最优目标值,以及'solution'中的最优解向量。* /静态int dense_optimize (GRBenv * env, int, int关口,双c *, / *目标函数的线性部分* /双* Q / *目标函数的二次部分* /双*,/ *约束矩阵* / char *, / *约束感官* /双*,/ * * /双*磅rhs向量,/ *变量下界* /双*乌兰巴托,/*变量的上界*/ char *vtype, /*变量类型(连续的,二进制的,等等)*/ double *解,double *objvalP) {GRBmodel *model = NULL;Int i, j, optimstatus;Int error = 0; int success = 0; /* Create an empty model */ error = GRBnewmodel(env, &model, "dense", cols, c, lb, ub, vtype, NULL); if (error) goto QUIT; error = GRBaddconstrs(model, rows, 0, NULL, NULL, NULL, sense, rhs, NULL); if (error) goto QUIT; /* Populate A matrix */ for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { if (A[i*cols+j] != 0) { error = GRBchgcoeffs(model, 1, &i, &j, &A[i*cols+j]); if (error) goto QUIT; } } } /* Populate Q matrix */ if (Q) { for (i = 0; i < cols; i++) { for (j = 0; j < cols; j++) { if (Q[i*cols+j] != 0) { error = GRBaddqpterms(model, 1, &i, &j, &Q[i*cols+j]); if (error) goto QUIT; } } } } /* Optimize model */ error = GRBoptimize(model); if (error) goto QUIT; /* Write model to 'dense.lp' */ error = GRBwrite(model, "dense.lp"); if (error) goto QUIT; /* Capture solution information */ error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus); if (error) goto QUIT; if (optimstatus == GRB_OPTIMAL) { error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, objvalP); if (error) goto QUIT; error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, cols, solution); if (error) goto QUIT; success = 1; } QUIT: /* Error reporting */ if (error) { printf("ERROR: %s\n", GRBgeterrormsg(env)); exit(1); } /* Free model */ GRBfreemodel(model); return success; } int main(int argc, char *argv[]) { GRBenv *env = NULL; int error = 0; double c[] = {1, 1, 0}; double Q[3][3] = {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}}; double A[2][3] = {{1, 2, 3}, {1, 1, 0}}; char sense[] = {'>', '>'}; double rhs[] = {4, 1}; double lb[] = {0, 0, 0}; double sol[3]; int solved; double objval; /* Create environment */ error = GRBloadenv(&env, "dense.log"); if (error) goto QUIT; /* Solve the model */ solved = dense_optimize(env, 2, 3, c, &Q[0][0], &A[0][0], sense, rhs, lb, NULL, NULL, sol, &objval); if (solved) printf("Solved: x=%.4f, y=%.4f, z=%.4f\n", sol[0], sol[1], sol[2]); QUIT: /* Free environment */ GRBfreeenv(env); return 0; }