manbet体育手机客户端


Fixanddive.java


/* Copyright 2019, 狗万app足彩Gurobi Optimization, LLC */ /*实现一个简单的MIP启发式。放松模型,根据分数对变量进行排序,并确定最接近整数变量的25%的分数变量。重复,直到松弛是整数可行或线性不可行的。* /进口gurobi。*;进口java.util。*;公开课Fixanddive{公共静态空main (String [] args){/ /比较类用于排序变量列表基于放松/ / fractionality类FractionalCompare实现比较< GRBVar >{公共int比较(GRBVar v1, GRBVar v2){尝试{双sol1 = Math.abs (v1.get (GRB.DoubleAttr.X));double sol2 = Math.abs(v2.get(grb . doubleattro . x));double frac1 =数学。abs (sol1 -数学。地板(sol1 + 0.5));double frac2 =数学。abs (sol2 -数学。floor(sol2 + 0.5)); if (frac1 < frac2) { return -1; } else if (frac1 == frac2) { return 0; } else { return 1; } } catch (GRBException e) { System.out.println("Error code: " + e.getErrorCode() + ". " + e.getMessage()); } return 0; } } if (args.length < 1) { System.out.println("Usage: java Fixanddive filename"); System.exit(1); } try { // Read model GRBEnv env = new GRBEnv(); GRBModel model = new GRBModel(env, args[0]); // Collect integer variables and relax them ArrayList intvars = new ArrayList(); for (GRBVar v : model.getVars()) { if (v.get(GRB.CharAttr.VType) != GRB.CONTINUOUS) { intvars.add(v); v.set(GRB.CharAttr.VType, GRB.CONTINUOUS); } } model.set(GRB.IntParam.OutputFlag, 0); model.optimize(); // Perform multiple iterations. In each iteration, identify the first // quartile of integer variables that are closest to an integer value // in the relaxation, fix them to the nearest integer, and repeat. for (int iter = 0; iter < 1000; ++iter) { // create a list of fractional variables, sorted in order of // increasing distance from the relaxation solution to the nearest // integer value ArrayList fractional = new ArrayList(); for (GRBVar v : intvars) { double sol = Math.abs(v.get(GRB.DoubleAttr.X)); if (Math.abs(sol - Math.floor(sol + 0.5)) > 1e-5) { fractional.add(v); } } System.out.println("Iteration " + iter + ", obj " + model.get(GRB.DoubleAttr.ObjVal) + ", fractional " + fractional.size()); if (fractional.size() == 0) { System.out.println("Found feasible solution - objective " + model.get(GRB.DoubleAttr.ObjVal)); break; } // Fix the first quartile to the nearest integer value Collections.sort(fractional, new FractionalCompare()); int nfix = Math.max(fractional.size() / 4, 1); for (int i = 0; i < nfix; ++i) { GRBVar v = fractional.get(i); double fixval = Math.floor(v.get(GRB.DoubleAttr.X) + 0.5); v.set(GRB.DoubleAttr.LB, fixval); v.set(GRB.DoubleAttr.UB, fixval); System.out.println(" Fix " + v.get(GRB.StringAttr.VarName) + " to " + fixval + " ( rel " + v.get(GRB.DoubleAttr.X) + " )"); } model.optimize(); // Check optimization result if (model.get(GRB.IntAttr.Status) != GRB.Status.OPTIMAL) { System.out.println("Relaxation is infeasible"); break; } } // Dispose of model and environment model.dispose(); env.dispose(); } catch (GRBException e) { System.out.println("Error code: " + e.getErrorCode() + ". " + e.getMessage()); } } }