javascript-lp-solver 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -12
- package/dist/index.browser.mjs +4321 -399
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.cjs +4335 -395
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +739 -14
- package/dist/index.mjs +4335 -395
- package/dist/index.mjs.map +1 -1
- package/dist/solver.global.js +4321 -399
- package/dist/solver.global.js.map +1 -1
- package/dist/types/expressions.d.ts +148 -0
- package/dist/types/external/lpsolve/main.d.ts +2 -7
- package/dist/types/external/lpsolve/reformat.d.ts +1 -6
- package/dist/types/external/main.d.ts +7 -0
- package/dist/types/implied-integers.d.ts +47 -0
- package/dist/types/main.d.ts +22 -6
- package/dist/types/model.d.ts +171 -0
- package/dist/types/polyopt.d.ts +20 -3
- package/dist/types/solver.miplib.test.d.ts +1 -0
- package/dist/types/solver.netlib.test.d.ts +1 -0
- package/dist/types/solver.property.test.d.ts +1 -0
- package/dist/types/tableau/backup.d.ts +49 -0
- package/dist/types/tableau/bounds.d.ts +68 -0
- package/dist/types/tableau/bounds.test.d.ts +1 -0
- package/dist/types/tableau/branch-and-cut.d.ts +14 -0
- package/dist/types/tableau/cutting-strategies.d.ts +34 -0
- package/dist/types/tableau/determinism.test.d.ts +1 -0
- package/dist/types/tableau/dynamic-modification.d.ts +77 -11
- package/dist/types/tableau/enhanced-branch-and-cut.d.ts +22 -4
- package/dist/types/tableau/gomory.d.ts +48 -0
- package/dist/types/tableau/gomory.test.d.ts +1 -0
- package/dist/types/tableau/incremental-branch-and-cut.d.ts +24 -0
- package/dist/types/tableau/kernel.d.ts +119 -0
- package/dist/types/tableau/kernel.test.d.ts +1 -0
- package/dist/types/tableau/log.d.ts +14 -0
- package/dist/types/tableau/min-heap.d.ts +39 -0
- package/dist/types/tableau/mip-utils.d.ts +31 -19
- package/dist/types/tableau/mir.d.ts +65 -0
- package/dist/types/tableau/mir.test.d.ts +1 -0
- package/dist/types/tableau/presolve.d.ts +12 -0
- package/dist/types/tableau/pseudocosts.d.ts +42 -0
- package/dist/types/tableau/pseudocosts.test.d.ts +1 -0
- package/dist/types/tableau/root-presolve.d.ts +33 -0
- package/dist/types/tableau/root-presolve.test.d.ts +1 -0
- package/dist/types/tableau/simplex.d.ts +46 -0
- package/dist/types/tableau/solution.d.ts +31 -12
- package/dist/types/tableau/tableau.d.ts +153 -0
- package/dist/types/tableau/types.d.ts +45 -0
- package/dist/types/types/solver.d.ts +119 -0
- package/package.json +3 -2
- package/dist/solver.cjs.js +0 -4448
- package/dist/types/tableau/branching-strategies.d.ts +0 -4
- package/dist/types/tableau/integer-properties.d.ts +0 -4
- package/dist/types/tableau/lu-factorization.d.ts +0 -61
- package/dist/types/tableau/lu-simplex.d.ts +0 -32
- package/dist/types/tableau/milp-solution.d.ts +0 -7
- package/dist/types/tableau/parallel-branch-and-cut.d.ts +0 -39
- package/dist/types/tableau/sparse-matrix.d.ts +0 -98
- package/dist/types/tableau/sparse-simplex.d.ts +0 -30
- package/dist/types/types/api.d.ts +0 -5
- package/dist/types/wasm/index.d.ts +0 -42
- /package/dist/types/{tableau/sparse-matrix.test.d.ts → implied-integers.test.d.ts} +0 -0
package/dist/solver.cjs.js
DELETED
|
@@ -1,4448 +0,0 @@
|
|
|
1
|
-
var __create = Object.create;
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
-
};
|
|
10
|
-
var __export = (target, all) => {
|
|
11
|
-
for (var name in all)
|
|
12
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
-
};
|
|
14
|
-
var __copyProps = (to, from, except, desc) => {
|
|
15
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
-
for (let key of __getOwnPropNames(from))
|
|
17
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
-
}
|
|
20
|
-
return to;
|
|
21
|
-
};
|
|
22
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
-
mod
|
|
29
|
-
));
|
|
30
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
31
|
-
|
|
32
|
-
// src/external/lpsolve/reformat.js
|
|
33
|
-
var require_reformat = __commonJS({
|
|
34
|
-
"src/external/lpsolve/reformat.js"(exports2, module2) {
|
|
35
|
-
function to_JSON(input) {
|
|
36
|
-
var rxo = {
|
|
37
|
-
/* jshint ignore:start */
|
|
38
|
-
is_blank: /^\W{0,}$/,
|
|
39
|
-
is_objective: /(max|min)(imize){0,}\:/i,
|
|
40
|
-
is_int: /^(?!\/\*)\W{0,}int/i,
|
|
41
|
-
is_bin: /^(?!\/\*)\W{0,}bin/i,
|
|
42
|
-
is_constraint: /(\>|\<){0,}\=/i,
|
|
43
|
-
is_unrestricted: /^\S{0,}unrestricted/i,
|
|
44
|
-
parse_lhs: /(\-|\+){0,1}\s{0,1}\d{0,}\.{0,}\d{0,}\s{0,}[A-Za-z]\S{0,}/gi,
|
|
45
|
-
parse_rhs: /(\-|\+){0,1}\d{1,}\.{0,}\d{0,}\W{0,}\;{0,1}$/i,
|
|
46
|
-
parse_dir: /(\>|\<){0,}\=/gi,
|
|
47
|
-
parse_int: /[^\s|^\,]+/gi,
|
|
48
|
-
parse_bin: /[^\s|^\,]+/gi,
|
|
49
|
-
get_num: /(\-|\+){0,1}(\W|^)\d+\.{0,1}\d{0,}/g,
|
|
50
|
-
get_word: /[A-Za-z].*/
|
|
51
|
-
/* jshint ignore:end */
|
|
52
|
-
}, model = {
|
|
53
|
-
opType: "",
|
|
54
|
-
optimize: "_obj",
|
|
55
|
-
constraints: {},
|
|
56
|
-
variables: {}
|
|
57
|
-
}, constraints = {
|
|
58
|
-
">=": "min",
|
|
59
|
-
"<=": "max",
|
|
60
|
-
"=": "equal"
|
|
61
|
-
}, tmp = "", tst = 0, ary = null, hldr = "", hldr2 = "", constraint = "", rhs = 0;
|
|
62
|
-
if (typeof input === "string") {
|
|
63
|
-
input = input.split("\n");
|
|
64
|
-
}
|
|
65
|
-
for (var i = 0; i < input.length; i++) {
|
|
66
|
-
constraint = "__" + i;
|
|
67
|
-
tmp = input[i];
|
|
68
|
-
tst = 0;
|
|
69
|
-
ary = null;
|
|
70
|
-
if (rxo.is_objective.test(tmp)) {
|
|
71
|
-
model.opType = tmp.match(/(max|min)/gi)[0];
|
|
72
|
-
ary = tmp.match(rxo.parse_lhs).map(function(d) {
|
|
73
|
-
return d.replace(/\s+/, "");
|
|
74
|
-
}).slice(1);
|
|
75
|
-
ary.forEach(function(d) {
|
|
76
|
-
hldr = d.match(rxo.get_num);
|
|
77
|
-
if (hldr === null) {
|
|
78
|
-
if (d.substr(0, 1) === "-") {
|
|
79
|
-
hldr = -1;
|
|
80
|
-
} else {
|
|
81
|
-
hldr = 1;
|
|
82
|
-
}
|
|
83
|
-
} else {
|
|
84
|
-
hldr = hldr[0];
|
|
85
|
-
}
|
|
86
|
-
hldr = parseFloat(hldr);
|
|
87
|
-
hldr2 = d.match(rxo.get_word)[0].replace(/\;$/, "");
|
|
88
|
-
model.variables[hldr2] = model.variables[hldr2] || {};
|
|
89
|
-
model.variables[hldr2]._obj = hldr;
|
|
90
|
-
});
|
|
91
|
-
} else if (rxo.is_int.test(tmp)) {
|
|
92
|
-
ary = tmp.match(rxo.parse_int).slice(1);
|
|
93
|
-
model.ints = model.ints || {};
|
|
94
|
-
ary.forEach(function(d) {
|
|
95
|
-
d = d.replace(";", "");
|
|
96
|
-
model.ints[d] = 1;
|
|
97
|
-
});
|
|
98
|
-
} else if (rxo.is_bin.test(tmp)) {
|
|
99
|
-
ary = tmp.match(rxo.parse_bin).slice(1);
|
|
100
|
-
model.binaries = model.binaries || {};
|
|
101
|
-
ary.forEach(function(d) {
|
|
102
|
-
d = d.replace(";", "");
|
|
103
|
-
model.binaries[d] = 1;
|
|
104
|
-
});
|
|
105
|
-
} else if (rxo.is_constraint.test(tmp)) {
|
|
106
|
-
var separatorIndex = tmp.indexOf(":");
|
|
107
|
-
var constraintExpression = separatorIndex === -1 ? tmp : tmp.slice(separatorIndex + 1);
|
|
108
|
-
ary = constraintExpression.match(rxo.parse_lhs).map(function(d) {
|
|
109
|
-
return d.replace(/\s+/, "");
|
|
110
|
-
});
|
|
111
|
-
ary.forEach(function(d) {
|
|
112
|
-
hldr = d.match(rxo.get_num);
|
|
113
|
-
if (hldr === null) {
|
|
114
|
-
if (d.substr(0, 1) === "-") {
|
|
115
|
-
hldr = -1;
|
|
116
|
-
} else {
|
|
117
|
-
hldr = 1;
|
|
118
|
-
}
|
|
119
|
-
} else {
|
|
120
|
-
hldr = hldr[0];
|
|
121
|
-
}
|
|
122
|
-
hldr = parseFloat(hldr);
|
|
123
|
-
hldr2 = d.match(rxo.get_word)[0];
|
|
124
|
-
model.variables[hldr2] = model.variables[hldr2] || {};
|
|
125
|
-
model.variables[hldr2][constraint] = hldr;
|
|
126
|
-
});
|
|
127
|
-
rhs = parseFloat(tmp.match(rxo.parse_rhs)[0]);
|
|
128
|
-
tmp = constraints[tmp.match(rxo.parse_dir)[0]];
|
|
129
|
-
model.constraints[constraint] = model.constraints[constraint] || {};
|
|
130
|
-
model.constraints[constraint][tmp] = rhs;
|
|
131
|
-
} else if (rxo.is_unrestricted.test(tmp)) {
|
|
132
|
-
ary = tmp.match(rxo.parse_int).slice(1);
|
|
133
|
-
model.unrestricted = model.unrestricted || {};
|
|
134
|
-
ary.forEach(function(d) {
|
|
135
|
-
d = d.replace(";", "");
|
|
136
|
-
model.unrestricted[d] = 1;
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
return model;
|
|
141
|
-
}
|
|
142
|
-
function from_JSON(model) {
|
|
143
|
-
if (!model) {
|
|
144
|
-
throw new Error("Solver requires a model to operate on");
|
|
145
|
-
}
|
|
146
|
-
var output = "", ary = [], norm = 1, lookup = {
|
|
147
|
-
max: "<=",
|
|
148
|
-
min: ">=",
|
|
149
|
-
equal: "="
|
|
150
|
-
}, rxClean = new RegExp("[^A-Za-z0-9_[{}/.&#$%~'@^]", "gi");
|
|
151
|
-
if (model.opType) {
|
|
152
|
-
output += model.opType + ":";
|
|
153
|
-
for (var x in model.variables) {
|
|
154
|
-
model.variables[x][x] = model.variables[x][x] ? model.variables[x][x] : 1;
|
|
155
|
-
if (model.variables[x][model.optimize]) {
|
|
156
|
-
output += " " + model.variables[x][model.optimize] + " " + x.replace(rxClean, "_");
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
} else {
|
|
160
|
-
output += "max:";
|
|
161
|
-
}
|
|
162
|
-
output += ";\n\n";
|
|
163
|
-
for (var xx in model.constraints) {
|
|
164
|
-
for (var y in model.constraints[xx]) {
|
|
165
|
-
if (typeof lookup[y] !== "undefined") {
|
|
166
|
-
for (var z in model.variables) {
|
|
167
|
-
if (typeof model.variables[z][xx] !== "undefined") {
|
|
168
|
-
output += " " + model.variables[z][xx] + " " + z.replace(rxClean, "_");
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
output += " " + lookup[y] + " " + model.constraints[xx][y];
|
|
172
|
-
output += ";\n";
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
if (model.ints) {
|
|
177
|
-
output += "\n\n";
|
|
178
|
-
for (var xxx in model.ints) {
|
|
179
|
-
output += "int " + xxx.replace(rxClean, "_") + ";\n";
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
if (model.unrestricted) {
|
|
183
|
-
output += "\n\n";
|
|
184
|
-
for (var xxxx in model.unrestricted) {
|
|
185
|
-
output += "unrestricted " + xxxx.replace(rxClean, "_") + ";\n";
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return output;
|
|
189
|
-
}
|
|
190
|
-
module2.exports = function(model) {
|
|
191
|
-
if (model.length) {
|
|
192
|
-
return to_JSON(model);
|
|
193
|
-
} else {
|
|
194
|
-
return from_JSON(model);
|
|
195
|
-
}
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
// src/external/lpsolve/main.js
|
|
201
|
-
var require_main = __commonJS({
|
|
202
|
-
"src/external/lpsolve/main.js"(exports2) {
|
|
203
|
-
exports2.reformat = require_reformat();
|
|
204
|
-
function clean_data(data) {
|
|
205
|
-
data = data.replace("\\r\\n", "\r\n");
|
|
206
|
-
data = data.split("\r\n");
|
|
207
|
-
data = data.filter(function(x) {
|
|
208
|
-
var rx;
|
|
209
|
-
rx = new RegExp(" 0$", "gi");
|
|
210
|
-
if (rx.test(x) === true) {
|
|
211
|
-
return false;
|
|
212
|
-
}
|
|
213
|
-
rx = new RegExp("\\d$", "gi");
|
|
214
|
-
if (rx.test(x) === false) {
|
|
215
|
-
return false;
|
|
216
|
-
}
|
|
217
|
-
return true;
|
|
218
|
-
}).map(function(x) {
|
|
219
|
-
return x.split(/\:{0,1} +(?=\d)/);
|
|
220
|
-
}).reduce(function(o, k, i) {
|
|
221
|
-
o[k[0]] = k[1];
|
|
222
|
-
return o;
|
|
223
|
-
}, {});
|
|
224
|
-
return data;
|
|
225
|
-
}
|
|
226
|
-
exports2.solve = function(model) {
|
|
227
|
-
return new Promise(function(res, rej) {
|
|
228
|
-
if (typeof window !== "undefined") {
|
|
229
|
-
rej("Function Not Available in Browser");
|
|
230
|
-
}
|
|
231
|
-
var data = require_reformat()(model);
|
|
232
|
-
if (!model.external) {
|
|
233
|
-
rej(
|
|
234
|
-
"Data for this function must be contained in the 'external' attribute. Not seeing anything there."
|
|
235
|
-
);
|
|
236
|
-
}
|
|
237
|
-
if (!model.external.binPath) {
|
|
238
|
-
rej("No Executable | Binary path provided in arguments as 'binPath'");
|
|
239
|
-
}
|
|
240
|
-
if (!model.external.args) {
|
|
241
|
-
rej("No arguments array for cli | bash provided on 'args' attribute");
|
|
242
|
-
}
|
|
243
|
-
if (!model.external.tempName) {
|
|
244
|
-
rej(
|
|
245
|
-
"No 'tempName' given. This is necessary to produce a staging file for the solver to operate on"
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
var fs = require("fs");
|
|
249
|
-
fs.writeFile(model.external.tempName, data, function(fe, fd) {
|
|
250
|
-
if (fe) {
|
|
251
|
-
rej(fe);
|
|
252
|
-
} else {
|
|
253
|
-
var exec = require("child_process").execFile;
|
|
254
|
-
model.external.args.push(model.external.tempName);
|
|
255
|
-
exec(model.external.binPath, model.external.args, function(e, data2) {
|
|
256
|
-
if (e) {
|
|
257
|
-
if (e.code === 1) {
|
|
258
|
-
res(clean_data(data2));
|
|
259
|
-
} else {
|
|
260
|
-
var codes = {
|
|
261
|
-
"-2": "Out of Memory",
|
|
262
|
-
1: "SUBOPTIMAL",
|
|
263
|
-
2: "INFEASIBLE",
|
|
264
|
-
3: "UNBOUNDED",
|
|
265
|
-
4: "DEGENERATE",
|
|
266
|
-
5: "NUMFAILURE",
|
|
267
|
-
6: "USER-ABORT",
|
|
268
|
-
7: "TIMEOUT",
|
|
269
|
-
9: "PRESOLVED",
|
|
270
|
-
25: "ACCURACY ERROR",
|
|
271
|
-
255: "FILE-ERROR"
|
|
272
|
-
};
|
|
273
|
-
var ret_obj = {
|
|
274
|
-
code: e.code,
|
|
275
|
-
meaning: codes[e.code],
|
|
276
|
-
data: data2
|
|
277
|
-
};
|
|
278
|
-
rej(ret_obj);
|
|
279
|
-
}
|
|
280
|
-
} else {
|
|
281
|
-
res(clean_data(data2));
|
|
282
|
-
}
|
|
283
|
-
});
|
|
284
|
-
}
|
|
285
|
-
});
|
|
286
|
-
});
|
|
287
|
-
};
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
// src/main.ts
|
|
292
|
-
var main_exports = {};
|
|
293
|
-
__export(main_exports, {
|
|
294
|
-
default: () => main_default2
|
|
295
|
-
});
|
|
296
|
-
module.exports = __toCommonJS(main_exports);
|
|
297
|
-
|
|
298
|
-
// src/tableau/solution.ts
|
|
299
|
-
var Solution = class {
|
|
300
|
-
constructor(tableau, evaluation, feasible, bounded) {
|
|
301
|
-
this.feasible = feasible;
|
|
302
|
-
this.evaluation = evaluation;
|
|
303
|
-
this.bounded = bounded;
|
|
304
|
-
this._tableau = tableau;
|
|
305
|
-
this.solutionSet = {};
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Generate the solution set mapping variable IDs to their values.
|
|
309
|
-
*/
|
|
310
|
-
generateSolutionSet() {
|
|
311
|
-
const solutionSet = {};
|
|
312
|
-
const tableau = this._tableau;
|
|
313
|
-
const varIndexByRow = tableau.varIndexByRow;
|
|
314
|
-
const variablesPerIndex = tableau.variablesPerIndex;
|
|
315
|
-
const matrix = tableau.matrix;
|
|
316
|
-
const width = tableau.width;
|
|
317
|
-
const rhsColumn = tableau.rhsColumn;
|
|
318
|
-
const lastRow = tableau.height - 1;
|
|
319
|
-
const roundingCoeff = Math.round(1 / tableau.precision);
|
|
320
|
-
for (let r = 1; r <= lastRow; r += 1) {
|
|
321
|
-
const varIndex = varIndexByRow[r];
|
|
322
|
-
const variable = variablesPerIndex[varIndex];
|
|
323
|
-
if (variable === void 0 || variable.isSlack === true) {
|
|
324
|
-
continue;
|
|
325
|
-
}
|
|
326
|
-
const varValue = matrix[r * width + rhsColumn];
|
|
327
|
-
solutionSet[variable.id] = Math.round((Number.EPSILON + varValue) * roundingCoeff) / roundingCoeff;
|
|
328
|
-
}
|
|
329
|
-
return solutionSet;
|
|
330
|
-
}
|
|
331
|
-
};
|
|
332
|
-
var MilpSolution = class extends Solution {
|
|
333
|
-
constructor(tableau, evaluation, feasible, bounded, branchAndCutIterations) {
|
|
334
|
-
super(tableau, evaluation, feasible, bounded);
|
|
335
|
-
this.iter = branchAndCutIterations;
|
|
336
|
-
}
|
|
337
|
-
};
|
|
338
|
-
|
|
339
|
-
// src/tableau/min-heap.ts
|
|
340
|
-
var BranchMinHeap = class {
|
|
341
|
-
constructor(initialCapacity = 64) {
|
|
342
|
-
this.heap = new Array(initialCapacity);
|
|
343
|
-
this.size = 0;
|
|
344
|
-
this.seqCounter = 0;
|
|
345
|
-
}
|
|
346
|
-
get length() {
|
|
347
|
-
return this.size;
|
|
348
|
-
}
|
|
349
|
-
isEmpty() {
|
|
350
|
-
return this.size === 0;
|
|
351
|
-
}
|
|
352
|
-
clear() {
|
|
353
|
-
this.size = 0;
|
|
354
|
-
this.seqCounter = 0;
|
|
355
|
-
}
|
|
356
|
-
// Compare: returns true if a should be before b (a has higher priority)
|
|
357
|
-
isBefore(a, b) {
|
|
358
|
-
if (a.branch.relaxedEvaluation !== b.branch.relaxedEvaluation) {
|
|
359
|
-
return a.branch.relaxedEvaluation < b.branch.relaxedEvaluation;
|
|
360
|
-
}
|
|
361
|
-
return a.seq > b.seq;
|
|
362
|
-
}
|
|
363
|
-
push(branch) {
|
|
364
|
-
const heap = this.heap;
|
|
365
|
-
let idx = this.size;
|
|
366
|
-
this.size++;
|
|
367
|
-
if (idx >= heap.length) {
|
|
368
|
-
heap.length = heap.length * 2;
|
|
369
|
-
}
|
|
370
|
-
const entry = { branch, seq: this.seqCounter++ };
|
|
371
|
-
while (idx > 0) {
|
|
372
|
-
const parentIdx = idx - 1 >> 1;
|
|
373
|
-
const parent = heap[parentIdx];
|
|
374
|
-
if (!this.isBefore(entry, parent)) {
|
|
375
|
-
break;
|
|
376
|
-
}
|
|
377
|
-
heap[idx] = parent;
|
|
378
|
-
idx = parentIdx;
|
|
379
|
-
}
|
|
380
|
-
heap[idx] = entry;
|
|
381
|
-
}
|
|
382
|
-
pop() {
|
|
383
|
-
if (this.size === 0) {
|
|
384
|
-
return void 0;
|
|
385
|
-
}
|
|
386
|
-
const heap = this.heap;
|
|
387
|
-
const result = heap[0].branch;
|
|
388
|
-
this.size--;
|
|
389
|
-
if (this.size === 0) {
|
|
390
|
-
return result;
|
|
391
|
-
}
|
|
392
|
-
const last = heap[this.size];
|
|
393
|
-
let idx = 0;
|
|
394
|
-
const halfSize = this.size >> 1;
|
|
395
|
-
while (idx < halfSize) {
|
|
396
|
-
let childIdx = (idx << 1) + 1;
|
|
397
|
-
let child = heap[childIdx];
|
|
398
|
-
const rightIdx = childIdx + 1;
|
|
399
|
-
if (rightIdx < this.size && this.isBefore(heap[rightIdx], child)) {
|
|
400
|
-
childIdx = rightIdx;
|
|
401
|
-
child = heap[rightIdx];
|
|
402
|
-
}
|
|
403
|
-
if (!this.isBefore(child, last)) {
|
|
404
|
-
break;
|
|
405
|
-
}
|
|
406
|
-
heap[idx] = child;
|
|
407
|
-
idx = childIdx;
|
|
408
|
-
}
|
|
409
|
-
heap[idx] = last;
|
|
410
|
-
return result;
|
|
411
|
-
}
|
|
412
|
-
peek() {
|
|
413
|
-
return this.size > 0 ? this.heap[0].branch : void 0;
|
|
414
|
-
}
|
|
415
|
-
};
|
|
416
|
-
|
|
417
|
-
// src/tableau/branch-and-cut.ts
|
|
418
|
-
function createCut(type, varIndex, value) {
|
|
419
|
-
return { type, varIndex, value };
|
|
420
|
-
}
|
|
421
|
-
function createBranch(relaxedEvaluation, cuts) {
|
|
422
|
-
return { relaxedEvaluation, cuts };
|
|
423
|
-
}
|
|
424
|
-
function createBranchAndCutService() {
|
|
425
|
-
const applyCuts = (tableau, branchingCuts) => {
|
|
426
|
-
tableau.restore();
|
|
427
|
-
tableau.addCutConstraints(branchingCuts);
|
|
428
|
-
tableau.simplex();
|
|
429
|
-
if (tableau.model?.useMIRCuts) {
|
|
430
|
-
let fractionalVolumeImproved = true;
|
|
431
|
-
while (fractionalVolumeImproved) {
|
|
432
|
-
const fractionalVolumeBefore = tableau.computeFractionalVolume(true);
|
|
433
|
-
tableau.applyMIRCuts();
|
|
434
|
-
tableau.simplex();
|
|
435
|
-
const fractionalVolumeAfter = tableau.computeFractionalVolume(true);
|
|
436
|
-
if (fractionalVolumeAfter >= 0.9 * fractionalVolumeBefore) {
|
|
437
|
-
fractionalVolumeImproved = false;
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
};
|
|
442
|
-
const branchAndCut = (tableau) => {
|
|
443
|
-
const branches = new BranchMinHeap();
|
|
444
|
-
let iterations = 0;
|
|
445
|
-
const tolerance = tableau.model?.tolerance ?? 0;
|
|
446
|
-
let toleranceFlag = true;
|
|
447
|
-
let terminalTime = 1e99;
|
|
448
|
-
if (tableau.model?.timeout) {
|
|
449
|
-
terminalTime = Date.now() + tableau.model.timeout;
|
|
450
|
-
}
|
|
451
|
-
let bestEvaluation = Infinity;
|
|
452
|
-
let bestBranch = null;
|
|
453
|
-
const bestOptionalObjectivesEvaluations = [];
|
|
454
|
-
for (let oInit = 0; oInit < tableau.optionalObjectives.length; oInit += 1) {
|
|
455
|
-
bestOptionalObjectivesEvaluations.push(Infinity);
|
|
456
|
-
}
|
|
457
|
-
const branch = createBranch(-Infinity, []);
|
|
458
|
-
let acceptableThreshold;
|
|
459
|
-
branches.push(branch);
|
|
460
|
-
while (!branches.isEmpty() && toleranceFlag === true && Date.now() < terminalTime) {
|
|
461
|
-
if (tableau.model?.isMinimization) {
|
|
462
|
-
acceptableThreshold = tableau.bestPossibleEval * (1 + tolerance);
|
|
463
|
-
} else {
|
|
464
|
-
acceptableThreshold = tableau.bestPossibleEval * (1 - tolerance);
|
|
465
|
-
}
|
|
466
|
-
if (tolerance > 0) {
|
|
467
|
-
if (bestEvaluation < acceptableThreshold) {
|
|
468
|
-
toleranceFlag = false;
|
|
469
|
-
}
|
|
470
|
-
}
|
|
471
|
-
const activeBranch = branches.pop();
|
|
472
|
-
if (activeBranch.relaxedEvaluation > bestEvaluation) {
|
|
473
|
-
continue;
|
|
474
|
-
}
|
|
475
|
-
const cuts = activeBranch.cuts;
|
|
476
|
-
applyCuts(tableau, cuts);
|
|
477
|
-
iterations++;
|
|
478
|
-
if (tableau.feasible === false) {
|
|
479
|
-
continue;
|
|
480
|
-
}
|
|
481
|
-
const evaluation = tableau.evaluation;
|
|
482
|
-
if (evaluation > bestEvaluation) {
|
|
483
|
-
continue;
|
|
484
|
-
}
|
|
485
|
-
if (evaluation === bestEvaluation) {
|
|
486
|
-
let isCurrentEvaluationWorse = true;
|
|
487
|
-
for (let o = 0; o < tableau.optionalObjectives.length; o += 1) {
|
|
488
|
-
if (tableau.optionalObjectives[o].reducedCosts[0] > bestOptionalObjectivesEvaluations[o]) {
|
|
489
|
-
break;
|
|
490
|
-
} else if (tableau.optionalObjectives[o].reducedCosts[0] < bestOptionalObjectivesEvaluations[o]) {
|
|
491
|
-
isCurrentEvaluationWorse = false;
|
|
492
|
-
break;
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
if (isCurrentEvaluationWorse) {
|
|
496
|
-
continue;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
if (tableau.isIntegral() === true) {
|
|
500
|
-
tableau.__isIntegral = true;
|
|
501
|
-
if (iterations === 1) {
|
|
502
|
-
tableau.branchAndCutIterations = iterations;
|
|
503
|
-
return;
|
|
504
|
-
}
|
|
505
|
-
bestBranch = activeBranch;
|
|
506
|
-
bestEvaluation = evaluation;
|
|
507
|
-
for (let oCopy = 0; oCopy < tableau.optionalObjectives.length; oCopy += 1) {
|
|
508
|
-
bestOptionalObjectivesEvaluations[oCopy] = tableau.optionalObjectives[oCopy].reducedCosts[0];
|
|
509
|
-
}
|
|
510
|
-
if (tableau.model?.keep_solutions) {
|
|
511
|
-
const nowSolution = tableau.model.tableau.getSolution();
|
|
512
|
-
const store = nowSolution.generateSolutionSet();
|
|
513
|
-
store.result = nowSolution.evaluation;
|
|
514
|
-
if (!tableau.model.solutions) {
|
|
515
|
-
tableau.model.solutions = [];
|
|
516
|
-
}
|
|
517
|
-
tableau.model.solutions.push(store);
|
|
518
|
-
}
|
|
519
|
-
} else {
|
|
520
|
-
if (iterations === 1) {
|
|
521
|
-
tableau.save();
|
|
522
|
-
}
|
|
523
|
-
const variable = tableau.getMostFractionalVar();
|
|
524
|
-
const varIndex = variable.index;
|
|
525
|
-
const cutsHigh = [];
|
|
526
|
-
const cutsLow = [];
|
|
527
|
-
const nCuts = cuts.length;
|
|
528
|
-
for (let c = 0; c < nCuts; c += 1) {
|
|
529
|
-
const cut = cuts[c];
|
|
530
|
-
if (cut.varIndex === varIndex) {
|
|
531
|
-
if (cut.type === "min") {
|
|
532
|
-
cutsLow.push(cut);
|
|
533
|
-
} else {
|
|
534
|
-
cutsHigh.push(cut);
|
|
535
|
-
}
|
|
536
|
-
} else {
|
|
537
|
-
cutsHigh.push(cut);
|
|
538
|
-
cutsLow.push(cut);
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
const min = Math.ceil(variable.value);
|
|
542
|
-
const max = Math.floor(variable.value);
|
|
543
|
-
const cutHigh = createCut("min", varIndex, min);
|
|
544
|
-
cutsHigh.push(cutHigh);
|
|
545
|
-
const cutLow = createCut("max", varIndex, max);
|
|
546
|
-
cutsLow.push(cutLow);
|
|
547
|
-
branches.push(createBranch(evaluation, cutsHigh));
|
|
548
|
-
branches.push(createBranch(evaluation, cutsLow));
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
if (bestBranch !== null) {
|
|
552
|
-
applyCuts(tableau, bestBranch.cuts);
|
|
553
|
-
}
|
|
554
|
-
tableau.branchAndCutIterations = iterations;
|
|
555
|
-
};
|
|
556
|
-
return { applyCuts, branchAndCut };
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
// src/tableau/simplex.ts
|
|
560
|
-
function simplex() {
|
|
561
|
-
this.bounded = true;
|
|
562
|
-
this.phase1();
|
|
563
|
-
if (this.feasible === true) {
|
|
564
|
-
this.phase2();
|
|
565
|
-
}
|
|
566
|
-
return this;
|
|
567
|
-
}
|
|
568
|
-
function phase1() {
|
|
569
|
-
const debugCheckForCycles = this.model.checkForCycles;
|
|
570
|
-
const varIndexesCycle = [];
|
|
571
|
-
const matrix = this.matrix;
|
|
572
|
-
const width = this.width;
|
|
573
|
-
const rhsColumn = this.rhsColumn;
|
|
574
|
-
const lastColumn = this.width - 1;
|
|
575
|
-
const lastRow = this.height - 1;
|
|
576
|
-
let unrestricted;
|
|
577
|
-
let iterations = 0;
|
|
578
|
-
while (true) {
|
|
579
|
-
let leavingRowIndex = 0;
|
|
580
|
-
let rhsValue = -this.precision;
|
|
581
|
-
for (let r = 1; r <= lastRow; r++) {
|
|
582
|
-
unrestricted = this.unrestrictedVars[this.varIndexByRow[r]] === true;
|
|
583
|
-
const value = matrix[r * width + rhsColumn];
|
|
584
|
-
if (value < rhsValue) {
|
|
585
|
-
rhsValue = value;
|
|
586
|
-
leavingRowIndex = r;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
if (leavingRowIndex === 0) {
|
|
590
|
-
this.feasible = true;
|
|
591
|
-
return iterations;
|
|
592
|
-
}
|
|
593
|
-
let enteringColumn = 0;
|
|
594
|
-
let maxQuotient = -Infinity;
|
|
595
|
-
const costRowOffset = 0;
|
|
596
|
-
const leavingRowOffset = leavingRowIndex * width;
|
|
597
|
-
for (let c = 1; c <= lastColumn; c++) {
|
|
598
|
-
const coefficient = matrix[leavingRowOffset + c];
|
|
599
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
600
|
-
if (unrestricted || coefficient < -this.precision) {
|
|
601
|
-
const quotient = -matrix[costRowOffset + c] / coefficient;
|
|
602
|
-
if (maxQuotient < quotient) {
|
|
603
|
-
maxQuotient = quotient;
|
|
604
|
-
enteringColumn = c;
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
if (enteringColumn === 0) {
|
|
609
|
-
this.feasible = false;
|
|
610
|
-
return iterations;
|
|
611
|
-
}
|
|
612
|
-
if (debugCheckForCycles) {
|
|
613
|
-
varIndexesCycle.push([
|
|
614
|
-
this.varIndexByRow[leavingRowIndex],
|
|
615
|
-
this.varIndexByCol[enteringColumn]
|
|
616
|
-
]);
|
|
617
|
-
const cycleData = this.checkForCycles(varIndexesCycle);
|
|
618
|
-
if (cycleData.length > 0) {
|
|
619
|
-
this.model.messages.push("Cycle in phase 1");
|
|
620
|
-
this.model.messages.push("Start :" + cycleData[0]);
|
|
621
|
-
this.model.messages.push("Length :" + cycleData[1]);
|
|
622
|
-
this.feasible = false;
|
|
623
|
-
return iterations;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
this.pivot(leavingRowIndex, enteringColumn);
|
|
627
|
-
iterations += 1;
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
function phase2() {
|
|
631
|
-
const debugCheckForCycles = this.model.checkForCycles;
|
|
632
|
-
const varIndexesCycle = [];
|
|
633
|
-
const matrix = this.matrix;
|
|
634
|
-
const width = this.width;
|
|
635
|
-
const rhsColumn = this.rhsColumn;
|
|
636
|
-
const lastColumn = this.width - 1;
|
|
637
|
-
const lastRow = this.height - 1;
|
|
638
|
-
const precision = this.precision;
|
|
639
|
-
const nOptionalObjectives = this.optionalObjectives.length;
|
|
640
|
-
let optionalCostsColumns = null;
|
|
641
|
-
let iterations = 0;
|
|
642
|
-
let reducedCost;
|
|
643
|
-
let unrestricted;
|
|
644
|
-
const nColumns = lastColumn;
|
|
645
|
-
const batchSize = this.pricingBatchSize > 0 ? this.pricingBatchSize : Math.min(500, Math.max(50, Math.floor(Math.sqrt(nColumns))));
|
|
646
|
-
const usePartialPricing = nColumns > batchSize * 2;
|
|
647
|
-
while (true) {
|
|
648
|
-
const costRowOffset = this.costRowIndex * width;
|
|
649
|
-
if (nOptionalObjectives > 0) {
|
|
650
|
-
optionalCostsColumns = [];
|
|
651
|
-
}
|
|
652
|
-
let enteringColumn = 0;
|
|
653
|
-
let enteringValue = precision;
|
|
654
|
-
let isReducedCostNegative = false;
|
|
655
|
-
if (usePartialPricing) {
|
|
656
|
-
const startBatch = this.pricingBatchStart;
|
|
657
|
-
let batchesScanned = 0;
|
|
658
|
-
const totalBatches = Math.ceil(nColumns / batchSize);
|
|
659
|
-
while (enteringColumn === 0 && batchesScanned < totalBatches) {
|
|
660
|
-
const batchStart = this.pricingBatchStart;
|
|
661
|
-
const batchEnd = Math.min(batchStart + batchSize - 1, lastColumn);
|
|
662
|
-
for (let c = batchStart; c <= batchEnd; c++) {
|
|
663
|
-
reducedCost = matrix[costRowOffset + c];
|
|
664
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
665
|
-
if (nOptionalObjectives > 0 && -precision < reducedCost && reducedCost < precision) {
|
|
666
|
-
optionalCostsColumns?.push(c);
|
|
667
|
-
continue;
|
|
668
|
-
}
|
|
669
|
-
if (unrestricted && reducedCost < 0) {
|
|
670
|
-
if (-reducedCost > enteringValue) {
|
|
671
|
-
enteringValue = -reducedCost;
|
|
672
|
-
enteringColumn = c;
|
|
673
|
-
isReducedCostNegative = true;
|
|
674
|
-
}
|
|
675
|
-
continue;
|
|
676
|
-
}
|
|
677
|
-
if (reducedCost > enteringValue) {
|
|
678
|
-
enteringValue = reducedCost;
|
|
679
|
-
enteringColumn = c;
|
|
680
|
-
isReducedCostNegative = false;
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
this.pricingBatchStart = batchEnd >= lastColumn ? 1 : batchEnd + 1;
|
|
684
|
-
batchesScanned++;
|
|
685
|
-
}
|
|
686
|
-
if (enteringColumn !== 0) {
|
|
687
|
-
this.pricingBatchStart = startBatch;
|
|
688
|
-
}
|
|
689
|
-
} else {
|
|
690
|
-
for (let c = 1; c <= lastColumn; c++) {
|
|
691
|
-
reducedCost = matrix[costRowOffset + c];
|
|
692
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
693
|
-
if (nOptionalObjectives > 0 && -precision < reducedCost && reducedCost < precision) {
|
|
694
|
-
optionalCostsColumns?.push(c);
|
|
695
|
-
continue;
|
|
696
|
-
}
|
|
697
|
-
if (unrestricted && reducedCost < 0) {
|
|
698
|
-
if (-reducedCost > enteringValue) {
|
|
699
|
-
enteringValue = -reducedCost;
|
|
700
|
-
enteringColumn = c;
|
|
701
|
-
isReducedCostNegative = true;
|
|
702
|
-
}
|
|
703
|
-
continue;
|
|
704
|
-
}
|
|
705
|
-
if (reducedCost > enteringValue) {
|
|
706
|
-
enteringValue = reducedCost;
|
|
707
|
-
enteringColumn = c;
|
|
708
|
-
isReducedCostNegative = false;
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
if (nOptionalObjectives > 0) {
|
|
713
|
-
let o = 0;
|
|
714
|
-
while (enteringColumn === 0 && optionalCostsColumns && optionalCostsColumns.length > 0 && o < nOptionalObjectives) {
|
|
715
|
-
const optionalCostsColumns2 = [];
|
|
716
|
-
const reducedCosts = this.optionalObjectives[o].reducedCosts;
|
|
717
|
-
enteringValue = precision;
|
|
718
|
-
for (let i = 0; i < optionalCostsColumns.length; i++) {
|
|
719
|
-
const c = optionalCostsColumns[i];
|
|
720
|
-
reducedCost = reducedCosts[c];
|
|
721
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
722
|
-
if (-precision < reducedCost && reducedCost < precision) {
|
|
723
|
-
optionalCostsColumns2.push(c);
|
|
724
|
-
continue;
|
|
725
|
-
}
|
|
726
|
-
if (unrestricted && reducedCost < 0) {
|
|
727
|
-
if (-reducedCost > enteringValue) {
|
|
728
|
-
enteringValue = -reducedCost;
|
|
729
|
-
enteringColumn = c;
|
|
730
|
-
isReducedCostNegative = true;
|
|
731
|
-
}
|
|
732
|
-
continue;
|
|
733
|
-
}
|
|
734
|
-
if (reducedCost > enteringValue) {
|
|
735
|
-
enteringValue = reducedCost;
|
|
736
|
-
enteringColumn = c;
|
|
737
|
-
isReducedCostNegative = false;
|
|
738
|
-
}
|
|
739
|
-
}
|
|
740
|
-
optionalCostsColumns = optionalCostsColumns2;
|
|
741
|
-
o += 1;
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
if (enteringColumn === 0) {
|
|
745
|
-
this.setEvaluation();
|
|
746
|
-
this.simplexIters += 1;
|
|
747
|
-
return iterations;
|
|
748
|
-
}
|
|
749
|
-
let leavingRow = 0;
|
|
750
|
-
let minQuotient = Infinity;
|
|
751
|
-
const varIndexByRow = this.varIndexByRow;
|
|
752
|
-
for (let r = 1; r <= lastRow; r++) {
|
|
753
|
-
const rowOffset = r * width;
|
|
754
|
-
const rhsValue = matrix[rowOffset + rhsColumn];
|
|
755
|
-
const colValue = matrix[rowOffset + enteringColumn];
|
|
756
|
-
if (-precision < colValue && colValue < precision) {
|
|
757
|
-
continue;
|
|
758
|
-
}
|
|
759
|
-
if (colValue > 0 && precision > rhsValue && rhsValue > -precision) {
|
|
760
|
-
minQuotient = 0;
|
|
761
|
-
leavingRow = r;
|
|
762
|
-
break;
|
|
763
|
-
}
|
|
764
|
-
const quotient = isReducedCostNegative ? -rhsValue / colValue : rhsValue / colValue;
|
|
765
|
-
if (quotient > precision && minQuotient > quotient) {
|
|
766
|
-
minQuotient = quotient;
|
|
767
|
-
leavingRow = r;
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
if (minQuotient === Infinity) {
|
|
771
|
-
this.evaluation = -Infinity;
|
|
772
|
-
this.bounded = false;
|
|
773
|
-
this.unboundedVarIndex = this.varIndexByCol[enteringColumn];
|
|
774
|
-
return iterations;
|
|
775
|
-
}
|
|
776
|
-
if (debugCheckForCycles) {
|
|
777
|
-
varIndexesCycle.push([
|
|
778
|
-
this.varIndexByRow[leavingRow],
|
|
779
|
-
this.varIndexByCol[enteringColumn]
|
|
780
|
-
]);
|
|
781
|
-
const cycleData = this.checkForCycles(varIndexesCycle);
|
|
782
|
-
if (cycleData.length > 0) {
|
|
783
|
-
this.model.messages.push("Cycle in phase 2");
|
|
784
|
-
this.model.messages.push("Start :" + cycleData[0]);
|
|
785
|
-
this.model.messages.push("Length :" + cycleData[1]);
|
|
786
|
-
this.feasible = false;
|
|
787
|
-
return iterations;
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
this.pivot(leavingRow, enteringColumn);
|
|
791
|
-
iterations += 1;
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
var nonZeroColumns = [];
|
|
795
|
-
function pivot(pivotRowIndex, pivotColumnIndex) {
|
|
796
|
-
const matrix = this.matrix;
|
|
797
|
-
const width = this.width;
|
|
798
|
-
const pivotRowOffset = pivotRowIndex * width;
|
|
799
|
-
const quotient = matrix[pivotRowOffset + pivotColumnIndex];
|
|
800
|
-
const height = this.height;
|
|
801
|
-
const leavingBasicIndex = this.varIndexByRow[pivotRowIndex];
|
|
802
|
-
const enteringBasicIndex = this.varIndexByCol[pivotColumnIndex];
|
|
803
|
-
this.varIndexByRow[pivotRowIndex] = enteringBasicIndex;
|
|
804
|
-
this.varIndexByCol[pivotColumnIndex] = leavingBasicIndex;
|
|
805
|
-
this.rowByVarIndex[enteringBasicIndex] = pivotRowIndex;
|
|
806
|
-
this.rowByVarIndex[leavingBasicIndex] = -1;
|
|
807
|
-
this.colByVarIndex[enteringBasicIndex] = -1;
|
|
808
|
-
this.colByVarIndex[leavingBasicIndex] = pivotColumnIndex;
|
|
809
|
-
let nNonZeroColumns = 0;
|
|
810
|
-
for (let c = 0; c < width; c++) {
|
|
811
|
-
const idx = pivotRowOffset + c;
|
|
812
|
-
const val = matrix[idx];
|
|
813
|
-
if (!(val >= -1e-16 && val <= 1e-16)) {
|
|
814
|
-
matrix[idx] = val / quotient;
|
|
815
|
-
nonZeroColumns[nNonZeroColumns] = c;
|
|
816
|
-
nNonZeroColumns++;
|
|
817
|
-
} else {
|
|
818
|
-
matrix[idx] = 0;
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
matrix[pivotRowOffset + pivotColumnIndex] = 1 / quotient;
|
|
822
|
-
for (let r = 0; r < height; r++) {
|
|
823
|
-
if (r !== pivotRowIndex) {
|
|
824
|
-
const rowOffset = r * width;
|
|
825
|
-
const pivotColVal = matrix[rowOffset + pivotColumnIndex];
|
|
826
|
-
if (!(pivotColVal >= -1e-16 && pivotColVal <= 1e-16)) {
|
|
827
|
-
const coefficient = pivotColVal;
|
|
828
|
-
if (!(coefficient >= -1e-16 && coefficient <= 1e-16)) {
|
|
829
|
-
for (let i = 0; i < nNonZeroColumns; i++) {
|
|
830
|
-
const c = nonZeroColumns[i];
|
|
831
|
-
const v0 = matrix[pivotRowOffset + c];
|
|
832
|
-
if (!(v0 >= -1e-16 && v0 <= 1e-16)) {
|
|
833
|
-
matrix[rowOffset + c] = matrix[rowOffset + c] - coefficient * v0;
|
|
834
|
-
} else if (v0 !== 0) {
|
|
835
|
-
matrix[pivotRowOffset + c] = 0;
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
matrix[rowOffset + pivotColumnIndex] = -coefficient / quotient;
|
|
839
|
-
} else if (coefficient !== 0) {
|
|
840
|
-
matrix[rowOffset + pivotColumnIndex] = 0;
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
const optionalObjectives = this.optionalObjectives;
|
|
846
|
-
const nOptionalObjectives = optionalObjectives.length;
|
|
847
|
-
if (nOptionalObjectives > 0) {
|
|
848
|
-
for (let o = 0; o < nOptionalObjectives; o++) {
|
|
849
|
-
const reducedCosts = optionalObjectives[o].reducedCosts;
|
|
850
|
-
const coefficient = reducedCosts[pivotColumnIndex];
|
|
851
|
-
if (coefficient !== 0) {
|
|
852
|
-
for (let i = 0; i < nNonZeroColumns; i++) {
|
|
853
|
-
const c = nonZeroColumns[i];
|
|
854
|
-
const v0 = matrix[pivotRowOffset + c];
|
|
855
|
-
if (v0 !== 0) {
|
|
856
|
-
reducedCosts[c] = reducedCosts[c] - coefficient * v0;
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
reducedCosts[pivotColumnIndex] = -coefficient / quotient;
|
|
860
|
-
}
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
function checkForCycles(varIndexes) {
|
|
865
|
-
for (let e1 = 0; e1 < varIndexes.length - 1; e1++) {
|
|
866
|
-
for (let e2 = e1 + 1; e2 < varIndexes.length; e2++) {
|
|
867
|
-
const elt1 = varIndexes[e1];
|
|
868
|
-
const elt2 = varIndexes[e2];
|
|
869
|
-
if (elt1[0] === elt2[0] && elt1[1] === elt2[1]) {
|
|
870
|
-
if (e2 - e1 > varIndexes.length - e2) {
|
|
871
|
-
break;
|
|
872
|
-
}
|
|
873
|
-
let cycleFound = true;
|
|
874
|
-
for (let i = 1; i < e2 - e1; i++) {
|
|
875
|
-
const tmp1 = varIndexes[e1 + i];
|
|
876
|
-
const tmp2 = varIndexes[e2 + i];
|
|
877
|
-
if (tmp1[0] !== tmp2[0] || tmp1[1] !== tmp2[1]) {
|
|
878
|
-
cycleFound = false;
|
|
879
|
-
break;
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
if (cycleFound) {
|
|
883
|
-
return [e1, e2 - e1];
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
return [];
|
|
889
|
-
}
|
|
890
|
-
|
|
891
|
-
// src/tableau/sparse-matrix.ts
|
|
892
|
-
var SparseMatrix = class _SparseMatrix {
|
|
893
|
-
constructor(nRows, nCols, precision = 1e-12) {
|
|
894
|
-
this.nRows = nRows;
|
|
895
|
-
this.nCols = nCols;
|
|
896
|
-
this.precision = precision;
|
|
897
|
-
this.values = [];
|
|
898
|
-
this.rowIndices = [];
|
|
899
|
-
this.colPointers = new Array(nCols + 1).fill(0);
|
|
900
|
-
this.workVector = new Float64Array(Math.max(nRows, nCols));
|
|
901
|
-
this.workIndices = [];
|
|
902
|
-
}
|
|
903
|
-
/**
|
|
904
|
-
* Create sparse matrix from dense Float64Array
|
|
905
|
-
*/
|
|
906
|
-
static fromDense(dense, width, height, precision = 1e-12) {
|
|
907
|
-
const sparse = new _SparseMatrix(height, width, precision);
|
|
908
|
-
const values = [];
|
|
909
|
-
const rowIndices = [];
|
|
910
|
-
const colPointers = [0];
|
|
911
|
-
for (let c = 0; c < width; c++) {
|
|
912
|
-
for (let r = 0; r < height; r++) {
|
|
913
|
-
const val = dense[r * width + c];
|
|
914
|
-
if (val < -precision || val > precision) {
|
|
915
|
-
values.push(val);
|
|
916
|
-
rowIndices.push(r);
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
colPointers.push(values.length);
|
|
920
|
-
}
|
|
921
|
-
sparse.values = values;
|
|
922
|
-
sparse.rowIndices = rowIndices;
|
|
923
|
-
sparse.colPointers = colPointers;
|
|
924
|
-
return sparse;
|
|
925
|
-
}
|
|
926
|
-
/**
|
|
927
|
-
* Convert to dense Float64Array
|
|
928
|
-
*/
|
|
929
|
-
toDense() {
|
|
930
|
-
const dense = new Float64Array(this.nRows * this.nCols);
|
|
931
|
-
for (let c = 0; c < this.nCols; c++) {
|
|
932
|
-
const start = this.colPointers[c];
|
|
933
|
-
const end = this.colPointers[c + 1];
|
|
934
|
-
for (let i = start; i < end; i++) {
|
|
935
|
-
const r = this.rowIndices[i];
|
|
936
|
-
dense[r * this.nCols + c] = this.values[i];
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
return dense;
|
|
940
|
-
}
|
|
941
|
-
/**
|
|
942
|
-
* Get value at (row, col)
|
|
943
|
-
*/
|
|
944
|
-
get(row, col) {
|
|
945
|
-
const start = this.colPointers[col];
|
|
946
|
-
const end = this.colPointers[col + 1];
|
|
947
|
-
let lo = start;
|
|
948
|
-
let hi = end;
|
|
949
|
-
while (lo < hi) {
|
|
950
|
-
const mid = lo + hi >>> 1;
|
|
951
|
-
if (this.rowIndices[mid] < row) {
|
|
952
|
-
lo = mid + 1;
|
|
953
|
-
} else {
|
|
954
|
-
hi = mid;
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
if (lo < end && this.rowIndices[lo] === row) {
|
|
958
|
-
return this.values[lo];
|
|
959
|
-
}
|
|
960
|
-
return 0;
|
|
961
|
-
}
|
|
962
|
-
/**
|
|
963
|
-
* Set value at (row, col)
|
|
964
|
-
* Handles insertion and removal of entries
|
|
965
|
-
*/
|
|
966
|
-
set(row, col, value) {
|
|
967
|
-
const start = this.colPointers[col];
|
|
968
|
-
const end = this.colPointers[col + 1];
|
|
969
|
-
const isZero = value >= -this.precision && value <= this.precision;
|
|
970
|
-
let lo = start;
|
|
971
|
-
let hi = end;
|
|
972
|
-
while (lo < hi) {
|
|
973
|
-
const mid = lo + hi >>> 1;
|
|
974
|
-
if (this.rowIndices[mid] < row) {
|
|
975
|
-
lo = mid + 1;
|
|
976
|
-
} else {
|
|
977
|
-
hi = mid;
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
const exists = lo < end && this.rowIndices[lo] === row;
|
|
981
|
-
if (exists) {
|
|
982
|
-
if (isZero) {
|
|
983
|
-
this.values.splice(lo, 1);
|
|
984
|
-
this.rowIndices.splice(lo, 1);
|
|
985
|
-
for (let c = col + 1; c <= this.nCols; c++) {
|
|
986
|
-
this.colPointers[c]--;
|
|
987
|
-
}
|
|
988
|
-
} else {
|
|
989
|
-
this.values[lo] = value;
|
|
990
|
-
}
|
|
991
|
-
} else if (!isZero) {
|
|
992
|
-
this.values.splice(lo, 0, value);
|
|
993
|
-
this.rowIndices.splice(lo, 0, row);
|
|
994
|
-
for (let c = col + 1; c <= this.nCols; c++) {
|
|
995
|
-
this.colPointers[c]++;
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
/**
|
|
1000
|
-
* Get column as sparse vector
|
|
1001
|
-
*/
|
|
1002
|
-
getColumn(col) {
|
|
1003
|
-
const start = this.colPointers[col];
|
|
1004
|
-
const end = this.colPointers[col + 1];
|
|
1005
|
-
const len = end - start;
|
|
1006
|
-
return {
|
|
1007
|
-
indices: this.rowIndices.slice(start, end),
|
|
1008
|
-
values: this.values.slice(start, end),
|
|
1009
|
-
length: len
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
/**
|
|
1013
|
-
* Get row as sparse vector (less efficient - requires full scan)
|
|
1014
|
-
*/
|
|
1015
|
-
getRow(row) {
|
|
1016
|
-
const indices = [];
|
|
1017
|
-
const values = [];
|
|
1018
|
-
for (let c = 0; c < this.nCols; c++) {
|
|
1019
|
-
const val = this.get(row, c);
|
|
1020
|
-
if (val !== 0) {
|
|
1021
|
-
indices.push(c);
|
|
1022
|
-
values.push(val);
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
return { indices, values, length: indices.length };
|
|
1026
|
-
}
|
|
1027
|
-
/**
|
|
1028
|
-
* Get row into pre-allocated dense array (more efficient for repeated access)
|
|
1029
|
-
* Returns array of non-zero column indices
|
|
1030
|
-
*/
|
|
1031
|
-
getRowDense(row, output) {
|
|
1032
|
-
const nonZeroCols = [];
|
|
1033
|
-
output.fill(0, 0, this.nCols);
|
|
1034
|
-
for (let c = 0; c < this.nCols; c++) {
|
|
1035
|
-
const start = this.colPointers[c];
|
|
1036
|
-
const end = this.colPointers[c + 1];
|
|
1037
|
-
let lo = start;
|
|
1038
|
-
let hi = end;
|
|
1039
|
-
while (lo < hi) {
|
|
1040
|
-
const mid = lo + hi >>> 1;
|
|
1041
|
-
if (this.rowIndices[mid] < row) {
|
|
1042
|
-
lo = mid + 1;
|
|
1043
|
-
} else {
|
|
1044
|
-
hi = mid;
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
if (lo < end && this.rowIndices[lo] === row) {
|
|
1048
|
-
output[c] = this.values[lo];
|
|
1049
|
-
nonZeroCols.push(c);
|
|
1050
|
-
}
|
|
1051
|
-
}
|
|
1052
|
-
return nonZeroCols;
|
|
1053
|
-
}
|
|
1054
|
-
/**
|
|
1055
|
-
* Add a new row (expands matrix vertically)
|
|
1056
|
-
*/
|
|
1057
|
-
addRow() {
|
|
1058
|
-
this.nRows++;
|
|
1059
|
-
if (this.workVector.length < this.nRows) {
|
|
1060
|
-
this.workVector = new Float64Array(this.nRows * 2);
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
/**
|
|
1064
|
-
* Add a new column (expands matrix horizontally)
|
|
1065
|
-
*/
|
|
1066
|
-
addColumn() {
|
|
1067
|
-
this.colPointers.push(this.colPointers[this.nCols]);
|
|
1068
|
-
this.nCols++;
|
|
1069
|
-
if (this.workVector.length < this.nCols) {
|
|
1070
|
-
this.workVector = new Float64Array(this.nCols * 2);
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
/**
|
|
1074
|
-
* Set entire column from sparse vector
|
|
1075
|
-
*/
|
|
1076
|
-
setColumn(col, sparseCol) {
|
|
1077
|
-
const oldStart = this.colPointers[col];
|
|
1078
|
-
const oldEnd = this.colPointers[col + 1];
|
|
1079
|
-
const oldLen = oldEnd - oldStart;
|
|
1080
|
-
const newLen = sparseCol.length;
|
|
1081
|
-
const diff = newLen - oldLen;
|
|
1082
|
-
if (diff !== 0) {
|
|
1083
|
-
if (diff > 0) {
|
|
1084
|
-
for (let i = 0; i < diff; i++) {
|
|
1085
|
-
this.values.splice(oldEnd, 0, 0);
|
|
1086
|
-
this.rowIndices.splice(oldEnd, 0, 0);
|
|
1087
|
-
}
|
|
1088
|
-
} else {
|
|
1089
|
-
this.values.splice(oldStart, -diff);
|
|
1090
|
-
this.rowIndices.splice(oldStart, -diff);
|
|
1091
|
-
}
|
|
1092
|
-
for (let c = col + 1; c <= this.nCols; c++) {
|
|
1093
|
-
this.colPointers[c] += diff;
|
|
1094
|
-
}
|
|
1095
|
-
}
|
|
1096
|
-
const start = this.colPointers[col];
|
|
1097
|
-
for (let i = 0; i < newLen; i++) {
|
|
1098
|
-
this.values[start + i] = sparseCol.values[i];
|
|
1099
|
-
this.rowIndices[start + i] = sparseCol.indices[i];
|
|
1100
|
-
}
|
|
1101
|
-
}
|
|
1102
|
-
/**
|
|
1103
|
-
* Number of non-zero entries
|
|
1104
|
-
*/
|
|
1105
|
-
get nnz() {
|
|
1106
|
-
return this.values.length;
|
|
1107
|
-
}
|
|
1108
|
-
/**
|
|
1109
|
-
* Density (fraction of non-zeros)
|
|
1110
|
-
*/
|
|
1111
|
-
get density() {
|
|
1112
|
-
return this.nnz / (this.nRows * this.nCols);
|
|
1113
|
-
}
|
|
1114
|
-
/**
|
|
1115
|
-
* Scale a row by a factor
|
|
1116
|
-
*/
|
|
1117
|
-
scaleRow(row, factor) {
|
|
1118
|
-
for (let c = 0; c < this.nCols; c++) {
|
|
1119
|
-
const start = this.colPointers[c];
|
|
1120
|
-
const end = this.colPointers[c + 1];
|
|
1121
|
-
for (let i = start; i < end; i++) {
|
|
1122
|
-
if (this.rowIndices[i] === row) {
|
|
1123
|
-
this.values[i] *= factor;
|
|
1124
|
-
break;
|
|
1125
|
-
}
|
|
1126
|
-
}
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
/**
|
|
1130
|
-
* Add scaled row to another row: targetRow += factor * sourceRow
|
|
1131
|
-
* This is the core operation in Gaussian elimination / pivot
|
|
1132
|
-
*/
|
|
1133
|
-
addScaledRow(targetRow, sourceRow, factor) {
|
|
1134
|
-
if (factor >= -this.precision && factor <= this.precision) {
|
|
1135
|
-
return;
|
|
1136
|
-
}
|
|
1137
|
-
const sourceNonZeros = this.getRowDense(sourceRow, this.workVector);
|
|
1138
|
-
for (const c of sourceNonZeros) {
|
|
1139
|
-
const sourceVal = this.workVector[c];
|
|
1140
|
-
const newVal = this.get(targetRow, c) + factor * sourceVal;
|
|
1141
|
-
this.set(targetRow, c, newVal);
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
/**
|
|
1145
|
-
* Perform pivot operation at (pivotRow, pivotCol)
|
|
1146
|
-
* This is optimized for sparse operations
|
|
1147
|
-
*/
|
|
1148
|
-
pivot(pivotRow, pivotCol) {
|
|
1149
|
-
const pivotVal = this.get(pivotRow, pivotCol);
|
|
1150
|
-
if (pivotVal === 0) {
|
|
1151
|
-
throw new Error("Cannot pivot on zero element");
|
|
1152
|
-
}
|
|
1153
|
-
const invPivot = 1 / pivotVal;
|
|
1154
|
-
const pivotRowNonZeros = this.getRowDense(pivotRow, this.workVector);
|
|
1155
|
-
for (const c of pivotRowNonZeros) {
|
|
1156
|
-
this.workVector[c] *= invPivot;
|
|
1157
|
-
}
|
|
1158
|
-
this.workVector[pivotCol] = invPivot;
|
|
1159
|
-
for (const c of pivotRowNonZeros) {
|
|
1160
|
-
this.set(pivotRow, c, this.workVector[c]);
|
|
1161
|
-
}
|
|
1162
|
-
this.set(pivotRow, pivotCol, invPivot);
|
|
1163
|
-
const pivotColData = this.getColumn(pivotCol);
|
|
1164
|
-
for (let i = 0; i < pivotColData.length; i++) {
|
|
1165
|
-
const r = pivotColData.indices[i];
|
|
1166
|
-
if (r === pivotRow) continue;
|
|
1167
|
-
const coefficient = pivotColData.values[i];
|
|
1168
|
-
if (coefficient >= -this.precision && coefficient <= this.precision) continue;
|
|
1169
|
-
for (const c of pivotRowNonZeros) {
|
|
1170
|
-
if (c === pivotCol) continue;
|
|
1171
|
-
const pivotRowVal = this.workVector[c];
|
|
1172
|
-
if (pivotRowVal >= -this.precision && pivotRowVal <= this.precision) continue;
|
|
1173
|
-
const newVal = this.get(r, c) - coefficient * pivotRowVal;
|
|
1174
|
-
this.set(r, c, newVal);
|
|
1175
|
-
}
|
|
1176
|
-
this.set(r, pivotCol, -coefficient * invPivot);
|
|
1177
|
-
}
|
|
1178
|
-
return pivotRowNonZeros;
|
|
1179
|
-
}
|
|
1180
|
-
/**
|
|
1181
|
-
* Clone the matrix
|
|
1182
|
-
*/
|
|
1183
|
-
clone() {
|
|
1184
|
-
const copy2 = new _SparseMatrix(this.nRows, this.nCols, this.precision);
|
|
1185
|
-
copy2.values = this.values.slice();
|
|
1186
|
-
copy2.rowIndices = this.rowIndices.slice();
|
|
1187
|
-
copy2.colPointers = this.colPointers.slice();
|
|
1188
|
-
return copy2;
|
|
1189
|
-
}
|
|
1190
|
-
};
|
|
1191
|
-
|
|
1192
|
-
// src/tableau/sparse-simplex.ts
|
|
1193
|
-
function sparseSimplex() {
|
|
1194
|
-
const sparse = SparseMatrix.fromDense(this.matrix, this.width, this.height, this.precision);
|
|
1195
|
-
this.bounded = true;
|
|
1196
|
-
const phase1Result = sparsePhase1.call(this, sparse);
|
|
1197
|
-
if (this.feasible === true) {
|
|
1198
|
-
sparsePhase2.call(this, sparse);
|
|
1199
|
-
}
|
|
1200
|
-
const dense = sparse.toDense();
|
|
1201
|
-
this.matrix.set(dense);
|
|
1202
|
-
return this;
|
|
1203
|
-
}
|
|
1204
|
-
function sparsePhase1(sparse) {
|
|
1205
|
-
const debugCheckForCycles = this.model.checkForCycles;
|
|
1206
|
-
const varIndexesCycle = [];
|
|
1207
|
-
const rhsColumn = this.rhsColumn;
|
|
1208
|
-
const lastColumn = this.width - 1;
|
|
1209
|
-
const lastRow = this.height - 1;
|
|
1210
|
-
const precision = this.precision;
|
|
1211
|
-
let unrestricted;
|
|
1212
|
-
let iterations = 0;
|
|
1213
|
-
while (true) {
|
|
1214
|
-
let leavingRowIndex = 0;
|
|
1215
|
-
let rhsValue = -precision;
|
|
1216
|
-
for (let r = 1; r <= lastRow; r++) {
|
|
1217
|
-
const value = sparse.get(r, rhsColumn);
|
|
1218
|
-
if (value < rhsValue) {
|
|
1219
|
-
rhsValue = value;
|
|
1220
|
-
leavingRowIndex = r;
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
if (leavingRowIndex === 0) {
|
|
1224
|
-
this.feasible = true;
|
|
1225
|
-
return iterations;
|
|
1226
|
-
}
|
|
1227
|
-
let enteringColumn = 0;
|
|
1228
|
-
let maxQuotient = -Infinity;
|
|
1229
|
-
const leavingRowData = sparse.getRow(leavingRowIndex);
|
|
1230
|
-
for (let i = 0; i < leavingRowData.length; i++) {
|
|
1231
|
-
const c = leavingRowData.indices[i];
|
|
1232
|
-
if (c === 0 || c === rhsColumn) continue;
|
|
1233
|
-
const coefficient = leavingRowData.values[i];
|
|
1234
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
1235
|
-
if (unrestricted || coefficient < -precision) {
|
|
1236
|
-
const costValue = sparse.get(0, c);
|
|
1237
|
-
const quotient = -costValue / coefficient;
|
|
1238
|
-
if (maxQuotient < quotient) {
|
|
1239
|
-
maxQuotient = quotient;
|
|
1240
|
-
enteringColumn = c;
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
}
|
|
1244
|
-
for (let c = 1; c <= lastColumn; c++) {
|
|
1245
|
-
if (c === rhsColumn) continue;
|
|
1246
|
-
const coefficient = sparse.get(leavingRowIndex, c);
|
|
1247
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
1248
|
-
if (unrestricted || coefficient < -precision) {
|
|
1249
|
-
const costValue = sparse.get(0, c);
|
|
1250
|
-
const quotient = -costValue / coefficient;
|
|
1251
|
-
if (maxQuotient < quotient) {
|
|
1252
|
-
maxQuotient = quotient;
|
|
1253
|
-
enteringColumn = c;
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
}
|
|
1257
|
-
if (enteringColumn === 0) {
|
|
1258
|
-
this.feasible = false;
|
|
1259
|
-
return iterations;
|
|
1260
|
-
}
|
|
1261
|
-
if (debugCheckForCycles) {
|
|
1262
|
-
varIndexesCycle.push([
|
|
1263
|
-
this.varIndexByRow[leavingRowIndex],
|
|
1264
|
-
this.varIndexByCol[enteringColumn]
|
|
1265
|
-
]);
|
|
1266
|
-
const cycleData = this.checkForCycles(varIndexesCycle);
|
|
1267
|
-
if (cycleData.length > 0) {
|
|
1268
|
-
this.model.messages.push("Cycle in phase 1");
|
|
1269
|
-
this.feasible = false;
|
|
1270
|
-
return iterations;
|
|
1271
|
-
}
|
|
1272
|
-
}
|
|
1273
|
-
sparsePivot.call(this, sparse, leavingRowIndex, enteringColumn);
|
|
1274
|
-
iterations += 1;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
function sparsePhase2(sparse) {
|
|
1278
|
-
const debugCheckForCycles = this.model.checkForCycles;
|
|
1279
|
-
const varIndexesCycle = [];
|
|
1280
|
-
const rhsColumn = this.rhsColumn;
|
|
1281
|
-
const lastColumn = this.width - 1;
|
|
1282
|
-
const lastRow = this.height - 1;
|
|
1283
|
-
const precision = this.precision;
|
|
1284
|
-
const nOptionalObjectives = this.optionalObjectives.length;
|
|
1285
|
-
let iterations = 0;
|
|
1286
|
-
let reducedCost;
|
|
1287
|
-
let unrestricted;
|
|
1288
|
-
const batchSize = Math.min(500, Math.max(50, Math.floor(Math.sqrt(lastColumn))));
|
|
1289
|
-
let batchStart = 1;
|
|
1290
|
-
while (true) {
|
|
1291
|
-
const costRow = 0;
|
|
1292
|
-
let enteringColumn = 0;
|
|
1293
|
-
let enteringValue = precision;
|
|
1294
|
-
let isReducedCostNegative = false;
|
|
1295
|
-
let batchesScanned = 0;
|
|
1296
|
-
const totalBatches = Math.ceil(lastColumn / batchSize);
|
|
1297
|
-
while (enteringColumn === 0 && batchesScanned < totalBatches) {
|
|
1298
|
-
const batchEnd = Math.min(batchStart + batchSize - 1, lastColumn);
|
|
1299
|
-
for (let c = batchStart; c <= batchEnd; c++) {
|
|
1300
|
-
if (c === rhsColumn) continue;
|
|
1301
|
-
reducedCost = sparse.get(costRow, c);
|
|
1302
|
-
unrestricted = this.unrestrictedVars[this.varIndexByCol[c]] === true;
|
|
1303
|
-
if (unrestricted && reducedCost < 0) {
|
|
1304
|
-
if (-reducedCost > enteringValue) {
|
|
1305
|
-
enteringValue = -reducedCost;
|
|
1306
|
-
enteringColumn = c;
|
|
1307
|
-
isReducedCostNegative = true;
|
|
1308
|
-
}
|
|
1309
|
-
continue;
|
|
1310
|
-
}
|
|
1311
|
-
if (reducedCost > enteringValue) {
|
|
1312
|
-
enteringValue = reducedCost;
|
|
1313
|
-
enteringColumn = c;
|
|
1314
|
-
isReducedCostNegative = false;
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
batchStart = batchEnd >= lastColumn ? 1 : batchEnd + 1;
|
|
1318
|
-
batchesScanned++;
|
|
1319
|
-
}
|
|
1320
|
-
if (enteringColumn === 0) {
|
|
1321
|
-
this.setEvaluation();
|
|
1322
|
-
this.simplexIters += 1;
|
|
1323
|
-
return iterations;
|
|
1324
|
-
}
|
|
1325
|
-
let leavingRow = 0;
|
|
1326
|
-
let minQuotient = Infinity;
|
|
1327
|
-
const enteringColData = sparse.getColumn(enteringColumn);
|
|
1328
|
-
for (let i = 0; i < enteringColData.length; i++) {
|
|
1329
|
-
const r = enteringColData.indices[i];
|
|
1330
|
-
if (r === 0) continue;
|
|
1331
|
-
const colValue = enteringColData.values[i];
|
|
1332
|
-
if (colValue >= -precision && colValue <= precision) continue;
|
|
1333
|
-
const rhsValue = sparse.get(r, rhsColumn);
|
|
1334
|
-
if (colValue > 0 && precision > rhsValue && rhsValue > -precision) {
|
|
1335
|
-
minQuotient = 0;
|
|
1336
|
-
leavingRow = r;
|
|
1337
|
-
break;
|
|
1338
|
-
}
|
|
1339
|
-
const quotient = isReducedCostNegative ? -rhsValue / colValue : rhsValue / colValue;
|
|
1340
|
-
if (quotient > precision && minQuotient > quotient) {
|
|
1341
|
-
minQuotient = quotient;
|
|
1342
|
-
leavingRow = r;
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
if (minQuotient === Infinity) {
|
|
1346
|
-
this.evaluation = -Infinity;
|
|
1347
|
-
this.bounded = false;
|
|
1348
|
-
this.unboundedVarIndex = this.varIndexByCol[enteringColumn];
|
|
1349
|
-
return iterations;
|
|
1350
|
-
}
|
|
1351
|
-
if (debugCheckForCycles) {
|
|
1352
|
-
varIndexesCycle.push([
|
|
1353
|
-
this.varIndexByRow[leavingRow],
|
|
1354
|
-
this.varIndexByCol[enteringColumn]
|
|
1355
|
-
]);
|
|
1356
|
-
const cycleData = this.checkForCycles(varIndexesCycle);
|
|
1357
|
-
if (cycleData.length > 0) {
|
|
1358
|
-
this.model.messages.push("Cycle in phase 2");
|
|
1359
|
-
this.feasible = false;
|
|
1360
|
-
return iterations;
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
sparsePivot.call(this, sparse, leavingRow, enteringColumn);
|
|
1364
|
-
iterations += 1;
|
|
1365
|
-
}
|
|
1366
|
-
}
|
|
1367
|
-
function sparsePivot(sparse, pivotRowIndex, pivotColumnIndex) {
|
|
1368
|
-
const leavingBasicIndex = this.varIndexByRow[pivotRowIndex];
|
|
1369
|
-
const enteringBasicIndex = this.varIndexByCol[pivotColumnIndex];
|
|
1370
|
-
this.varIndexByRow[pivotRowIndex] = enteringBasicIndex;
|
|
1371
|
-
this.varIndexByCol[pivotColumnIndex] = leavingBasicIndex;
|
|
1372
|
-
this.rowByVarIndex[enteringBasicIndex] = pivotRowIndex;
|
|
1373
|
-
this.rowByVarIndex[leavingBasicIndex] = -1;
|
|
1374
|
-
this.colByVarIndex[enteringBasicIndex] = -1;
|
|
1375
|
-
this.colByVarIndex[leavingBasicIndex] = pivotColumnIndex;
|
|
1376
|
-
sparse.pivot(pivotRowIndex, pivotColumnIndex);
|
|
1377
|
-
const optionalObjectives = this.optionalObjectives;
|
|
1378
|
-
const nOptionalObjectives = optionalObjectives.length;
|
|
1379
|
-
if (nOptionalObjectives > 0) {
|
|
1380
|
-
const pivotVal = sparse.get(pivotRowIndex, pivotColumnIndex);
|
|
1381
|
-
const pivotRowData = sparse.getRow(pivotRowIndex);
|
|
1382
|
-
for (let o = 0; o < nOptionalObjectives; o++) {
|
|
1383
|
-
const reducedCosts = optionalObjectives[o].reducedCosts;
|
|
1384
|
-
const coefficient = reducedCosts[pivotColumnIndex];
|
|
1385
|
-
if (coefficient !== 0) {
|
|
1386
|
-
for (let i = 0; i < pivotRowData.length; i++) {
|
|
1387
|
-
const c = pivotRowData.indices[i];
|
|
1388
|
-
const v0 = pivotRowData.values[i];
|
|
1389
|
-
if (v0 !== 0) {
|
|
1390
|
-
reducedCosts[c] = reducedCosts[c] - coefficient * v0;
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
reducedCosts[pivotColumnIndex] = -coefficient * pivotVal;
|
|
1394
|
-
}
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
|
-
var SPARSE_THRESHOLD = Infinity;
|
|
1399
|
-
var DENSITY_THRESHOLD = 0.1;
|
|
1400
|
-
function shouldUseSparse(tableau) {
|
|
1401
|
-
const totalCells = tableau.width * tableau.height;
|
|
1402
|
-
if (totalCells < SPARSE_THRESHOLD) {
|
|
1403
|
-
return false;
|
|
1404
|
-
}
|
|
1405
|
-
const matrix = tableau.matrix;
|
|
1406
|
-
const width = tableau.width;
|
|
1407
|
-
const startRow = 1;
|
|
1408
|
-
const sampleRows = Math.min(20, tableau.height - 1);
|
|
1409
|
-
let nonZeros = 0;
|
|
1410
|
-
for (let r = startRow; r < startRow + sampleRows; r++) {
|
|
1411
|
-
const rowOffset = r * width;
|
|
1412
|
-
for (let c = 0; c < width; c++) {
|
|
1413
|
-
if (matrix[rowOffset + c] !== 0) {
|
|
1414
|
-
nonZeros++;
|
|
1415
|
-
}
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
const estimatedDensity = nonZeros / (sampleRows * width);
|
|
1419
|
-
return estimatedDensity < DENSITY_THRESHOLD;
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
// src/expressions.ts
|
|
1423
|
-
var Variable = class {
|
|
1424
|
-
constructor(id, cost, index, priority) {
|
|
1425
|
-
this.id = id;
|
|
1426
|
-
this.cost = cost;
|
|
1427
|
-
this.index = index;
|
|
1428
|
-
this.value = 0;
|
|
1429
|
-
this.priority = priority;
|
|
1430
|
-
}
|
|
1431
|
-
};
|
|
1432
|
-
var IntegerVariable = class extends Variable {
|
|
1433
|
-
constructor(id, cost, index, priority) {
|
|
1434
|
-
super(id, cost, index, priority);
|
|
1435
|
-
this.isInteger = true;
|
|
1436
|
-
}
|
|
1437
|
-
};
|
|
1438
|
-
var SlackVariable = class extends Variable {
|
|
1439
|
-
constructor(id, index) {
|
|
1440
|
-
super(id, 0, index, 0);
|
|
1441
|
-
this.isSlack = true;
|
|
1442
|
-
}
|
|
1443
|
-
};
|
|
1444
|
-
var Term = class {
|
|
1445
|
-
constructor(variable, coefficient) {
|
|
1446
|
-
this.variable = variable;
|
|
1447
|
-
this.coefficient = coefficient;
|
|
1448
|
-
}
|
|
1449
|
-
};
|
|
1450
|
-
function createRelaxationVariable(model, weight, priority) {
|
|
1451
|
-
if (priority === 0 || priority === "required") {
|
|
1452
|
-
return null;
|
|
1453
|
-
}
|
|
1454
|
-
const normalizedWeight = weight === void 0 ? 1 : weight;
|
|
1455
|
-
const normalizedPriority = priority === void 0 ? 1 : priority;
|
|
1456
|
-
const actualWeight = model.isMinimization === false ? -normalizedWeight : normalizedWeight;
|
|
1457
|
-
return model.addVariable(
|
|
1458
|
-
actualWeight,
|
|
1459
|
-
"r" + model.relaxationIndex++,
|
|
1460
|
-
false,
|
|
1461
|
-
false,
|
|
1462
|
-
normalizedPriority
|
|
1463
|
-
);
|
|
1464
|
-
}
|
|
1465
|
-
var Constraint = class {
|
|
1466
|
-
constructor(rhs, isUpperBound, index, model) {
|
|
1467
|
-
this.slack = new SlackVariable("s" + index, index);
|
|
1468
|
-
this.index = index;
|
|
1469
|
-
this.model = model;
|
|
1470
|
-
this.rhs = rhs;
|
|
1471
|
-
this.isUpperBound = isUpperBound;
|
|
1472
|
-
this.terms = [];
|
|
1473
|
-
this.termsByVarIndex = {};
|
|
1474
|
-
this.relaxation = null;
|
|
1475
|
-
}
|
|
1476
|
-
addTerm(coefficient, variable) {
|
|
1477
|
-
const varIndex = variable.index;
|
|
1478
|
-
const term = this.termsByVarIndex[varIndex];
|
|
1479
|
-
if (term === void 0) {
|
|
1480
|
-
const newTerm = new Term(variable, coefficient);
|
|
1481
|
-
this.termsByVarIndex[varIndex] = newTerm;
|
|
1482
|
-
this.terms.push(newTerm);
|
|
1483
|
-
const signedCoefficient = this.isUpperBound === true ? -coefficient : coefficient;
|
|
1484
|
-
this.model.updateConstraintCoefficient(this, variable, signedCoefficient);
|
|
1485
|
-
} else {
|
|
1486
|
-
const newCoefficient = term.coefficient + coefficient;
|
|
1487
|
-
this.setVariableCoefficient(newCoefficient, variable);
|
|
1488
|
-
}
|
|
1489
|
-
return this;
|
|
1490
|
-
}
|
|
1491
|
-
// TODO: Implement term removal if required by consumers.
|
|
1492
|
-
removeTerm(_term) {
|
|
1493
|
-
return this;
|
|
1494
|
-
}
|
|
1495
|
-
setRightHandSide(newRhs) {
|
|
1496
|
-
if (newRhs !== this.rhs) {
|
|
1497
|
-
let difference = newRhs - this.rhs;
|
|
1498
|
-
if (this.isUpperBound === true) {
|
|
1499
|
-
difference = -difference;
|
|
1500
|
-
}
|
|
1501
|
-
this.rhs = newRhs;
|
|
1502
|
-
this.model.updateRightHandSide(this, difference);
|
|
1503
|
-
}
|
|
1504
|
-
return this;
|
|
1505
|
-
}
|
|
1506
|
-
setVariableCoefficient(newCoefficient, variable) {
|
|
1507
|
-
const varIndex = variable.index;
|
|
1508
|
-
if (varIndex === -1) {
|
|
1509
|
-
console.warn(
|
|
1510
|
-
"[Constraint.setVariableCoefficient] Trying to change coefficient of inexistant variable."
|
|
1511
|
-
);
|
|
1512
|
-
return;
|
|
1513
|
-
}
|
|
1514
|
-
const term = this.termsByVarIndex[varIndex];
|
|
1515
|
-
if (term === void 0) {
|
|
1516
|
-
this.addTerm(newCoefficient, variable);
|
|
1517
|
-
} else if (newCoefficient !== term.coefficient) {
|
|
1518
|
-
let difference = newCoefficient - term.coefficient;
|
|
1519
|
-
if (this.isUpperBound === true) {
|
|
1520
|
-
difference = -difference;
|
|
1521
|
-
}
|
|
1522
|
-
term.coefficient = newCoefficient;
|
|
1523
|
-
this.model.updateConstraintCoefficient(this, variable, difference);
|
|
1524
|
-
}
|
|
1525
|
-
return this;
|
|
1526
|
-
}
|
|
1527
|
-
relax(weight, priority) {
|
|
1528
|
-
this.relaxation = createRelaxationVariable(this.model, weight, priority);
|
|
1529
|
-
this._relax(this.relaxation);
|
|
1530
|
-
}
|
|
1531
|
-
_relax(relaxationVariable) {
|
|
1532
|
-
if (relaxationVariable === null) {
|
|
1533
|
-
return;
|
|
1534
|
-
}
|
|
1535
|
-
if (this.isUpperBound) {
|
|
1536
|
-
this.setVariableCoefficient(-1, relaxationVariable);
|
|
1537
|
-
} else {
|
|
1538
|
-
this.setVariableCoefficient(1, relaxationVariable);
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
};
|
|
1542
|
-
var Equality = class {
|
|
1543
|
-
constructor(constraintUpper, constraintLower) {
|
|
1544
|
-
this.isEquality = true;
|
|
1545
|
-
this.upperBound = constraintUpper;
|
|
1546
|
-
this.lowerBound = constraintLower;
|
|
1547
|
-
this.model = constraintUpper.model;
|
|
1548
|
-
this.rhs = constraintUpper.rhs;
|
|
1549
|
-
this.relaxation = null;
|
|
1550
|
-
}
|
|
1551
|
-
addTerm(coefficient, variable) {
|
|
1552
|
-
this.upperBound.addTerm(coefficient, variable);
|
|
1553
|
-
this.lowerBound.addTerm(coefficient, variable);
|
|
1554
|
-
return this;
|
|
1555
|
-
}
|
|
1556
|
-
// TODO: Implement term removal if required by consumers.
|
|
1557
|
-
removeTerm(_term) {
|
|
1558
|
-
this.upperBound.removeTerm(_term);
|
|
1559
|
-
this.lowerBound.removeTerm(_term);
|
|
1560
|
-
return this;
|
|
1561
|
-
}
|
|
1562
|
-
setRightHandSide(rhs) {
|
|
1563
|
-
this.upperBound.setRightHandSide(rhs);
|
|
1564
|
-
this.lowerBound.setRightHandSide(rhs);
|
|
1565
|
-
this.rhs = rhs;
|
|
1566
|
-
}
|
|
1567
|
-
relax(weight, priority) {
|
|
1568
|
-
this.relaxation = createRelaxationVariable(this.model, weight, priority);
|
|
1569
|
-
this.upperBound.relaxation = this.relaxation;
|
|
1570
|
-
this.upperBound._relax(this.relaxation);
|
|
1571
|
-
this.lowerBound.relaxation = this.relaxation;
|
|
1572
|
-
this.lowerBound._relax(this.relaxation);
|
|
1573
|
-
}
|
|
1574
|
-
};
|
|
1575
|
-
var Numeral = class {
|
|
1576
|
-
constructor(value) {
|
|
1577
|
-
this.value = value;
|
|
1578
|
-
}
|
|
1579
|
-
};
|
|
1580
|
-
|
|
1581
|
-
// src/tableau/cutting-strategies.ts
|
|
1582
|
-
function addCutConstraints(cutConstraints) {
|
|
1583
|
-
const nCutConstraints = cutConstraints.length;
|
|
1584
|
-
const height = this.height;
|
|
1585
|
-
const heightWithCuts = height + nCutConstraints;
|
|
1586
|
-
const width = this.width;
|
|
1587
|
-
const lastColumn = width - 1;
|
|
1588
|
-
const oldMatrix = this.matrix;
|
|
1589
|
-
const newSize = heightWithCuts * width;
|
|
1590
|
-
if (oldMatrix.length < newSize) {
|
|
1591
|
-
const newMatrix = new Float64Array(newSize);
|
|
1592
|
-
newMatrix.set(oldMatrix);
|
|
1593
|
-
this.matrix = newMatrix;
|
|
1594
|
-
}
|
|
1595
|
-
const matrix = this.matrix;
|
|
1596
|
-
this.height = heightWithCuts;
|
|
1597
|
-
this.nVars = this.width + this.height - 2;
|
|
1598
|
-
for (let h = 0; h < nCutConstraints; h += 1) {
|
|
1599
|
-
const cut = cutConstraints[h];
|
|
1600
|
-
const cutRow = height + h;
|
|
1601
|
-
const cutRowOffset = cutRow * width;
|
|
1602
|
-
const sign = cut.type === "min" ? -1 : 1;
|
|
1603
|
-
const varIndex = cut.varIndex;
|
|
1604
|
-
let varRowIndex = this.rowByVarIndex[varIndex];
|
|
1605
|
-
if (varRowIndex === -1) {
|
|
1606
|
-
matrix[cutRowOffset + this.rhsColumn] = sign * cut.value;
|
|
1607
|
-
for (let c = 1; c <= lastColumn; c += 1) {
|
|
1608
|
-
matrix[cutRowOffset + c] = 0;
|
|
1609
|
-
}
|
|
1610
|
-
matrix[cutRowOffset + this.colByVarIndex[varIndex]] = sign;
|
|
1611
|
-
} else {
|
|
1612
|
-
const varRowOffset = varRowIndex * width;
|
|
1613
|
-
const varValue = matrix[varRowOffset + this.rhsColumn];
|
|
1614
|
-
matrix[cutRowOffset + this.rhsColumn] = sign * (cut.value - varValue);
|
|
1615
|
-
for (let c = 1; c <= lastColumn; c += 1) {
|
|
1616
|
-
matrix[cutRowOffset + c] = -sign * matrix[varRowOffset + c];
|
|
1617
|
-
}
|
|
1618
|
-
}
|
|
1619
|
-
varRowIndex = this.getNewElementIndex();
|
|
1620
|
-
this.varIndexByRow[cutRow] = varRowIndex;
|
|
1621
|
-
this.rowByVarIndex[varRowIndex] = cutRow;
|
|
1622
|
-
this.colByVarIndex[varRowIndex] = -1;
|
|
1623
|
-
this.variablesPerIndex[varRowIndex] = new SlackVariable("s" + varRowIndex, varRowIndex);
|
|
1624
|
-
this.nVars += 1;
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
function addLowerBoundMIRCut(rowIndex) {
|
|
1628
|
-
if (rowIndex === this.costRowIndex) {
|
|
1629
|
-
return false;
|
|
1630
|
-
}
|
|
1631
|
-
const width = this.width;
|
|
1632
|
-
const matrix = this.matrix;
|
|
1633
|
-
const cutRowOffset = rowIndex * width;
|
|
1634
|
-
const integerVar = this.variablesPerIndex[this.varIndexByRow[rowIndex]];
|
|
1635
|
-
if (integerVar === void 0 || !integerVar.isInteger) {
|
|
1636
|
-
return false;
|
|
1637
|
-
}
|
|
1638
|
-
const rhsValue = matrix[cutRowOffset + this.rhsColumn];
|
|
1639
|
-
const fractionalPart = rhsValue - Math.floor(rhsValue);
|
|
1640
|
-
if (fractionalPart < this.precision || fractionalPart > 1 - this.precision) {
|
|
1641
|
-
return false;
|
|
1642
|
-
}
|
|
1643
|
-
const height = this.height;
|
|
1644
|
-
const newRowOffset = height * width;
|
|
1645
|
-
const newSize = (height + 1) * width;
|
|
1646
|
-
if (matrix.length < newSize) {
|
|
1647
|
-
const newMatrix = new Float64Array(newSize);
|
|
1648
|
-
newMatrix.set(matrix);
|
|
1649
|
-
this.matrix = newMatrix;
|
|
1650
|
-
}
|
|
1651
|
-
const mat = this.matrix;
|
|
1652
|
-
this.height += 1;
|
|
1653
|
-
this.nVars += 1;
|
|
1654
|
-
const slackVarIndex = this.getNewElementIndex();
|
|
1655
|
-
this.varIndexByRow[height] = slackVarIndex;
|
|
1656
|
-
this.rowByVarIndex[slackVarIndex] = height;
|
|
1657
|
-
this.colByVarIndex[slackVarIndex] = -1;
|
|
1658
|
-
this.variablesPerIndex[slackVarIndex] = new SlackVariable("s" + slackVarIndex, slackVarIndex);
|
|
1659
|
-
mat[newRowOffset + this.rhsColumn] = Math.floor(rhsValue);
|
|
1660
|
-
for (let colIndex = 1; colIndex < this.varIndexByCol.length; colIndex += 1) {
|
|
1661
|
-
const variable = this.variablesPerIndex[this.varIndexByCol[colIndex]];
|
|
1662
|
-
const coefficient = mat[cutRowOffset + colIndex];
|
|
1663
|
-
if (variable !== void 0 && variable.isInteger) {
|
|
1664
|
-
const termCoeff = Math.floor(coefficient) + Math.max(0, coefficient - Math.floor(coefficient) - fractionalPart) / (1 - fractionalPart);
|
|
1665
|
-
mat[newRowOffset + colIndex] = termCoeff;
|
|
1666
|
-
} else {
|
|
1667
|
-
mat[newRowOffset + colIndex] = Math.min(0, coefficient / (1 - fractionalPart));
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
for (let c = 0; c < width; c += 1) {
|
|
1671
|
-
mat[newRowOffset + c] -= mat[cutRowOffset + c];
|
|
1672
|
-
}
|
|
1673
|
-
return true;
|
|
1674
|
-
}
|
|
1675
|
-
function addUpperBoundMIRCut(rowIndex) {
|
|
1676
|
-
if (rowIndex === this.costRowIndex) {
|
|
1677
|
-
return false;
|
|
1678
|
-
}
|
|
1679
|
-
const width = this.width;
|
|
1680
|
-
const matrix = this.matrix;
|
|
1681
|
-
const cutRowOffset = rowIndex * width;
|
|
1682
|
-
const integerVar = this.variablesPerIndex[this.varIndexByRow[rowIndex]];
|
|
1683
|
-
if (integerVar === void 0 || !integerVar.isInteger) {
|
|
1684
|
-
return false;
|
|
1685
|
-
}
|
|
1686
|
-
const rhsValue = matrix[cutRowOffset + this.rhsColumn];
|
|
1687
|
-
const fractionalPart = rhsValue - Math.floor(rhsValue);
|
|
1688
|
-
if (fractionalPart < this.precision || fractionalPart > 1 - this.precision) {
|
|
1689
|
-
return false;
|
|
1690
|
-
}
|
|
1691
|
-
const height = this.height;
|
|
1692
|
-
const newRowOffset = height * width;
|
|
1693
|
-
const newSize = (height + 1) * width;
|
|
1694
|
-
if (matrix.length < newSize) {
|
|
1695
|
-
const newMatrix = new Float64Array(newSize);
|
|
1696
|
-
newMatrix.set(matrix);
|
|
1697
|
-
this.matrix = newMatrix;
|
|
1698
|
-
}
|
|
1699
|
-
const mat = this.matrix;
|
|
1700
|
-
this.height += 1;
|
|
1701
|
-
this.nVars += 1;
|
|
1702
|
-
const slackVarIndex = this.getNewElementIndex();
|
|
1703
|
-
this.varIndexByRow[height] = slackVarIndex;
|
|
1704
|
-
this.rowByVarIndex[slackVarIndex] = height;
|
|
1705
|
-
this.colByVarIndex[slackVarIndex] = -1;
|
|
1706
|
-
this.variablesPerIndex[slackVarIndex] = new SlackVariable("s" + slackVarIndex, slackVarIndex);
|
|
1707
|
-
mat[newRowOffset + this.rhsColumn] = -fractionalPart;
|
|
1708
|
-
for (let colIndex = 1; colIndex < this.varIndexByCol.length; colIndex += 1) {
|
|
1709
|
-
const variable = this.variablesPerIndex[this.varIndexByCol[colIndex]];
|
|
1710
|
-
const coefficient = mat[cutRowOffset + colIndex];
|
|
1711
|
-
const termCoeff = coefficient - Math.floor(coefficient);
|
|
1712
|
-
if (variable !== void 0 && variable.isInteger) {
|
|
1713
|
-
mat[newRowOffset + colIndex] = termCoeff <= fractionalPart ? -termCoeff : -(1 - termCoeff) * fractionalPart / termCoeff;
|
|
1714
|
-
} else {
|
|
1715
|
-
mat[newRowOffset + colIndex] = coefficient >= 0 ? -coefficient : coefficient * fractionalPart / (1 - fractionalPart);
|
|
1716
|
-
}
|
|
1717
|
-
}
|
|
1718
|
-
return true;
|
|
1719
|
-
}
|
|
1720
|
-
function applyMIRCuts() {
|
|
1721
|
-
const height = this.height;
|
|
1722
|
-
let cutsAdded = 0;
|
|
1723
|
-
const maxCuts = 10;
|
|
1724
|
-
for (let r = 1; r < height && cutsAdded < maxCuts; r++) {
|
|
1725
|
-
if (this.addLowerBoundMIRCut(r)) {
|
|
1726
|
-
cutsAdded++;
|
|
1727
|
-
}
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
|
|
1731
|
-
// src/tableau/dynamic-modification.ts
|
|
1732
|
-
function putInBase(varIndex) {
|
|
1733
|
-
const width = this.width;
|
|
1734
|
-
let r = this.rowByVarIndex[varIndex];
|
|
1735
|
-
if (r === -1) {
|
|
1736
|
-
const c = this.colByVarIndex[varIndex];
|
|
1737
|
-
for (let r1 = 1; r1 < this.height; r1 += 1) {
|
|
1738
|
-
const coefficient = this.matrix[r1 * width + c];
|
|
1739
|
-
if (coefficient < -this.precision || this.precision < coefficient) {
|
|
1740
|
-
r = r1;
|
|
1741
|
-
break;
|
|
1742
|
-
}
|
|
1743
|
-
}
|
|
1744
|
-
this.pivot(r, c);
|
|
1745
|
-
}
|
|
1746
|
-
return r;
|
|
1747
|
-
}
|
|
1748
|
-
function takeOutOfBase(varIndex) {
|
|
1749
|
-
const width = this.width;
|
|
1750
|
-
let c = this.colByVarIndex[varIndex];
|
|
1751
|
-
if (c === -1) {
|
|
1752
|
-
const r = this.rowByVarIndex[varIndex];
|
|
1753
|
-
const pivotRowOffset = r * width;
|
|
1754
|
-
for (let c1 = 1; c1 < this.height; c1 += 1) {
|
|
1755
|
-
const coefficient = this.matrix[pivotRowOffset + c1];
|
|
1756
|
-
if (coefficient < -this.precision || this.precision < coefficient) {
|
|
1757
|
-
c = c1;
|
|
1758
|
-
break;
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
this.pivot(r, c);
|
|
1762
|
-
}
|
|
1763
|
-
return c;
|
|
1764
|
-
}
|
|
1765
|
-
function updateVariableValues() {
|
|
1766
|
-
const width = this.width;
|
|
1767
|
-
const matrix = this.matrix;
|
|
1768
|
-
const rhsColumn = this.rhsColumn;
|
|
1769
|
-
const nVars = this.variables.length;
|
|
1770
|
-
const roundingCoeff = Math.round(1 / this.precision);
|
|
1771
|
-
for (let v = 0; v < nVars; v += 1) {
|
|
1772
|
-
const variable = this.variables[v];
|
|
1773
|
-
const varIndex = variable.index;
|
|
1774
|
-
const r = this.rowByVarIndex[varIndex];
|
|
1775
|
-
if (r === -1) {
|
|
1776
|
-
variable.value = 0;
|
|
1777
|
-
} else {
|
|
1778
|
-
const varValue = matrix[r * width + rhsColumn];
|
|
1779
|
-
variable.value = Math.round((varValue + Number.EPSILON) * roundingCoeff) / roundingCoeff;
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
}
|
|
1783
|
-
function updateRightHandSide(constraint, difference) {
|
|
1784
|
-
const width = this.width;
|
|
1785
|
-
const matrix = this.matrix;
|
|
1786
|
-
const rhsColumn = this.rhsColumn;
|
|
1787
|
-
const lastRow = this.height - 1;
|
|
1788
|
-
const constraintRow = this.rowByVarIndex[constraint.index];
|
|
1789
|
-
if (constraintRow === -1) {
|
|
1790
|
-
const slackColumn = this.colByVarIndex[constraint.index];
|
|
1791
|
-
for (let r = 0; r <= lastRow; r += 1) {
|
|
1792
|
-
const rowOffset = r * width;
|
|
1793
|
-
matrix[rowOffset + rhsColumn] -= difference * matrix[rowOffset + slackColumn];
|
|
1794
|
-
}
|
|
1795
|
-
const nOptionalObjectives = this.optionalObjectives.length;
|
|
1796
|
-
if (nOptionalObjectives > 0) {
|
|
1797
|
-
for (let o = 0; o < nOptionalObjectives; o += 1) {
|
|
1798
|
-
const reducedCosts = this.optionalObjectives[o].reducedCosts;
|
|
1799
|
-
reducedCosts[rhsColumn] -= difference * reducedCosts[slackColumn];
|
|
1800
|
-
}
|
|
1801
|
-
}
|
|
1802
|
-
} else {
|
|
1803
|
-
matrix[constraintRow * width + rhsColumn] -= difference;
|
|
1804
|
-
}
|
|
1805
|
-
}
|
|
1806
|
-
function updateConstraintCoefficient(constraint, variable, difference) {
|
|
1807
|
-
if (constraint.index === variable.index) {
|
|
1808
|
-
throw new Error(
|
|
1809
|
-
"[Tableau.updateConstraintCoefficient] constraint index should not be equal to variable index !"
|
|
1810
|
-
);
|
|
1811
|
-
}
|
|
1812
|
-
const width = this.width;
|
|
1813
|
-
const matrix = this.matrix;
|
|
1814
|
-
const r = this.putInBase(constraint.index);
|
|
1815
|
-
const rowOffset = r * width;
|
|
1816
|
-
const colVar = this.colByVarIndex[variable.index];
|
|
1817
|
-
if (colVar === -1) {
|
|
1818
|
-
const rowVar = this.rowByVarIndex[variable.index];
|
|
1819
|
-
const rowVarOffset = rowVar * width;
|
|
1820
|
-
for (let c = 0; c < width; c += 1) {
|
|
1821
|
-
matrix[rowOffset + c] += difference * matrix[rowVarOffset + c];
|
|
1822
|
-
}
|
|
1823
|
-
} else {
|
|
1824
|
-
matrix[rowOffset + colVar] -= difference;
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
function updateCost(variable, difference) {
|
|
1828
|
-
const width = this.width;
|
|
1829
|
-
const matrix = this.matrix;
|
|
1830
|
-
const varIndex = variable.index;
|
|
1831
|
-
const lastColumn = width - 1;
|
|
1832
|
-
const varColumn = this.colByVarIndex[varIndex];
|
|
1833
|
-
if (varColumn === -1) {
|
|
1834
|
-
const variableRowOffset = this.rowByVarIndex[varIndex] * width;
|
|
1835
|
-
if (variable.priority === 0) {
|
|
1836
|
-
for (let c = 0; c <= lastColumn; c += 1) {
|
|
1837
|
-
matrix[c] += difference * matrix[variableRowOffset + c];
|
|
1838
|
-
}
|
|
1839
|
-
} else {
|
|
1840
|
-
const reducedCosts = this.objectivesByPriority[variable.priority].reducedCosts;
|
|
1841
|
-
for (let c = 0; c <= lastColumn; c += 1) {
|
|
1842
|
-
reducedCosts[c] += difference * matrix[variableRowOffset + c];
|
|
1843
|
-
}
|
|
1844
|
-
}
|
|
1845
|
-
} else {
|
|
1846
|
-
matrix[varColumn] -= difference;
|
|
1847
|
-
}
|
|
1848
|
-
}
|
|
1849
|
-
function addConstraint(constraint) {
|
|
1850
|
-
const sign = constraint.isUpperBound ? 1 : -1;
|
|
1851
|
-
const lastRow = this.height;
|
|
1852
|
-
const width = this.width;
|
|
1853
|
-
const lastColumn = width - 1;
|
|
1854
|
-
const newRowCount = lastRow + 1;
|
|
1855
|
-
const requiredSize = newRowCount * width;
|
|
1856
|
-
if (this.matrix.length < requiredSize) {
|
|
1857
|
-
const currentCapacity = this.matrix.length;
|
|
1858
|
-
const minGrowth = Math.max(width * 16, Math.floor(currentCapacity * 0.5));
|
|
1859
|
-
const newCapacity = currentCapacity + minGrowth;
|
|
1860
|
-
const oldMatrix = this.matrix;
|
|
1861
|
-
const newMatrix = new Float64Array(newCapacity);
|
|
1862
|
-
newMatrix.set(oldMatrix);
|
|
1863
|
-
this.matrix = newMatrix;
|
|
1864
|
-
}
|
|
1865
|
-
const matrix = this.matrix;
|
|
1866
|
-
const constraintRowOffset = lastRow * width;
|
|
1867
|
-
for (let c = 0; c <= lastColumn; c += 1) {
|
|
1868
|
-
matrix[constraintRowOffset + c] = 0;
|
|
1869
|
-
}
|
|
1870
|
-
matrix[constraintRowOffset + this.rhsColumn] = sign * constraint.rhs;
|
|
1871
|
-
const terms = constraint.terms;
|
|
1872
|
-
const nTerms = terms.length;
|
|
1873
|
-
for (let t = 0; t < nTerms; t += 1) {
|
|
1874
|
-
const term = terms[t];
|
|
1875
|
-
const coefficient = term.coefficient;
|
|
1876
|
-
const varIndex = term.variable.index;
|
|
1877
|
-
const varRowIndex = this.rowByVarIndex[varIndex];
|
|
1878
|
-
if (varRowIndex === -1) {
|
|
1879
|
-
matrix[constraintRowOffset + this.colByVarIndex[varIndex]] += sign * coefficient;
|
|
1880
|
-
} else {
|
|
1881
|
-
const varRowOffset = varRowIndex * width;
|
|
1882
|
-
for (let c = 0; c <= lastColumn; c += 1) {
|
|
1883
|
-
matrix[constraintRowOffset + c] -= sign * coefficient * matrix[varRowOffset + c];
|
|
1884
|
-
}
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
const slackIndex = constraint.index;
|
|
1888
|
-
this.varIndexByRow[lastRow] = slackIndex;
|
|
1889
|
-
this.rowByVarIndex[slackIndex] = lastRow;
|
|
1890
|
-
this.colByVarIndex[slackIndex] = -1;
|
|
1891
|
-
this.height += 1;
|
|
1892
|
-
}
|
|
1893
|
-
function removeConstraint(constraint) {
|
|
1894
|
-
const slackIndex = constraint.index;
|
|
1895
|
-
const lastRow = this.height - 1;
|
|
1896
|
-
const width = this.width;
|
|
1897
|
-
const matrix = this.matrix;
|
|
1898
|
-
const r = this.putInBase(slackIndex);
|
|
1899
|
-
const rowOffset = r * width;
|
|
1900
|
-
const lastRowOffset = lastRow * width;
|
|
1901
|
-
for (let c = 0; c < width; c++) {
|
|
1902
|
-
const tmp = matrix[lastRowOffset + c];
|
|
1903
|
-
matrix[lastRowOffset + c] = matrix[rowOffset + c];
|
|
1904
|
-
matrix[rowOffset + c] = tmp;
|
|
1905
|
-
}
|
|
1906
|
-
this.varIndexByRow[r] = this.varIndexByRow[lastRow];
|
|
1907
|
-
this.varIndexByRow[lastRow] = -1;
|
|
1908
|
-
this.rowByVarIndex[slackIndex] = -1;
|
|
1909
|
-
this.availableIndexes[this.availableIndexes.length] = slackIndex;
|
|
1910
|
-
constraint.slack.index = -1;
|
|
1911
|
-
this.height -= 1;
|
|
1912
|
-
}
|
|
1913
|
-
function addVariable(variable) {
|
|
1914
|
-
const lastRow = this.height - 1;
|
|
1915
|
-
const oldWidth = this.width;
|
|
1916
|
-
const newWidth = oldWidth + 1;
|
|
1917
|
-
const height = this.height;
|
|
1918
|
-
const cost = this.model.isMinimization === true ? -variable.cost : variable.cost;
|
|
1919
|
-
const priority = variable.priority;
|
|
1920
|
-
const oldMatrix = this.matrix;
|
|
1921
|
-
const newMatrix = new Float64Array(height * newWidth);
|
|
1922
|
-
for (let r = 0; r < height; r++) {
|
|
1923
|
-
const oldOffset = r * oldWidth;
|
|
1924
|
-
const newOffset = r * newWidth;
|
|
1925
|
-
for (let c = 0; c < oldWidth; c++) {
|
|
1926
|
-
newMatrix[newOffset + c] = oldMatrix[oldOffset + c];
|
|
1927
|
-
}
|
|
1928
|
-
}
|
|
1929
|
-
this.matrix = newMatrix;
|
|
1930
|
-
this.width = newWidth;
|
|
1931
|
-
const lastColumn = newWidth - 1;
|
|
1932
|
-
const nOptionalObjectives = this.optionalObjectives.length;
|
|
1933
|
-
if (nOptionalObjectives > 0) {
|
|
1934
|
-
for (let o = 0; o < nOptionalObjectives; o += 1) {
|
|
1935
|
-
this.optionalObjectives[o].reducedCosts[lastColumn] = 0;
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
if (priority === 0) {
|
|
1939
|
-
newMatrix[lastColumn] = cost;
|
|
1940
|
-
} else {
|
|
1941
|
-
this.setOptionalObjective(priority, lastColumn, cost);
|
|
1942
|
-
newMatrix[lastColumn] = 0;
|
|
1943
|
-
}
|
|
1944
|
-
this.colByVarIndex[variable.index] = lastColumn;
|
|
1945
|
-
this.varIndexByCol[lastColumn] = variable.index;
|
|
1946
|
-
}
|
|
1947
|
-
function removeVariable(variable) {
|
|
1948
|
-
const varIndex = variable.index;
|
|
1949
|
-
const width = this.width;
|
|
1950
|
-
const matrix = this.matrix;
|
|
1951
|
-
const lastColumn = width - 1;
|
|
1952
|
-
const c = this.takeOutOfBase(varIndex);
|
|
1953
|
-
const lastRow = this.height - 1;
|
|
1954
|
-
for (let r = 0; r <= lastRow; r += 1) {
|
|
1955
|
-
const rowOffset = r * width;
|
|
1956
|
-
matrix[rowOffset + c] = matrix[rowOffset + lastColumn];
|
|
1957
|
-
}
|
|
1958
|
-
this.varIndexByCol[c] = this.varIndexByCol[lastColumn];
|
|
1959
|
-
this.rowByVarIndex[varIndex] = -1;
|
|
1960
|
-
this.colByVarIndex[varIndex] = -1;
|
|
1961
|
-
this.availableIndexes[this.availableIndexes.length] = varIndex;
|
|
1962
|
-
this.width -= 1;
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
// src/tableau/backup.ts
|
|
1966
|
-
function copy() {
|
|
1967
|
-
const copy2 = new this.constructor(this.precision, this.branchAndCutService);
|
|
1968
|
-
copy2.width = this.width;
|
|
1969
|
-
copy2.height = this.height;
|
|
1970
|
-
copy2.nVars = this.nVars;
|
|
1971
|
-
copy2.model = this.model;
|
|
1972
|
-
copy2.variables = this.variables;
|
|
1973
|
-
copy2.variablesPerIndex = this.variablesPerIndex;
|
|
1974
|
-
copy2.unrestrictedVars = this.unrestrictedVars;
|
|
1975
|
-
copy2.lastElementIndex = this.lastElementIndex;
|
|
1976
|
-
copy2.varIndexByRow = this.varIndexByRow.slice();
|
|
1977
|
-
copy2.varIndexByCol = this.varIndexByCol.slice();
|
|
1978
|
-
copy2.rowByVarIndex = this.rowByVarIndex.slice();
|
|
1979
|
-
copy2.colByVarIndex = this.colByVarIndex.slice();
|
|
1980
|
-
copy2.availableIndexes = this.availableIndexes.slice();
|
|
1981
|
-
const optionalObjectivesCopy = [];
|
|
1982
|
-
for (let o = 0; o < this.optionalObjectives.length; o++) {
|
|
1983
|
-
optionalObjectivesCopy[o] = this.optionalObjectives[o].copy();
|
|
1984
|
-
}
|
|
1985
|
-
copy2.optionalObjectives = optionalObjectivesCopy;
|
|
1986
|
-
copy2.objectivesByPriority = { ...this.objectivesByPriority };
|
|
1987
|
-
copy2.optionalObjectivePerPriority = { ...this.optionalObjectivePerPriority };
|
|
1988
|
-
copy2.matrix = new Float64Array(this.matrix);
|
|
1989
|
-
return copy2;
|
|
1990
|
-
}
|
|
1991
|
-
function save() {
|
|
1992
|
-
this.savedState = this.copy();
|
|
1993
|
-
}
|
|
1994
|
-
function restore() {
|
|
1995
|
-
if (this.savedState === null) {
|
|
1996
|
-
return;
|
|
1997
|
-
}
|
|
1998
|
-
const save2 = this.savedState;
|
|
1999
|
-
this.nVars = save2.nVars;
|
|
2000
|
-
this.model = save2.model;
|
|
2001
|
-
this.variables = save2.variables;
|
|
2002
|
-
this.variablesPerIndex = save2.variablesPerIndex;
|
|
2003
|
-
this.unrestrictedVars = save2.unrestrictedVars;
|
|
2004
|
-
this.lastElementIndex = save2.lastElementIndex;
|
|
2005
|
-
this.width = save2.width;
|
|
2006
|
-
this.height = save2.height;
|
|
2007
|
-
this.matrix.set(save2.matrix);
|
|
2008
|
-
const savedBasicIndexes = save2.varIndexByRow;
|
|
2009
|
-
const height = this.height;
|
|
2010
|
-
for (let c = 0; c < height; c += 1) {
|
|
2011
|
-
this.varIndexByRow[c] = savedBasicIndexes[c];
|
|
2012
|
-
}
|
|
2013
|
-
this.varIndexByRow.length = height;
|
|
2014
|
-
const savedNonBasicIndexes = save2.varIndexByCol;
|
|
2015
|
-
const width = this.width;
|
|
2016
|
-
for (let r = 0; r < width; r += 1) {
|
|
2017
|
-
this.varIndexByCol[r] = savedNonBasicIndexes[r];
|
|
2018
|
-
}
|
|
2019
|
-
this.varIndexByCol.length = width;
|
|
2020
|
-
const savedRows = save2.rowByVarIndex;
|
|
2021
|
-
const savedCols = save2.colByVarIndex;
|
|
2022
|
-
for (let v = 0; v < this.nVars; v += 1) {
|
|
2023
|
-
this.rowByVarIndex[v] = savedRows[v];
|
|
2024
|
-
this.colByVarIndex[v] = savedCols[v];
|
|
2025
|
-
}
|
|
2026
|
-
if (save2.optionalObjectives.length > 0 && this.optionalObjectives.length > 0) {
|
|
2027
|
-
this.optionalObjectives = [];
|
|
2028
|
-
this.optionalObjectivePerPriority = {};
|
|
2029
|
-
for (let o = 0; o < save2.optionalObjectives.length; o++) {
|
|
2030
|
-
const optionalObjectiveCopy = save2.optionalObjectives[o].copy();
|
|
2031
|
-
this.optionalObjectives[o] = optionalObjectiveCopy;
|
|
2032
|
-
this.optionalObjectivePerPriority[optionalObjectiveCopy.priority] = optionalObjectiveCopy;
|
|
2033
|
-
this.objectivesByPriority[optionalObjectiveCopy.priority] = optionalObjectiveCopy;
|
|
2034
|
-
}
|
|
2035
|
-
}
|
|
2036
|
-
}
|
|
2037
|
-
|
|
2038
|
-
// src/tableau/mip-utils.ts
|
|
2039
|
-
function countIntegerValues() {
|
|
2040
|
-
let count = 0;
|
|
2041
|
-
const width = this.width;
|
|
2042
|
-
const matrix = this.matrix;
|
|
2043
|
-
const rhsColumn = this.rhsColumn;
|
|
2044
|
-
for (let r = 1; r < this.height; r += 1) {
|
|
2045
|
-
const variable = this.variablesPerIndex[this.varIndexByRow[r]];
|
|
2046
|
-
if (variable !== void 0 && variable.isInteger) {
|
|
2047
|
-
const value = matrix[r * width + rhsColumn];
|
|
2048
|
-
const decimalPart = value - Math.floor(value);
|
|
2049
|
-
if (decimalPart < this.precision && -decimalPart < this.precision) {
|
|
2050
|
-
count += 1;
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
return count;
|
|
2055
|
-
}
|
|
2056
|
-
function isIntegral() {
|
|
2057
|
-
const width = this.width;
|
|
2058
|
-
const matrix = this.matrix;
|
|
2059
|
-
const rhsColumn = this.rhsColumn;
|
|
2060
|
-
const integerVariables = this.model.integerVariables;
|
|
2061
|
-
const nIntegerVars = integerVariables.length;
|
|
2062
|
-
for (let v = 0; v < nIntegerVars; v++) {
|
|
2063
|
-
const varIndex = integerVariables[v].index;
|
|
2064
|
-
const row = this.rowByVarIndex[varIndex];
|
|
2065
|
-
if (row !== -1) {
|
|
2066
|
-
const value = matrix[row * width + rhsColumn];
|
|
2067
|
-
if (Math.abs(value - Math.round(value)) > this.precision) {
|
|
2068
|
-
return false;
|
|
2069
|
-
}
|
|
2070
|
-
}
|
|
2071
|
-
}
|
|
2072
|
-
return true;
|
|
2073
|
-
}
|
|
2074
|
-
function computeFractionalVolume(ignoreIntegerValues) {
|
|
2075
|
-
let volume = -1;
|
|
2076
|
-
const width = this.width;
|
|
2077
|
-
const matrix = this.matrix;
|
|
2078
|
-
const rhsColumn = this.rhsColumn;
|
|
2079
|
-
for (let r = 1; r < this.height; r += 1) {
|
|
2080
|
-
const variable = this.variablesPerIndex[this.varIndexByRow[r]];
|
|
2081
|
-
if (variable !== void 0 && variable.isInteger) {
|
|
2082
|
-
const value = matrix[r * width + rhsColumn];
|
|
2083
|
-
const distance = Math.abs(value);
|
|
2084
|
-
if (Math.min(distance - Math.floor(distance), Math.floor(distance + 1)) < this.precision) {
|
|
2085
|
-
if (ignoreIntegerValues !== true) {
|
|
2086
|
-
return 0;
|
|
2087
|
-
}
|
|
2088
|
-
} else if (volume === -1) {
|
|
2089
|
-
volume = distance;
|
|
2090
|
-
} else {
|
|
2091
|
-
volume *= distance;
|
|
2092
|
-
}
|
|
2093
|
-
}
|
|
2094
|
-
}
|
|
2095
|
-
return volume === -1 ? 0 : volume;
|
|
2096
|
-
}
|
|
2097
|
-
function getMostFractionalVar() {
|
|
2098
|
-
let biggestFraction = 0;
|
|
2099
|
-
let selectedVarIndex = null;
|
|
2100
|
-
let selectedVarValue = 0;
|
|
2101
|
-
const width = this.width;
|
|
2102
|
-
const matrix = this.matrix;
|
|
2103
|
-
const rhsColumn = this.rhsColumn;
|
|
2104
|
-
const integerVars = this.model.integerVariables;
|
|
2105
|
-
const nIntegerVars = integerVars.length;
|
|
2106
|
-
for (let v = 0; v < nIntegerVars; v += 1) {
|
|
2107
|
-
const varIndex = integerVars[v].index;
|
|
2108
|
-
const row = this.rowByVarIndex[varIndex];
|
|
2109
|
-
if (row !== -1) {
|
|
2110
|
-
const varValue = matrix[row * width + rhsColumn];
|
|
2111
|
-
const fraction = Math.abs(varValue - Math.round(varValue));
|
|
2112
|
-
if (fraction > biggestFraction) {
|
|
2113
|
-
biggestFraction = fraction;
|
|
2114
|
-
selectedVarIndex = varIndex;
|
|
2115
|
-
selectedVarValue = varValue;
|
|
2116
|
-
}
|
|
2117
|
-
}
|
|
2118
|
-
}
|
|
2119
|
-
return { index: selectedVarIndex, value: selectedVarValue };
|
|
2120
|
-
}
|
|
2121
|
-
function getFractionalVarWithLowestCost() {
|
|
2122
|
-
let highestCost = Infinity;
|
|
2123
|
-
let selectedVarIndex = null;
|
|
2124
|
-
let selectedVarValue = null;
|
|
2125
|
-
const width = this.width;
|
|
2126
|
-
const matrix = this.matrix;
|
|
2127
|
-
const rhsColumn = this.rhsColumn;
|
|
2128
|
-
const integerVars = this.model.integerVariables;
|
|
2129
|
-
const nIntegerVars = integerVars.length;
|
|
2130
|
-
for (let v = 0; v < nIntegerVars; v += 1) {
|
|
2131
|
-
const variable = integerVars[v];
|
|
2132
|
-
const varIndex = variable.index;
|
|
2133
|
-
const varRow = this.rowByVarIndex[varIndex];
|
|
2134
|
-
if (varRow !== -1) {
|
|
2135
|
-
const varValue = matrix[varRow * width + rhsColumn];
|
|
2136
|
-
if (Math.abs(varValue - Math.round(varValue)) > this.precision && variable.cost < highestCost) {
|
|
2137
|
-
highestCost = variable.cost;
|
|
2138
|
-
selectedVarIndex = varIndex;
|
|
2139
|
-
selectedVarValue = varValue;
|
|
2140
|
-
}
|
|
2141
|
-
}
|
|
2142
|
-
}
|
|
2143
|
-
return { index: selectedVarIndex, value: selectedVarValue };
|
|
2144
|
-
}
|
|
2145
|
-
|
|
2146
|
-
// src/tableau/log.ts
|
|
2147
|
-
var DEBUG_ENABLED = false;
|
|
2148
|
-
function log(message, force) {
|
|
2149
|
-
if (!DEBUG_ENABLED && !force) {
|
|
2150
|
-
return this;
|
|
2151
|
-
}
|
|
2152
|
-
console.log("****", message, "****");
|
|
2153
|
-
console.log("Nb Variables", this.width - 1);
|
|
2154
|
-
console.log("Nb Constraints", this.height - 1);
|
|
2155
|
-
console.log("Basic Indexes", this.varIndexByRow);
|
|
2156
|
-
console.log("Non Basic Indexes", this.varIndexByCol);
|
|
2157
|
-
console.log("Rows", this.rowByVarIndex);
|
|
2158
|
-
console.log("Cols", this.colByVarIndex);
|
|
2159
|
-
const digitPrecision = 5;
|
|
2160
|
-
const matrix = this.matrix;
|
|
2161
|
-
const width = this.width;
|
|
2162
|
-
let varNameRowString = "";
|
|
2163
|
-
const spacePerColumn = [" "];
|
|
2164
|
-
let j;
|
|
2165
|
-
let c;
|
|
2166
|
-
let varIndex;
|
|
2167
|
-
let varName;
|
|
2168
|
-
let varNameLength;
|
|
2169
|
-
let valueSpace;
|
|
2170
|
-
let nameSpace;
|
|
2171
|
-
for (c = 1; c < this.width; c += 1) {
|
|
2172
|
-
varIndex = this.varIndexByCol[c];
|
|
2173
|
-
const variable = this.variablesPerIndex[varIndex];
|
|
2174
|
-
if (variable === void 0) {
|
|
2175
|
-
varName = "c" + varIndex;
|
|
2176
|
-
} else {
|
|
2177
|
-
varName = variable.id;
|
|
2178
|
-
}
|
|
2179
|
-
varNameLength = varName.length;
|
|
2180
|
-
valueSpace = " ";
|
|
2181
|
-
nameSpace = " ";
|
|
2182
|
-
if (varNameLength > 5) {
|
|
2183
|
-
valueSpace += " ";
|
|
2184
|
-
} else {
|
|
2185
|
-
nameSpace += " ";
|
|
2186
|
-
}
|
|
2187
|
-
spacePerColumn[c] = valueSpace;
|
|
2188
|
-
varNameRowString += nameSpace + varName;
|
|
2189
|
-
}
|
|
2190
|
-
console.log(varNameRowString);
|
|
2191
|
-
let signSpace;
|
|
2192
|
-
const costRowOffset = this.costRowIndex * width;
|
|
2193
|
-
let firstRowString = " ";
|
|
2194
|
-
for (j = 1; j < this.width; j += 1) {
|
|
2195
|
-
signSpace = " ";
|
|
2196
|
-
firstRowString += signSpace;
|
|
2197
|
-
firstRowString += spacePerColumn[j];
|
|
2198
|
-
firstRowString += matrix[costRowOffset + j].toFixed(digitPrecision);
|
|
2199
|
-
}
|
|
2200
|
-
signSpace = " ";
|
|
2201
|
-
firstRowString += signSpace + spacePerColumn[0] + matrix[costRowOffset].toFixed(digitPrecision);
|
|
2202
|
-
console.log(firstRowString + " Z");
|
|
2203
|
-
for (let r = 1; r < this.height; r += 1) {
|
|
2204
|
-
const rowOffset = r * width;
|
|
2205
|
-
let rowString = " ";
|
|
2206
|
-
for (c = 1; c < this.width; c += 1) {
|
|
2207
|
-
signSpace = " ";
|
|
2208
|
-
rowString += signSpace + spacePerColumn[c] + matrix[rowOffset + c].toFixed(digitPrecision);
|
|
2209
|
-
}
|
|
2210
|
-
signSpace = " ";
|
|
2211
|
-
rowString += signSpace + spacePerColumn[0] + matrix[rowOffset].toFixed(digitPrecision);
|
|
2212
|
-
varIndex = this.varIndexByRow[r];
|
|
2213
|
-
const variable = this.variablesPerIndex[varIndex];
|
|
2214
|
-
if (variable === void 0) {
|
|
2215
|
-
varName = "c" + varIndex;
|
|
2216
|
-
} else {
|
|
2217
|
-
varName = variable.id;
|
|
2218
|
-
}
|
|
2219
|
-
console.log(rowString + " " + varName);
|
|
2220
|
-
}
|
|
2221
|
-
console.log("");
|
|
2222
|
-
const nOptionalObjectives = this.optionalObjectives.length;
|
|
2223
|
-
if (nOptionalObjectives > 0) {
|
|
2224
|
-
console.log(" Optional objectives:");
|
|
2225
|
-
for (let o = 0; o < nOptionalObjectives; o += 1) {
|
|
2226
|
-
const reducedCosts = this.optionalObjectives[o].reducedCosts;
|
|
2227
|
-
let reducedCostsString = "";
|
|
2228
|
-
for (j = 1; j < this.width; j += 1) {
|
|
2229
|
-
signSpace = reducedCosts[j] < 0 ? "" : " ";
|
|
2230
|
-
reducedCostsString += signSpace;
|
|
2231
|
-
reducedCostsString += spacePerColumn[j];
|
|
2232
|
-
reducedCostsString += reducedCosts[j].toFixed(digitPrecision);
|
|
2233
|
-
}
|
|
2234
|
-
signSpace = reducedCosts[0] < 0 ? "" : " ";
|
|
2235
|
-
reducedCostsString += signSpace + spacePerColumn[0] + reducedCosts[0].toFixed(digitPrecision);
|
|
2236
|
-
console.log(reducedCostsString + " z" + o);
|
|
2237
|
-
}
|
|
2238
|
-
}
|
|
2239
|
-
console.log("Feasible?", this.feasible);
|
|
2240
|
-
console.log("evaluation", this.evaluation);
|
|
2241
|
-
return this;
|
|
2242
|
-
}
|
|
2243
|
-
|
|
2244
|
-
// src/tableau/tableau.ts
|
|
2245
|
-
function createOptionalObjective(priority, nColumns, reducedCosts) {
|
|
2246
|
-
return {
|
|
2247
|
-
priority,
|
|
2248
|
-
reducedCosts: reducedCosts ? reducedCosts.slice() : new Array(nColumns).fill(0),
|
|
2249
|
-
copy() {
|
|
2250
|
-
return createOptionalObjective(
|
|
2251
|
-
this.priority,
|
|
2252
|
-
this.reducedCosts.length,
|
|
2253
|
-
this.reducedCosts
|
|
2254
|
-
);
|
|
2255
|
-
}
|
|
2256
|
-
};
|
|
2257
|
-
}
|
|
2258
|
-
var Tableau = class {
|
|
2259
|
-
constructor(precision = 1e-8, branchAndCutService) {
|
|
2260
|
-
this.model = null;
|
|
2261
|
-
this.matrix = new Float64Array(0);
|
|
2262
|
-
this.width = 0;
|
|
2263
|
-
this.height = 0;
|
|
2264
|
-
this.costRowIndex = 0;
|
|
2265
|
-
this.rhsColumn = 0;
|
|
2266
|
-
this.variablesPerIndex = [];
|
|
2267
|
-
this.unrestrictedVars = {};
|
|
2268
|
-
this.feasible = true;
|
|
2269
|
-
this.evaluation = 0;
|
|
2270
|
-
this.simplexIters = 0;
|
|
2271
|
-
this.varIndexByRow = [];
|
|
2272
|
-
this.varIndexByCol = [];
|
|
2273
|
-
this.rowByVarIndex = [];
|
|
2274
|
-
this.colByVarIndex = [];
|
|
2275
|
-
this.optionalObjectives = [];
|
|
2276
|
-
this.objectivesByPriority = {};
|
|
2277
|
-
this.optionalObjectivePerPriority = {};
|
|
2278
|
-
this.savedState = null;
|
|
2279
|
-
this.availableIndexes = [];
|
|
2280
|
-
this.lastElementIndex = 0;
|
|
2281
|
-
this.variables = [];
|
|
2282
|
-
this.nVars = 0;
|
|
2283
|
-
this.bounded = true;
|
|
2284
|
-
this.unboundedVarIndex = null;
|
|
2285
|
-
this.branchAndCutIterations = 0;
|
|
2286
|
-
this.bestPossibleEval = 0;
|
|
2287
|
-
// Partial pricing state for phase2 optimization
|
|
2288
|
-
this.pricingBatchStart = 1;
|
|
2289
|
-
this.pricingBatchSize = 0;
|
|
2290
|
-
this.precision = precision;
|
|
2291
|
-
this.branchAndCutService = branchAndCutService ?? createBranchAndCutService();
|
|
2292
|
-
}
|
|
2293
|
-
// ========== Core Simplex Operations ==========
|
|
2294
|
-
simplex() {
|
|
2295
|
-
if (shouldUseSparse(this)) {
|
|
2296
|
-
sparseSimplex.call(this);
|
|
2297
|
-
} else {
|
|
2298
|
-
simplex.call(this);
|
|
2299
|
-
}
|
|
2300
|
-
return this;
|
|
2301
|
-
}
|
|
2302
|
-
phase1() {
|
|
2303
|
-
return phase1.call(this);
|
|
2304
|
-
}
|
|
2305
|
-
phase2() {
|
|
2306
|
-
return phase2.call(this);
|
|
2307
|
-
}
|
|
2308
|
-
pivot(pivotRowIndex, pivotColumnIndex) {
|
|
2309
|
-
pivot.call(this, pivotRowIndex, pivotColumnIndex);
|
|
2310
|
-
}
|
|
2311
|
-
checkForCycles(varIndexes) {
|
|
2312
|
-
return checkForCycles.call(this, varIndexes);
|
|
2313
|
-
}
|
|
2314
|
-
// ========== Integer/MIP Properties ==========
|
|
2315
|
-
countIntegerValues() {
|
|
2316
|
-
return countIntegerValues.call(this);
|
|
2317
|
-
}
|
|
2318
|
-
isIntegral() {
|
|
2319
|
-
return isIntegral.call(this);
|
|
2320
|
-
}
|
|
2321
|
-
computeFractionalVolume(ignoreIntegerValues) {
|
|
2322
|
-
return computeFractionalVolume.call(this, ignoreIntegerValues);
|
|
2323
|
-
}
|
|
2324
|
-
// ========== Cutting Strategies ==========
|
|
2325
|
-
addCutConstraints(branchingCuts) {
|
|
2326
|
-
addCutConstraints.call(this, branchingCuts);
|
|
2327
|
-
}
|
|
2328
|
-
applyMIRCuts() {
|
|
2329
|
-
applyMIRCuts.call(this);
|
|
2330
|
-
}
|
|
2331
|
-
addLowerBoundMIRCut(rowIndex) {
|
|
2332
|
-
return addLowerBoundMIRCut.call(this, rowIndex);
|
|
2333
|
-
}
|
|
2334
|
-
addUpperBoundMIRCut(rowIndex) {
|
|
2335
|
-
return addUpperBoundMIRCut.call(this, rowIndex);
|
|
2336
|
-
}
|
|
2337
|
-
// ========== Branching Strategies ==========
|
|
2338
|
-
getMostFractionalVar() {
|
|
2339
|
-
return getMostFractionalVar.call(this);
|
|
2340
|
-
}
|
|
2341
|
-
getFractionalVarWithLowestCost() {
|
|
2342
|
-
return getFractionalVarWithLowestCost.call(this);
|
|
2343
|
-
}
|
|
2344
|
-
// ========== Dynamic Modification ==========
|
|
2345
|
-
putInBase(varIndex) {
|
|
2346
|
-
return putInBase.call(this, varIndex);
|
|
2347
|
-
}
|
|
2348
|
-
takeOutOfBase(varIndex) {
|
|
2349
|
-
return takeOutOfBase.call(this, varIndex);
|
|
2350
|
-
}
|
|
2351
|
-
updateVariableValues() {
|
|
2352
|
-
updateVariableValues.call(this);
|
|
2353
|
-
}
|
|
2354
|
-
updateRightHandSide(constraint, difference) {
|
|
2355
|
-
updateRightHandSide.call(this, constraint, difference);
|
|
2356
|
-
}
|
|
2357
|
-
updateConstraintCoefficient(constraint, variable, difference) {
|
|
2358
|
-
updateConstraintCoefficient.call(this, constraint, variable, difference);
|
|
2359
|
-
}
|
|
2360
|
-
updateCost(variable, difference) {
|
|
2361
|
-
updateCost.call(this, variable, difference);
|
|
2362
|
-
}
|
|
2363
|
-
addConstraint(constraint) {
|
|
2364
|
-
addConstraint.call(this, constraint);
|
|
2365
|
-
}
|
|
2366
|
-
removeConstraint(constraint) {
|
|
2367
|
-
removeConstraint.call(this, constraint);
|
|
2368
|
-
}
|
|
2369
|
-
addVariable(variable) {
|
|
2370
|
-
addVariable.call(this, variable);
|
|
2371
|
-
}
|
|
2372
|
-
removeVariable(variable) {
|
|
2373
|
-
removeVariable.call(this, variable);
|
|
2374
|
-
}
|
|
2375
|
-
// ========== Backup/Restore ==========
|
|
2376
|
-
copy() {
|
|
2377
|
-
return copy.call(this);
|
|
2378
|
-
}
|
|
2379
|
-
save() {
|
|
2380
|
-
save.call(this);
|
|
2381
|
-
}
|
|
2382
|
-
restore() {
|
|
2383
|
-
restore.call(this);
|
|
2384
|
-
}
|
|
2385
|
-
// ========== Debug ==========
|
|
2386
|
-
log(message) {
|
|
2387
|
-
log.call(this, message);
|
|
2388
|
-
return this;
|
|
2389
|
-
}
|
|
2390
|
-
// ========== Branch and Cut ==========
|
|
2391
|
-
applyCuts(branchingCuts) {
|
|
2392
|
-
this.branchAndCutService.applyCuts(this, branchingCuts);
|
|
2393
|
-
}
|
|
2394
|
-
branchAndCut() {
|
|
2395
|
-
this.branchAndCutService.branchAndCut(this);
|
|
2396
|
-
}
|
|
2397
|
-
// ========== Solution ==========
|
|
2398
|
-
solve() {
|
|
2399
|
-
if ((this.model?.getNumberOfIntegerVariables() ?? 0) > 0) {
|
|
2400
|
-
this.branchAndCut();
|
|
2401
|
-
} else {
|
|
2402
|
-
this.simplex();
|
|
2403
|
-
}
|
|
2404
|
-
this.updateVariableValues();
|
|
2405
|
-
return this.getSolution();
|
|
2406
|
-
}
|
|
2407
|
-
getSolution() {
|
|
2408
|
-
const evaluation = this.model?.isMinimization === true ? this.evaluation : -this.evaluation;
|
|
2409
|
-
if ((this.model?.getNumberOfIntegerVariables() ?? 0) > 0) {
|
|
2410
|
-
return new MilpSolution(
|
|
2411
|
-
this,
|
|
2412
|
-
evaluation,
|
|
2413
|
-
this.feasible,
|
|
2414
|
-
this.bounded,
|
|
2415
|
-
this.branchAndCutIterations
|
|
2416
|
-
);
|
|
2417
|
-
} else {
|
|
2418
|
-
return new Solution(this, evaluation, this.feasible, this.bounded);
|
|
2419
|
-
}
|
|
2420
|
-
}
|
|
2421
|
-
// ========== Initialization ==========
|
|
2422
|
-
setOptionalObjective(priority, column, cost) {
|
|
2423
|
-
let objectiveForPriority = this.objectivesByPriority[priority];
|
|
2424
|
-
if (objectiveForPriority === void 0) {
|
|
2425
|
-
const nColumns = Math.max(this.width, column + 1);
|
|
2426
|
-
objectiveForPriority = createOptionalObjective(priority, nColumns);
|
|
2427
|
-
this.objectivesByPriority[priority] = objectiveForPriority;
|
|
2428
|
-
this.optionalObjectivePerPriority[priority] = objectiveForPriority;
|
|
2429
|
-
this.optionalObjectives.push(objectiveForPriority);
|
|
2430
|
-
this.optionalObjectives.sort((a, b) => a.priority - b.priority);
|
|
2431
|
-
}
|
|
2432
|
-
objectiveForPriority.reducedCosts[column] = cost;
|
|
2433
|
-
}
|
|
2434
|
-
initialize(width, height, variables, unrestrictedVars) {
|
|
2435
|
-
this.variables = variables;
|
|
2436
|
-
this.unrestrictedVars = unrestrictedVars;
|
|
2437
|
-
this.width = width;
|
|
2438
|
-
this.height = height;
|
|
2439
|
-
this.matrix = new Float64Array(width * height);
|
|
2440
|
-
this.varIndexByRow = new Array(this.height);
|
|
2441
|
-
this.varIndexByCol = new Array(this.width);
|
|
2442
|
-
this.varIndexByRow[0] = -1;
|
|
2443
|
-
this.varIndexByCol[0] = -1;
|
|
2444
|
-
this.nVars = width + height - 2;
|
|
2445
|
-
this.rowByVarIndex = new Array(this.nVars);
|
|
2446
|
-
this.colByVarIndex = new Array(this.nVars);
|
|
2447
|
-
this.lastElementIndex = this.nVars;
|
|
2448
|
-
}
|
|
2449
|
-
_resetMatrix() {
|
|
2450
|
-
if (this.model === null) {
|
|
2451
|
-
throw new Error("[Tableau._resetMatrix] Model not set");
|
|
2452
|
-
}
|
|
2453
|
-
const matrix = this.matrix;
|
|
2454
|
-
const width = this.width;
|
|
2455
|
-
const variables = this.model.variables;
|
|
2456
|
-
const constraints = this.model.constraints;
|
|
2457
|
-
const nVars = variables.length;
|
|
2458
|
-
const nConstraints = constraints.length;
|
|
2459
|
-
const coeff = this.model.isMinimization === true ? -1 : 1;
|
|
2460
|
-
for (let v = 0; v < nVars; v += 1) {
|
|
2461
|
-
const variable = variables[v];
|
|
2462
|
-
const priority = variable.priority;
|
|
2463
|
-
const cost = coeff * variable.cost;
|
|
2464
|
-
if (priority === 0) {
|
|
2465
|
-
matrix[v + 1] = cost;
|
|
2466
|
-
} else {
|
|
2467
|
-
this.setOptionalObjective(priority, v + 1, cost);
|
|
2468
|
-
}
|
|
2469
|
-
const varIndex = variables[v].index;
|
|
2470
|
-
this.rowByVarIndex[varIndex] = -1;
|
|
2471
|
-
this.colByVarIndex[varIndex] = v + 1;
|
|
2472
|
-
this.varIndexByCol[v + 1] = varIndex;
|
|
2473
|
-
}
|
|
2474
|
-
let rowIndex = 1;
|
|
2475
|
-
for (let c = 0; c < nConstraints; c += 1) {
|
|
2476
|
-
const constraint = constraints[c];
|
|
2477
|
-
const constraintIndex = constraint.index;
|
|
2478
|
-
this.rowByVarIndex[constraintIndex] = rowIndex;
|
|
2479
|
-
this.colByVarIndex[constraintIndex] = -1;
|
|
2480
|
-
this.varIndexByRow[rowIndex] = constraintIndex;
|
|
2481
|
-
const terms = constraint.terms;
|
|
2482
|
-
const nTerms = terms.length;
|
|
2483
|
-
const rowOffset = rowIndex * width;
|
|
2484
|
-
rowIndex++;
|
|
2485
|
-
if (constraint.isUpperBound) {
|
|
2486
|
-
for (let t = 0; t < nTerms; t += 1) {
|
|
2487
|
-
const term = terms[t];
|
|
2488
|
-
const column = this.colByVarIndex[term.variable.index];
|
|
2489
|
-
matrix[rowOffset + column] = term.coefficient;
|
|
2490
|
-
}
|
|
2491
|
-
matrix[rowOffset] = constraint.rhs;
|
|
2492
|
-
} else {
|
|
2493
|
-
for (let t = 0; t < nTerms; t += 1) {
|
|
2494
|
-
const term = terms[t];
|
|
2495
|
-
const column = this.colByVarIndex[term.variable.index];
|
|
2496
|
-
matrix[rowOffset + column] = -term.coefficient;
|
|
2497
|
-
}
|
|
2498
|
-
matrix[rowOffset] = -constraint.rhs;
|
|
2499
|
-
}
|
|
2500
|
-
}
|
|
2501
|
-
}
|
|
2502
|
-
setModel(model) {
|
|
2503
|
-
this.model = model;
|
|
2504
|
-
const width = model.nVariables + 1;
|
|
2505
|
-
const height = model.nConstraints + 1;
|
|
2506
|
-
this.initialize(width, height, model.variables, model.unrestrictedVariables);
|
|
2507
|
-
this._resetMatrix();
|
|
2508
|
-
return this;
|
|
2509
|
-
}
|
|
2510
|
-
getNewElementIndex() {
|
|
2511
|
-
if (this.availableIndexes.length > 0) {
|
|
2512
|
-
return this.availableIndexes.pop();
|
|
2513
|
-
}
|
|
2514
|
-
const index = this.lastElementIndex;
|
|
2515
|
-
this.lastElementIndex += 1;
|
|
2516
|
-
return index;
|
|
2517
|
-
}
|
|
2518
|
-
density() {
|
|
2519
|
-
let density = 0;
|
|
2520
|
-
const matrix = this.matrix;
|
|
2521
|
-
const width = this.width;
|
|
2522
|
-
for (let r = 0; r < this.height; r++) {
|
|
2523
|
-
const rowOffset = r * width;
|
|
2524
|
-
for (let c = 0; c < width; c++) {
|
|
2525
|
-
if (matrix[rowOffset + c] !== 0) {
|
|
2526
|
-
density += 1;
|
|
2527
|
-
}
|
|
2528
|
-
}
|
|
2529
|
-
}
|
|
2530
|
-
return density / (this.height * this.width);
|
|
2531
|
-
}
|
|
2532
|
-
setEvaluation() {
|
|
2533
|
-
const roundingCoeff = Math.round(1 / this.precision);
|
|
2534
|
-
const evaluation = this.matrix[this.costRowIndex * this.width + this.rhsColumn];
|
|
2535
|
-
const roundedEvaluation = Math.round((Number.EPSILON + evaluation) * roundingCoeff) / roundingCoeff;
|
|
2536
|
-
this.evaluation = roundedEvaluation;
|
|
2537
|
-
if (this.simplexIters === 0) {
|
|
2538
|
-
this.bestPossibleEval = roundedEvaluation;
|
|
2539
|
-
}
|
|
2540
|
-
}
|
|
2541
|
-
};
|
|
2542
|
-
|
|
2543
|
-
// src/tableau/index.ts
|
|
2544
|
-
var tableau_default = Tableau;
|
|
2545
|
-
|
|
2546
|
-
// src/tableau/presolve.ts
|
|
2547
|
-
function tightenCoefficients(model, result) {
|
|
2548
|
-
let changed = false;
|
|
2549
|
-
for (const constraint of model.constraints) {
|
|
2550
|
-
if (result.removedConstraints.has(constraint)) continue;
|
|
2551
|
-
if (!constraint.isUpperBound) continue;
|
|
2552
|
-
let minActivity = 0;
|
|
2553
|
-
for (const term of constraint.terms) {
|
|
2554
|
-
if (result.fixedVariables.has(term.variable)) {
|
|
2555
|
-
minActivity += term.coefficient * result.fixedVariables.get(term.variable);
|
|
2556
|
-
} else {
|
|
2557
|
-
const bounds = result.tightenedBounds.get(term.variable) ?? {};
|
|
2558
|
-
const lower = bounds.lower ?? 0;
|
|
2559
|
-
if (term.coefficient > 0) {
|
|
2560
|
-
minActivity += term.coefficient * lower;
|
|
2561
|
-
} else {
|
|
2562
|
-
const upper = bounds.upper ?? Infinity;
|
|
2563
|
-
minActivity += term.coefficient * upper;
|
|
2564
|
-
}
|
|
2565
|
-
}
|
|
2566
|
-
}
|
|
2567
|
-
const slack = constraint.rhs - minActivity;
|
|
2568
|
-
if (slack < 0) continue;
|
|
2569
|
-
for (const term of constraint.terms) {
|
|
2570
|
-
if (result.fixedVariables.has(term.variable)) continue;
|
|
2571
|
-
if (!term.variable.isInteger) continue;
|
|
2572
|
-
if (term.coefficient <= 0) continue;
|
|
2573
|
-
const bounds = result.tightenedBounds.get(term.variable) ?? {};
|
|
2574
|
-
const lower = bounds.lower ?? 0;
|
|
2575
|
-
const upper = bounds.upper ?? 1;
|
|
2576
|
-
if (lower >= -0.5 && upper <= 1.5) {
|
|
2577
|
-
const effectiveCoeff = term.coefficient * (upper - lower);
|
|
2578
|
-
if (effectiveCoeff > slack + 1e-6) {
|
|
2579
|
-
const impliedUpper = lower + slack / term.coefficient;
|
|
2580
|
-
if (impliedUpper < upper - 1e-6) {
|
|
2581
|
-
const current = result.tightenedBounds.get(term.variable) ?? {};
|
|
2582
|
-
if (!current.upper || impliedUpper < current.upper) {
|
|
2583
|
-
result.tightenedBounds.set(term.variable, {
|
|
2584
|
-
...current,
|
|
2585
|
-
upper: impliedUpper
|
|
2586
|
-
});
|
|
2587
|
-
result.stats.boundsTightened++;
|
|
2588
|
-
changed = true;
|
|
2589
|
-
}
|
|
2590
|
-
}
|
|
2591
|
-
}
|
|
2592
|
-
}
|
|
2593
|
-
}
|
|
2594
|
-
}
|
|
2595
|
-
return changed;
|
|
2596
|
-
}
|
|
2597
|
-
function removeRedundantConstraints(model, result) {
|
|
2598
|
-
let changed = false;
|
|
2599
|
-
for (const constraint of model.constraints) {
|
|
2600
|
-
if (result.removedConstraints.has(constraint)) continue;
|
|
2601
|
-
let minActivity = 0;
|
|
2602
|
-
let maxActivity = 0;
|
|
2603
|
-
for (const term of constraint.terms) {
|
|
2604
|
-
const fixed = result.fixedVariables.get(term.variable);
|
|
2605
|
-
if (fixed !== void 0) {
|
|
2606
|
-
minActivity += term.coefficient * fixed;
|
|
2607
|
-
maxActivity += term.coefficient * fixed;
|
|
2608
|
-
continue;
|
|
2609
|
-
}
|
|
2610
|
-
const bounds = result.tightenedBounds.get(term.variable) ?? {};
|
|
2611
|
-
const lower = bounds.lower ?? 0;
|
|
2612
|
-
const upper = bounds.upper ?? Infinity;
|
|
2613
|
-
if (term.coefficient > 0) {
|
|
2614
|
-
minActivity += term.coefficient * lower;
|
|
2615
|
-
maxActivity += term.coefficient * (upper === Infinity ? 1e10 : upper);
|
|
2616
|
-
} else {
|
|
2617
|
-
minActivity += term.coefficient * (upper === Infinity ? 1e10 : upper);
|
|
2618
|
-
maxActivity += term.coefficient * lower;
|
|
2619
|
-
}
|
|
2620
|
-
}
|
|
2621
|
-
if (constraint.isUpperBound) {
|
|
2622
|
-
if (maxActivity <= constraint.rhs + 1e-6) {
|
|
2623
|
-
result.removedConstraints.add(constraint);
|
|
2624
|
-
result.stats.constraintsRemoved++;
|
|
2625
|
-
changed = true;
|
|
2626
|
-
}
|
|
2627
|
-
if (minActivity > constraint.rhs + 1e-6) {
|
|
2628
|
-
result.isInfeasible = true;
|
|
2629
|
-
return false;
|
|
2630
|
-
}
|
|
2631
|
-
} else {
|
|
2632
|
-
if (minActivity >= constraint.rhs - 1e-6) {
|
|
2633
|
-
result.removedConstraints.add(constraint);
|
|
2634
|
-
result.stats.constraintsRemoved++;
|
|
2635
|
-
changed = true;
|
|
2636
|
-
}
|
|
2637
|
-
if (maxActivity < constraint.rhs - 1e-6) {
|
|
2638
|
-
result.isInfeasible = true;
|
|
2639
|
-
return false;
|
|
2640
|
-
}
|
|
2641
|
-
}
|
|
2642
|
-
}
|
|
2643
|
-
return changed;
|
|
2644
|
-
}
|
|
2645
|
-
function presolve(model) {
|
|
2646
|
-
const result = {
|
|
2647
|
-
fixedVariables: /* @__PURE__ */ new Map(),
|
|
2648
|
-
removedConstraints: /* @__PURE__ */ new Set(),
|
|
2649
|
-
tightenedBounds: /* @__PURE__ */ new Map(),
|
|
2650
|
-
isInfeasible: false,
|
|
2651
|
-
stats: {
|
|
2652
|
-
variablesFixed: 0,
|
|
2653
|
-
constraintsRemoved: 0,
|
|
2654
|
-
boundsTightened: 0
|
|
2655
|
-
}
|
|
2656
|
-
};
|
|
2657
|
-
let changed = true;
|
|
2658
|
-
let passes = 0;
|
|
2659
|
-
const maxPasses = 5;
|
|
2660
|
-
while (changed && passes < maxPasses) {
|
|
2661
|
-
changed = false;
|
|
2662
|
-
passes++;
|
|
2663
|
-
for (const constraint of model.constraints) {
|
|
2664
|
-
if (result.removedConstraints.has(constraint)) continue;
|
|
2665
|
-
const activeTerms = constraint.terms.filter(
|
|
2666
|
-
(t) => !result.fixedVariables.has(t.variable)
|
|
2667
|
-
);
|
|
2668
|
-
if (activeTerms.length === 0) {
|
|
2669
|
-
let lhs = 0;
|
|
2670
|
-
for (const term of constraint.terms) {
|
|
2671
|
-
const fixedVal = result.fixedVariables.get(term.variable);
|
|
2672
|
-
if (fixedVal !== void 0) {
|
|
2673
|
-
lhs += term.coefficient * fixedVal;
|
|
2674
|
-
}
|
|
2675
|
-
}
|
|
2676
|
-
const satisfied = constraint.isUpperBound ? lhs <= constraint.rhs + 1e-6 : lhs >= constraint.rhs - 1e-6;
|
|
2677
|
-
if (!satisfied) {
|
|
2678
|
-
result.isInfeasible = true;
|
|
2679
|
-
return result;
|
|
2680
|
-
}
|
|
2681
|
-
result.removedConstraints.add(constraint);
|
|
2682
|
-
result.stats.constraintsRemoved++;
|
|
2683
|
-
changed = true;
|
|
2684
|
-
} else if (activeTerms.length === 1) {
|
|
2685
|
-
const term = activeTerms[0];
|
|
2686
|
-
const variable = term.variable;
|
|
2687
|
-
const coeff = term.coefficient;
|
|
2688
|
-
let rhsAdj = constraint.rhs;
|
|
2689
|
-
for (const t of constraint.terms) {
|
|
2690
|
-
if (t.variable !== variable) {
|
|
2691
|
-
const fixedVal = result.fixedVariables.get(t.variable);
|
|
2692
|
-
if (fixedVal !== void 0) {
|
|
2693
|
-
rhsAdj -= t.coefficient * fixedVal;
|
|
2694
|
-
}
|
|
2695
|
-
}
|
|
2696
|
-
}
|
|
2697
|
-
const bound = rhsAdj / coeff;
|
|
2698
|
-
if (constraint.isUpperBound) {
|
|
2699
|
-
if (coeff > 0) {
|
|
2700
|
-
const current = result.tightenedBounds.get(variable);
|
|
2701
|
-
if (!current?.upper || bound < current.upper) {
|
|
2702
|
-
result.tightenedBounds.set(variable, {
|
|
2703
|
-
...current,
|
|
2704
|
-
upper: bound
|
|
2705
|
-
});
|
|
2706
|
-
result.stats.boundsTightened++;
|
|
2707
|
-
changed = true;
|
|
2708
|
-
}
|
|
2709
|
-
} else {
|
|
2710
|
-
const current = result.tightenedBounds.get(variable);
|
|
2711
|
-
if (!current?.lower || bound > current.lower) {
|
|
2712
|
-
result.tightenedBounds.set(variable, {
|
|
2713
|
-
...current,
|
|
2714
|
-
lower: bound
|
|
2715
|
-
});
|
|
2716
|
-
result.stats.boundsTightened++;
|
|
2717
|
-
changed = true;
|
|
2718
|
-
}
|
|
2719
|
-
}
|
|
2720
|
-
}
|
|
2721
|
-
result.removedConstraints.add(constraint);
|
|
2722
|
-
result.stats.constraintsRemoved++;
|
|
2723
|
-
}
|
|
2724
|
-
}
|
|
2725
|
-
for (const [variable, bounds] of result.tightenedBounds) {
|
|
2726
|
-
if (result.fixedVariables.has(variable)) continue;
|
|
2727
|
-
if (bounds.lower !== void 0 && bounds.upper !== void 0) {
|
|
2728
|
-
if (bounds.lower > bounds.upper + 1e-6) {
|
|
2729
|
-
result.isInfeasible = true;
|
|
2730
|
-
return result;
|
|
2731
|
-
}
|
|
2732
|
-
if (Math.abs(bounds.lower - bounds.upper) < 1e-6) {
|
|
2733
|
-
let fixedValue = bounds.lower;
|
|
2734
|
-
if (variable.isInteger) {
|
|
2735
|
-
fixedValue = Math.round(fixedValue);
|
|
2736
|
-
}
|
|
2737
|
-
result.fixedVariables.set(variable, fixedValue);
|
|
2738
|
-
result.stats.variablesFixed++;
|
|
2739
|
-
changed = true;
|
|
2740
|
-
}
|
|
2741
|
-
}
|
|
2742
|
-
if (variable.isInteger && bounds.lower !== void 0 && bounds.lower >= 0.5) {
|
|
2743
|
-
const upperBound = bounds.upper ?? Infinity;
|
|
2744
|
-
if (upperBound <= 1.5) {
|
|
2745
|
-
result.fixedVariables.set(variable, 1);
|
|
2746
|
-
result.stats.variablesFixed++;
|
|
2747
|
-
changed = true;
|
|
2748
|
-
}
|
|
2749
|
-
}
|
|
2750
|
-
if (variable.isInteger && bounds.upper !== void 0 && bounds.upper <= 0.5) {
|
|
2751
|
-
const lowerBound = bounds.lower ?? 0;
|
|
2752
|
-
if (lowerBound >= -0.5) {
|
|
2753
|
-
result.fixedVariables.set(variable, 0);
|
|
2754
|
-
result.stats.variablesFixed++;
|
|
2755
|
-
changed = true;
|
|
2756
|
-
}
|
|
2757
|
-
}
|
|
2758
|
-
}
|
|
2759
|
-
if (removeRedundantConstraints(model, result)) {
|
|
2760
|
-
changed = true;
|
|
2761
|
-
}
|
|
2762
|
-
if (result.isInfeasible) return result;
|
|
2763
|
-
if (tightenCoefficients(model, result)) {
|
|
2764
|
-
changed = true;
|
|
2765
|
-
}
|
|
2766
|
-
}
|
|
2767
|
-
return result;
|
|
2768
|
-
}
|
|
2769
|
-
|
|
2770
|
-
// src/model.ts
|
|
2771
|
-
var Model = class {
|
|
2772
|
-
constructor(precision, name, branchAndCutService) {
|
|
2773
|
-
this.tableau = new Tableau(precision, branchAndCutService);
|
|
2774
|
-
this.name = name;
|
|
2775
|
-
this.variables = [];
|
|
2776
|
-
this.integerVariables = [];
|
|
2777
|
-
this.unrestrictedVariables = {};
|
|
2778
|
-
this.constraints = [];
|
|
2779
|
-
this.nConstraints = 0;
|
|
2780
|
-
this.nVariables = 0;
|
|
2781
|
-
this.isMinimization = true;
|
|
2782
|
-
this.tableauInitialized = false;
|
|
2783
|
-
this.relaxationIndex = 1;
|
|
2784
|
-
this.useMIRCuts = false;
|
|
2785
|
-
this.checkForCycles = true;
|
|
2786
|
-
this.messages = [];
|
|
2787
|
-
this.availableIndexes = [];
|
|
2788
|
-
this.lastElementIndex = 0;
|
|
2789
|
-
this.usePresolve = true;
|
|
2790
|
-
this.presolveResult = null;
|
|
2791
|
-
}
|
|
2792
|
-
minimize() {
|
|
2793
|
-
this.isMinimization = true;
|
|
2794
|
-
return this;
|
|
2795
|
-
}
|
|
2796
|
-
maximize() {
|
|
2797
|
-
this.isMinimization = false;
|
|
2798
|
-
return this;
|
|
2799
|
-
}
|
|
2800
|
-
_getNewElementIndex() {
|
|
2801
|
-
if (this.availableIndexes.length > 0) {
|
|
2802
|
-
return this.availableIndexes.pop();
|
|
2803
|
-
}
|
|
2804
|
-
const index = this.lastElementIndex;
|
|
2805
|
-
this.lastElementIndex += 1;
|
|
2806
|
-
return index;
|
|
2807
|
-
}
|
|
2808
|
-
_addConstraint(constraint) {
|
|
2809
|
-
const slackVariable = constraint.slack;
|
|
2810
|
-
this.tableau.variablesPerIndex[slackVariable.index] = slackVariable;
|
|
2811
|
-
this.constraints.push(constraint);
|
|
2812
|
-
this.nConstraints += 1;
|
|
2813
|
-
if (this.tableauInitialized === true) {
|
|
2814
|
-
this.tableau.addConstraint(constraint);
|
|
2815
|
-
}
|
|
2816
|
-
}
|
|
2817
|
-
smallerThan(rhs) {
|
|
2818
|
-
const constraint = new Constraint(rhs, true, this.tableau.getNewElementIndex(), this);
|
|
2819
|
-
this._addConstraint(constraint);
|
|
2820
|
-
return constraint;
|
|
2821
|
-
}
|
|
2822
|
-
greaterThan(rhs) {
|
|
2823
|
-
const constraint = new Constraint(rhs, false, this.tableau.getNewElementIndex(), this);
|
|
2824
|
-
this._addConstraint(constraint);
|
|
2825
|
-
return constraint;
|
|
2826
|
-
}
|
|
2827
|
-
equal(rhs) {
|
|
2828
|
-
const constraintUpper = new Constraint(rhs, true, this.tableau.getNewElementIndex(), this);
|
|
2829
|
-
this._addConstraint(constraintUpper);
|
|
2830
|
-
const constraintLower = new Constraint(rhs, false, this.tableau.getNewElementIndex(), this);
|
|
2831
|
-
this._addConstraint(constraintLower);
|
|
2832
|
-
return new Equality(constraintUpper, constraintLower);
|
|
2833
|
-
}
|
|
2834
|
-
addVariable(cost, id, isInteger, isUnrestricted, priority) {
|
|
2835
|
-
if (typeof priority === "string") {
|
|
2836
|
-
switch (priority) {
|
|
2837
|
-
case "required":
|
|
2838
|
-
priority = 0;
|
|
2839
|
-
break;
|
|
2840
|
-
case "strong":
|
|
2841
|
-
priority = 1;
|
|
2842
|
-
break;
|
|
2843
|
-
case "medium":
|
|
2844
|
-
priority = 2;
|
|
2845
|
-
break;
|
|
2846
|
-
case "weak":
|
|
2847
|
-
priority = 3;
|
|
2848
|
-
break;
|
|
2849
|
-
default:
|
|
2850
|
-
priority = 0;
|
|
2851
|
-
break;
|
|
2852
|
-
}
|
|
2853
|
-
}
|
|
2854
|
-
const varIndex = this.tableau.getNewElementIndex();
|
|
2855
|
-
const identifier = id ?? "v" + varIndex;
|
|
2856
|
-
const normalizedCost = cost ?? 0;
|
|
2857
|
-
const normalizedPriority = priority ?? 0;
|
|
2858
|
-
let variable;
|
|
2859
|
-
if (isInteger) {
|
|
2860
|
-
const integerVariable = new IntegerVariable(
|
|
2861
|
-
identifier,
|
|
2862
|
-
normalizedCost,
|
|
2863
|
-
varIndex,
|
|
2864
|
-
normalizedPriority
|
|
2865
|
-
);
|
|
2866
|
-
this.integerVariables.push(integerVariable);
|
|
2867
|
-
variable = integerVariable;
|
|
2868
|
-
} else {
|
|
2869
|
-
variable = new Variable(identifier, normalizedCost, varIndex, normalizedPriority);
|
|
2870
|
-
}
|
|
2871
|
-
this.variables.push(variable);
|
|
2872
|
-
this.tableau.variablesPerIndex[varIndex] = variable;
|
|
2873
|
-
if (isUnrestricted) {
|
|
2874
|
-
this.unrestrictedVariables[varIndex] = true;
|
|
2875
|
-
}
|
|
2876
|
-
this.nVariables += 1;
|
|
2877
|
-
if (this.tableauInitialized === true) {
|
|
2878
|
-
this.tableau.addVariable(variable);
|
|
2879
|
-
}
|
|
2880
|
-
return variable;
|
|
2881
|
-
}
|
|
2882
|
-
_removeConstraint(constraint) {
|
|
2883
|
-
const idx = this.constraints.indexOf(constraint);
|
|
2884
|
-
if (idx === -1) {
|
|
2885
|
-
console.warn("[Model.removeConstraint] Constraint not present in model");
|
|
2886
|
-
return;
|
|
2887
|
-
}
|
|
2888
|
-
this.constraints.splice(idx, 1);
|
|
2889
|
-
this.nConstraints -= 1;
|
|
2890
|
-
if (this.tableauInitialized === true) {
|
|
2891
|
-
this.tableau.removeConstraint(constraint);
|
|
2892
|
-
}
|
|
2893
|
-
if (constraint.relaxation) {
|
|
2894
|
-
this.removeVariable(constraint.relaxation);
|
|
2895
|
-
}
|
|
2896
|
-
}
|
|
2897
|
-
//-------------------------------------------------------------------
|
|
2898
|
-
// For dynamic model modification
|
|
2899
|
-
//-------------------------------------------------------------------
|
|
2900
|
-
removeConstraint(constraint) {
|
|
2901
|
-
if (constraint.isEquality) {
|
|
2902
|
-
const equalityConstraint = constraint;
|
|
2903
|
-
this._removeConstraint(equalityConstraint.upperBound);
|
|
2904
|
-
this._removeConstraint(equalityConstraint.lowerBound);
|
|
2905
|
-
} else {
|
|
2906
|
-
this._removeConstraint(constraint);
|
|
2907
|
-
}
|
|
2908
|
-
return this;
|
|
2909
|
-
}
|
|
2910
|
-
removeVariable(variable) {
|
|
2911
|
-
const idx = this.variables.indexOf(variable);
|
|
2912
|
-
if (idx === -1) {
|
|
2913
|
-
console.warn("[Model.removeVariable] Variable not present in model");
|
|
2914
|
-
return;
|
|
2915
|
-
}
|
|
2916
|
-
this.variables.splice(idx, 1);
|
|
2917
|
-
if (this.tableauInitialized === true) {
|
|
2918
|
-
this.tableau.removeVariable(variable);
|
|
2919
|
-
}
|
|
2920
|
-
return this;
|
|
2921
|
-
}
|
|
2922
|
-
updateRightHandSide(constraint, difference) {
|
|
2923
|
-
if (this.tableauInitialized === true) {
|
|
2924
|
-
this.tableau.updateRightHandSide(constraint, difference);
|
|
2925
|
-
}
|
|
2926
|
-
return this;
|
|
2927
|
-
}
|
|
2928
|
-
updateConstraintCoefficient(constraint, variable, difference) {
|
|
2929
|
-
if (this.tableauInitialized === true) {
|
|
2930
|
-
this.tableau.updateConstraintCoefficient(constraint, variable, difference);
|
|
2931
|
-
}
|
|
2932
|
-
return this;
|
|
2933
|
-
}
|
|
2934
|
-
setCost(cost, variable) {
|
|
2935
|
-
let difference = cost - variable.cost;
|
|
2936
|
-
if (this.isMinimization === false) {
|
|
2937
|
-
difference = -difference;
|
|
2938
|
-
}
|
|
2939
|
-
variable.cost = cost;
|
|
2940
|
-
this.tableau.updateCost(variable, difference);
|
|
2941
|
-
return this;
|
|
2942
|
-
}
|
|
2943
|
-
//-------------------------------------------------------------------
|
|
2944
|
-
//-------------------------------------------------------------------
|
|
2945
|
-
loadJson(jsonModel) {
|
|
2946
|
-
this.isMinimization = jsonModel.opType !== "max";
|
|
2947
|
-
const variables = jsonModel.variables;
|
|
2948
|
-
const constraints = jsonModel.constraints;
|
|
2949
|
-
const constraintsMin = {};
|
|
2950
|
-
const constraintsMax = {};
|
|
2951
|
-
const constraintIds = Object.keys(constraints);
|
|
2952
|
-
const nConstraintIds = constraintIds.length;
|
|
2953
|
-
for (let c = 0; c < nConstraintIds; c += 1) {
|
|
2954
|
-
const constraintId = constraintIds[c];
|
|
2955
|
-
const constraint = constraints[constraintId];
|
|
2956
|
-
const equal = constraint.equal;
|
|
2957
|
-
const weight = constraint.weight;
|
|
2958
|
-
const priority = constraint.priority;
|
|
2959
|
-
const relaxed = weight !== void 0 || priority !== void 0;
|
|
2960
|
-
let lowerBound;
|
|
2961
|
-
let upperBound;
|
|
2962
|
-
if (equal === void 0) {
|
|
2963
|
-
const min = constraint.min;
|
|
2964
|
-
if (min !== void 0) {
|
|
2965
|
-
lowerBound = this.greaterThan(min);
|
|
2966
|
-
constraintsMin[constraintId] = lowerBound;
|
|
2967
|
-
if (relaxed) {
|
|
2968
|
-
lowerBound.relax(weight, priority);
|
|
2969
|
-
}
|
|
2970
|
-
}
|
|
2971
|
-
const max = constraint.max;
|
|
2972
|
-
if (max !== void 0) {
|
|
2973
|
-
upperBound = this.smallerThan(max);
|
|
2974
|
-
constraintsMax[constraintId] = upperBound;
|
|
2975
|
-
if (relaxed) {
|
|
2976
|
-
upperBound.relax(weight, priority);
|
|
2977
|
-
}
|
|
2978
|
-
}
|
|
2979
|
-
} else {
|
|
2980
|
-
lowerBound = this.greaterThan(equal);
|
|
2981
|
-
constraintsMin[constraintId] = lowerBound;
|
|
2982
|
-
upperBound = this.smallerThan(equal);
|
|
2983
|
-
constraintsMax[constraintId] = upperBound;
|
|
2984
|
-
const equality = new Equality(lowerBound, upperBound);
|
|
2985
|
-
if (relaxed) {
|
|
2986
|
-
equality.relax(weight, priority);
|
|
2987
|
-
}
|
|
2988
|
-
}
|
|
2989
|
-
}
|
|
2990
|
-
const variableIds = Object.keys(variables);
|
|
2991
|
-
const nVariables = variableIds.length;
|
|
2992
|
-
this.tolerance = jsonModel.tolerance || 0;
|
|
2993
|
-
if (jsonModel.timeout) {
|
|
2994
|
-
this.timeout = jsonModel.timeout;
|
|
2995
|
-
}
|
|
2996
|
-
if (jsonModel.options) {
|
|
2997
|
-
if (jsonModel.options.timeout) {
|
|
2998
|
-
this.timeout = jsonModel.options.timeout;
|
|
2999
|
-
}
|
|
3000
|
-
if (this.tolerance === 0) {
|
|
3001
|
-
this.tolerance = jsonModel.options.tolerance || 0;
|
|
3002
|
-
}
|
|
3003
|
-
if (jsonModel.options.useMIRCuts) {
|
|
3004
|
-
this.useMIRCuts = jsonModel.options.useMIRCuts;
|
|
3005
|
-
}
|
|
3006
|
-
if (typeof jsonModel.options.exitOnCycles === "undefined") {
|
|
3007
|
-
this.checkForCycles = true;
|
|
3008
|
-
} else {
|
|
3009
|
-
this.checkForCycles = jsonModel.options.exitOnCycles;
|
|
3010
|
-
}
|
|
3011
|
-
if (jsonModel.options.keep_solutions) {
|
|
3012
|
-
this.keep_solutions = jsonModel.options.keep_solutions;
|
|
3013
|
-
} else {
|
|
3014
|
-
this.keep_solutions = false;
|
|
3015
|
-
}
|
|
3016
|
-
if (jsonModel.options.presolve !== void 0) {
|
|
3017
|
-
this.usePresolve = jsonModel.options.presolve;
|
|
3018
|
-
}
|
|
3019
|
-
}
|
|
3020
|
-
const integerVarIds = jsonModel.ints || {};
|
|
3021
|
-
const binaryVarIds = jsonModel.binaries || {};
|
|
3022
|
-
const unrestrictedVarIds = jsonModel.unrestricted || {};
|
|
3023
|
-
const objectiveName = jsonModel.optimize;
|
|
3024
|
-
for (let v = 0; v < nVariables; v += 1) {
|
|
3025
|
-
const variableId = variableIds[v];
|
|
3026
|
-
const variableConstraints = variables[variableId];
|
|
3027
|
-
const cost = variableConstraints[objectiveName] || 0;
|
|
3028
|
-
const isBinary = !!binaryVarIds[variableId];
|
|
3029
|
-
const isInteger = !!integerVarIds[variableId] || isBinary;
|
|
3030
|
-
const isUnrestricted = !!unrestrictedVarIds[variableId];
|
|
3031
|
-
const variable = this.addVariable(cost, variableId, isInteger, isUnrestricted);
|
|
3032
|
-
if (isBinary) {
|
|
3033
|
-
this.smallerThan(1).addTerm(1, variable);
|
|
3034
|
-
}
|
|
3035
|
-
const constraintNames = Object.keys(variableConstraints);
|
|
3036
|
-
for (let c = 0; c < constraintNames.length; c += 1) {
|
|
3037
|
-
const constraintName = constraintNames[c];
|
|
3038
|
-
if (constraintName === objectiveName) {
|
|
3039
|
-
continue;
|
|
3040
|
-
}
|
|
3041
|
-
const coefficient = variableConstraints[constraintName];
|
|
3042
|
-
const constraintMin = constraintsMin[constraintName];
|
|
3043
|
-
if (constraintMin !== void 0) {
|
|
3044
|
-
constraintMin.addTerm(coefficient, variable);
|
|
3045
|
-
}
|
|
3046
|
-
const constraintMax = constraintsMax[constraintName];
|
|
3047
|
-
if (constraintMax !== void 0) {
|
|
3048
|
-
constraintMax.addTerm(coefficient, variable);
|
|
3049
|
-
}
|
|
3050
|
-
}
|
|
3051
|
-
}
|
|
3052
|
-
return this;
|
|
3053
|
-
}
|
|
3054
|
-
//-------------------------------------------------------------------
|
|
3055
|
-
//-------------------------------------------------------------------
|
|
3056
|
-
getNumberOfIntegerVariables() {
|
|
3057
|
-
return this.integerVariables.length;
|
|
3058
|
-
}
|
|
3059
|
-
solve() {
|
|
3060
|
-
if (this.usePresolve && this.presolveResult === null) {
|
|
3061
|
-
this.presolveResult = presolve(this);
|
|
3062
|
-
if (this.presolveResult.isInfeasible) {
|
|
3063
|
-
this.tableau.feasible = false;
|
|
3064
|
-
return this.tableau.getSolution();
|
|
3065
|
-
}
|
|
3066
|
-
this.applyPresolveReductions(this.presolveResult);
|
|
3067
|
-
}
|
|
3068
|
-
if (this.tableauInitialized === false) {
|
|
3069
|
-
this.tableau.setModel(this);
|
|
3070
|
-
this.tableauInitialized = true;
|
|
3071
|
-
}
|
|
3072
|
-
return this.tableau.solve();
|
|
3073
|
-
}
|
|
3074
|
-
/**
|
|
3075
|
-
* Apply presolve reductions to the model.
|
|
3076
|
-
* Sets fixed variable values and removes redundant constraints.
|
|
3077
|
-
*/
|
|
3078
|
-
applyPresolveReductions(result) {
|
|
3079
|
-
for (const [variable, value] of result.fixedVariables) {
|
|
3080
|
-
variable.value = value;
|
|
3081
|
-
variable.cost = 0;
|
|
3082
|
-
}
|
|
3083
|
-
}
|
|
3084
|
-
isFeasible() {
|
|
3085
|
-
return this.tableau.feasible;
|
|
3086
|
-
}
|
|
3087
|
-
save() {
|
|
3088
|
-
this.tableau.save();
|
|
3089
|
-
}
|
|
3090
|
-
restore() {
|
|
3091
|
-
this.tableau.restore();
|
|
3092
|
-
}
|
|
3093
|
-
activateMIRCuts(useMIRCuts) {
|
|
3094
|
-
this.useMIRCuts = useMIRCuts;
|
|
3095
|
-
}
|
|
3096
|
-
debug(debugCheckForCycles) {
|
|
3097
|
-
this.checkForCycles = debugCheckForCycles;
|
|
3098
|
-
}
|
|
3099
|
-
log(message) {
|
|
3100
|
-
return this.tableau.log(message);
|
|
3101
|
-
}
|
|
3102
|
-
};
|
|
3103
|
-
var model_default = Model;
|
|
3104
|
-
|
|
3105
|
-
// src/validation.ts
|
|
3106
|
-
var validation_exports = {};
|
|
3107
|
-
__export(validation_exports, {
|
|
3108
|
-
CleanObjectiveAttributes: () => CleanObjectiveAttributes,
|
|
3109
|
-
WarnOnTypos: () => WarnOnTypos
|
|
3110
|
-
});
|
|
3111
|
-
var PROPERTY_TYPOS = {
|
|
3112
|
-
optype: "opType",
|
|
3113
|
-
OpType: "opType",
|
|
3114
|
-
op_type: "opType",
|
|
3115
|
-
type: "opType",
|
|
3116
|
-
optimise: "optimize",
|
|
3117
|
-
Optimize: "optimize",
|
|
3118
|
-
objective: "optimize",
|
|
3119
|
-
constraint: "constraints",
|
|
3120
|
-
Constraints: "constraints",
|
|
3121
|
-
variable: "variables",
|
|
3122
|
-
Variables: "variables",
|
|
3123
|
-
vars: "variables",
|
|
3124
|
-
int: "ints",
|
|
3125
|
-
integers: "ints",
|
|
3126
|
-
Ints: "ints",
|
|
3127
|
-
binary: "binaries",
|
|
3128
|
-
Binaries: "binaries"
|
|
3129
|
-
};
|
|
3130
|
-
var CONSTRAINT_TYPOS = {
|
|
3131
|
-
minimum: "min",
|
|
3132
|
-
maximum: "max",
|
|
3133
|
-
Min: "min",
|
|
3134
|
-
Max: "max",
|
|
3135
|
-
eq: "equal",
|
|
3136
|
-
equals: "equal",
|
|
3137
|
-
Equal: "equal"
|
|
3138
|
-
};
|
|
3139
|
-
function WarnOnTypos(model) {
|
|
3140
|
-
const modelKeys = Object.keys(model);
|
|
3141
|
-
for (const key of modelKeys) {
|
|
3142
|
-
const correction = PROPERTY_TYPOS[key];
|
|
3143
|
-
if (correction) {
|
|
3144
|
-
console.warn(
|
|
3145
|
-
`[jsLPSolver] Warning: Model has '${key}' but expected '${correction}'. This may cause unexpected behavior.`
|
|
3146
|
-
);
|
|
3147
|
-
}
|
|
3148
|
-
}
|
|
3149
|
-
if (!model.optimize && !modelKeys.some((k) => PROPERTY_TYPOS[k] === "optimize")) {
|
|
3150
|
-
console.warn(
|
|
3151
|
-
`[jsLPSolver] Warning: Model is missing 'optimize' property. The solver needs to know which attribute to optimize.`
|
|
3152
|
-
);
|
|
3153
|
-
}
|
|
3154
|
-
if (!model.opType && !modelKeys.some((k) => PROPERTY_TYPOS[k] === "opType")) {
|
|
3155
|
-
console.warn(
|
|
3156
|
-
`[jsLPSolver] Warning: Model is missing 'opType' property. Defaulting to 'max'. Use 'opType: "max"' or 'opType: "min"' to be explicit.`
|
|
3157
|
-
);
|
|
3158
|
-
}
|
|
3159
|
-
if (model.constraints) {
|
|
3160
|
-
for (const [constraintName, constraint] of Object.entries(model.constraints)) {
|
|
3161
|
-
if (typeof constraint === "object" && constraint !== null) {
|
|
3162
|
-
for (const prop of Object.keys(constraint)) {
|
|
3163
|
-
const correction = CONSTRAINT_TYPOS[prop];
|
|
3164
|
-
if (correction) {
|
|
3165
|
-
console.warn(
|
|
3166
|
-
`[jsLPSolver] Warning: Constraint '${constraintName}' has '${prop}' but expected '${correction}'.`
|
|
3167
|
-
);
|
|
3168
|
-
}
|
|
3169
|
-
}
|
|
3170
|
-
}
|
|
3171
|
-
}
|
|
3172
|
-
}
|
|
3173
|
-
return model;
|
|
3174
|
-
}
|
|
3175
|
-
function CleanObjectiveAttributes(model) {
|
|
3176
|
-
let fakeAttr;
|
|
3177
|
-
let x;
|
|
3178
|
-
let z;
|
|
3179
|
-
if (typeof model.optimize === "string") {
|
|
3180
|
-
if (model.constraints[model.optimize]) {
|
|
3181
|
-
fakeAttr = Math.random();
|
|
3182
|
-
for (x in model.variables) {
|
|
3183
|
-
if (model.variables[x][model.optimize]) {
|
|
3184
|
-
model.variables[x][fakeAttr] = model.variables[x][model.optimize];
|
|
3185
|
-
}
|
|
3186
|
-
}
|
|
3187
|
-
model.constraints[fakeAttr] = model.constraints[model.optimize];
|
|
3188
|
-
delete model.constraints[model.optimize];
|
|
3189
|
-
return model;
|
|
3190
|
-
}
|
|
3191
|
-
return model;
|
|
3192
|
-
} else {
|
|
3193
|
-
for (z in model.optimize) {
|
|
3194
|
-
if (model.constraints[z]) {
|
|
3195
|
-
if (model.constraints[z] === "equal") {
|
|
3196
|
-
delete model.optimize[z];
|
|
3197
|
-
} else {
|
|
3198
|
-
fakeAttr = Math.random();
|
|
3199
|
-
for (x in model.variables) {
|
|
3200
|
-
if (model.variables[x][z]) {
|
|
3201
|
-
model.variables[x][fakeAttr] = model.variables[x][z];
|
|
3202
|
-
}
|
|
3203
|
-
}
|
|
3204
|
-
model.constraints[fakeAttr] = model.constraints[z];
|
|
3205
|
-
delete model.constraints[z];
|
|
3206
|
-
}
|
|
3207
|
-
}
|
|
3208
|
-
}
|
|
3209
|
-
return model;
|
|
3210
|
-
}
|
|
3211
|
-
}
|
|
3212
|
-
|
|
3213
|
-
// src/external/main.ts
|
|
3214
|
-
var import_main = __toESM(require_main());
|
|
3215
|
-
var lpsolveSolver = import_main.default;
|
|
3216
|
-
var External = {
|
|
3217
|
-
lpsolve: lpsolveSolver
|
|
3218
|
-
};
|
|
3219
|
-
var main_default = External;
|
|
3220
|
-
|
|
3221
|
-
// src/polyopt.ts
|
|
3222
|
-
function cloneModel(model) {
|
|
3223
|
-
return JSON.parse(JSON.stringify(model));
|
|
3224
|
-
}
|
|
3225
|
-
function asPolyoptSolution(value) {
|
|
3226
|
-
if (value && typeof value === "object") {
|
|
3227
|
-
return value;
|
|
3228
|
-
}
|
|
3229
|
-
throw new Error("Polyopt requires the solver to return an object result.");
|
|
3230
|
-
}
|
|
3231
|
-
function backfillObjectiveAttributes(solution, workingModel, objectiveKeys) {
|
|
3232
|
-
for (const attribute of objectiveKeys) {
|
|
3233
|
-
if (workingModel.variables[attribute]) {
|
|
3234
|
-
continue;
|
|
3235
|
-
}
|
|
3236
|
-
if (typeof solution[attribute] !== "number") {
|
|
3237
|
-
solution[attribute] = 0;
|
|
3238
|
-
}
|
|
3239
|
-
for (const [variableName, coefficients] of Object.entries(workingModel.variables)) {
|
|
3240
|
-
const variableContribution = coefficients[attribute];
|
|
3241
|
-
const solvedValue = solution[variableName];
|
|
3242
|
-
if (typeof variableContribution === "number" && typeof solvedValue === "number") {
|
|
3243
|
-
solution[attribute] += solvedValue * variableContribution;
|
|
3244
|
-
}
|
|
3245
|
-
}
|
|
3246
|
-
}
|
|
3247
|
-
}
|
|
3248
|
-
function buildVectorKey(solution, objectiveKeys) {
|
|
3249
|
-
const suffix = objectiveKeys.map((key) => {
|
|
3250
|
-
const value = solution[key];
|
|
3251
|
-
return typeof value === "number" ? Math.round(value * 1e3) / 1e3 : 0;
|
|
3252
|
-
}).join("-");
|
|
3253
|
-
return `base-${suffix}`;
|
|
3254
|
-
}
|
|
3255
|
-
function computeRanges(vertices) {
|
|
3256
|
-
const ranges = {};
|
|
3257
|
-
for (const vertex of vertices) {
|
|
3258
|
-
for (const [key, value] of Object.entries(vertex)) {
|
|
3259
|
-
if (typeof value !== "number") {
|
|
3260
|
-
continue;
|
|
3261
|
-
}
|
|
3262
|
-
const current = ranges[key] ?? {
|
|
3263
|
-
min: Number.POSITIVE_INFINITY,
|
|
3264
|
-
max: Number.NEGATIVE_INFINITY
|
|
3265
|
-
};
|
|
3266
|
-
ranges[key] = {
|
|
3267
|
-
min: Math.min(current.min, value),
|
|
3268
|
-
max: Math.max(current.max, value)
|
|
3269
|
-
};
|
|
3270
|
-
}
|
|
3271
|
-
}
|
|
3272
|
-
for (const vertex of vertices) {
|
|
3273
|
-
for (const key of Object.keys(ranges)) {
|
|
3274
|
-
if (typeof vertex[key] !== "number") {
|
|
3275
|
-
vertex[key] = 0;
|
|
3276
|
-
}
|
|
3277
|
-
ranges[key].min = Math.min(ranges[key].min, vertex[key]);
|
|
3278
|
-
ranges[key].max = Math.max(ranges[key].max, vertex[key]);
|
|
3279
|
-
}
|
|
3280
|
-
}
|
|
3281
|
-
for (const [key, range] of Object.entries(ranges)) {
|
|
3282
|
-
if (!Number.isFinite(range.min)) {
|
|
3283
|
-
ranges[key] = { min: 0, max: 0 };
|
|
3284
|
-
}
|
|
3285
|
-
}
|
|
3286
|
-
return ranges;
|
|
3287
|
-
}
|
|
3288
|
-
function Polyopt(solver2, model) {
|
|
3289
|
-
const workingModel = cloneModel(model);
|
|
3290
|
-
const objectives = workingModel.optimize;
|
|
3291
|
-
const objectiveKeys = Object.keys(objectives);
|
|
3292
|
-
if (objectiveKeys.length === 0) {
|
|
3293
|
-
throw new Error("Multi-objective solve requires at least one objective definition.");
|
|
3294
|
-
}
|
|
3295
|
-
const workingRecord = workingModel;
|
|
3296
|
-
delete workingRecord.optimize;
|
|
3297
|
-
delete workingRecord.opType;
|
|
3298
|
-
const aggregatedTargets = {};
|
|
3299
|
-
const uniqueVectors = /* @__PURE__ */ new Set();
|
|
3300
|
-
const paretoVertices = [];
|
|
3301
|
-
for (const key of objectiveKeys) {
|
|
3302
|
-
aggregatedTargets[key] = 0;
|
|
3303
|
-
}
|
|
3304
|
-
for (const objectiveName of objectiveKeys) {
|
|
3305
|
-
workingModel.optimize = objectiveName;
|
|
3306
|
-
workingModel.opType = objectives[objectiveName];
|
|
3307
|
-
const solution = asPolyoptSolution(solver2.Solve(workingModel, void 0, void 0, true));
|
|
3308
|
-
backfillObjectiveAttributes(solution, workingModel, objectiveKeys);
|
|
3309
|
-
const vectorKey = buildVectorKey(solution, objectiveKeys);
|
|
3310
|
-
if (uniqueVectors.has(vectorKey)) {
|
|
3311
|
-
continue;
|
|
3312
|
-
}
|
|
3313
|
-
uniqueVectors.add(vectorKey);
|
|
3314
|
-
for (const key of objectiveKeys) {
|
|
3315
|
-
const value = solution[key];
|
|
3316
|
-
if (typeof value === "number") {
|
|
3317
|
-
aggregatedTargets[key] += value;
|
|
3318
|
-
}
|
|
3319
|
-
}
|
|
3320
|
-
const { feasible, result, bounded, ...paretoPayload } = solution;
|
|
3321
|
-
paretoVertices.push(paretoPayload);
|
|
3322
|
-
}
|
|
3323
|
-
for (const key of objectiveKeys) {
|
|
3324
|
-
workingModel.constraints[key] = { equal: aggregatedTargets[key] / uniqueVectors.size };
|
|
3325
|
-
}
|
|
3326
|
-
const syntheticObjective = `cheater-${Math.random()}`;
|
|
3327
|
-
workingModel.optimize = syntheticObjective;
|
|
3328
|
-
workingModel.opType = "max";
|
|
3329
|
-
for (const variable of Object.values(workingModel.variables)) {
|
|
3330
|
-
variable[syntheticObjective] = 1;
|
|
3331
|
-
}
|
|
3332
|
-
const ranges = computeRanges(paretoVertices);
|
|
3333
|
-
const midpoint = asPolyoptSolution(solver2.Solve(workingModel, void 0, void 0, true));
|
|
3334
|
-
return {
|
|
3335
|
-
midpoint,
|
|
3336
|
-
vertices: paretoVertices,
|
|
3337
|
-
ranges
|
|
3338
|
-
};
|
|
3339
|
-
}
|
|
3340
|
-
|
|
3341
|
-
// src/main.ts
|
|
3342
|
-
var import_reformat = __toESM(require_reformat());
|
|
3343
|
-
|
|
3344
|
-
// src/tableau/enhanced-branch-and-cut.ts
|
|
3345
|
-
function createCut2(type, varIndex, value) {
|
|
3346
|
-
return { type, varIndex, value };
|
|
3347
|
-
}
|
|
3348
|
-
function createBranch2(relaxedEvaluation, cuts, depth) {
|
|
3349
|
-
return { relaxedEvaluation, cuts, depth };
|
|
3350
|
-
}
|
|
3351
|
-
function createEnhancedBranchAndCutService(options = {}) {
|
|
3352
|
-
const {
|
|
3353
|
-
nodeSelection = "hybrid",
|
|
3354
|
-
branching = "pseudocost",
|
|
3355
|
-
useDiving = true,
|
|
3356
|
-
strongBranchingCandidates = 5
|
|
3357
|
-
} = options;
|
|
3358
|
-
const pseudoCosts = /* @__PURE__ */ new Map();
|
|
3359
|
-
const getPseudoCost = (varIndex) => {
|
|
3360
|
-
let data = pseudoCosts.get(varIndex);
|
|
3361
|
-
if (!data) {
|
|
3362
|
-
data = { upSum: 0, upCount: 0, downSum: 0, downCount: 0 };
|
|
3363
|
-
pseudoCosts.set(varIndex, data);
|
|
3364
|
-
}
|
|
3365
|
-
return data;
|
|
3366
|
-
};
|
|
3367
|
-
const updatePseudoCost = (varIndex, direction, improvement, fraction) => {
|
|
3368
|
-
const data = getPseudoCost(varIndex);
|
|
3369
|
-
const normalizedImprovement = improvement / (direction === "up" ? 1 - fraction : fraction);
|
|
3370
|
-
if (direction === "up") {
|
|
3371
|
-
data.upSum += normalizedImprovement;
|
|
3372
|
-
data.upCount++;
|
|
3373
|
-
} else {
|
|
3374
|
-
data.downSum += normalizedImprovement;
|
|
3375
|
-
data.downCount++;
|
|
3376
|
-
}
|
|
3377
|
-
};
|
|
3378
|
-
const getScore = (varIndex, fraction) => {
|
|
3379
|
-
const data = getPseudoCost(varIndex);
|
|
3380
|
-
const upPseudo = data.upCount > 0 ? data.upSum / data.upCount : 1;
|
|
3381
|
-
const downPseudo = data.downCount > 0 ? data.downSum / data.downCount : 1;
|
|
3382
|
-
const upEstimate = upPseudo * (1 - fraction);
|
|
3383
|
-
const downEstimate = downPseudo * fraction;
|
|
3384
|
-
return Math.max(upEstimate, 1e-6) * Math.max(downEstimate, 1e-6);
|
|
3385
|
-
};
|
|
3386
|
-
const selectBranchingVariable = (tableau, currentEval) => {
|
|
3387
|
-
const width = tableau.width;
|
|
3388
|
-
const matrix = tableau.matrix;
|
|
3389
|
-
const rhsColumn = tableau.rhsColumn;
|
|
3390
|
-
const integerVars = tableau.model.integerVariables;
|
|
3391
|
-
const precision = tableau.precision;
|
|
3392
|
-
let candidates = [];
|
|
3393
|
-
for (const variable of integerVars) {
|
|
3394
|
-
const varIndex = variable.index;
|
|
3395
|
-
const row = tableau.rowByVarIndex[varIndex];
|
|
3396
|
-
if (row !== -1) {
|
|
3397
|
-
const value = matrix[row * width + rhsColumn];
|
|
3398
|
-
const fraction = Math.abs(value - Math.round(value));
|
|
3399
|
-
if (fraction > precision) {
|
|
3400
|
-
candidates.push({ index: varIndex, value, fraction });
|
|
3401
|
-
}
|
|
3402
|
-
}
|
|
3403
|
-
}
|
|
3404
|
-
if (candidates.length === 0) return null;
|
|
3405
|
-
if (branching === "most-fractional") {
|
|
3406
|
-
candidates.sort((a, b) => b.fraction - a.fraction);
|
|
3407
|
-
return { index: candidates[0].index, value: candidates[0].value };
|
|
3408
|
-
}
|
|
3409
|
-
if (branching === "pseudocost") {
|
|
3410
|
-
let bestScore = -Infinity;
|
|
3411
|
-
let bestCandidate = candidates[0];
|
|
3412
|
-
for (const candidate of candidates) {
|
|
3413
|
-
const score = getScore(candidate.index, candidate.fraction);
|
|
3414
|
-
if (score > bestScore) {
|
|
3415
|
-
bestScore = score;
|
|
3416
|
-
bestCandidate = candidate;
|
|
3417
|
-
}
|
|
3418
|
-
}
|
|
3419
|
-
return { index: bestCandidate.index, value: bestCandidate.value };
|
|
3420
|
-
}
|
|
3421
|
-
if (branching === "strong") {
|
|
3422
|
-
candidates.sort((a, b) => b.fraction - a.fraction);
|
|
3423
|
-
candidates = candidates.slice(0, strongBranchingCandidates);
|
|
3424
|
-
let bestScore = -Infinity;
|
|
3425
|
-
let bestCandidate = candidates[0];
|
|
3426
|
-
for (const candidate of candidates) {
|
|
3427
|
-
const data = getPseudoCost(candidate.index);
|
|
3428
|
-
if (data.upCount >= 2 && data.downCount >= 2) {
|
|
3429
|
-
const score = getScore(candidate.index, candidate.fraction);
|
|
3430
|
-
if (score > bestScore) {
|
|
3431
|
-
bestScore = score;
|
|
3432
|
-
bestCandidate = candidate;
|
|
3433
|
-
}
|
|
3434
|
-
} else {
|
|
3435
|
-
const score = candidate.fraction * (1 - candidate.fraction);
|
|
3436
|
-
if (score > bestScore) {
|
|
3437
|
-
bestScore = score;
|
|
3438
|
-
bestCandidate = candidate;
|
|
3439
|
-
}
|
|
3440
|
-
}
|
|
3441
|
-
}
|
|
3442
|
-
return { index: bestCandidate.index, value: bestCandidate.value };
|
|
3443
|
-
}
|
|
3444
|
-
return { index: candidates[0].index, value: candidates[0].value };
|
|
3445
|
-
};
|
|
3446
|
-
const applyCuts = (tableau, branchingCuts) => {
|
|
3447
|
-
tableau.restore();
|
|
3448
|
-
tableau.addCutConstraints(branchingCuts);
|
|
3449
|
-
tableau.simplex();
|
|
3450
|
-
if (tableau.model?.useMIRCuts && tableau.feasible) {
|
|
3451
|
-
let fractionalVolumeImproved = true;
|
|
3452
|
-
let mirIterations = 0;
|
|
3453
|
-
const maxMIRIterations = 3;
|
|
3454
|
-
while (fractionalVolumeImproved && mirIterations < maxMIRIterations) {
|
|
3455
|
-
const fractionalVolumeBefore = tableau.computeFractionalVolume(true);
|
|
3456
|
-
tableau.applyMIRCuts();
|
|
3457
|
-
tableau.simplex();
|
|
3458
|
-
const fractionalVolumeAfter = tableau.computeFractionalVolume(true);
|
|
3459
|
-
mirIterations++;
|
|
3460
|
-
if (fractionalVolumeAfter >= 0.9 * fractionalVolumeBefore) {
|
|
3461
|
-
fractionalVolumeImproved = false;
|
|
3462
|
-
}
|
|
3463
|
-
}
|
|
3464
|
-
}
|
|
3465
|
-
};
|
|
3466
|
-
const branchAndCut = (tableau) => {
|
|
3467
|
-
const branches = new BranchMinHeap();
|
|
3468
|
-
const depthFirstStack = [];
|
|
3469
|
-
let iterations = 0;
|
|
3470
|
-
const tolerance = tableau.model?.tolerance ?? 0;
|
|
3471
|
-
let toleranceFlag = true;
|
|
3472
|
-
let terminalTime = 1e99;
|
|
3473
|
-
if (tableau.model?.timeout) {
|
|
3474
|
-
terminalTime = Date.now() + tableau.model.timeout;
|
|
3475
|
-
}
|
|
3476
|
-
let bestEvaluation = Infinity;
|
|
3477
|
-
let bestBranch = null;
|
|
3478
|
-
const bestOptionalObjectivesEvaluations = [];
|
|
3479
|
-
for (let oInit = 0; oInit < tableau.optionalObjectives.length; oInit += 1) {
|
|
3480
|
-
bestOptionalObjectivesEvaluations.push(Infinity);
|
|
3481
|
-
}
|
|
3482
|
-
const switchTobestFirstAfterSolutions = 1;
|
|
3483
|
-
let solutionsFound = 0;
|
|
3484
|
-
let useDepthFirst = nodeSelection === "depth-first" || nodeSelection === "hybrid";
|
|
3485
|
-
const branch = createBranch2(-Infinity, [], 0);
|
|
3486
|
-
let acceptableThreshold;
|
|
3487
|
-
if (useDepthFirst) {
|
|
3488
|
-
depthFirstStack.push(branch);
|
|
3489
|
-
} else {
|
|
3490
|
-
branches.push(branch);
|
|
3491
|
-
}
|
|
3492
|
-
while ((useDepthFirst ? depthFirstStack.length > 0 : !branches.isEmpty()) && toleranceFlag === true && Date.now() < terminalTime) {
|
|
3493
|
-
if (tableau.model?.isMinimization) {
|
|
3494
|
-
acceptableThreshold = tableau.bestPossibleEval * (1 + tolerance);
|
|
3495
|
-
} else {
|
|
3496
|
-
acceptableThreshold = tableau.bestPossibleEval * (1 - tolerance);
|
|
3497
|
-
}
|
|
3498
|
-
if (tolerance > 0 && bestEvaluation < acceptableThreshold) {
|
|
3499
|
-
toleranceFlag = false;
|
|
3500
|
-
}
|
|
3501
|
-
let activeBranch;
|
|
3502
|
-
if (useDepthFirst && depthFirstStack.length > 0) {
|
|
3503
|
-
activeBranch = depthFirstStack.pop();
|
|
3504
|
-
} else if (!branches.isEmpty()) {
|
|
3505
|
-
activeBranch = branches.pop();
|
|
3506
|
-
} else {
|
|
3507
|
-
break;
|
|
3508
|
-
}
|
|
3509
|
-
if (activeBranch.relaxedEvaluation > bestEvaluation) {
|
|
3510
|
-
continue;
|
|
3511
|
-
}
|
|
3512
|
-
const cuts = activeBranch.cuts;
|
|
3513
|
-
const parentEval = tableau.evaluation;
|
|
3514
|
-
applyCuts(tableau, cuts);
|
|
3515
|
-
iterations++;
|
|
3516
|
-
if (!tableau.feasible) {
|
|
3517
|
-
continue;
|
|
3518
|
-
}
|
|
3519
|
-
const evaluation = tableau.evaluation;
|
|
3520
|
-
if (evaluation > bestEvaluation) {
|
|
3521
|
-
continue;
|
|
3522
|
-
}
|
|
3523
|
-
if (cuts.length > 0 && parentEval !== 0) {
|
|
3524
|
-
const lastCut = cuts[cuts.length - 1];
|
|
3525
|
-
const improvement = Math.abs(evaluation - parentEval);
|
|
3526
|
-
const fraction = 0.5;
|
|
3527
|
-
updatePseudoCost(
|
|
3528
|
-
lastCut.varIndex,
|
|
3529
|
-
lastCut.type === "min" ? "up" : "down",
|
|
3530
|
-
improvement,
|
|
3531
|
-
fraction
|
|
3532
|
-
);
|
|
3533
|
-
}
|
|
3534
|
-
if (evaluation === bestEvaluation) {
|
|
3535
|
-
let isCurrentEvaluationWorse = true;
|
|
3536
|
-
for (let o = 0; o < tableau.optionalObjectives.length; o++) {
|
|
3537
|
-
if (tableau.optionalObjectives[o].reducedCosts[0] > bestOptionalObjectivesEvaluations[o]) {
|
|
3538
|
-
break;
|
|
3539
|
-
} else if (tableau.optionalObjectives[o].reducedCosts[0] < bestOptionalObjectivesEvaluations[o]) {
|
|
3540
|
-
isCurrentEvaluationWorse = false;
|
|
3541
|
-
break;
|
|
3542
|
-
}
|
|
3543
|
-
}
|
|
3544
|
-
if (isCurrentEvaluationWorse) {
|
|
3545
|
-
continue;
|
|
3546
|
-
}
|
|
3547
|
-
}
|
|
3548
|
-
if (tableau.isIntegral()) {
|
|
3549
|
-
tableau.__isIntegral = true;
|
|
3550
|
-
solutionsFound++;
|
|
3551
|
-
if (iterations === 1) {
|
|
3552
|
-
tableau.branchAndCutIterations = iterations;
|
|
3553
|
-
return;
|
|
3554
|
-
}
|
|
3555
|
-
bestBranch = activeBranch;
|
|
3556
|
-
bestEvaluation = evaluation;
|
|
3557
|
-
for (let oCopy = 0; oCopy < tableau.optionalObjectives.length; oCopy++) {
|
|
3558
|
-
bestOptionalObjectivesEvaluations[oCopy] = tableau.optionalObjectives[oCopy].reducedCosts[0];
|
|
3559
|
-
}
|
|
3560
|
-
if (tableau.model?.keep_solutions) {
|
|
3561
|
-
const nowSolution = tableau.model.tableau.getSolution();
|
|
3562
|
-
const store = nowSolution.generateSolutionSet();
|
|
3563
|
-
store.result = nowSolution.evaluation;
|
|
3564
|
-
if (!tableau.model.solutions) {
|
|
3565
|
-
tableau.model.solutions = [];
|
|
3566
|
-
}
|
|
3567
|
-
tableau.model.solutions.push(store);
|
|
3568
|
-
}
|
|
3569
|
-
if (nodeSelection === "hybrid" && solutionsFound >= switchTobestFirstAfterSolutions) {
|
|
3570
|
-
useDepthFirst = false;
|
|
3571
|
-
while (depthFirstStack.length > 0) {
|
|
3572
|
-
branches.push(depthFirstStack.pop());
|
|
3573
|
-
}
|
|
3574
|
-
}
|
|
3575
|
-
} else {
|
|
3576
|
-
if (iterations === 1) {
|
|
3577
|
-
tableau.save();
|
|
3578
|
-
}
|
|
3579
|
-
const variable = selectBranchingVariable(tableau, evaluation);
|
|
3580
|
-
if (!variable) continue;
|
|
3581
|
-
const varIndex = variable.index;
|
|
3582
|
-
const varValue = variable.value;
|
|
3583
|
-
const cutsHigh = [];
|
|
3584
|
-
const cutsLow = [];
|
|
3585
|
-
const nCuts = cuts.length;
|
|
3586
|
-
for (let c = 0; c < nCuts; c++) {
|
|
3587
|
-
const cut = cuts[c];
|
|
3588
|
-
if (cut.varIndex === varIndex) {
|
|
3589
|
-
if (cut.type === "min") {
|
|
3590
|
-
cutsLow.push(cut);
|
|
3591
|
-
} else {
|
|
3592
|
-
cutsHigh.push(cut);
|
|
3593
|
-
}
|
|
3594
|
-
} else {
|
|
3595
|
-
cutsHigh.push(cut);
|
|
3596
|
-
cutsLow.push(cut);
|
|
3597
|
-
}
|
|
3598
|
-
}
|
|
3599
|
-
const min = Math.ceil(varValue);
|
|
3600
|
-
const max = Math.floor(varValue);
|
|
3601
|
-
const cutHigh = createCut2("min", varIndex, min);
|
|
3602
|
-
cutsHigh.push(cutHigh);
|
|
3603
|
-
const cutLow = createCut2("max", varIndex, max);
|
|
3604
|
-
cutsLow.push(cutLow);
|
|
3605
|
-
const newDepth = activeBranch.depth + 1;
|
|
3606
|
-
if (useDepthFirst) {
|
|
3607
|
-
depthFirstStack.push(createBranch2(evaluation, cutsLow, newDepth));
|
|
3608
|
-
depthFirstStack.push(createBranch2(evaluation, cutsHigh, newDepth));
|
|
3609
|
-
} else {
|
|
3610
|
-
branches.push(createBranch2(evaluation, cutsHigh, newDepth));
|
|
3611
|
-
branches.push(createBranch2(evaluation, cutsLow, newDepth));
|
|
3612
|
-
}
|
|
3613
|
-
}
|
|
3614
|
-
}
|
|
3615
|
-
if (bestBranch !== null) {
|
|
3616
|
-
applyCuts(tableau, bestBranch.cuts);
|
|
3617
|
-
}
|
|
3618
|
-
tableau.branchAndCutIterations = iterations;
|
|
3619
|
-
};
|
|
3620
|
-
return { applyCuts, branchAndCut };
|
|
3621
|
-
}
|
|
3622
|
-
|
|
3623
|
-
// src/tableau/incremental-branch-and-cut.ts
|
|
3624
|
-
function createCheckpoint(tableau) {
|
|
3625
|
-
return {
|
|
3626
|
-
matrix: new Float64Array(tableau.matrix),
|
|
3627
|
-
width: tableau.width,
|
|
3628
|
-
height: tableau.height,
|
|
3629
|
-
nVars: tableau.nVars,
|
|
3630
|
-
varIndexByRow: tableau.varIndexByRow.slice(),
|
|
3631
|
-
varIndexByCol: tableau.varIndexByCol.slice(),
|
|
3632
|
-
rowByVarIndex: tableau.rowByVarIndex.slice(),
|
|
3633
|
-
colByVarIndex: tableau.colByVarIndex.slice(),
|
|
3634
|
-
availableIndexes: tableau.availableIndexes.slice(),
|
|
3635
|
-
lastElementIndex: tableau.lastElementIndex,
|
|
3636
|
-
evaluation: tableau.evaluation,
|
|
3637
|
-
feasible: tableau.feasible
|
|
3638
|
-
};
|
|
3639
|
-
}
|
|
3640
|
-
function restoreCheckpoint(tableau, checkpoint) {
|
|
3641
|
-
if (tableau.matrix.length >= checkpoint.matrix.length) {
|
|
3642
|
-
tableau.matrix.set(checkpoint.matrix);
|
|
3643
|
-
} else {
|
|
3644
|
-
tableau.matrix = new Float64Array(checkpoint.matrix);
|
|
3645
|
-
}
|
|
3646
|
-
tableau.width = checkpoint.width;
|
|
3647
|
-
tableau.height = checkpoint.height;
|
|
3648
|
-
tableau.nVars = checkpoint.nVars;
|
|
3649
|
-
const height = checkpoint.height;
|
|
3650
|
-
for (let i = 0; i < height; i++) {
|
|
3651
|
-
tableau.varIndexByRow[i] = checkpoint.varIndexByRow[i];
|
|
3652
|
-
}
|
|
3653
|
-
tableau.varIndexByRow.length = height;
|
|
3654
|
-
const width = checkpoint.width;
|
|
3655
|
-
for (let i = 0; i < width; i++) {
|
|
3656
|
-
tableau.varIndexByCol[i] = checkpoint.varIndexByCol[i];
|
|
3657
|
-
}
|
|
3658
|
-
tableau.varIndexByCol.length = width;
|
|
3659
|
-
const nVars = checkpoint.nVars;
|
|
3660
|
-
for (let i = 0; i < nVars; i++) {
|
|
3661
|
-
tableau.rowByVarIndex[i] = checkpoint.rowByVarIndex[i];
|
|
3662
|
-
tableau.colByVarIndex[i] = checkpoint.colByVarIndex[i];
|
|
3663
|
-
}
|
|
3664
|
-
tableau.availableIndexes = checkpoint.availableIndexes.slice();
|
|
3665
|
-
tableau.lastElementIndex = checkpoint.lastElementIndex;
|
|
3666
|
-
tableau.evaluation = checkpoint.evaluation;
|
|
3667
|
-
tableau.feasible = checkpoint.feasible;
|
|
3668
|
-
}
|
|
3669
|
-
function createCut3(type, varIndex, value) {
|
|
3670
|
-
return { type, varIndex, value };
|
|
3671
|
-
}
|
|
3672
|
-
function createBranch3(relaxedEvaluation, cuts, depth, parentCheckpoint, newCut) {
|
|
3673
|
-
return { relaxedEvaluation, cuts, depth, parentCheckpoint, newCut };
|
|
3674
|
-
}
|
|
3675
|
-
function createIncrementalBranchAndCutService(options = {}) {
|
|
3676
|
-
const {
|
|
3677
|
-
nodeSelection = "hybrid",
|
|
3678
|
-
branching = "pseudocost",
|
|
3679
|
-
maxCheckpoints = 50
|
|
3680
|
-
// Limit checkpoints to avoid memory overhead
|
|
3681
|
-
} = options;
|
|
3682
|
-
const pseudoCosts = /* @__PURE__ */ new Map();
|
|
3683
|
-
const getPseudoCost = (varIndex) => {
|
|
3684
|
-
let data = pseudoCosts.get(varIndex);
|
|
3685
|
-
if (!data) {
|
|
3686
|
-
data = { upSum: 0, upCount: 0, downSum: 0, downCount: 0 };
|
|
3687
|
-
pseudoCosts.set(varIndex, data);
|
|
3688
|
-
}
|
|
3689
|
-
return data;
|
|
3690
|
-
};
|
|
3691
|
-
const updatePseudoCost = (varIndex, direction, improvement, fraction) => {
|
|
3692
|
-
const data = getPseudoCost(varIndex);
|
|
3693
|
-
const normalizedImprovement = improvement / (direction === "up" ? 1 - fraction : fraction);
|
|
3694
|
-
if (direction === "up") {
|
|
3695
|
-
data.upSum += normalizedImprovement;
|
|
3696
|
-
data.upCount++;
|
|
3697
|
-
} else {
|
|
3698
|
-
data.downSum += normalizedImprovement;
|
|
3699
|
-
data.downCount++;
|
|
3700
|
-
}
|
|
3701
|
-
};
|
|
3702
|
-
const getScore = (varIndex, fraction) => {
|
|
3703
|
-
const data = getPseudoCost(varIndex);
|
|
3704
|
-
const upPseudo = data.upCount > 0 ? data.upSum / data.upCount : 1;
|
|
3705
|
-
const downPseudo = data.downCount > 0 ? data.downSum / data.downCount : 1;
|
|
3706
|
-
const upEstimate = upPseudo * (1 - fraction);
|
|
3707
|
-
const downEstimate = downPseudo * fraction;
|
|
3708
|
-
return Math.max(upEstimate, 1e-6) * Math.max(downEstimate, 1e-6);
|
|
3709
|
-
};
|
|
3710
|
-
const selectBranchingVariable = (tableau) => {
|
|
3711
|
-
const width = tableau.width;
|
|
3712
|
-
const matrix = tableau.matrix;
|
|
3713
|
-
const rhsColumn = tableau.rhsColumn;
|
|
3714
|
-
const integerVars = tableau.model.integerVariables;
|
|
3715
|
-
const precision = tableau.precision;
|
|
3716
|
-
const candidates = [];
|
|
3717
|
-
for (const variable of integerVars) {
|
|
3718
|
-
const varIndex = variable.index;
|
|
3719
|
-
const row = tableau.rowByVarIndex[varIndex];
|
|
3720
|
-
if (row !== -1) {
|
|
3721
|
-
const value = matrix[row * width + rhsColumn];
|
|
3722
|
-
const fraction = Math.abs(value - Math.round(value));
|
|
3723
|
-
if (fraction > precision) {
|
|
3724
|
-
candidates.push({ index: varIndex, value, fraction });
|
|
3725
|
-
}
|
|
3726
|
-
}
|
|
3727
|
-
}
|
|
3728
|
-
if (candidates.length === 0) return null;
|
|
3729
|
-
if (branching === "most-fractional") {
|
|
3730
|
-
candidates.sort((a, b) => b.fraction - a.fraction);
|
|
3731
|
-
return candidates[0];
|
|
3732
|
-
}
|
|
3733
|
-
let bestScore = -Infinity;
|
|
3734
|
-
let bestCandidate = candidates[0];
|
|
3735
|
-
for (const candidate of candidates) {
|
|
3736
|
-
const score = getScore(candidate.index, candidate.fraction);
|
|
3737
|
-
if (score > bestScore) {
|
|
3738
|
-
bestScore = score;
|
|
3739
|
-
bestCandidate = candidate;
|
|
3740
|
-
}
|
|
3741
|
-
}
|
|
3742
|
-
return bestCandidate;
|
|
3743
|
-
};
|
|
3744
|
-
const applyCuts = (tableau, branchingCuts) => {
|
|
3745
|
-
tableau.restore();
|
|
3746
|
-
tableau.addCutConstraints(branchingCuts);
|
|
3747
|
-
tableau.simplex();
|
|
3748
|
-
if (tableau.model?.useMIRCuts && tableau.feasible) {
|
|
3749
|
-
let fractionalVolumeImproved = true;
|
|
3750
|
-
let mirIterations = 0;
|
|
3751
|
-
const maxMIRIterations = 3;
|
|
3752
|
-
while (fractionalVolumeImproved && mirIterations < maxMIRIterations) {
|
|
3753
|
-
const fractionalVolumeBefore = tableau.computeFractionalVolume(true);
|
|
3754
|
-
tableau.applyMIRCuts();
|
|
3755
|
-
tableau.simplex();
|
|
3756
|
-
const fractionalVolumeAfter = tableau.computeFractionalVolume(true);
|
|
3757
|
-
mirIterations++;
|
|
3758
|
-
if (fractionalVolumeAfter >= 0.9 * fractionalVolumeBefore) {
|
|
3759
|
-
fractionalVolumeImproved = false;
|
|
3760
|
-
}
|
|
3761
|
-
}
|
|
3762
|
-
}
|
|
3763
|
-
};
|
|
3764
|
-
const applyIncrementalCuts = (tableau, branch) => {
|
|
3765
|
-
if (branch.parentCheckpoint && branch.newCut) {
|
|
3766
|
-
restoreCheckpoint(tableau, branch.parentCheckpoint);
|
|
3767
|
-
tableau.addCutConstraints([branch.newCut]);
|
|
3768
|
-
tableau.simplex();
|
|
3769
|
-
} else {
|
|
3770
|
-
tableau.restore();
|
|
3771
|
-
tableau.addCutConstraints(branch.cuts);
|
|
3772
|
-
tableau.simplex();
|
|
3773
|
-
}
|
|
3774
|
-
if (tableau.model?.useMIRCuts && tableau.feasible) {
|
|
3775
|
-
let fractionalVolumeImproved = true;
|
|
3776
|
-
let mirIterations = 0;
|
|
3777
|
-
const maxMIRIterations = 3;
|
|
3778
|
-
while (fractionalVolumeImproved && mirIterations < maxMIRIterations) {
|
|
3779
|
-
const fractionalVolumeBefore = tableau.computeFractionalVolume(true);
|
|
3780
|
-
tableau.applyMIRCuts();
|
|
3781
|
-
tableau.simplex();
|
|
3782
|
-
const fractionalVolumeAfter = tableau.computeFractionalVolume(true);
|
|
3783
|
-
mirIterations++;
|
|
3784
|
-
if (fractionalVolumeAfter >= 0.9 * fractionalVolumeBefore) {
|
|
3785
|
-
fractionalVolumeImproved = false;
|
|
3786
|
-
}
|
|
3787
|
-
}
|
|
3788
|
-
}
|
|
3789
|
-
};
|
|
3790
|
-
const branchAndCut = (tableau) => {
|
|
3791
|
-
const branches = new BranchMinHeap();
|
|
3792
|
-
const depthFirstStack = [];
|
|
3793
|
-
let iterations = 0;
|
|
3794
|
-
let checkpointCount = 0;
|
|
3795
|
-
const tolerance = tableau.model?.tolerance ?? 0;
|
|
3796
|
-
let toleranceFlag = true;
|
|
3797
|
-
let terminalTime = 1e99;
|
|
3798
|
-
if (tableau.model?.timeout) {
|
|
3799
|
-
terminalTime = Date.now() + tableau.model.timeout;
|
|
3800
|
-
}
|
|
3801
|
-
let bestEvaluation = Infinity;
|
|
3802
|
-
let bestBranch = null;
|
|
3803
|
-
const bestOptionalObjectivesEvaluations = [];
|
|
3804
|
-
for (let oInit = 0; oInit < tableau.optionalObjectives.length; oInit++) {
|
|
3805
|
-
bestOptionalObjectivesEvaluations.push(Infinity);
|
|
3806
|
-
}
|
|
3807
|
-
const switchToBestFirstAfterSolutions = 1;
|
|
3808
|
-
let solutionsFound = 0;
|
|
3809
|
-
let useDepthFirst = nodeSelection === "depth-first" || nodeSelection === "hybrid";
|
|
3810
|
-
const rootBranch = createBranch3(-Infinity, [], 0);
|
|
3811
|
-
if (useDepthFirst) {
|
|
3812
|
-
depthFirstStack.push(rootBranch);
|
|
3813
|
-
} else {
|
|
3814
|
-
branches.push(rootBranch);
|
|
3815
|
-
}
|
|
3816
|
-
while ((useDepthFirst ? depthFirstStack.length > 0 : !branches.isEmpty()) && toleranceFlag === true && Date.now() < terminalTime) {
|
|
3817
|
-
let acceptableThreshold;
|
|
3818
|
-
if (tableau.model?.isMinimization) {
|
|
3819
|
-
acceptableThreshold = tableau.bestPossibleEval * (1 + tolerance);
|
|
3820
|
-
} else {
|
|
3821
|
-
acceptableThreshold = tableau.bestPossibleEval * (1 - tolerance);
|
|
3822
|
-
}
|
|
3823
|
-
if (tolerance > 0 && bestEvaluation < acceptableThreshold) {
|
|
3824
|
-
toleranceFlag = false;
|
|
3825
|
-
}
|
|
3826
|
-
let activeBranch;
|
|
3827
|
-
if (useDepthFirst && depthFirstStack.length > 0) {
|
|
3828
|
-
activeBranch = depthFirstStack.pop();
|
|
3829
|
-
} else if (!branches.isEmpty()) {
|
|
3830
|
-
activeBranch = branches.pop();
|
|
3831
|
-
} else {
|
|
3832
|
-
break;
|
|
3833
|
-
}
|
|
3834
|
-
if (activeBranch.relaxedEvaluation > bestEvaluation) {
|
|
3835
|
-
continue;
|
|
3836
|
-
}
|
|
3837
|
-
const parentEval = tableau.evaluation;
|
|
3838
|
-
applyIncrementalCuts(tableau, activeBranch);
|
|
3839
|
-
iterations++;
|
|
3840
|
-
if (!tableau.feasible) {
|
|
3841
|
-
continue;
|
|
3842
|
-
}
|
|
3843
|
-
const evaluation = tableau.evaluation;
|
|
3844
|
-
if (evaluation > bestEvaluation) {
|
|
3845
|
-
continue;
|
|
3846
|
-
}
|
|
3847
|
-
if (activeBranch.newCut && parentEval !== 0) {
|
|
3848
|
-
const improvement = Math.abs(evaluation - parentEval);
|
|
3849
|
-
const fraction = 0.5;
|
|
3850
|
-
updatePseudoCost(
|
|
3851
|
-
activeBranch.newCut.varIndex,
|
|
3852
|
-
activeBranch.newCut.type === "min" ? "up" : "down",
|
|
3853
|
-
improvement,
|
|
3854
|
-
fraction
|
|
3855
|
-
);
|
|
3856
|
-
}
|
|
3857
|
-
if (evaluation === bestEvaluation) {
|
|
3858
|
-
let isCurrentEvaluationWorse = true;
|
|
3859
|
-
for (let o = 0; o < tableau.optionalObjectives.length; o++) {
|
|
3860
|
-
if (tableau.optionalObjectives[o].reducedCosts[0] > bestOptionalObjectivesEvaluations[o]) {
|
|
3861
|
-
break;
|
|
3862
|
-
} else if (tableau.optionalObjectives[o].reducedCosts[0] < bestOptionalObjectivesEvaluations[o]) {
|
|
3863
|
-
isCurrentEvaluationWorse = false;
|
|
3864
|
-
break;
|
|
3865
|
-
}
|
|
3866
|
-
}
|
|
3867
|
-
if (isCurrentEvaluationWorse) {
|
|
3868
|
-
continue;
|
|
3869
|
-
}
|
|
3870
|
-
}
|
|
3871
|
-
if (tableau.isIntegral()) {
|
|
3872
|
-
tableau.__isIntegral = true;
|
|
3873
|
-
solutionsFound++;
|
|
3874
|
-
if (iterations === 1) {
|
|
3875
|
-
tableau.branchAndCutIterations = iterations;
|
|
3876
|
-
return;
|
|
3877
|
-
}
|
|
3878
|
-
bestBranch = activeBranch;
|
|
3879
|
-
bestEvaluation = evaluation;
|
|
3880
|
-
for (let oCopy = 0; oCopy < tableau.optionalObjectives.length; oCopy++) {
|
|
3881
|
-
bestOptionalObjectivesEvaluations[oCopy] = tableau.optionalObjectives[oCopy].reducedCosts[0];
|
|
3882
|
-
}
|
|
3883
|
-
if (tableau.model?.keep_solutions) {
|
|
3884
|
-
const nowSolution = tableau.model.tableau.getSolution();
|
|
3885
|
-
const store = nowSolution.generateSolutionSet();
|
|
3886
|
-
store.result = nowSolution.evaluation;
|
|
3887
|
-
if (!tableau.model.solutions) {
|
|
3888
|
-
tableau.model.solutions = [];
|
|
3889
|
-
}
|
|
3890
|
-
tableau.model.solutions.push(store);
|
|
3891
|
-
}
|
|
3892
|
-
if (nodeSelection === "hybrid" && solutionsFound >= switchToBestFirstAfterSolutions) {
|
|
3893
|
-
useDepthFirst = false;
|
|
3894
|
-
while (depthFirstStack.length > 0) {
|
|
3895
|
-
branches.push(depthFirstStack.pop());
|
|
3896
|
-
}
|
|
3897
|
-
}
|
|
3898
|
-
} else {
|
|
3899
|
-
if (iterations === 1) {
|
|
3900
|
-
tableau.save();
|
|
3901
|
-
}
|
|
3902
|
-
const variable = selectBranchingVariable(tableau);
|
|
3903
|
-
if (!variable) continue;
|
|
3904
|
-
const varIndex = variable.index;
|
|
3905
|
-
const varValue = variable.value;
|
|
3906
|
-
let checkpoint;
|
|
3907
|
-
if (useDepthFirst && checkpointCount < maxCheckpoints) {
|
|
3908
|
-
checkpoint = createCheckpoint(tableau);
|
|
3909
|
-
checkpointCount++;
|
|
3910
|
-
}
|
|
3911
|
-
const cutsHigh = [];
|
|
3912
|
-
const cutsLow = [];
|
|
3913
|
-
const nCuts = activeBranch.cuts.length;
|
|
3914
|
-
for (let c = 0; c < nCuts; c++) {
|
|
3915
|
-
const cut = activeBranch.cuts[c];
|
|
3916
|
-
if (cut.varIndex === varIndex) {
|
|
3917
|
-
if (cut.type === "min") {
|
|
3918
|
-
cutsLow.push(cut);
|
|
3919
|
-
} else {
|
|
3920
|
-
cutsHigh.push(cut);
|
|
3921
|
-
}
|
|
3922
|
-
} else {
|
|
3923
|
-
cutsHigh.push(cut);
|
|
3924
|
-
cutsLow.push(cut);
|
|
3925
|
-
}
|
|
3926
|
-
}
|
|
3927
|
-
const min = Math.ceil(varValue);
|
|
3928
|
-
const max = Math.floor(varValue);
|
|
3929
|
-
const cutHigh = createCut3("min", varIndex, min);
|
|
3930
|
-
cutsHigh.push(cutHigh);
|
|
3931
|
-
const cutLow = createCut3("max", varIndex, max);
|
|
3932
|
-
cutsLow.push(cutLow);
|
|
3933
|
-
const newDepth = activeBranch.depth + 1;
|
|
3934
|
-
if (useDepthFirst) {
|
|
3935
|
-
depthFirstStack.push(
|
|
3936
|
-
createBranch3(evaluation, cutsLow, newDepth, checkpoint, cutLow)
|
|
3937
|
-
);
|
|
3938
|
-
depthFirstStack.push(
|
|
3939
|
-
createBranch3(evaluation, cutsHigh, newDepth, checkpoint, cutHigh)
|
|
3940
|
-
);
|
|
3941
|
-
} else {
|
|
3942
|
-
branches.push(createBranch3(evaluation, cutsHigh, newDepth));
|
|
3943
|
-
branches.push(createBranch3(evaluation, cutsLow, newDepth));
|
|
3944
|
-
}
|
|
3945
|
-
}
|
|
3946
|
-
}
|
|
3947
|
-
if (bestBranch !== null) {
|
|
3948
|
-
applyCuts(tableau, bestBranch.cuts);
|
|
3949
|
-
}
|
|
3950
|
-
tableau.branchAndCutIterations = iterations;
|
|
3951
|
-
};
|
|
3952
|
-
return { applyCuts, branchAndCut };
|
|
3953
|
-
}
|
|
3954
|
-
|
|
3955
|
-
// src/tableau/parallel-branch-and-cut.ts
|
|
3956
|
-
var WorkerClass = null;
|
|
3957
|
-
var isMainThread = true;
|
|
3958
|
-
var workerThreadsModule = null;
|
|
3959
|
-
try {
|
|
3960
|
-
workerThreadsModule = require("worker_threads");
|
|
3961
|
-
WorkerClass = workerThreadsModule.Worker;
|
|
3962
|
-
isMainThread = workerThreadsModule.isMainThread;
|
|
3963
|
-
} catch {
|
|
3964
|
-
}
|
|
3965
|
-
function isParallelAvailable() {
|
|
3966
|
-
return WorkerClass !== null && isMainThread;
|
|
3967
|
-
}
|
|
3968
|
-
async function solveParallel(model, config = {}) {
|
|
3969
|
-
if (!isParallelAvailable()) {
|
|
3970
|
-
throw new Error("Parallel B&B not available (requires Node.js worker_threads)");
|
|
3971
|
-
}
|
|
3972
|
-
const numWorkers = config.numWorkers ?? Math.max(1, require("os").cpus().length - 1);
|
|
3973
|
-
const verbose = config.verbose ?? false;
|
|
3974
|
-
const maxNodes = config.maxNodes ?? 1e4;
|
|
3975
|
-
const isMin = model.opType === "min";
|
|
3976
|
-
const timeout = model.timeout ? Date.now() + model.timeout : Infinity;
|
|
3977
|
-
const tolerance = model.tolerance ?? 0;
|
|
3978
|
-
const workerCode = `
|
|
3979
|
-
const { parentPort, workerData } = require('worker_threads');
|
|
3980
|
-
const path = require('path');
|
|
3981
|
-
const fs = require('fs');
|
|
3982
|
-
|
|
3983
|
-
const workerId = workerData.workerId;
|
|
3984
|
-
|
|
3985
|
-
// Find solver module at runtime
|
|
3986
|
-
let solver;
|
|
3987
|
-
const possiblePaths = [
|
|
3988
|
-
path.resolve(process.cwd(), 'dist', 'solver.cjs.js'),
|
|
3989
|
-
path.resolve(__dirname, '..', 'dist', 'solver.cjs.js'),
|
|
3990
|
-
path.resolve(__dirname, '..', '..', 'dist', 'solver.cjs.js'),
|
|
3991
|
-
];
|
|
3992
|
-
|
|
3993
|
-
for (const p of possiblePaths) {
|
|
3994
|
-
if (fs.existsSync(p)) {
|
|
3995
|
-
solver = require(p);
|
|
3996
|
-
break;
|
|
3997
|
-
}
|
|
3998
|
-
}
|
|
3999
|
-
|
|
4000
|
-
if (!solver) {
|
|
4001
|
-
throw new Error('Could not find solver module');
|
|
4002
|
-
}
|
|
4003
|
-
|
|
4004
|
-
const solverDefault = solver.default || solver;
|
|
4005
|
-
|
|
4006
|
-
// Signal ready for work
|
|
4007
|
-
parentPort.postMessage({ type: 'ready', workerId });
|
|
4008
|
-
|
|
4009
|
-
parentPort.on('message', (msg) => {
|
|
4010
|
-
if (msg.type === 'shutdown') {
|
|
4011
|
-
process.exit(0);
|
|
4012
|
-
}
|
|
4013
|
-
|
|
4014
|
-
if (msg.type === 'task') {
|
|
4015
|
-
const result = processTask(msg);
|
|
4016
|
-
parentPort.postMessage(result);
|
|
4017
|
-
// Signal ready for more work
|
|
4018
|
-
parentPort.postMessage({ type: 'ready', workerId });
|
|
4019
|
-
}
|
|
4020
|
-
});
|
|
4021
|
-
|
|
4022
|
-
function processTask(task) {
|
|
4023
|
-
try {
|
|
4024
|
-
// Deep copy model
|
|
4025
|
-
const model = JSON.parse(JSON.stringify(task.modelJson));
|
|
4026
|
-
|
|
4027
|
-
// Apply branch cuts
|
|
4028
|
-
for (let i = 0; i < task.cuts.length; i++) {
|
|
4029
|
-
const cut = task.cuts[i];
|
|
4030
|
-
const cname = '__pcut_' + i + '_' + cut.varName;
|
|
4031
|
-
model.constraints[cname] = cut.type === 'min' ? { min: cut.value } : { max: cut.value };
|
|
4032
|
-
if (model.variables[cut.varName]) {
|
|
4033
|
-
model.variables[cut.varName][cname] = 1;
|
|
4034
|
-
}
|
|
4035
|
-
}
|
|
4036
|
-
|
|
4037
|
-
// Solve LP relaxation
|
|
4038
|
-
const lpModel = { ...model };
|
|
4039
|
-
delete lpModel.ints;
|
|
4040
|
-
delete lpModel.binaries;
|
|
4041
|
-
|
|
4042
|
-
const lpResult = solverDefault.Solve(lpModel);
|
|
4043
|
-
|
|
4044
|
-
if (!lpResult.feasible) {
|
|
4045
|
-
return { type: 'result', id: task.id, feasible: false, integral: false, evaluation: Infinity, solution: null, childBranches: [] };
|
|
4046
|
-
}
|
|
4047
|
-
|
|
4048
|
-
const evaluation = lpResult.result || 0;
|
|
4049
|
-
|
|
4050
|
-
// Prune by bound
|
|
4051
|
-
const dominated = task.isMinimization ? evaluation > task.bestBound : evaluation < task.bestBound;
|
|
4052
|
-
if (dominated) {
|
|
4053
|
-
return { type: 'result', id: task.id, feasible: true, integral: false, evaluation, solution: null, childBranches: [] };
|
|
4054
|
-
}
|
|
4055
|
-
|
|
4056
|
-
// Check integrality
|
|
4057
|
-
const intVars = { ...task.modelJson.ints, ...task.modelJson.binaries };
|
|
4058
|
-
let isIntegral = true;
|
|
4059
|
-
let mostFracVar = null;
|
|
4060
|
-
let mostFracValue = 0;
|
|
4061
|
-
let maxFrac = 0;
|
|
4062
|
-
|
|
4063
|
-
for (const varName of Object.keys(intVars)) {
|
|
4064
|
-
const val = lpResult[varName] || 0;
|
|
4065
|
-
const frac = Math.abs(val - Math.round(val));
|
|
4066
|
-
if (frac > 1e-6) {
|
|
4067
|
-
isIntegral = false;
|
|
4068
|
-
if (frac > maxFrac) { maxFrac = frac; mostFracVar = varName; mostFracValue = val; }
|
|
4069
|
-
}
|
|
4070
|
-
}
|
|
4071
|
-
|
|
4072
|
-
if (isIntegral) {
|
|
4073
|
-
const solution = {};
|
|
4074
|
-
for (const v of Object.keys(task.modelJson.variables)) {
|
|
4075
|
-
if (lpResult[v] !== undefined) solution[v] = lpResult[v];
|
|
4076
|
-
}
|
|
4077
|
-
return { type: 'result', id: task.id, feasible: true, integral: true, evaluation, solution, childBranches: [] };
|
|
4078
|
-
}
|
|
4079
|
-
|
|
4080
|
-
// Create child branches
|
|
4081
|
-
const childBranches = [];
|
|
4082
|
-
if (mostFracVar) {
|
|
4083
|
-
childBranches.push({ cuts: [...task.cuts, { type: 'max', varName: mostFracVar, value: Math.floor(mostFracValue) }], relaxedEvaluation: evaluation });
|
|
4084
|
-
childBranches.push({ cuts: [...task.cuts, { type: 'min', varName: mostFracVar, value: Math.ceil(mostFracValue) }], relaxedEvaluation: evaluation });
|
|
4085
|
-
}
|
|
4086
|
-
return { type: 'result', id: task.id, feasible: true, integral: false, evaluation, solution: null, childBranches };
|
|
4087
|
-
} catch (err) {
|
|
4088
|
-
return { type: 'result', id: task.id, feasible: false, integral: false, evaluation: Infinity, solution: null, childBranches: [] };
|
|
4089
|
-
}
|
|
4090
|
-
}
|
|
4091
|
-
`;
|
|
4092
|
-
const workers = [];
|
|
4093
|
-
for (let i = 0; i < numWorkers; i++) {
|
|
4094
|
-
workers.push(new WorkerClass(workerCode, { eval: true, workerData: { workerId: i } }));
|
|
4095
|
-
}
|
|
4096
|
-
const queue = [{ cuts: [], relaxedEvaluation: isMin ? -Infinity : Infinity }];
|
|
4097
|
-
const readyWorkers = [];
|
|
4098
|
-
const busyWorkers = /* @__PURE__ */ new Set();
|
|
4099
|
-
let bestBound = isMin ? Infinity : -Infinity;
|
|
4100
|
-
let bestSolution = null;
|
|
4101
|
-
let totalIters = 0;
|
|
4102
|
-
let taskId = 0;
|
|
4103
|
-
let resolveMain = null;
|
|
4104
|
-
function dispatchWork(workerId) {
|
|
4105
|
-
if (queue.length === 0 || totalIters >= maxNodes || Date.now() >= timeout) {
|
|
4106
|
-
readyWorkers.push(workerId);
|
|
4107
|
-
checkCompletion();
|
|
4108
|
-
return;
|
|
4109
|
-
}
|
|
4110
|
-
if (tolerance > 0 && bestSolution && queue.length > 0) {
|
|
4111
|
-
const bestPossible = isMin ? Math.min(...queue.map((b) => b.relaxedEvaluation)) : Math.max(...queue.map((b) => b.relaxedEvaluation));
|
|
4112
|
-
const threshold = isMin ? bestPossible * (1 + tolerance) : bestPossible * (1 - tolerance);
|
|
4113
|
-
if (isMin ? bestBound <= threshold : bestBound >= threshold) {
|
|
4114
|
-
readyWorkers.push(workerId);
|
|
4115
|
-
checkCompletion();
|
|
4116
|
-
return;
|
|
4117
|
-
}
|
|
4118
|
-
}
|
|
4119
|
-
queue.sort((a, b) => isMin ? a.relaxedEvaluation - b.relaxedEvaluation : b.relaxedEvaluation - a.relaxedEvaluation);
|
|
4120
|
-
while (queue.length > 0) {
|
|
4121
|
-
const dominated = isMin ? queue[0].relaxedEvaluation > bestBound : queue[0].relaxedEvaluation < bestBound;
|
|
4122
|
-
if (!dominated) break;
|
|
4123
|
-
queue.shift();
|
|
4124
|
-
}
|
|
4125
|
-
if (queue.length === 0) {
|
|
4126
|
-
readyWorkers.push(workerId);
|
|
4127
|
-
checkCompletion();
|
|
4128
|
-
return;
|
|
4129
|
-
}
|
|
4130
|
-
const branch = queue.shift();
|
|
4131
|
-
const task = {
|
|
4132
|
-
type: "task",
|
|
4133
|
-
id: taskId++,
|
|
4134
|
-
modelJson: model,
|
|
4135
|
-
cuts: branch.cuts,
|
|
4136
|
-
bestBound,
|
|
4137
|
-
isMinimization: isMin
|
|
4138
|
-
};
|
|
4139
|
-
busyWorkers.add(workerId);
|
|
4140
|
-
if (verbose) {
|
|
4141
|
-
console.log(`[ParallelBB] Worker ${workerId} processing task ${task.id} (queue: ${queue.length}, busy: ${busyWorkers.size})`);
|
|
4142
|
-
}
|
|
4143
|
-
workers[workerId].postMessage(task);
|
|
4144
|
-
}
|
|
4145
|
-
function checkCompletion() {
|
|
4146
|
-
if (busyWorkers.size === 0 && (queue.length === 0 || totalIters >= maxNodes || Date.now() >= timeout)) {
|
|
4147
|
-
if (resolveMain) {
|
|
4148
|
-
resolveMain();
|
|
4149
|
-
}
|
|
4150
|
-
}
|
|
4151
|
-
}
|
|
4152
|
-
function handleMessage(workerId, msg) {
|
|
4153
|
-
if (msg.type === "ready") {
|
|
4154
|
-
busyWorkers.delete(workerId);
|
|
4155
|
-
dispatchWork(workerId);
|
|
4156
|
-
} else if (msg.type === "result") {
|
|
4157
|
-
totalIters++;
|
|
4158
|
-
if (verbose && totalIters <= 10) {
|
|
4159
|
-
console.log(`[ParallelBB] Result #${totalIters}: feasible=${msg.feasible}, integral=${msg.integral}, eval=${msg.evaluation.toFixed(2)}`);
|
|
4160
|
-
}
|
|
4161
|
-
if (msg.integral && msg.solution) {
|
|
4162
|
-
const isBetter = isMin ? msg.evaluation < bestBound : msg.evaluation > bestBound;
|
|
4163
|
-
if (isBetter) {
|
|
4164
|
-
bestBound = msg.evaluation;
|
|
4165
|
-
bestSolution = msg.solution;
|
|
4166
|
-
if (verbose) {
|
|
4167
|
-
console.log(`[ParallelBB] New incumbent: ${bestBound}`);
|
|
4168
|
-
}
|
|
4169
|
-
}
|
|
4170
|
-
}
|
|
4171
|
-
for (const child of msg.childBranches) {
|
|
4172
|
-
const dominated = isMin ? child.relaxedEvaluation > bestBound : child.relaxedEvaluation < bestBound;
|
|
4173
|
-
if (!dominated) {
|
|
4174
|
-
queue.push(child);
|
|
4175
|
-
}
|
|
4176
|
-
}
|
|
4177
|
-
while (readyWorkers.length > 0 && queue.length > 0) {
|
|
4178
|
-
const idleWorker = readyWorkers.shift();
|
|
4179
|
-
dispatchWork(idleWorker);
|
|
4180
|
-
}
|
|
4181
|
-
}
|
|
4182
|
-
}
|
|
4183
|
-
const workersReady = /* @__PURE__ */ new Set();
|
|
4184
|
-
let allWorkersReady = null;
|
|
4185
|
-
await new Promise((resolve) => {
|
|
4186
|
-
allWorkersReady = resolve;
|
|
4187
|
-
for (let i = 0; i < numWorkers; i++) {
|
|
4188
|
-
const workerId = i;
|
|
4189
|
-
workers[i].on("message", (msg) => {
|
|
4190
|
-
if (msg.type === "ready" && !workersReady.has(workerId)) {
|
|
4191
|
-
workersReady.add(workerId);
|
|
4192
|
-
if (verbose) {
|
|
4193
|
-
console.log(`[ParallelBB] Worker ${workerId} ready (${workersReady.size}/${numWorkers})`);
|
|
4194
|
-
}
|
|
4195
|
-
if (workersReady.size === numWorkers && allWorkersReady) {
|
|
4196
|
-
allWorkersReady();
|
|
4197
|
-
}
|
|
4198
|
-
} else {
|
|
4199
|
-
handleMessage(workerId, msg);
|
|
4200
|
-
}
|
|
4201
|
-
});
|
|
4202
|
-
workers[i].on("error", (err) => {
|
|
4203
|
-
if (verbose) console.error(`[ParallelBB] Worker ${workerId} error:`, err);
|
|
4204
|
-
busyWorkers.delete(workerId);
|
|
4205
|
-
if (!workersReady.has(workerId)) {
|
|
4206
|
-
workersReady.add(workerId);
|
|
4207
|
-
if (workersReady.size === numWorkers && allWorkersReady) {
|
|
4208
|
-
allWorkersReady();
|
|
4209
|
-
}
|
|
4210
|
-
}
|
|
4211
|
-
dispatchWork(workerId);
|
|
4212
|
-
});
|
|
4213
|
-
}
|
|
4214
|
-
setTimeout(() => {
|
|
4215
|
-
if (workersReady.size < numWorkers && allWorkersReady) {
|
|
4216
|
-
if (verbose) console.log(`[ParallelBB] Timeout waiting for workers, ${workersReady.size} ready`);
|
|
4217
|
-
allWorkersReady();
|
|
4218
|
-
}
|
|
4219
|
-
}, 2e3);
|
|
4220
|
-
});
|
|
4221
|
-
if (verbose) {
|
|
4222
|
-
console.log(`[ParallelBB] All ${numWorkers} workers ready, starting...`);
|
|
4223
|
-
}
|
|
4224
|
-
for (let i = 0; i < numWorkers; i++) {
|
|
4225
|
-
dispatchWork(i);
|
|
4226
|
-
}
|
|
4227
|
-
await new Promise((resolve) => {
|
|
4228
|
-
resolveMain = resolve;
|
|
4229
|
-
checkCompletion();
|
|
4230
|
-
});
|
|
4231
|
-
for (const w of workers) {
|
|
4232
|
-
w.postMessage({ type: "shutdown" });
|
|
4233
|
-
w.terminate();
|
|
4234
|
-
}
|
|
4235
|
-
if (verbose) {
|
|
4236
|
-
console.log(`[ParallelBB] Completed: ${totalIters} nodes explored, best=${bestBound}`);
|
|
4237
|
-
}
|
|
4238
|
-
return {
|
|
4239
|
-
feasible: bestSolution !== null,
|
|
4240
|
-
result: bestSolution !== null ? bestBound : isMin ? Infinity : -Infinity,
|
|
4241
|
-
solution: bestSolution ?? {},
|
|
4242
|
-
iterations: totalIters
|
|
4243
|
-
};
|
|
4244
|
-
}
|
|
4245
|
-
function shouldUseParallel(model) {
|
|
4246
|
-
if (!isParallelAvailable()) return false;
|
|
4247
|
-
const numInts = Object.keys(model.ints ?? {}).length + Object.keys(model.binaries ?? {}).length;
|
|
4248
|
-
const numVars = Object.keys(model.variables ?? {}).length;
|
|
4249
|
-
const numCons = Object.keys(model.constraints ?? {}).length;
|
|
4250
|
-
return numInts >= 20 && numVars * numCons >= 1e4;
|
|
4251
|
-
}
|
|
4252
|
-
|
|
4253
|
-
// src/main.ts
|
|
4254
|
-
var Solver = class {
|
|
4255
|
-
constructor() {
|
|
4256
|
-
// Expose constructors for programmatic model building
|
|
4257
|
-
this.Model = model_default;
|
|
4258
|
-
this.Tableau = tableau_default;
|
|
4259
|
-
this.Constraint = Constraint;
|
|
4260
|
-
this.Variable = Variable;
|
|
4261
|
-
this.Numeral = Numeral;
|
|
4262
|
-
this.Term = Term;
|
|
4263
|
-
// External solver integrations
|
|
4264
|
-
this.External = main_default;
|
|
4265
|
-
this.ReformatLP = import_reformat.default;
|
|
4266
|
-
// Branch-and-cut service (default implementation)
|
|
4267
|
-
this.branchAndCutService = createBranchAndCutService();
|
|
4268
|
-
this.branchAndCut = (tableau) => this.branchAndCutService.branchAndCut(tableau);
|
|
4269
|
-
// Reference to the last solved model (useful for debugging)
|
|
4270
|
-
this.lastSolvedModel = null;
|
|
4271
|
-
}
|
|
4272
|
-
/**
|
|
4273
|
-
* Select the appropriate branch-and-cut service based on model options.
|
|
4274
|
-
*
|
|
4275
|
-
* Enhanced strategies can be enabled via model.options:
|
|
4276
|
-
* - nodeSelection: 'best-first' | 'depth-first' | 'hybrid'
|
|
4277
|
-
* - branching: 'most-fractional' | 'pseudocost' | 'strong'
|
|
4278
|
-
* - useIncremental: true to use incremental state management (experimental)
|
|
4279
|
-
*/
|
|
4280
|
-
selectBranchAndCutService(model) {
|
|
4281
|
-
const options = model.options;
|
|
4282
|
-
const useEnhanced = options?.nodeSelection || options?.branching;
|
|
4283
|
-
const useIncremental = options?.useIncremental === true;
|
|
4284
|
-
if (useIncremental) {
|
|
4285
|
-
return createIncrementalBranchAndCutService({
|
|
4286
|
-
nodeSelection: options?.nodeSelection ?? "hybrid",
|
|
4287
|
-
branching: options?.branching ?? "pseudocost"
|
|
4288
|
-
});
|
|
4289
|
-
}
|
|
4290
|
-
if (useEnhanced) {
|
|
4291
|
-
return createEnhancedBranchAndCutService({
|
|
4292
|
-
nodeSelection: options?.nodeSelection ?? "hybrid",
|
|
4293
|
-
branching: options?.branching ?? "pseudocost",
|
|
4294
|
-
useDiving: true
|
|
4295
|
-
});
|
|
4296
|
-
}
|
|
4297
|
-
return createBranchAndCutService();
|
|
4298
|
-
}
|
|
4299
|
-
/**
|
|
4300
|
-
* Solve a linear or mixed-integer programming problem.
|
|
4301
|
-
*
|
|
4302
|
-
* @param model - Problem definition (JSON format or Model instance)
|
|
4303
|
-
* @param precision - Tolerance for integer constraints (default: 1e-9)
|
|
4304
|
-
* @param full - If true, return full Solution object; otherwise return simplified result
|
|
4305
|
-
* @param validate - If true, run model through validation functions
|
|
4306
|
-
* @returns Solution object or simplified result with variable values
|
|
4307
|
-
*/
|
|
4308
|
-
Solve(model, precision, full, validate) {
|
|
4309
|
-
if (validate) {
|
|
4310
|
-
for (const test in validation_exports) {
|
|
4311
|
-
const validator = validation_exports[test];
|
|
4312
|
-
if (typeof validator === "function") {
|
|
4313
|
-
model = validator(model);
|
|
4314
|
-
}
|
|
4315
|
-
}
|
|
4316
|
-
}
|
|
4317
|
-
if (!model) {
|
|
4318
|
-
throw new Error("Solver requires a model to operate on");
|
|
4319
|
-
}
|
|
4320
|
-
if (typeof model.optimize === "object") {
|
|
4321
|
-
if (Object.keys(model.optimize).length > 1) {
|
|
4322
|
-
return Polyopt(this, model);
|
|
4323
|
-
}
|
|
4324
|
-
}
|
|
4325
|
-
if (model.external) {
|
|
4326
|
-
return this.solveWithExternalSolver(model);
|
|
4327
|
-
}
|
|
4328
|
-
let modelInstance;
|
|
4329
|
-
if (!(model instanceof model_default)) {
|
|
4330
|
-
const branchAndCutService = this.selectBranchAndCutService(model);
|
|
4331
|
-
modelInstance = new model_default(precision, void 0, branchAndCutService).loadJson(
|
|
4332
|
-
model
|
|
4333
|
-
);
|
|
4334
|
-
} else {
|
|
4335
|
-
modelInstance = model;
|
|
4336
|
-
}
|
|
4337
|
-
const solution = modelInstance.solve();
|
|
4338
|
-
this.lastSolvedModel = modelInstance;
|
|
4339
|
-
solution.solutionSet = solution.generateSolutionSet();
|
|
4340
|
-
if (full) {
|
|
4341
|
-
return solution;
|
|
4342
|
-
}
|
|
4343
|
-
return this.buildSimplifiedResult(solution);
|
|
4344
|
-
}
|
|
4345
|
-
/**
|
|
4346
|
-
* Delegate solving to an external solver (e.g., lp_solve).
|
|
4347
|
-
*/
|
|
4348
|
-
solveWithExternalSolver(model) {
|
|
4349
|
-
const solvers = Object.keys(main_default);
|
|
4350
|
-
const solverList = JSON.stringify(solvers);
|
|
4351
|
-
if (!model.external?.solver) {
|
|
4352
|
-
throw new Error(
|
|
4353
|
-
`Model has 'external' object without solver attribute. Available: ${solverList}`
|
|
4354
|
-
);
|
|
4355
|
-
}
|
|
4356
|
-
const requestedSolver = model.external.solver;
|
|
4357
|
-
if (!main_default[requestedSolver]) {
|
|
4358
|
-
throw new Error(`Solver '${requestedSolver}' not supported. Available: ${solverList}`);
|
|
4359
|
-
}
|
|
4360
|
-
return main_default[requestedSolver].solve(model);
|
|
4361
|
-
}
|
|
4362
|
-
/**
|
|
4363
|
-
* Build a simplified result object from a full solution.
|
|
4364
|
-
*/
|
|
4365
|
-
buildSimplifiedResult(solution) {
|
|
4366
|
-
const result = {
|
|
4367
|
-
feasible: solution.feasible,
|
|
4368
|
-
result: solution.evaluation,
|
|
4369
|
-
bounded: solution.bounded
|
|
4370
|
-
};
|
|
4371
|
-
if (solution._tableau.__isIntegral) {
|
|
4372
|
-
result.isIntegral = true;
|
|
4373
|
-
}
|
|
4374
|
-
for (const varId of Object.keys(solution.solutionSet)) {
|
|
4375
|
-
const value = solution.solutionSet[varId];
|
|
4376
|
-
if (value !== 0) {
|
|
4377
|
-
result[varId] = value;
|
|
4378
|
-
}
|
|
4379
|
-
}
|
|
4380
|
-
return result;
|
|
4381
|
-
}
|
|
4382
|
-
/**
|
|
4383
|
-
* Solve a multi-objective optimization problem.
|
|
4384
|
-
*
|
|
4385
|
-
* Returns a compromise solution using the mid-point formula between
|
|
4386
|
-
* individually optimized objectives.
|
|
4387
|
-
*
|
|
4388
|
-
* @example
|
|
4389
|
-
* const model = {
|
|
4390
|
-
* optimize: { profit: "max", risk: "min" },
|
|
4391
|
-
* constraints: { budget: { max: 1000 } },
|
|
4392
|
-
* variables: { ... }
|
|
4393
|
-
* };
|
|
4394
|
-
* const result = solver.MultiObjective(model);
|
|
4395
|
-
*/
|
|
4396
|
-
MultiObjective(model) {
|
|
4397
|
-
return Polyopt(this, model);
|
|
4398
|
-
}
|
|
4399
|
-
/**
|
|
4400
|
-
* Solve a MIP using parallel branch-and-cut (async, Node.js only).
|
|
4401
|
-
*
|
|
4402
|
-
* Uses worker threads to explore multiple B&B branches in parallel.
|
|
4403
|
-
* Automatically falls back to sequential solving if:
|
|
4404
|
-
* - Not running in Node.js
|
|
4405
|
-
* - Problem is too small (< 10 integer vars or problem size < 1000)
|
|
4406
|
-
* - options.useParallel is false
|
|
4407
|
-
*
|
|
4408
|
-
* @example
|
|
4409
|
-
* const result = await solver.SolveAsync(model, { useParallel: true });
|
|
4410
|
-
*/
|
|
4411
|
-
async SolveAsync(model, options) {
|
|
4412
|
-
const useParallel = options?.useParallel ?? shouldUseParallel(model);
|
|
4413
|
-
if (useParallel && isParallelAvailable()) {
|
|
4414
|
-
const result = await solveParallel(model, {
|
|
4415
|
-
numWorkers: options?.numWorkers ?? model.options?.numWorkers,
|
|
4416
|
-
verbose: options?.verbose
|
|
4417
|
-
});
|
|
4418
|
-
const solveResult = {
|
|
4419
|
-
feasible: result.feasible,
|
|
4420
|
-
result: result.result,
|
|
4421
|
-
bounded: true,
|
|
4422
|
-
isIntegral: result.feasible
|
|
4423
|
-
};
|
|
4424
|
-
for (const [key, value] of Object.entries(result.solution)) {
|
|
4425
|
-
if (value !== 0) {
|
|
4426
|
-
solveResult[key] = value;
|
|
4427
|
-
}
|
|
4428
|
-
}
|
|
4429
|
-
return solveResult;
|
|
4430
|
-
}
|
|
4431
|
-
return this.Solve(model);
|
|
4432
|
-
}
|
|
4433
|
-
/**
|
|
4434
|
-
* Check if parallel B&B is available in current environment.
|
|
4435
|
-
*/
|
|
4436
|
-
isParallelAvailable() {
|
|
4437
|
-
return isParallelAvailable();
|
|
4438
|
-
}
|
|
4439
|
-
};
|
|
4440
|
-
var solver = new Solver();
|
|
4441
|
-
if (typeof define === "function") {
|
|
4442
|
-
define([], () => solver);
|
|
4443
|
-
} else if (typeof window === "object") {
|
|
4444
|
-
window.solver = solver;
|
|
4445
|
-
} else if (typeof self === "object") {
|
|
4446
|
-
self.solver = solver;
|
|
4447
|
-
}
|
|
4448
|
-
var main_default2 = solver;
|