vector <double> solve(int verbose, vector <vector <double> > M) { vector <double> solution; try { GRBEnv env = GRBEnv(); int numPoints = M.size(); int numCircles = M.back().size(); GRBVar p[numPoints]; double coeff[numPoints]; GRBModel model = GRBModel(env); GRBLinExpr expr; if(!verbose) model.getEnv().set(GRB_IntParam_OutputFlag, 0); for (int i=0;i<numPoints;i++){ p[i] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY); coeff[i] = 1.0; } expr.addTerms(coeff, p,numPoints); model.update(); model.setObjective(expr, GRB_MINIMIZE); for(int i=0;i<numCircles;i++){ GRBLinExpr cexpr; double ccoeff[numPoints]; for(int j=0;j<numPoints;j++){ ccoeff[j] = M[j].back(); M[j].pop_back(); } cexpr.addTerms(ccoeff,p,numPoints); model.addConstr(cexpr, GRB_GREATER_EQUAL,1.0); } // Optimize model model.optimize(); for (int i=0;i<numPoints;i++){ solution.push_back((double)p[i].get(GRB_DoubleAttr_X)); } } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } return solution; }
int main(int argc, char *argv[]) { try { GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); // Create variables GRBVar x = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "x"); GRBVar y = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "y"); GRBVar z = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "z"); // Integrate new variables model.update(); // Set objective: maximize x + y + 2 z model.setObjective(x + y + 2 * z, GRB_MAXIMIZE); // Add constraint: x + 2 y + 3 z <= 4 model.addConstr(x + 2 * y + 3 * z <= 4, "c0"); // Add constraint: x + y >= 1 model.addConstr(x + y >= 1, "c1"); // Optimize model model.optimize(); cout << x.get(GRB_StringAttr_VarName) << " " << x.get(GRB_DoubleAttr_X) << endl; cout << y.get(GRB_StringAttr_VarName) << " " << y.get(GRB_DoubleAttr_X) << endl; cout << z.get(GRB_StringAttr_VarName) << " " << z.get(GRB_DoubleAttr_X) << endl; cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl; } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } return 0; }
int main(int argc, char *argv[]) { try { GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); // Create variables GRBVar x1 = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_INTEGER, "x1"); GRBVar x2 = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_INTEGER, "x2"); // Integrate new variables model.update(); // Set objective: maximize 2 x1 + x2 model.setObjective(2 * x1 + x2, GRB_MAXIMIZE); // Add constraint: x2 + 0.1 x1 <= 8 model.addConstr(x2 + 0.1 * x1 <= 8, "c0"); // Add constraint: x2 + 5 x1 <= 70 model.addConstr(x2 + 5 * x1 <= 70, "c1"); // Optimize model model.optimize(); cout << x1.get(GRB_StringAttr_VarName) << " " << x1.get(GRB_DoubleAttr_X) << endl; cout << x2.get(GRB_StringAttr_VarName) << " " << x2.get(GRB_DoubleAttr_X) << endl; cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl; } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } return 0; }
int main(int argc, char *argv[]) { if (argc < 2) { cout << "Usage: feasopt_c++ filename" << endl; return 1; } GRBEnv* env = 0; GRBConstr* c = 0; try { env = new GRBEnv(); GRBModel feasmodel = GRBModel(*env, argv[1]); // Create a copy to use FeasRelax feature later */ GRBModel feasmodel1 = GRBModel(feasmodel); // clear objective feasmodel.setObjective(GRBLinExpr(0.0)); // add slack variables c = feasmodel.getConstrs(); for (int i = 0; i < feasmodel.get(GRB_IntAttr_NumConstrs); ++i) { char sense = c[i].get(GRB_CharAttr_Sense); if (sense != '>') { double coef = -1.0; feasmodel.addVar(0.0, GRB_INFINITY, 1.0, GRB_CONTINUOUS, 1, &c[i], &coef, "ArtN_" + c[i].get(GRB_StringAttr_ConstrName)); } if (sense != '<') { double coef = 1.0; feasmodel.addVar(0.0, GRB_INFINITY, 1.0, GRB_CONTINUOUS, 1, &c[i], &coef, "ArtP_" + c[i].get(GRB_StringAttr_ConstrName)); } } feasmodel.update(); // optimize modified model feasmodel.write("feasopt.lp"); feasmodel.optimize(); // use FeasRelax feature */ feasmodel1.feasRelax(GRB_FEASRELAX_LINEAR, true, false, true); feasmodel1.write("feasopt1.lp"); feasmodel1.optimize(); } catch (GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch (...) { cout << "Error during optimization" << endl; } delete[] c; delete env; return 0; }
int main(){//int argc,char** argv){ int nbPOI= -1; int maxT= -1; //int dt= 1; cin>>nbPOI>> maxT; vector<double> reward (nbPOI, 0); vector<double> time (nbPOI, 0); vector< vector<double > > dist (nbPOI, vector<double>(nbPOI)); for(int i =0; i<nbPOI; ++i){ cin>> reward[i]; } for(int i =0; i<nbPOI; ++i){ cin>> time[i]; } for(int i =0; i<nbPOI; ++i){ for(int j =0; j<nbPOI; ++j){ cin>> dist[i][j]; } } try { GRBEnv env = GRBEnv(); GRBModel* model = new GRBModel(env); vector< vector<GRBVar> > x(nbPOI, vector<GRBVar>(nbPOI)); vector< GRBVar > ordre(nbPOI); for(int i =0; i<nbPOI; ++i){ for(int j =0; j<nbPOI; ++j){ x[i][j]=model->addVar(0.0, 1.0, 0.0, GRB_BINARY, "x_"+to_string(i)+to_string(j)); } } for(int i =0; i<nbPOI; ++i){ ordre[i]=model->addVar(0.0, GRB_INFINITY, 0.0, GRB_INTEGER, "o_"+to_string(i)); } model->update(); int constr_count=0; for(int i =0; i<nbPOI; ++i){ for(int j =0; j<nbPOI; ++j){ //sum of entering flow = sum entering flow GRBLinExpr expr1 = 0; GRBLinExpr expr2 = 0; for(int k=0; k<nbPOI; ++k){ expr1+= x[k][i]; expr2+=x[i][k]; } model->addConstr(expr1-expr2, GRB_EQUAL, 0,"c_"+to_string(constr_count++)); if(i==0) model->addConstr(expr1, GRB_EQUAL, 1,"c_"+to_string(constr_count++)); else model->addConstr(expr1, GRB_LESS_EQUAL, 1,"c_"+to_string(constr_count++)); } } for(int i =0; i<nbPOI; ++i){ for(int j =1; j<nbPOI; ++j){ //order constraint GRBLinExpr expr = 0; expr+= ordre[i]-ordre[j]+1-nbPOI*(1-x[i][j]); model->addConstr(expr, GRB_LESS_EQUAL, 0,"c_"+to_string(constr_count++)); } } //Time constraint GRBLinExpr total_time = 0; for(int i =0; i<nbPOI; ++i){ for(int j =0; j<nbPOI; ++j){ total_time+= (dist[i][j]+time[j])*x[i][j]; } } model->addConstr(total_time, GRB_LESS_EQUAL, maxT,"Time"); //objective GRBLinExpr total_reward = 0; for(int i =0; i<nbPOI; ++i){ for(int j =0; j<nbPOI; ++j){ total_reward+= reward[j]*x[i][j]; } } model->setObjective(total_reward, GRB_MAXIMIZE); model->update(); model->optimize(); int verbose=1; if(verbose>1){ for(int i =0; i<nbPOI; ++i){ for(int j =0; j<nbPOI; ++j){ cout<<x[i][j].get(GRB_StringAttr_VarName) << ":"<<x[i][j].get(GRB_DoubleAttr_X)<<endl; } } for(int j =0; j<nbPOI; ++j){ cout<<ordre[j].get(GRB_StringAttr_VarName) << ":"<<ordre[j].get(GRB_DoubleAttr_X)<<endl; } } //extract the path vector<int> path; bool found=0; int current=0; int final=0; bool finish=0; while(!finish){ for(int j=0; j<(int)x[0].size();++j){ if(x[current][j].get(GRB_DoubleAttr_X)>0){ // cout<<"on node"<<current<<" "<<j<<endl; path.push_back(current); // x[current][j]=0; current=j; if(current== final) finish=1; found=1; break; } } if(!found){ cerr<<"Nothing interesting to do, going directly to final node"<<endl; path.push_back(current); current=final; finish=1; } }
ChannelsFitness ILPChannelingGurobi(DataStructure *dataStructure, double const alpha) { try { unsigned int messageCount; double alphaCoef = alpha; GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); //model.getEnv().set(GRB_DoubleParam_TimeLimit, 3600); ChannelsFitness cfResult; CAMessage *messages; messageCount = static_cast<unsigned int>(AggregateMessages(dataStructure, messages)); vector<int> w(messageCount); transform(messages, messages + messageCount, w.begin(), [](CAMessage &message) { return message.payload; }); int sumW = 0; for (int i = 0; i < messageCount; i++) { for (int j = 0; j < static_cast<int>(messages[i].nodes.size()); j++) { if (dataStructure->nodesOnBothChannels[messages[i].nodes[j]] != 1) { sumW += messages[i].payload; break; } } } if (alphaCoef < 0) alphaCoef = 1.0 / sumW; GRBVar z = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "z"); GRBVar Pa = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "Pa"); GRBVar Pb = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "Pb"); GRBVar Pg = model.addVar(0.0, GRB_INFINITY, 0.0, GRB_CONTINUOUS, "Pg"); vector<GRBVar> Uea(messageCount); vector<GRBVar> Ueb(messageCount); vector<GRBVar> xi(static_cast<unsigned int>(dataStructure->nodeCount)); generate_n(Uea.begin(), messageCount, [&model]() { return model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "Uea"); }); generate_n(Ueb.begin(), messageCount, [&model]() { return model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS, "Ueb"); }); generate_n(xi.begin(), dataStructure->nodeCount, [&model]() { return model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "xi"); }); model.update(); model.setObjective(z + alphaCoef * Pg, GRB_MINIMIZE); model.addConstr(Pa <= z); model.addConstr(Pb <= z); model.addConstr(Pa + Pb - sumW == Pg); model.addConstr(expSum(Uea, w) == Pa); model.addConstr(expSum(Ueb, w) == Pb); for (int e = 0; e < messageCount; e++) { for (int i = 0; i < static_cast<int>(messages[e].nodes.size()); i++) // Problem!!! { if (dataStructure->nodesOnBothChannels[messages[e].nodes[i]] != 1) { model.addConstr(xi[messages[e].nodes[i]] - Uea[e] <= 0); model.addConstr(xi[messages[e].nodes[i]] + Ueb[e] >= 1); } } } model.addConstr(xi[0] == 1); model.optimize(); switch (model.get(GRB_IntAttr_Status)) { case GRB_INFEASIBLE: case GRB_UNBOUNDED: cfResult.channelA = cfResult.channelB = cfResult.gateway = -1; return cfResult; case GRB_TIME_LIMIT: if (model.get(GRB_IntAttr_SolCount) <= 0) { cfResult.channelA = cfResult.channelB = cfResult.gateway = -1; return cfResult; } default: break; } for (int i = 0; i < dataStructure->nodeCount; i++) dataStructure->nodesChannel[i] = static_cast<char>(xi[i].get(GRB_DoubleAttr_X)); /*for(i = 0; i < number_variables; i++) { printf("%d ", static_cast<int>(glp_mip_col_val(mip,i+1))); }*/ cfResult.channelA = static_cast<int>(floor(Pa.get(GRB_DoubleAttr_X) + 0.5)); cfResult.channelB = static_cast<int>(floor(Pb.get(GRB_DoubleAttr_X) + 0.5)); cfResult.gateway = static_cast<int>(floor(Pg.get(GRB_DoubleAttr_X) + 0.5)); for (int i = 0; i < dataStructure->nodeCount; i++) { printf("%d ", static_cast<int>(xi[i].get(GRB_DoubleAttr_X))); } printf("\n"); printf("/ %d, %d, %d\n", cfResult.channelA, cfResult.channelB, cfResult.gateway); delete[] messages; return cfResult; } catch (GRBException e) { cout << e.getMessage() << "\n"; } }
void BVH_balancing::Solve( const std::map<int, std::set<int> > &compatibility, size_t no_bones, std::map<int, int>& assignments ){ std::map<int, int> Bn_to_index, index_to_Bn; size_t index = 0; size_t no_branchings = compatibility.size(); assert( no_bones > 0 ); assert( no_branchings > 0 ); for( const auto& item : compatibility ){ if( Bn_to_index.count(item.first) > 0 ) { continue; } // skip if alredy mapped Bn_to_index[item.first] = index; index_to_Bn[index] = item.first; ++index; } // entire optimization goes inside a try catch statement. // in case of errors, I want it to crash! try{ GRBEnv env; GRBModel model = GRBModel( env ); /* CREATE VARIABLES */ std::vector<GRBVar> vars( no_bones * no_branchings ); for( size_t r = 0; r < no_bones; ++r ){ for( size_t c = 0; c < no_branchings; ++c ){ size_t idx = matIndex( r, c, no_branchings ); std::stringstream var_name; var_name << "A( " << r << ", " << c << " )"; assert( compatibility.count( index_to_Bn[c] ) > 0 ); bool is_connected = compatibility.at( index_to_Bn[c] ).count( r ); vars[idx] = model.addVar( 0.0, ( is_connected > 0 ? 1.0 : 0.0 ), 1.0, GRB_BINARY, var_name.str()); } } model.update(); // Create Objective Function. // for each branching node i : #bones( Bn_i )^2 // hence I need to sum the number of bones assigned to each branching node GRBQuadExpr obj; std::vector<GRBLinExpr> cols( no_branchings ); for( size_t c = 0; c < no_branchings; ++c ){ for( size_t r = 0; r < no_bones; ++r ){ size_t idx = matIndex( r, c, no_branchings ); cols[c] += vars[idx]; } } for( size_t c = 0; c < no_branchings; ++c ){ obj += cols[c] * cols[c]; } model.setObjective( obj ); model.update(); // create constraint : each bone can be assigned to only one branching node. // this means that the summation of each row's values must be equal to 1.0 for( size_t r = 0; r < no_bones; ++r ){ GRBLinExpr row_sum; for( size_t c = 0; c < no_branchings; ++c ){ size_t idx = matIndex( r, c, no_branchings ); row_sum += vars[idx]; } model.addConstr( row_sum == 1.0 ); } model.update(); // Optimize model.optimize(); int status = model.get(GRB_IntAttr_Status); if (status == GRB_OPTIMAL) { std::cout << "The optimal objective is " << model.get(GRB_DoubleAttr_ObjVal) << std::endl; // return results! // printResults(vars, no_bones, no_branchings ); getResults( index_to_Bn, vars, assignments, no_bones, no_branchings ); return; } /************************************/ /* ERROR HANDLING */ /************************************/ if (status == GRB_UNBOUNDED){ std::cout << "The model cannot be solved because it is unbounded" << std::endl; assert(false); } if ((status != GRB_INF_OR_UNBD) && (status != GRB_INFEASIBLE)) { std::cout << "Optimization was stopped with status " << status << std::endl; assert( false ); } GRBConstr* c = 0; // do IIS std::cout << "The model is infeasible; computing IIS" << std::endl; model.computeIIS(); std::cout << "\nThe following constraint(s) cannot be satisfied:" << std::endl; c = model.getConstrs(); for (int i = 0; i < model.get(GRB_IntAttr_NumConstrs); ++i){ if (c[i].get(GRB_IntAttr_IISConstr) == 1) { std::cout << c[i].get(GRB_StringAttr_ConstrName) << std::endl; } } } /* EXCEPTION HANDLING */ catch (GRBException e) { std::cout << "Error code = " << e.getErrorCode() << std::endl; std::cout << e.getMessage() << std::endl; assert( false ); } catch (...){ std::cout << "Exception during optimization" << std::endl; assert( false ); } }
int main(){ float peso1, peso2, peso3,peso4; int origem, destino; // vértices para cada aresta; int id = 0; // id das arestas que leremos do arquivo para criar o grafo cin>>n; // quantidade de vértices do grafo; arestas = new short*[n]; coeficienteObjetv = new double*[n]; matrix_peso1 = new double*[n]; matrix_peso2 = new double*[n]; matrix_peso3 = new double*[n]; matrix_peso4 = new double*[n]; for (int i=0; i<n; i++){ arestas[i] = new short[n]; coeficienteObjetv[i] = new double[n]; matrix_peso1[i] = new double[n]; matrix_peso2[i] = new double[n]; matrix_peso3[i] = new double[n]; matrix_peso4[i] = new double[n]; } GRBEnv env = GRBEnv();; env.set("OutputFlag","0"); GRBModel model = GRBModel(env);; GRBVar **y, **x; float epslon = 0.0001; //cin>>epslon; y = new GRBVar*[n]; x = new GRBVar*[n]; for (int i=0; i<n;i++){ y[i] = new GRBVar[n]; x[i] = new GRBVar[n]; } int constrCont=0; // Create variables for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ arestas[i][j] = 0; } } while (cin>>origem){ cin>>destino; cin>>peso1; cin>>peso2; cin>>peso3; cin>>peso4; coeficienteObjetv[origem][destino] = (peso1*epslon + peso2*epslon + peso3*epslon + peso4)*(-1); // o problema é de maximizacao x[origem][destino] = model.addVar(0.0, 100000, 0.0, GRB_CONTINUOUS, "x"+to_string(origem)+to_string(destino)); x[destino][origem] = model.addVar(0.0, 100000, 0.0, GRB_CONTINUOUS, "x"+to_string(destino)+to_string(origem)); y[origem][destino] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "y"+to_string(origem)+to_string(destino)); arestas[origem][destino] = 1; arestas[destino][origem] = 1; matrix_peso1[origem][destino] = peso1*(-1); matrix_peso2[origem][destino] = peso2*(-1); matrix_peso3[origem][destino] = peso3*(-1); matrix_peso4[origem][destino] = peso4*(-1); id++; } int nA = id; // quantidade de arestas do grafo int m = 1;// por default, o m falado por Lokman and Koksalan sera igual a 1 model.update(); // Set objective: GRBLinExpr exprObjet; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (arestas[i][j] == 1) exprObjet.addTerms(&coeficienteObjetv[i][j], &y[i][j],1); } } model.setObjective(exprObjet,GRB_MAXIMIZE); // constraint 3.9 (FERNANDES, 2016) GRBLinExpr constr5 ; double coefff = 1; for (int j=0+1; j<n; j++){ if (arestas[0][j] == 1) constr5.addTerms(&coefff,&x[0][j],1); } model.addConstr(constr5, GRB_EQUAL, n-1,to_string(constrCont++)); // // Add constraint 3.10 (FERNANDES, 2016) double com = -1; for (int j=1; j<n; j++){ GRBLinExpr constr2 = 0; for (int i=0; i<n; i++){ if (arestas[i][j] == 1){ constr2.addTerms(&coefff,&x[i][j],1); constr2.addTerms(&com,&x[j][i],1); } } model.addConstr(constr2, GRB_EQUAL, 1,to_string(constrCont++)); } double coef = (double) n - 1; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (arestas[i][j] == 1){ GRBLinExpr constr8; GRBLinExpr constr9; constr8.addTerms(&coef,&y[i][j],1); constr9.addTerms(&coefff ,&x[i][j],1); constr9.addTerms(&coefff ,&x[j][i],1); model.addConstr(constr8, GRB_GREATER_EQUAL, constr9,to_string(constrCont++)); } } } //cout<<"Modelo carregado"<<endl; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (arestas[i][j] == 1){ GRBLinExpr constr22; GRBLinExpr constr33; constr22.addTerms(&coefff ,&y[i][j],1); constr33.addTerms(&coefff ,&x[i][j],1); constr33.addTerms(&coefff ,&x[j][i],1); // cout<<constr22<<GRB_LESS_EQUAL<<constr33<<endl; model.addConstr(constr22, GRB_LESS_EQUAL, constr33,to_string(constrCont++)); } } } int nn = 0; // o 'n' do algoritmo de Lokman and Koksalan //int kk_estrela = 0; // o 'k*' do algoritmo 2 de Lokman and Koksalan int MM = 100000000; // o 'M' do algoritmo 2 de Lokman and Koksalan int z4_k_estrela; // pra guardar o Z_p^(P^(b^(k*,n))) do algoritmo 2 de Lokman and Koksalan /* * Algoritmo 2 de Lokman and Koksalan */ try { times(&tempsInit); // para medir o tempo em caso limite pthread_t thread_time; pthread_attr_t attr; int nnnnnnnn=0; if(pthread_create(&thread_time, NULL, &tempo, (void*)nnnnnnnn)){ // on criee efectivement la thread de rechaufage cout<<"Error to create the thread"<<endl; exit(EXIT_FAILURE); } // bool auxbol = false; // vira true (e o será pra sempre) quando resolvemos um modelo diferente do SIMPLES int optimstatus; short **result = new short*[n]; for (int ii=0; ii<n; ii++){ result[ii] = new short[n]; } model.optimize(); // P0,4 --> n=0 (modelo SIMPLES) optimstatus = model.get(GRB_IntAttr_Status); int z1=0,z2=0,z3=0,z4=0; if (optimstatus != GRB_INFEASIBLE){ for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (arestas[i][j] == 1){ result[i][j] = y[i][j].get(GRB_DoubleAttr_X); // GUARDA O RESULTADO z1+=result[i][j]*matrix_peso1[i][j]; // calcula os pesos z2+=result[i][j]*matrix_peso2[i][j]; z3+=result[i][j]*matrix_peso3[i][j]; z4+=result[i][j]*matrix_peso4[i][j]; } } } S.push_back(result); Pesos ppp = (Pesos){z1,z2,z3,z4}; Z.push_back(ppp); nn++; } do{ // esse loop para quando z4_k_estrela==-MM z4_k_estrela =(-1)*MM; // guarda o maximo short **z_n_plus_1 = new short*[n]; for (int ii=0; ii<n; ii++){ z_n_plus_1[ii] = new short[n]; } int z1_estrela, z2_estrela, z3_estrela; for (int ki=-1; ki<nn; ki++){ // no algoritmo original, ki deve variar de 0 à n (existindo solucoes de 1 à n). //aqui, portanto, fazemos k de -1 à n-1, porque as solucoes vao de 0 à n-1 for (int kj=-1; kj<nn; kj++){ // como i de ver menor que j, a unica possibilidade é i=1 e j=2, pois p-2=2 //cout<<ki<<" "<<kj<<endl; //cout<< Z[ki].peso1<<" "<< Z[kj].peso2<<endl; //if (kj!=-1 && ki!=-1 && (Z[ki].peso1 + 1 <= Z[kj].peso1)){ //Primeiramente, prepara o b1 e b2 e b3 int b1,b2,b3; //b1 if (ki==-1) b1=(-1)*MM; // -M else { b1 = Z[ki].peso1 + 1; } //b2 if (kj==-1) b2=(-1)*MM; // -M else { if (Z[kj].peso1 >= b1){ b2 = Z[kj].peso2 + 1; } else b2=(-1)*MM; // -M } //b3 b3 = (-1)*MM; // Snk = vazio for (int ii=0; ii<S.size(); ii++){ if (Z[ii].peso1>=b1 && Z[ii].peso2>=b2) { if (Z[ii].peso3 > b3){ b3 = Z[ii].peso3; } } } if (b3!=(-1)*MM) b3=b3+1; // max + 1 //cout <<"b1= "<<b1<<" b2= "<<" "<<b2<<" b3= "<<b3<<endl; if (auxbol == true){ // remove as restricoes de z2>b2 e adiciona novas GRBConstr cb1 = model.getConstrByName("cb1"); GRBConstr cb2 = model.getConstrByName("cb2"); GRBConstr cb3 = model.getConstrByName("cb3"); model.remove(cb1); model.remove(cb2); model.remove(cb3); } GRBLinExpr cb1; GRBLinExpr cb2; GRBLinExpr cb3; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (arestas[i][j] == 1){ cb1.addTerms(&matrix_peso1[i][j], &y[i][j],1); cb2.addTerms(&matrix_peso2[i][j], &y[i][j],1); cb3.addTerms(&matrix_peso3[i][j], &y[i][j],1); } } } model.addConstr(cb1, GRB_GREATER_EQUAL, b1,"cb1"); model.addConstr(cb2, GRB_GREATER_EQUAL, b2,"cb2"); model.addConstr(cb3, GRB_GREATER_EQUAL, b3,"cb3"); // AGORA RESOLVE-SE O MODELO auxbol=true; model.optimize(); optimstatus = model.get(GRB_IntAttr_Status); if (optimstatus != GRB_INFEASIBLE){ short **result = new short*[n]; for (int ii=0; ii<n; ii++){ result[ii] = new short[n]; } z1=0,z2=0,z3=0,z4=0; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ if (arestas[i][j] == 1){ result[i][j] = y[i][j].get(GRB_DoubleAttr_X); // GUARDA O RESULTADO z1+=result[i][j]*matrix_peso1[i][j]; // calcula os pesos z2+=result[i][j]*matrix_peso2[i][j]; z3+=result[i][j]*matrix_peso3[i][j]; z4+=result[i][j]*matrix_peso4[i][j]; } } } if (z4>z4_k_estrela){ z1_estrela = z1; z2_estrela = z2; z3_estrela = z3; z4_k_estrela = z4; for (int i=0; i<n; i++){ for (int j=i+1; j<n; j++){ z_n_plus_1[i][j] = result[i][j]; } } } } //} } } if (z4_k_estrela!=(-1)*MM){ S.push_back(z_n_plus_1); Pesos pppp = (Pesos){z1_estrela,z2_estrela,z3_estrela,z4_k_estrela}; Z.push_back(pppp); nn++; //cout<<"nn = "<<nn<<endl; } } while (z4_k_estrela!=(-1)*MM); times(&tempsFinal1); /* current time */ // clock final clock_t user_time1 = (tempsFinal1.tms_utime - tempsInit.tms_utime); cout<<user_time1<<endl; cout<<(float) user_time1 / (float) sysconf(_SC_CLK_TCK)<<endl;//"Tempo do usuario por segundo : " cout<<"RESULTADO FINAL..."<<endl; printResultado(); } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } return 0; }
vector <double> solve2(vector <vector <double> > M) { vector <double> solution; try { GRBEnv env = GRBEnv(); vector <vector <double> > N = M; int numPoints = M.size(); int numCircles = M.back().size(); //cout<<"solving for "<<numCircles<<" circles and "<<numPoints<<" points"<<endl; GRBVar p[numPoints]; double coeff[numPoints]; GRBModel model = GRBModel(env); GRBLinExpr expr; // Create variables for (int i=0;i<numPoints;i++){ p[i] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY); coeff[i] = 1.0; } expr.addTerms(coeff, p,numPoints); // Integrate new variables model.update(); // Set objective: maximize x + y + 2 z model.setObjective(expr, GRB_MINIMIZE); for(int i=0;i<numCircles;i++){ GRBLinExpr cexpr; double ccoeff[numPoints]; for(int j=0;j<numPoints;j++){ ccoeff[j] = M[j].back(); M[j].pop_back(); } cexpr.addTerms(ccoeff,p,numPoints); model.addConstr(cexpr, GRB_GREATER_EQUAL,1.0); } // Optimize model model.optimize(); int c=0; for (int i=0;i<numPoints;i++){ solution.push_back((double)p[i].get(GRB_DoubleAttr_X)); c += solution.back(); } model.addConstr(expr, GRB_EQUAL, c); int temp; int temp2; for (int i=0;i<numPoints;i++){ temp=0; while(N.back().size()){ temp = temp + (N.back()).back(); N.back().pop_back(); } coeff[i] = temp; N.pop_back(); } expr.addTerms(coeff, p,numPoints); if (rand()%2) model.setObjective(expr, GRB_MINIMIZE); else model.setObjective(expr, GRB_MAXIMIZE); model.optimize(); solution.clear(); c=0; for (int i=0;i<numPoints;i++){ solution.push_back((double)p[i].get(GRB_DoubleAttr_X)); c += solution.back(); } } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; // cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } return solution; }
int main(int argc, char *argv[]) { GRBEnv* env = 0; GRBConstr* c = 0; GRBVar* v = 0; GRBVar** x = 0; GRBVar* slacks = 0; GRBVar* totShifts = 0; GRBVar* diffShifts = 0; int xCt = 0; try { // Sample data const int nShifts = 14; const int nWorkers = 7; // Sets of days and workers string Shifts[] = { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6", "Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13", "Sun14" }; string Workers[] = { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" }; // Number of workers required for each shift double shiftRequirements[] = { 3, 2, 4, 4, 5, 6, 5, 2, 2, 3, 4, 6, 7, 5 }; // Worker availability: 0 if the worker is unavailable for a shift double availability[][nShifts] = { { 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 }, { 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 }, { 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, { 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1 }, { 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1 }, { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }; // Model env = new GRBEnv(); GRBModel model = GRBModel(*env); model.set(GRB_StringAttr_ModelName, "assignment"); // Assignment variables: x[w][s] == 1 if worker w is assigned // to shift s. This is no longer a pure assignment model, so we must // use binary variables. x = new GRBVar*[nWorkers]; for (int w = 0; w < nWorkers; ++w) { x[w] = model.addVars(nShifts); xCt++; model.update(); for (int s = 0; s < nShifts; ++s) { ostringstream vname; vname << Workers[w] << "." << Shifts[s]; x[w][s].set(GRB_DoubleAttr_UB, availability[w][s]); x[w][s].set(GRB_CharAttr_VType, GRB_BINARY); x[w][s].set(GRB_StringAttr_VarName, vname.str()); } } // Slack variables for each shift constraint so that the shifts can // be satisfied slacks = model.addVars(nShifts); model.update(); for (int s = 0; s < nShifts; ++s) { ostringstream vname; vname << Shifts[s] << "Slack"; slacks[s].set(GRB_StringAttr_VarName, vname.str()); } // Variable to represent the total slack GRBVar totSlack = model.addVar(0, GRB_INFINITY, 0, GRB_CONTINUOUS, "totSlack"); // Variables to count the total shifts worked by each worker totShifts = model.addVars(nWorkers); model.update(); for (int w = 0; w < nWorkers; ++w) { ostringstream vname; vname << Workers[w] << "TotShifts"; totShifts[w].set(GRB_StringAttr_VarName, vname.str()); } // Update model to integrate new variables model.update(); GRBLinExpr lhs; // Constraint: assign exactly shiftRequirements[s] workers // to each shift s for (int s = 0; s < nShifts; ++s) { lhs = 0; lhs += slacks[s]; for (int w = 0; w < nWorkers; ++w) { lhs += x[w][s]; } model.addConstr(lhs == shiftRequirements[s], Shifts[s]); } // Constraint: set totSlack equal to the total slack lhs = 0; for (int s = 0; s < nShifts; ++s) { lhs += slacks[s]; } model.addConstr(lhs == totSlack, "totSlack"); // Constraint: compute the total number of shifts for each worker for (int w = 0; w < nWorkers; ++w) { lhs = 0; for (int s = 0; s < nShifts; ++s) { lhs += x[w][s]; } ostringstream vname; vname << "totShifts" << Workers[w]; model.addConstr(lhs == totShifts[w], vname.str()); } // Objective: minimize the total slack GRBLinExpr obj = 0; obj += totSlack; model.setObjective(obj); // Optimize int status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts); if (status != GRB_OPTIMAL) { return 1; } // Constrain the slack by setting its upper and lower bounds totSlack.set(GRB_DoubleAttr_UB, totSlack.get(GRB_DoubleAttr_X)); totSlack.set(GRB_DoubleAttr_LB, totSlack.get(GRB_DoubleAttr_X)); // Variable to count the average number of shifts worked GRBVar avgShifts = model.addVar(0, GRB_INFINITY, 0, GRB_CONTINUOUS, "avgShifts"); // Variables to count the difference from average for each worker; // note that these variables can take negative values. diffShifts = model.addVars(nWorkers); model.update(); for (int w = 0; w < nWorkers; ++w) { ostringstream vname; vname << Workers[w] << "Diff"; diffShifts[w].set(GRB_StringAttr_VarName, vname.str()); diffShifts[w].set(GRB_DoubleAttr_LB, -GRB_INFINITY); } // Update model to integrate new variables model.update(); // Constraint: compute the average number of shifts worked lhs = 0; for (int w = 0; w < nWorkers; ++w) { lhs += totShifts[w]; } model.addConstr(lhs == nWorkers * avgShifts, "avgShifts"); // Constraint: compute the difference from the average number of shifts for (int w = 0; w < nWorkers; ++w) { lhs = 0; lhs += totShifts[w]; lhs -= avgShifts; ostringstream vname; vname << Workers[w] << "Diff"; model.addConstr(lhs == diffShifts[w], vname.str()); } // Objective: minimize the sum of the square of the difference from the // average number of shifts worked GRBQuadExpr qobj; for (int w = 0; w < nWorkers; ++w) { qobj += diffShifts[w] * diffShifts[w]; } model.setObjective(qobj); // Optimize status = solveAndPrint(model, totSlack, nWorkers, Workers, totShifts); if (status != GRB_OPTIMAL) { return 1; } } catch (GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch (...) { cout << "Exception during optimization" << endl; } delete[] c; delete[] v; for (int i = 0; i < xCt; ++i) { delete[] x[i]; } delete[] x; delete[] slacks; delete[] totShifts; delete[] diffShifts; delete env; return 0; }
int main (int argc, char * argv[]) { chrono :: steady_clock :: time_point tBegin = chrono :: steady_clock :: now(); string I ("0"); ulint timeLimit = 10; if (argc >= 2) { I = string (argv[1]); } if (argc >= 3) { timeLimit = atoi(argv[2]); } ulint nComplete, k, t, n, m, root; double d; cin >> nComplete >> d >> k >> t >> n >> m >> root; vector <ulint> penalty (nComplete); // vector with de penalties of each vectex vector < list < pair <ulint, ulint> > > adj (nComplete); // adjacency lists for the graph for (ulint v = 0; v < nComplete; v++) { cin >> penalty[v]; } vector <ulint> solutionV (nComplete, 0); // reading solution vertices for (ulint i = 0; i < n; i++) { ulint v; cin >> v; solutionV[v] = 1; } vector < pair < pair <ulint, ulint> , ulint> > E (m); // vector of edges with the format ((u, v), w) map < pair <ulint, ulint>, ulint> mE; // map an edge to its ID vector < vector <ulint> > paths (m); // reading graph for (ulint e = 0; e < m; e++) { ulint u, v, w, pathSize; cin >> u >> v >> w >> pathSize; adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); E[e] = make_pair(make_pair(u, v), w); mE[make_pair(u, v)] = e; mE[make_pair(v, u)] = e; paths[e] = vector <ulint> (pathSize); for (ulint i = 0; i < pathSize; i++) { cin >> paths[e][i]; } } try { string N = itos(nComplete); stringstream ssD; ssD << fixed << setprecision(1) << d; string D = ssD.str(); D.erase(remove(D.begin(), D.end(), '.'), D.end()); string K = itos(k); string T = itos(t); ifstream remainingTimeFile ("./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/remainingTime.txt"); lint remainingTime = 0; if (remainingTimeFile.is_open()) { remainingTimeFile >> remainingTime; } if (remainingTime > 0) { timeLimit += remainingTime; } GRBEnv env = GRBEnv(); env.set(GRB_IntParam_LazyConstraints, 1); env.set(GRB_IntParam_LogToConsole, 0); env.set(GRB_StringParam_LogFile, "./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/log2.txt"); env.set(GRB_DoubleParam_TimeLimit, ((double) timeLimit)); GRBModel model = GRBModel(env); model.getEnv().set(GRB_IntParam_LazyConstraints, 1); model.getEnv().set(GRB_IntParam_LogToConsole, 0); model.getEnv().set(GRB_StringParam_LogFile, "./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/log2.txt"); model.getEnv().set(GRB_DoubleParam_TimeLimit, ((double) timeLimit)); vector <GRBVar> y (nComplete); // ∀ v ∈ V for (ulint v = 0; v < nComplete; v++) { // y_v ∈ {0.0, 1.0} y[v] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "y_" + itos(v)); } vector <GRBVar> x (m); // ∀ e ∈ E for (ulint e = 0; e < m; e++) { ulint u, v; u = E[e].first.first; v = E[e].first.second; // y_e ∈ {0.0, 1.0} x[e] = model.addVar(0.0, 1.0, 0.0, GRB_BINARY, "x_" + itos(u) + "_" + itos(v)); } model.update(); GRBLinExpr obj = 0.0; // obj = ∑ ce * xe for (ulint e = 0; e < m; e++) { ulint w; w = E[e].second; obj += w * x[e]; } // obj += ∑ πv * (1 - yv) for (ulint v = 0; v < nComplete; v++) { obj += penalty[v] * (1.0 - y[v]); } model.setObjective(obj, GRB_MINIMIZE); // yu == 1 model.addConstr(y[root] == 1.0, "c_0"); // dominance // ∀ v ∈ V for (ulint v = 0; v < nComplete; v++) { if (solutionV[v] == 1) { GRBLinExpr constr = 0.0; constr += y[v]; model.addConstr(constr == 1, "c_1_" + itos(v)); } } // each vertex must have exactly two edges adjacent to itself // ∀ v ∈ V for (ulint v = 0; v < nComplete; v++) { // ∑ xe == 2 * yv , e ∈ δ({v}) GRBLinExpr constr = 0.0; for (list < pair <ulint, ulint> > :: iterator it = adj[v].begin(); it != adj[v].end(); it++) { ulint w = (*it).first; // destination ulint e = mE[make_pair(v, w)]; constr += x[e]; } model.addConstr(constr == 2.0 * y[v], "c_2_" + itos(v)); } subtourelim cb = subtourelim(y, x, nComplete, m, E, mE, root); model.setCallback(&cb); model.optimize(); if (model.get(GRB_IntAttr_SolCount) > 0) { ulint solutionCost = 0; set <ulint> solutionVectices; vector < pair <ulint, ulint> > solutionEdges; solutionCost = round(model.get(GRB_DoubleAttr_ObjVal)); for (ulint v = 0; v < nComplete; v++) { if (y[v].get(GRB_DoubleAttr_X) >= 0.5) { solutionVectices.insert(v); } } for (ulint e = 0; e < m; e++) { if (x[e].get(GRB_DoubleAttr_X) >= 0.5) { for (ulint i = 0; i < paths[e].size() - 1; i++) { pair <ulint, ulint> edge; if (paths[e][i] < paths[e][i + 1]) { edge.first = paths[e][i]; edge.second = paths[e][i + 1]; } else { edge.first = paths[e][i + 1]; edge.second = paths[e][i]; } solutionEdges.push_back(edge); } } } cout << solutionVectices.size() << ' ' << solutionEdges.size() << ' ' << solutionCost << endl; for (set <ulint> :: iterator it = solutionVectices.begin(); it != solutionVectices.end(); it++) { ulint v = *it; cout << v << endl; } for (vector < pair <ulint, ulint> > :: iterator it = solutionEdges.begin(); it != solutionEdges.end(); it++) { pair <ulint, ulint> e = *it; cout << e.first << " " << e.second << endl; } } else { cout << "0 0 0" << endl; } // exporting model model.write("./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/model2.lp"); ofstream objValFile ("./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/objVal2.txt", ofstream :: out); objValFile << model.get(GRB_DoubleAttr_ObjVal); objValFile.close(); ofstream gapFile ("./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/gap2.txt", ofstream :: out); gapFile << model.get(GRB_DoubleAttr_MIPGap); gapFile.close(); chrono :: steady_clock :: time_point tEnd = chrono :: steady_clock :: now(); chrono :: nanoseconds elapsedTime = chrono :: duration_cast <chrono :: nanoseconds> (tEnd - tBegin); ofstream elapsedTimeFile ("./output/N" + N + "D" + D + "K" + K + "T" + T + "I" + I + "/elapsedTime2.txt", ofstream :: out); elapsedTimeFile << elapsedTime.count(); elapsedTimeFile.close(); } catch (GRBException e) {