Please correct my code
AnsweredI am a beginner to use "Gurobi". I wrote the code to solve the assignment problem as you can see below. Once. I run the code. Complier reported that "Error code: 0.Failed to create model".
So, could anyone please help me fix the bugs. Thank you.
--------------------------------------------------------------------------------------
import gurobi.*;
public class Assignment {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try{
// Define the cost matrix
// Number of rows: number of vehicles
// Number of columns: number of jobs
double[][] cost = {
{150, 160, 90, 120, 150},
{90, 90, 120, 90, 140},
{120, 120, 150, 120, 90},
{100, 90, 150, 150, 120},
{140, 120, 90, 140, 90},
{180, 150, 180, 120, 120},
{160, 120, 160, 100, 150},
{110, 100, 130, 80, 110}};
int n = cost.length; //numVehicles
int m = cost[0].length; //numJobs
//Creat empty environment
GRBEnv env = new GRBEnv(true);
// Creat empty model
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "Assignment");
//Create variables
GRBVar [][] x = new GRBVar[n][m];
for (int i =0;i<n;i++){
for(int j =0;j<m;j++){
x[i][j] = model.addVar(0.0, 1.0,0, GRB.BINARY,
"x["+String.valueOf(i)+"]["+String.valueOf(j)+"]");
}
}
//Set Objective Function
GRBLinExpr expr = new GRBLinExpr ();
for(int i =0;i<n;i++){
for(int j =0;j<m;j++){
expr.addTerm(cost[i][j], x[i][j]);
}
}
//The objective is to minize cost
model.set(GRB.IntAttr.ModelSense,GRB.MINIMIZE);
//Define Constraint:
// (1) Each vehicle performs no more than one job
for(int i=0;i<n;i++){
GRBLinExpr row = new GRBLinExpr();
for(int j=0;j<m;j++){
row.addTerm(1, x[i][j]);
}
model.addConstr(row,GRB.LESS_EQUAL,1,"row "+i);
}
// (2) Every job must be scheduled
for (int j=0;j<m;j++){
GRBLinExpr col = new GRBLinExpr();
for(int i=0;i<n;i++ ){
col.addTerm(1,x[i][j]);
}
model.addConstr(col, GRB.EQUAL,1.0,"col"+j);
}
//Optimize
model.optimize();
System.out.println("\nTotal: 0 "+model.get(GRB.DoubleAttr.ObjVal));
// Dispose of model and environment
model.dispose();
env.dispose();
} catch(GRBException e){
System.out.println("Error code: " +e.getErrorCode() + "." +
e.getMessage());
}
}
}
0
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi!
You are creating an empty environment using
GRBEnv env = new GRBEnv(true);
Please just use the normal environment constructor (without the \(\texttt{true}\) argument) to make Gurobi find your license and start a proper environment. Alternatively, you need to start the environment explicitly, using
env.start()
Cheers,
Matthias0 -
Matthias Miltenberger Thank you so much.
0
Post is closed for comments.
Comments
3 comments