Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark mode
Gurobi Example Tour
Light LogoDark Logo
Gurobi
Back to top

Mip2.java#

/* Copyright 2025, Gurobi Optimization, LLC *//* This example reads a MIP model from a file, solves it and   prints the objective values from all feasible solutions   generated while solving the MIP. Then it creates the fixed   model and solves that model. */importcom.gurobi.gurobi.*;publicclassMip2{publicstaticvoidmain(String[]args){if(args.length<1){System.out.println("Usage: java Mip2 filename");System.exit(1);}try{GRBEnvenv=newGRBEnv();GRBModelmodel=newGRBModel(env,args[0]);if(model.get(GRB.IntAttr.IsMIP)==0){System.out.println("Model is not a MIP");System.exit(1);}model.optimize();intoptimstatus=model.get(GRB.IntAttr.Status);doubleobjval=0;if(optimstatus==GRB.Status.OPTIMAL){objval=model.get(GRB.DoubleAttr.ObjVal);System.out.println("Optimal objective: "+objval);}elseif(optimstatus==GRB.Status.INF_OR_UNBD){System.out.println("Model is infeasible or unbounded");return;}elseif(optimstatus==GRB.Status.INFEASIBLE){System.out.println("Model is infeasible");return;}elseif(optimstatus==GRB.Status.UNBOUNDED){System.out.println("Model is unbounded");return;}else{System.out.println("Optimization was stopped with status = "+optimstatus);return;}/* Iterate over the solutions and compute the objectives */System.out.println();for(intk=0;k<model.get(GRB.IntAttr.SolCount);++k){model.set(GRB.IntParam.SolutionNumber,k);doubleobjn=model.get(GRB.DoubleAttr.PoolNObjVal);System.out.println("Solution "+k+" has objective: "+objn);}System.out.println();/* Create a fixed model, turn off presolve and solve */GRBModelfixed=model.fixedModel();fixed.set(GRB.IntParam.Presolve,0);fixed.optimize();intfoptimstatus=fixed.get(GRB.IntAttr.Status);if(foptimstatus!=GRB.Status.OPTIMAL){System.err.println("Error: fixed model isn't optimal");return;}doublefobjval=fixed.get(GRB.DoubleAttr.ObjVal);if(Math.abs(fobjval-objval)>1.0e-6*(1.0+Math.abs(objval))){System.err.println("Error: objective values are different");return;}GRBVar[]fvars=fixed.getVars();double[]x=fixed.get(GRB.DoubleAttr.X,fvars);String[]vnames=fixed.get(GRB.StringAttr.VarName,fvars);for(intj=0;j<fvars.length;j++){if(x[j]!=0.0){System.out.println(vnames[j]+" "+x[j]);}}// Dispose of models and environmentfixed.dispose();model.dispose();env.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());}}}

Help and Feedback


[8]
ページ先頭

©2009-2025 Movatter.jp