本文整理匯總了Java中gurobi.GRB.StringAttr類的典型用法代碼示例。如果您正苦於以下問題:Java StringAttr類的具體用法?Java StringAttr怎麽用?Java StringAttr使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
StringAttr類屬於gurobi.GRB包,在下文中一共展示了StringAttr類的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: solveRelaxedModel
import gurobi.GRB.StringAttr; //導入依賴的package包/類
public static GRBModel solveRelaxedModel(GRBModel model) throws GRBException {
GRBConstr[] ctr = model.getConstrs();
for (GRBConstr c : ctr) {
String name = c.get(StringAttr.ConstrName);
if (name.startsWith("tech")) {
model.remove(c);
System.out.println("Removed constraint " + name);
}
}
model.update();
model.optimize();
return model;
}
示例2: toString
import gurobi.GRB.StringAttr; //導入依賴的package包/類
@Override
public String toString() {
StringBuilder lhs = new StringBuilder();
for (int e = 0; e < mLinExpr.size(); e++) {
try {
double coef = mLinExpr.getCoeff(e);
if (coef > 0) {
if (e > 0) {
lhs.append(" ");
}
if (coef != 1) {
lhs.append(String.format("%s*%s", GRBUtilities.coefToString(coef), mLinExpr
.getVar(e).get(StringAttr.VarName)));
} else {
lhs.append(String.format("%s", mLinExpr.getVar(e).get(StringAttr.VarName)));
}
}
} catch (GRBException e1) {
lhs.append("NA");
}
}
return String.format("%s: %s %s %s", getName(), lhs, getSense(), getRHS());
}
示例3: dumpModelStats
import gurobi.GRB.StringAttr; //導入依賴的package包/類
private void dumpModelStats(List<HalfEdge> edges) throws GRBException {
print ("profile count " + (globalProfs == null ? 0 : globalProfs.size()));
print ("acute corner constraints " + countBadCorners);
print ("parallel edge constraints " + countBadEdges);
print ("nearby profile terms " + countNearbyProfiles);
print ("total half edges " + edges.size() );
print ("total faces " + faceInfo.size() );
if ( profFit.get( edges.get(0) ) != null)
print ("total profiles " + profFit.get( edges.get(0) ).length );
print( "total edge length " + totalEdgeLength );
print( "\nobjective fn breakdown follows...\n" );
Cache<String, Double> penalties = new Cach<String, Double>( x -> 0. );
Cache<String, Integer> count = new Cach<String, Integer>( x -> 0 );
for ( GRBVar v : model.getVars() ) {
penalties.cache.put( v.get( StringAttr.VarName ),
penalties.get( v.get( StringAttr.VarName ) ) + v.get( GRB.DoubleAttr.Obj ) * v.get( GRB.DoubleAttr.X ) );
count.cache.put( v.get( StringAttr.VarName ), count.get( v.get( StringAttr.VarName ) ) + 1 );
}
List<String> vals = new ArrayList<>( penalties.cache.keySet() );
Collections.sort( vals );
double obj = penalties.cache.values().stream().mapToDouble( x -> x ).sum();
for ( String k : vals )
print( k + "(" + count.get( k ) + ") :: " + penalties.get( k ) + " " );
print( "\ntotal obj " + obj + "\n\n" );
}
示例4: testReal
import gurobi.GRB.StringAttr; //導入依賴的package包/類
private static void testReal(int presolve) {
System.out.println("TEST WITH PRESOLVE = " + presolve);
System.out.println("==================================================");
try {
sEnv.set(IntParam.Presolve, presolve);
GRBModel model = new GRBModel(sEnv, "gurobi/_model.lp");
model.set(StringAttr.ModelName, "test_pres" + presolve);
GRBVar[] vars = model.getVars();
model.read("gurobi/_model_start.mst");
checkStartSolution(model, 100);
model.optimize();
// Print first solution
int solCount = model.get(IntAttr.SolCount);
if (solCount > 0) {
sEnv.set(IntParam.SolutionNumber, solCount - 1);
double[] vals = model.get(DoubleAttr.Xn, vars);
String[] names = model.get(StringAttr.VarName, vars);
for (int i = 0; i < vars.length; i++) {
if (vals[i] > 1e-3)
System.out.printf("%s %s\n", names[i], vals[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("==================================================");
}
示例5: checkStartSolution
import gurobi.GRB.StringAttr; //導入依賴的package包/類
public static boolean checkStartSolution(GRBModel model, int nodes) throws GRBException {
boolean[] visited = new boolean[nodes];
GRBConstr[] ctr = model.getConstrs();
GRBVar[] vars = model.getVars();
double[] starts = model.get(DoubleAttr.Start, vars);
for (int i = 0; i < starts.length; i++) {
if (starts[i] == 1) {
for (int n = 0; n < visited.length; n++) {
if (model.getCoeff(ctr[n], vars[i]) == 1)
visited[n] = true;
}
}
}
boolean ok = true;
for (int n = 0; n < visited.length; n++) {
if (!visited[n]) {
ok = false;
System.out.printf("Unvisited node: %s (%s)\n", (n + 26),
ctr[n].get(StringAttr.ConstrName));
}
}
if (ok)
System.out.println("Initial solution is feasible");
else
System.out.println("Initial solution is not feasible");
return ok;
}
示例6: runModel
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Run a model stored in a file
*
* @param modelFile
* the model file
* @param solFile
* the initial solution file
* @param detStatFile
* the path of the detailed stats path
* @param statComment
* a comment for the detailed stats file
* @param ttStatFile
* the collector for time to target values
*/
public static void runModel(File modelFile, File solFile, String detStatFile, String statComment,
String ttStatFile, double startObj) {
GRBModel model = null;
try {
String modelName = getModelName(modelFile.getName());
TRSPLogging.getRunLogger().info("Running model %s (initial solution: %s)", modelFile, solFile);
model = GurobiModelSolver.readModel(modelFile.getAbsolutePath(),
solFile != null && solFile.exists() ? solFile.getAbsolutePath() : null, false);
model.set(StringAttr.ModelName, modelName);
TRSPGRBStatCollector bench = new TRSPGRBStatCollector(model, statComment, detStatFile, ttStatFile);
TRSPLogging.getRunLogger().info(" Starting the optimizer");
bench.call();
bench.collectStats();
} catch (Exception e) {
TRSPLogging.getRunLogger().exception("GurobiBenchmarking.runModel", e);
} finally {
if (model != null)
model.dispose();
}
}
示例7: setCoveringConstraintsSense
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Set the sense of the set covering constraints
*
* @param model
* the model to be modified
* @param sense
* the sense of constraints (GRB.EQUAL or GRB.GREATER_EQUAL)
* @throws GRBException
*/
public static void setCoveringConstraintsSense(GRBModel model, char sense) throws GRBException {
GRBConstr[] ctr = model.getConstrs();
String[] names = model.get(StringAttr.ConstrName, ctr);
// Change all constraints to sense
for (int i = 0; i < ctr.length; i++) {
if (names[i].startsWith("cover"))
ctr[i].set(CharAttr.Sense, sense);
}
model.update();
}
示例8: addEmptyTours
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Add empty tours to the model and change the technician constraint sense to GRB.EQUAL
*
* @param model
* the model to be edited
* @throws GRBException
*/
public static void addEmptyTours(GRBModel model) throws GRBException {
GRBConstr[] ctr = model.getConstrs();
String[] names = model.get(StringAttr.ConstrName, ctr);
// Change all constraints to sense
ArrayList<GRBConstr> techConstr = new ArrayList<GRBConstr>(25);
for (int i = 0; i < ctr.length; i++) {
if (names[i].startsWith("tech"))
techConstr.add(ctr[i]);
}
int techCount = techConstr.size();
double lb[] = new double[techCount];
double ub[] = new double[techCount];
char type[] = new char[techCount];
double c[] = new double[techCount];
String n[] = new String[techCount];
GRBColumn col[] = new GRBColumn[techCount];
for (int i = 0; i < techCount; i++) {
lb[i] = 0;
ub[i] = 1;
type[i] = GRB.BINARY;
c[i] = 0;
n[i] = techConstr.get(i).get(StringAttr.ConstrName).replace("tech", "dummy");
col[i] = new GRBColumn();
col[i].addTerm(1, techConstr.get(i));
techConstr.get(i).set(CharAttr.Sense, GRB.EQUAL);
}
model.addVars(lb, ub, c, type, n, col);
model.update();
}
示例9: setModel
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Sets the model and attach the corresponding callbacks to it
*
* @param model
* the model to be monitored
*/
public void setModel(GRBModel model) {
mModel = model;
mStatus = null;
if (mModel == null)
return;
// Read the initial solution value
double initObj = 0;
boolean startDef = false;
String name = "model";
try {
name = mModel.get(StringAttr.ModelName);
GRBVar vars[] = mModel.getVars();
double starts[] = mModel.get(DoubleAttr.Start, vars);
double costs[] = mModel.get(DoubleAttr.Obj, vars);
for (int i = 0; i < starts.length; i++) {
if (starts[i] != GRB.UNDEFINED) {
startDef = false;
initObj += costs[i] * starts[i];
}
}
} catch (GRBException e) {
TRSPLogging.getRunLogger().exception("GurobiBenchmarking.main", e);
}
mInitialObj = initObj;
mStartDefined = startDef;
mCallback = new GRBBenchCallback(mDetailStatFile, name, mStatComment, mStartDefined, TARGET_GAPS, TIME_SLICES,
mInitialObj);
mModel.setCallback(mCallback);
}
示例10: toString
import gurobi.GRB.StringAttr; //導入依賴的package包/類
@Override
public String toString() {
StringBuilder variables = new StringBuilder();
StringBuilder obj = new StringBuilder();
StringBuilder constraints = new StringBuilder();
try {
if (getModel().get(IntAttr.ModelSense) < 0) {
obj.append("Max ");
} else {
obj.append("Min ");
}
} catch (GRBException e1) {
}
GRBVar[] vars = getModel().getVars();
GRBConstr[] ctr = getModel().getConstrs();
// Arrays.sort(vars, new GRBVarComparator());
// Arrays.sort(ctr, new GRBConstrComparator());
for (GRBVar v : vars) {
variables.append(GRBUtilities.varToString(v));
variables.append("\n");
try {
obj.append(String.format("%s*%s ", v.get(DoubleAttr.Obj), v.get(StringAttr.VarName)));
} catch (GRBException e) {
obj.append(String.format("%s ", e.getMessage()));
}
}
// variables.append("Constraints:\n");
for (GRBConstr c : ctr) {
constraints.append(GRBUtilities.constrToString(c, getModel()));
constraints.append("\n");
}
return String.format("Variables:\n%s\n\nObj:%s\ns.t.:\n%s", variables, obj, constraints);
}
示例11: varToString
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Returns a string describing the given variable
*
* @param var
* @return a string describing the given variable
*/
public static String varToString(GRBVar var) {
try {
return String.format("%s [%s,%s] c=%.3f: %s", var.get(StringAttr.VarName), var.get(DoubleAttr.LB),
var.get(DoubleAttr.UB), var.get(DoubleAttr.Obj), var.get(CharAttr.VType));
} catch (GRBException e) {
return String.format("%s:%s", var, e.getMessage());
}
}
示例12: collectStats
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Collect and write the statistics once the model was optimized
*
* @throws IllegalStateException
* if the optimization is not finished
*/
public synchronized void collectStats() {
if (mRunning)
throw new IllegalStateException("Model optimization has not terminated");
try {
mStatus = GRBUtilities.convertStatus(mModel.get(IntAttr.Status));
} catch (GRBException e1) {
mStatus = SolverStatus.UNKNOWN_STATUS;
TRSPLogging.getBaseLogger().exception("GurobiRun.collectStats", e1);
}
mCallback.solverStopped(mStatus);
// Collect stats
Object[] stats = new Object[TT_LABELS.length];
try {
stats[0] = mModel.get(StringAttr.ModelName);
double obj = mModel.get(DoubleAttr.ObjVal);
double bnd = mModel.get(DoubleAttr.ObjBound);
stats[7] = obj;
stats[8] = bnd;
stats[9] = Math.abs((obj - bnd) / obj);
} catch (GRBException e) {
TRSPLogging.getBaseLogger().exception("GurobiRun.collectStats", e);
}
stats[1] = mStartDefined;
stats[2] = mStatus;
stats[3] = mModel.getVars().length;
stats[4] = mCallback.getRemovedColumns();
stats[5] = mModel.getConstrs().length;
stats[6] = mInitialObj;
for (int j = 0; j < TARGET_GAPS.length; j++) {
stats[j + TT_LAB_OFFSET] = mCallback.getTimeToTarget(j);
}
for (int j = 0; j < TIME_SLICES.length; j++) {
stats[j + TT_LAB_OFFSET + TARGET_GAPS.length] = mCallback.getImpAtTime(j);
}
// TRSPLogging.getRunLogger().info(" Collecting stats: %s", Utilities.toShortString(stats));
mTargetCollector.collect(stats);
if (mCallback.getRemovedColumns() < mModel.getVars().length
&& (mStatus == SolverStatus.OPTIMAL || mStatus == SolverStatus.INTERRUPTED || mStatus == SolverStatus.TIME_LIMIT)) {
mCallback.flush();
}
}
示例13: writeMST
import gurobi.GRB.StringAttr; //導入依賴的package包/類
/**
* Write the {@link DoubleAttr#Start} attribute of all the variables of a {@link GRBModel model}
*
* @param model
* the model from which the start values will be extracted
* @param file
* the path of the destination file
* @returns the written {@link File}
* @throws IOException
* @throws GRBException
*/
public static File writeMST(GRBModel model, String file) throws IOException, GRBException {
if (!file.endsWith(".mst"))
file = file + ".mst";
File mst = new File(file);
if (!mst.exists())
mst.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(mst, false));
GRBVar[] vars = model.getVars();
double[] start = model.get(DoubleAttr.Start, vars);
String[] names = model.get(StringAttr.VarName, vars);
String modelName = null;
try {
modelName = model.get(StringAttr.ModelName);
} catch (GRBException e) {
// Ignore
} finally {
if (modelName == null)
modelName = file;
}
out.write("# MIP start for ");
out.write(modelName);
out.newLine();
for (int i = 0; i < start.length; i++) {
if (start[i] != GRB.UNDEFINED) {
out.append(names[i]);
out.write(" ");
out.write(start[i] + "");
out.newLine();
}
}
out.flush();
out.close();
return mst;
}