forked from xiongwq16/cplex-java-api-tutorial-zh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiet.java
More file actions
353 lines (297 loc) · 13.4 KB
/
Diet.java
File metadata and controls
353 lines (297 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package examples;
/* --------------------------------------------------------------------------
* File: Diet.java
* Version 12.9.0
* --------------------------------------------------------------------------
* Licensed Materials - Property of IBM
* 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
* Copyright IBM Corporation 2001, 2019. All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with
* IBM Corp.
* --------------------------------------------------------------------------
*
* Reads data for a dietary problem, builds the model, and solves it.
*
* Input data:
* foodMin[j] minimum amount of food j to use
* foodMax[j] maximum amount of food j to use
* foodCost[j] cost for one unit of food j
* nutrMin[i] minimum amount of nutrient i
* nutrMax[i] maximum amount of nutrient i
* nutrPerFood[i][j] nutrition amount of nutrient i in food j
*
* Modeling variables:
* buy[j] amount of food j to purchase
*
* Objective:
* minimize sum(j) buy[j] * foodCost[j]
*
* Constraints:
* forall foods i: nutrMin[i] <= sum(j) buy[j] * nutrPer[i][j] <= nutrMax[j]
*
* Options:
* - build the model by column, rather than by row
* - restrict to selecting integral food quantities
* - create a multi-objective model
*
* See the usage message for more details.
*/
import ilog.concert.*;
import ilog.cplex.*;
import ilog.cplex.IloCplex.MultiObjIntInfo;
import ilog.cplex.IloCplex.MultiObjLongInfo;
import ilog.cplex.IloCplex.MultiObjNumInfo;
public class Diet {
/**
* Print a usage message to stderr and abort.
*/
static void usage() {
System.err.println();
System.err.println("Usage: Diet [options...] <datafile>");
System.err.println(" By default, the problem will be generated by rows.");
System.err.println();
System.err.println(" Supported options are:");
System.err.println(" -r generate problem by row");
System.err.println(" -c generate problem by column");
System.err.println(" -i restrict to integral food quantities (i.e., convert to a MIP)");
System.err.println(" -m create a multi-objective problem where, in addition to");
System.err.println(" minimizing cost, the number of unique foods selected is");
System.err.println(" maximized (can be combined with -i)");
System.err.println();
System.exit(2);
}
/**
* A class to store problem data.
*/
static class Data {
int nFoods;
int nNutrs;
double[] foodCost;
double[] foodMin;
double[] foodMax;
double[] nutrMin;
double[] nutrMax;
double[][] nutrPerFood;
Data(String filename) throws IloException, java.io.IOException, InputDataReader.InputDataReaderException {
InputDataReader reader = new InputDataReader(filename);
foodCost = reader.readDoubleArray();
foodMin = reader.readDoubleArray();
foodMax = reader.readDoubleArray();
nutrMin = reader.readDoubleArray();
nutrMax = reader.readDoubleArray();
nutrPerFood = reader.readDoubleArrayArray();
nFoods = foodMax.length;
nNutrs = nutrMax.length;
if (nFoods != foodMin.length || nFoods != foodMax.length)
throw new IloException("inconsistent data in file " + filename);
if (nNutrs != nutrMin.length || nNutrs != nutrPerFood.length)
throw new IloException("inconsistent data in file " + filename);
for (int i = 0; i < nNutrs; ++i) {
if (nutrPerFood[i].length != nFoods)
throw new IloException("inconsistent data in file " + filename);
}
}
}
static void buildModelByRow(IloModeler model, Data data, IloNumVar[] buy, IloObjective cost, IloNumVarType type)
throws IloException {
int nFoods = data.nFoods;
int nNutrs = data.nNutrs;
for (int j = 0; j < nFoods; j++) {
buy[j] = model.numVar(data.foodMin[j], data.foodMax[j], type);
}
cost.setExpr(model.scalProd(data.foodCost, buy));
for (int i = 0; i < nNutrs; i++) {
model.addRange(data.nutrMin[i], model.scalProd(data.nutrPerFood[i], buy), data.nutrMax[i]);
}
}
/**
* 按列的形式添加变量 .<br>
*/
static void buildModelByColumn(IloMPModeler model, Data data, IloNumVar[] buy, IloObjective cost,
IloNumVarType type) throws IloException {
int nFoods = data.nFoods;
int nNutrs = data.nNutrs;
IloRange[] constraint = new IloRange[nNutrs];
for (int i = 0; i < nNutrs; i++) {
constraint[i] = model.addRange(data.nutrMin[i], data.nutrMax[i]);
}
for (int j = 0; j < nFoods; j++) {
IloColumn col = model.column(cost, data.foodCost[j]);
for (int i = 0; i < nNutrs; i++) {
col = col.and(model.column(constraint[i], data.nutrPerFood[i][j]));
}
buy[j] = model.numVar(col, data.foodMin[j], data.foodMax[j], type);
}
}
static void createMultiObj(IloCplex cplex, IloNumVar[] buy, IloObjective cost, IloObjective variety)
throws IloException {
// Create binary variables for each food.
IloNumVar[] varUsed = cplex.numVarArray(buy.length, 0.0, 1.0, IloNumVarType.Bool);
// Add indicator constraints that force the binary variables to 1 if
// a food is purchased/used.
for (int i = 0; i < buy.length; ++i) {
cplex.add(cplex.ifThen(cplex.eq(varUsed[i], 0), cplex.eq(buy[i], 0.0)));
cplex.add(cplex.ifThen(cplex.eq(buy[i], 0.0), cplex.eq(varUsed[i], 0)));
}
// Set up the second objective so that it maximizes the sum of the
// binary variables.
variety.setExpr(cplex.sum(varUsed));
variety.setSense(IloObjectiveSense.Maximize);
// Create an array of objectives:
// - the first objective minimizes the cost
// - the second objective maximizes the variety
IloNumExpr[] objArray = new IloNumExpr[] { cost.getExpr(), variety.getExpr() };
// Use a negative weight to maximize the second objective. The
// objective senses of all objective functions must match. Hence, we
// have to formulate max(sum) as min(-sum).
double[] weights = new double[] { 1.0, -1.0 };
// Adjust priorities such that we optimize the first objective
// first (i.e., give it a higher priority).
int[] priorities = new int[] { 2, 1 };
// Allow a small degradation in the first objective.
double[] absTols = new double[] { 0.5, 0.0 };
double[] relTols = new double[] { 0.0, 0.0 };
// 多目标设置
// Add the lexicographic objective to the model.
cplex.add(cplex.minimize(cplex.staticLex(objArray, weights, priorities, absTols, relTols, "staticLex1")));
}
static void printSolutionStat(String what, String val) {
System.out.printf(" %s: %s%n", what, (val != null) ? val : "---");
}
static void printMultiObjInfo(IloCplex cplex, MultiObjIntInfo what, int subprob) throws IloException {
String valString = null;
try {
valString = Integer.toString(cplex.getMultiObjInfo(what, subprob));
} catch (IloException ignore) {
}
printSolutionStat(what.toString(), valString);
}
static void printMultiObjInfo(IloCplex cplex, MultiObjLongInfo what, int subprob) throws IloException {
String valString = null;
try {
valString = Long.toString(cplex.getMultiObjInfo(what, subprob));
} catch (IloException ignore) {
}
printSolutionStat(what.toString(), valString);
}
static void printMultiObjInfo(IloCplex cplex, MultiObjNumInfo what, int subprob) throws IloException {
String valString = null;
try {
valString = Double.toString(cplex.getMultiObjInfo(what, subprob));
} catch (IloException ignore) {
}
printSolutionStat(what.toString(), valString);
}
static void printSolutionStats(IloCplex cplex) throws IloException {
final int num = cplex.getMultiObjNsolves();
for (int i = 0; i < num; ++i) {
int prio = cplex.getMultiObjInfo(MultiObjIntInfo.MultiObjPriority, i);
System.out.printf("subproblem %d [priority %d]:%n", i, prio);
printMultiObjInfo(cplex, MultiObjIntInfo.MultiObjError, i);
printMultiObjInfo(cplex, MultiObjIntInfo.MultiObjStatus, i);
printMultiObjInfo(cplex, MultiObjNumInfo.MultiObjTime, i);
printMultiObjInfo(cplex, MultiObjNumInfo.MultiObjDetTime, i);
printMultiObjInfo(cplex, MultiObjLongInfo.MultiObjNiterations, i);
printMultiObjInfo(cplex, MultiObjNumInfo.MultiObjObjValue, i);
printMultiObjInfo(cplex, MultiObjNumInfo.MultiObjBestObjValue, i);
printMultiObjInfo(cplex, MultiObjLongInfo.MultiObjNnodes, i);
printMultiObjInfo(cplex, MultiObjLongInfo.MultiObjNnodesLeft, i);
}
}
public static void main(String[] args) throws Exception {
// Set default arguments and parse command line.
String filename = "./data/diet.dat";
boolean byColumn = false;
IloNumVarType varType = IloNumVarType.Float;
boolean multiobj = false;
for (int i = 0; i < args.length; i++) {
if (args[i].charAt(0) == '-') {
if (args[i].equals("-r"))
byColumn = false;
else if (args[i].equals("-c"))
byColumn = true;
else if (args[i].equals("-i"))
varType = IloNumVarType.Int;
else if (args[i].equals("-m"))
multiobj = true;
else {
System.err.printf("Unknown argument: %s%n", args[i]);
usage();
}
} else {
filename = args[i];
}
}
// Read the data.
Data data = new Data(filename);
final int nFoods = data.nFoods;
IloCplex cplex = new IloCplex();
try {
// Build model
IloNumVar[] buy = new IloNumVar[nFoods];
IloObjective cost = cplex.minimize();
cost.setName("cost");
if (byColumn)
buildModelByColumn(cplex, data, buy, cost, varType);
else
buildModelByRow(cplex, data, buy, cost, varType);
// Optionally, create a second objective.
IloObjective variety = cplex.maximize();
variety.setName("number of foods");
if (multiobj) {
createMultiObj(cplex, buy, cost, variety);
} else {
cplex.add(cost);
}
// Write a copy of the problem to a file.
cplex.exportModel("Diet.java.lp");
// Solve model
if (multiobj) {
// Set multi-objective display level to "detailed".
cplex.setParam(IloCplex.Param.MultiObjective.Display, 2);
// Purely for demonstrative purposes, set global and local limits
// using parameter sets.
// First, set the global deterministic time limit.
cplex.setParam(IloCplex.Param.DetTimeLimit, 60000);
// Second, create a parameter set for each priority.
IloCplex.ParameterSet[] params = new IloCplex.ParameterSet[2];
params[0] = new IloCplex.ParameterSet();
params[1] = new IloCplex.ParameterSet();
// Set the local deterministic time limits. Optimization will stop
// whenever either the global or local limit is exceeded.
params[0].setParam(IloCplex.Param.DetTimeLimit, 50000);
params[1].setParam(IloCplex.Param.DetTimeLimit, 25000);
// Optimize the multi-objective problem and apply the parameter
// sets that were created above. The parameter sets are used
// one-by-one by each optimization.
if (!cplex.solve(params))
throw new IloException("Failed to optimize");
} else {
if (!cplex.solve())
throw new IloException("Failed to optimize");
}
// Print the solution status.
System.out.println();
System.out.println("Solution status = " + cplex.getStatus());
// Print the objective value(s).
if (multiobj) {
System.out.printf("Solution value 0 (%s) = %f%n", cost.getName(), cplex.getValue(cost.getExpr(), -1));
System.out.printf("Solution value 1 (%s) = %f%n", variety.getName(),
cplex.getValue(variety.getExpr(), -1));
System.out.println();
printSolutionStats(cplex);
} else {
System.out.printf("Solution value = %f%n", cplex.getObjValue());
}
System.out.println();
// Print the solution values.
for (int i = 0; i < nFoods; i++) {
System.out.printf("Food %d: Buy = %f%n", i, cplex.getValue(buy[i]));
}
} finally {
cplex.end();
}
}
}