@mark1russell7/linear 0.1.0 → 0.1.1
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 +41 -0
- package/build/index.d.ts +90 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +346 -3
- package/build/index.js.map +1 -1
- package/package.json +5 -3
- package/src/certificate.ts +6 -2
- package/src/index.ts +2 -0
- package/src/integer.ts +345 -0
package/README.md
CHANGED
|
@@ -61,6 +61,44 @@ A Farkas ray proves that no point is feasible: for each `x >= 0` that meets the
|
|
|
61
61
|
|
|
62
62
|
Only the first stage can be infeasible, because each later stage keeps the optimal point of the stage before it. A later stage can be unbounded after optimal stages, because its objective is new.
|
|
63
63
|
|
|
64
|
+
## Integer programs
|
|
65
|
+
|
|
66
|
+
An `IntegerProgram` is a linear program with a list `integer` of variable indices. Each of these variables takes integer values only. The other variables stay continuous.
|
|
67
|
+
|
|
68
|
+
`solveIntegerProgram(program, options)` uses branch and bound on the exact simplex. The search goes depth first. It branches on the fractional integer variable with the smallest index, and it takes the child `x_j <= k` first. A node is a leaf when its relaxation has no point or has no better optimum than the best integer point.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { checkIntegerCertificate, linearProgram, solveIntegerProgram } from "@mark1russell7/linear";
|
|
72
|
+
|
|
73
|
+
const program = {
|
|
74
|
+
...linearProgram({
|
|
75
|
+
sense: "max",
|
|
76
|
+
objective: [5, 4],
|
|
77
|
+
constraints: [
|
|
78
|
+
{ coefficients: [6, 4], relation: "<=", rhs: 24 },
|
|
79
|
+
{ coefficients: [1, 2], relation: "<=", rhs: 6 },
|
|
80
|
+
],
|
|
81
|
+
}),
|
|
82
|
+
integer: [0, 1],
|
|
83
|
+
};
|
|
84
|
+
const result = solveIntegerProgram(program);
|
|
85
|
+
// result is optimal: x = (4, 0), value 20. The relaxation gives x = (3, 3/2), value 21.
|
|
86
|
+
checkIntegerCertificate(program, result).valid; // true
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
| Status | Certificate | The conditions that `checkIntegerCertificate` examines |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| `optimal` | The point `x`, its value and the tree | `x` is a feasible integer point with the value `c x`. The tree covers each integer point, and the value of each leaf is not better. |
|
|
92
|
+
| `infeasible` | The tree | The tree covers each integer point, and each leaf has a Farkas ray. |
|
|
93
|
+
| `unbounded` | An integer point `x` and a direction | The conditions of `checkCertificate`. Also, each integer variable of the point and of the direction is an integer. |
|
|
94
|
+
| `limit` | The best point, if any, a bound and the tree | The point is a feasible integer point. Each closed leaf and the parent of each open node have a value that is not better than the bound. |
|
|
95
|
+
|
|
96
|
+
The tree covers each integer point when each branched node has the two children `x_j <= k` and `x_j >= k + 1`. Each leaf has the certificate of its relaxation.
|
|
97
|
+
|
|
98
|
+
An unbounded relaxation starts a search for one integer point with the objective 0. The rows are rational, so a program with an integer point has the unbounded directions of its relaxation. The direction times the common denominator of its entries is an integer direction.
|
|
99
|
+
|
|
100
|
+
The search can go on with no end, for example on the line `2x - 2y = 1`. The option `nodeLimit` stops it, and the default is 10000 relaxations. The result `limit` then gives the best point that the search found and a proved bound of the optimum.
|
|
101
|
+
|
|
64
102
|
## The tests
|
|
65
103
|
|
|
66
104
|
- Each result of the simplex on 3 seeded families of small programs goes through `checkCertificate`. The families are random programs, programs with equality rows, and degenerate programs with many zero right sides.
|
|
@@ -68,5 +106,8 @@ Only the first stage can be infeasible, because each later stage keeps the optim
|
|
|
68
106
|
- Changed certificates fail the check: a new value, a moved point, a moved dual, a negated ray and a negated direction.
|
|
69
107
|
- The cycling examples of Beale and of Chvátal end under the rule of Bland. The test also shows that the rule of the largest coefficient meets an earlier basis again on them.
|
|
70
108
|
- Property tests on random matrices examine `rank`, `nullSpace` and `solve`.
|
|
109
|
+
- Each result of `solveIntegerProgram` on 3 seeded families goes through `checkIntegerCertificate`. The families are integer programs in a box, mixed programs in a box and programs with no box.
|
|
110
|
+
- In a box, an enumeration of each integer point gives the status and the optimal value. The enumeration uses the vertex enumeration for the continuous variables, not the simplex. The solver agrees with it on each case.
|
|
111
|
+
- The optimum of the relaxation, rounded down, misses the integer optimum on some programs in a box. This is the base.
|
|
71
112
|
|
|
72
113
|
The property tests use `fast-check` with a fixed seed. The variable `PROPERTY_RUNS` sets the count of cases of each property, and the default is 300.
|
package/build/index.d.ts
CHANGED
|
@@ -191,5 +191,94 @@ interface CertificateCheck {
|
|
|
191
191
|
* direction improves the objective.
|
|
192
192
|
*/
|
|
193
193
|
export declare function checkCertificate(program: LinearProgram, result: LinearProgramResult): CertificateCheck;
|
|
194
|
-
|
|
194
|
+
/** A linear program in which each variable of the list `integer` takes integer values only. The other variables are continuous. */
|
|
195
|
+
interface IntegerProgram extends LinearProgram {
|
|
196
|
+
/** The indices of the integer variables. */
|
|
197
|
+
readonly integer: readonly number[];
|
|
198
|
+
}
|
|
199
|
+
/** The row that a node adds to the rows of its parent: `x[variable] <= value` or `x[variable] >= value`. The value is an integer. */
|
|
200
|
+
interface Branch {
|
|
201
|
+
readonly variable: number;
|
|
202
|
+
readonly relation: "<=" | ">=";
|
|
203
|
+
readonly value: Rational;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The outcome of a node of the tree.
|
|
207
|
+
*
|
|
208
|
+
* - `branched`: the node has two children. One child adds `x_j <= k`, and the other child adds `x_j >= k + 1`.
|
|
209
|
+
* - `integer`: the relaxation of the node has an optimum with an integer value on each integer variable.
|
|
210
|
+
* - `bound`: the optimum of the relaxation is not better than the best integer point that the solve found before the node.
|
|
211
|
+
* - `infeasible`: the relaxation of the node has no point.
|
|
212
|
+
* - `open`: the solve stopped at its limit before the node.
|
|
213
|
+
*/
|
|
214
|
+
type NodeOutcome = "branched" | "integer" | "bound" | "infeasible" | "open";
|
|
215
|
+
/** One node of the tree. The root is node 0. Each other node has a parent with a smaller index. */
|
|
216
|
+
interface BranchNode {
|
|
217
|
+
readonly parent: number | undefined;
|
|
218
|
+
readonly branch: Branch | undefined;
|
|
219
|
+
readonly outcome: NodeOutcome;
|
|
220
|
+
/** The result of the relaxation of the node, with its certificate. An open node has no result. */
|
|
221
|
+
readonly result: LinearProgramResult | undefined;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The result of an integer program, with its certificate.
|
|
225
|
+
*
|
|
226
|
+
* - `optimal`: the point `x`, its value, and the tree. Each leaf proves that its integer points are not better than `x`.
|
|
227
|
+
* - `infeasible`: the tree. Each leaf has a Farkas ray, so the program has no integer point.
|
|
228
|
+
* - `unbounded`: an integer point `x` and a direction `direction` with an integer value on each integer variable.
|
|
229
|
+
* Each point `x + t direction` with an integer `t >= 0` is an integer point, and the objective improves without limit.
|
|
230
|
+
* - `limit`: the solve stopped at its limit. It gives the best integer point that it found, if any. `bound` is a bound of the
|
|
231
|
+
* optimum that the tree proves. A program with an unbounded relaxation gives no bound.
|
|
232
|
+
*/
|
|
233
|
+
type IntegerProgramResult = {
|
|
234
|
+
readonly status: "optimal";
|
|
235
|
+
readonly x: Vector;
|
|
236
|
+
readonly value: Rational;
|
|
237
|
+
readonly tree: readonly BranchNode[];
|
|
238
|
+
} | {
|
|
239
|
+
readonly status: "infeasible";
|
|
240
|
+
readonly tree: readonly BranchNode[];
|
|
241
|
+
} | {
|
|
242
|
+
readonly status: "unbounded";
|
|
243
|
+
readonly x: Vector;
|
|
244
|
+
readonly direction: Vector;
|
|
245
|
+
} | {
|
|
246
|
+
readonly status: "limit";
|
|
247
|
+
readonly x: Vector | undefined;
|
|
248
|
+
readonly value: Rational | undefined;
|
|
249
|
+
readonly bound: Rational | undefined;
|
|
250
|
+
readonly tree: readonly BranchNode[];
|
|
251
|
+
};
|
|
252
|
+
/** The options of `solveIntegerProgram`. */
|
|
253
|
+
interface IntegerOptions {
|
|
254
|
+
/** The largest count of relaxations that the solve solves. The default is 10000. */
|
|
255
|
+
readonly nodeLimit?: number;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches
|
|
259
|
+
* on the fractional integer variable with the smallest index.
|
|
260
|
+
*
|
|
261
|
+
* - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.
|
|
262
|
+
* - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is
|
|
263
|
+
* unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.
|
|
264
|
+
* - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.
|
|
265
|
+
*
|
|
266
|
+
* @throws {RangeError} A row has a length that is not the count of variables.
|
|
267
|
+
* @throws {RangeError} An integer variable is not a variable of the program.
|
|
268
|
+
* @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.
|
|
269
|
+
*/
|
|
270
|
+
export declare function solveIntegerProgram(program: IntegerProgram, options?: IntegerOptions): IntegerProgramResult;
|
|
271
|
+
/**
|
|
272
|
+
* This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.
|
|
273
|
+
*
|
|
274
|
+
* - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer
|
|
275
|
+
* point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its
|
|
276
|
+
* relaxation, and its value is not better than the value of the point.
|
|
277
|
+
* - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.
|
|
278
|
+
* - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.
|
|
279
|
+
* - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed
|
|
280
|
+
* leaf has a valid certificate. With a bound, each leaf and the parent of each open node have a value that is not better than the bound.
|
|
281
|
+
*/
|
|
282
|
+
export declare function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): CertificateCheck;
|
|
283
|
+
export type { Branch, BranchNode, CertificateCheck, Constraint, ConstraintInput, IntegerOptions, IntegerProgram, IntegerProgramResult, LexicographicResult, LexicographicStage, LinearProgram, LinearProgramInput, LinearProgramResult, Matrix, NodeOutcome, Objective, RationalInput, Relation, RowEchelon, Sense, SolveResult, Vector };
|
|
195
284
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/vector.ts","../src/matrix.ts","../src/program.ts","../src/simplex.ts","../src/lexicographic.ts","../src/certificate.ts"],"mappings":";;KAQY,kBAAkB;;KAGlB,kBAAkB;;KAGlB,gBAAgB;;;;;;;wBAQZ,WAAW,OAAO,gBAAgB;;wBAelC,OAAO,iBAAiB,kBAAkB;;;;;;wBAS1C,OAAO,yBAAyB,qBAAqB;;;;;;wBAWrD,UAAU,GAAG;;;;;;wBAab,IAAI,GAAG,QAAQ,GAAG,SAAS;;;;;;wBAY3B,SAAS,GAAG,QAAQ,GAAG,SAAS;;wBAKhC,UAAU,GAAG,QAAQ,mBAAiC;;UC9ErD;WACN,QAAQ;WACR;;;;;;;wBAoCK,KAAK,GAAG,SAAS;;wBAQjB,KAAK,GAAG;;;;;;wBASR,UAAU,GAAG,QAAQ,mBAAiC;;;;;KAmB1D;WACG;WAA2B,GAAG;WAAiB,WAAW;;WAC1D;WAAiC,aAAa;;;;;;;;wBAQ7C,MAAM,GAAG,QAAQ,GAAG,QAAQ,mBAAiC;;KCpFjE;;KAGA;;UAGK;WACN,cAAc;WACd,UAAU;WACV,KAAK;;;;;;UAOC;WACN,OAAO;WACP,WAAW;WACX,sBAAsB;;;;;;;;;;KAWrB;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,MAAM;;WAChF;WAA+B,KAAK;;WACpC;WAA8B,GAAG;WAAiB,WAAW;;;UAG3D;WACN,uBAAuB;WACvB,UAAU;WACV,KAAK;;;UAIC;WACN,OAAO;WACP,oBAAoB;WACpB,sBAAsB;;;;;;;wBAQjB,cAAc,OAAO,qBAAqB;;;;;;;wBCyK1C,mBAAmB,SAAS,gBAAgB;;UC7N3C;WACN,OAAO;WACP,cAAc;;;UAIR;WACN,SAAS;WACT,QAAQ;;;;;;;KAQP;WACG;WAA4B,GAAG;WAAiB,iBAAiB;WAAqB,iBAAiB;;WACvG;WAA6C,iBAAiB;;;;;;;;;wBAS7D,mBAAmB,sBAAsB,cAAc,qBAAqB,cAAc;;UC5BzF;WACN;WACA;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/vector.ts","../src/matrix.ts","../src/program.ts","../src/simplex.ts","../src/lexicographic.ts","../src/certificate.ts","../src/integer.ts"],"mappings":";;KAQY,kBAAkB;;KAGlB,kBAAkB;;KAGlB,gBAAgB;;;;;;;wBAQZ,WAAW,OAAO,gBAAgB;;wBAelC,OAAO,iBAAiB,kBAAkB;;;;;;wBAS1C,OAAO,yBAAyB,qBAAqB;;;;;;wBAWrD,UAAU,GAAG;;;;;;wBAab,IAAI,GAAG,QAAQ,GAAG,SAAS;;;;;;wBAY3B,SAAS,GAAG,QAAQ,GAAG,SAAS;;wBAKhC,UAAU,GAAG,QAAQ,mBAAiC;;UC9ErD;WACN,QAAQ;WACR;;;;;;;wBAoCK,KAAK,GAAG,SAAS;;wBAQjB,KAAK,GAAG;;;;;;wBASR,UAAU,GAAG,QAAQ,mBAAiC;;;;;KAmB1D;WACG;WAA2B,GAAG;WAAiB,WAAW;;WAC1D;WAAiC,aAAa;;;;;;;;wBAQ7C,MAAM,GAAG,QAAQ,GAAG,QAAQ,mBAAiC;;KCpFjE;;KAGA;;UAGK;WACN,cAAc;WACd,UAAU;WACV,KAAK;;;;;;UAOC;WACN,OAAO;WACP,WAAW;WACX,sBAAsB;;;;;;;;;;KAWrB;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,MAAM;;WAChF;WAA+B,KAAK;;WACpC;WAA8B,GAAG;WAAiB,WAAW;;;UAG3D;WACN,uBAAuB;WACvB,UAAU;WACV,KAAK;;;UAIC;WACN,OAAO;WACP,oBAAoB;WACpB,sBAAsB;;;;;;;wBAQjB,cAAc,OAAO,qBAAqB;;;;;;;wBCyK1C,mBAAmB,SAAS,gBAAgB;;UC7N3C;WACN,OAAO;WACP,cAAc;;;UAIR;WACN,SAAS;WACT,QAAQ;;;;;;;KAQP;WACG;WAA4B,GAAG;WAAiB,iBAAiB;WAAqB,iBAAiB;;WACvG;WAA6C,iBAAiB;;;;;;;;;wBAS7D,mBAAmB,sBAAsB,cAAc,qBAAqB,cAAc;;UC5BzF;WACN;WACA;;;;;;;;;;;;wBAqHK,iBAAiB,SAAS,eAAe,QAAQ,sBAAsB;;UCrHtE,uBAAuB;;WAE7B;;;UAIM;WACN;WACA;WACA,OAAO;;;;;;;;;;;KAYN;;UAGK;WACN;WACA,QAAQ;WACR,SAAS;;WAET,QAAQ;;;;;;;;;;;;KAaP;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,eAAe;;WACzF;WAA+B,eAAe;;WAC9C;WAA8B,GAAG;WAAiB,WAAW;;WAE7D;WACA,GAAG;WACH,OAAO;WACP,OAAO;WACP,eAAe;;;UAIb;;WAEN;;;;;;;;;;;;;;;wBAkHK,oBAAoB,SAAS,gBAAgB,UAAS,iBAAsB;;;;;;;;;;;;wBA6H5E,wBAAwB,SAAS,gBAAgB,QAAQ,uBAAuB"}
|
package/build/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ONE, ZERO, add, compare, div, equals, fromDecimal, fromNumber, inverse, mul, neg, rational, sign, sub, toString } from "@mark1russell7/rational";
|
|
1
|
+
import { ONE, ZERO, add, compare, div, equals, floor, fromDecimal, fromNumber, gcd, inverse, isInteger, mul, neg, rational, sign, sub, toString } from "@mark1russell7/rational";
|
|
2
2
|
// src/vector.ts
|
|
3
3
|
/**
|
|
4
4
|
* Exact vectors and matrices over the rationals of `@mark1russell7/rational`.
|
|
@@ -477,7 +477,11 @@ function holds(s, relation) {
|
|
|
477
477
|
function columnSums(program, y) {
|
|
478
478
|
return program.objective.map((_, j) => dot(program.constraints.map((c) => c.coefficients[j]), y));
|
|
479
479
|
}
|
|
480
|
-
/**
|
|
480
|
+
/**
|
|
481
|
+
* This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`.
|
|
482
|
+
*
|
|
483
|
+
* @internal
|
|
484
|
+
*/
|
|
481
485
|
function checkFeasible(program, x, failures) {
|
|
482
486
|
if (x.length !== program.objective.length) {
|
|
483
487
|
failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);
|
|
@@ -572,6 +576,345 @@ function checkCertificate(program, result) {
|
|
|
572
576
|
failures
|
|
573
577
|
};
|
|
574
578
|
}
|
|
575
|
-
|
|
579
|
+
// src/integer.ts
|
|
580
|
+
/**
|
|
581
|
+
* Integer programs: branch and bound on the exact simplex. The certificate of a result is the tree of its nodes.
|
|
582
|
+
*
|
|
583
|
+
* @packageDocumentation
|
|
584
|
+
*/
|
|
585
|
+
/**
|
|
586
|
+
* This function gives the problems of the list `integer` of a program: an index that is not an integer, or not a variable.
|
|
587
|
+
*
|
|
588
|
+
* @internal
|
|
589
|
+
*/
|
|
590
|
+
function integerProblems(program) {
|
|
591
|
+
const n = program.objective.length;
|
|
592
|
+
return program.integer.filter((j) => !Number.isInteger(j) || j < 0 || j >= n).map((j) => `the integer variable ${String(j)} is not a variable of the program`);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* This function gives the program of a node: the rows of the program, then the row of each branch on the path from the root.
|
|
596
|
+
*
|
|
597
|
+
* @internal
|
|
598
|
+
*/
|
|
599
|
+
function nodeProgram(program, tree, id) {
|
|
600
|
+
const rows = [];
|
|
601
|
+
const n = program.objective.length;
|
|
602
|
+
for (let at = id; at !== void 0; at = tree[at]?.parent) {
|
|
603
|
+
const branch = tree[at]?.branch;
|
|
604
|
+
if (branch === void 0) continue;
|
|
605
|
+
const coefficients = Array.from({ length: n }, (_, j) => j === branch.variable ? ONE : ZERO);
|
|
606
|
+
rows.push({
|
|
607
|
+
coefficients,
|
|
608
|
+
relation: branch.relation,
|
|
609
|
+
rhs: branch.value
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
return {
|
|
613
|
+
...program,
|
|
614
|
+
constraints: [...program.constraints, ...rows.reverse()]
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* This function searches the tree depth first. It branches on the fractional integer variable with the smallest index, and it
|
|
619
|
+
* takes the child `x_j <= k` first. With `first`, it stops at the first integer point.
|
|
620
|
+
*/
|
|
621
|
+
function search(program, integer, limit, first, root) {
|
|
622
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
623
|
+
const nodes = [{
|
|
624
|
+
parent: void 0,
|
|
625
|
+
branch: void 0,
|
|
626
|
+
outcome: "open",
|
|
627
|
+
result: void 0
|
|
628
|
+
}];
|
|
629
|
+
const stack = [0];
|
|
630
|
+
let best;
|
|
631
|
+
let solved = 0;
|
|
632
|
+
while (stack.length > 0 && solved < limit) {
|
|
633
|
+
const id = stack.pop();
|
|
634
|
+
const node = nodes[id];
|
|
635
|
+
const result = id === 0 ? root : solveLinearProgram(nodeProgram(program, nodes, id));
|
|
636
|
+
solved++;
|
|
637
|
+
node.result = result;
|
|
638
|
+
if (result.status === "infeasible") {
|
|
639
|
+
node.outcome = "infeasible";
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
if (result.status === "unbounded") throw new Error("linear: the relaxation of a node is unbounded, and the relaxation of the root is not");
|
|
643
|
+
if (best !== void 0 && compare(result.value, best.value) * s <= 0) {
|
|
644
|
+
node.outcome = "bound";
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
const j = integer.find((k) => !isInteger(result.x[k]));
|
|
648
|
+
if (j === void 0) {
|
|
649
|
+
node.outcome = "integer";
|
|
650
|
+
best = {
|
|
651
|
+
x: result.x,
|
|
652
|
+
value: result.value
|
|
653
|
+
};
|
|
654
|
+
if (first) return {
|
|
655
|
+
best,
|
|
656
|
+
nodes,
|
|
657
|
+
stopped: false
|
|
658
|
+
};
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
node.outcome = "branched";
|
|
662
|
+
const k = floor(result.x[j]);
|
|
663
|
+
nodes.push({
|
|
664
|
+
parent: id,
|
|
665
|
+
branch: {
|
|
666
|
+
variable: j,
|
|
667
|
+
relation: ">=",
|
|
668
|
+
value: add(k, ONE)
|
|
669
|
+
},
|
|
670
|
+
outcome: "open",
|
|
671
|
+
result: void 0
|
|
672
|
+
});
|
|
673
|
+
stack.push(nodes.length - 1);
|
|
674
|
+
nodes.push({
|
|
675
|
+
parent: id,
|
|
676
|
+
branch: {
|
|
677
|
+
variable: j,
|
|
678
|
+
relation: "<=",
|
|
679
|
+
value: k
|
|
680
|
+
},
|
|
681
|
+
outcome: "open",
|
|
682
|
+
result: void 0
|
|
683
|
+
});
|
|
684
|
+
stack.push(nodes.length - 1);
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
best,
|
|
688
|
+
nodes,
|
|
689
|
+
stopped: stack.length > 0
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
/** This function gives the direction times the least common multiple of its denominators, so each entry is an integer. */
|
|
693
|
+
function integral(direction) {
|
|
694
|
+
let m = 1n;
|
|
695
|
+
for (const v of direction) m = m / gcd(m, v.d) * v.d;
|
|
696
|
+
return direction.map((v) => rational(v.n * (m / v.d)));
|
|
697
|
+
}
|
|
698
|
+
/** This function gives the frozen tree of the nodes of a search. */
|
|
699
|
+
function treeOf(nodes) {
|
|
700
|
+
return nodes.map(({ parent, branch, outcome, result }) => ({
|
|
701
|
+
parent,
|
|
702
|
+
branch,
|
|
703
|
+
outcome,
|
|
704
|
+
result
|
|
705
|
+
}));
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches
|
|
709
|
+
* on the fractional integer variable with the smallest index.
|
|
710
|
+
*
|
|
711
|
+
* - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.
|
|
712
|
+
* - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is
|
|
713
|
+
* unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.
|
|
714
|
+
* - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.
|
|
715
|
+
*
|
|
716
|
+
* @throws {RangeError} A row has a length that is not the count of variables.
|
|
717
|
+
* @throws {RangeError} An integer variable is not a variable of the program.
|
|
718
|
+
* @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.
|
|
719
|
+
*/
|
|
720
|
+
function solveIntegerProgram(program, options = {}) {
|
|
721
|
+
checkShape(program);
|
|
722
|
+
const problems = integerProblems(program);
|
|
723
|
+
if (problems.length > 0) throw new RangeError(`linear: ${problems.join(", ")}`);
|
|
724
|
+
const limit = options.nodeLimit ?? 1e4;
|
|
725
|
+
if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`linear: the node limit ${String(limit)} is not an integer of 1 or more`);
|
|
726
|
+
const integer = [...new Set(program.integer)].sort((a, b) => a - b);
|
|
727
|
+
const root = solveLinearProgram(program);
|
|
728
|
+
if (root.status === "unbounded") {
|
|
729
|
+
const zero = {
|
|
730
|
+
...program,
|
|
731
|
+
objective: program.objective.map(() => ZERO)
|
|
732
|
+
};
|
|
733
|
+
const found = search(zero, integer, limit, true, solveLinearProgram(zero));
|
|
734
|
+
if (found.best !== void 0) return {
|
|
735
|
+
status: "unbounded",
|
|
736
|
+
x: found.best.x,
|
|
737
|
+
direction: integral(root.direction)
|
|
738
|
+
};
|
|
739
|
+
const tree = treeOf(found.nodes);
|
|
740
|
+
if (found.stopped) return {
|
|
741
|
+
status: "limit",
|
|
742
|
+
x: void 0,
|
|
743
|
+
value: void 0,
|
|
744
|
+
bound: void 0,
|
|
745
|
+
tree
|
|
746
|
+
};
|
|
747
|
+
return {
|
|
748
|
+
status: "infeasible",
|
|
749
|
+
tree
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
const found = search(program, integer, limit, false, root);
|
|
753
|
+
const tree = treeOf(found.nodes);
|
|
754
|
+
if (found.stopped) {
|
|
755
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
756
|
+
let bound = found.best?.value;
|
|
757
|
+
for (const node of found.nodes) {
|
|
758
|
+
if (node.outcome !== "open" || node.parent === void 0) continue;
|
|
759
|
+
const parent = found.nodes[node.parent]?.result;
|
|
760
|
+
if (parent?.status === "optimal" && (bound === void 0 || compare(parent.value, bound) * s > 0)) bound = parent.value;
|
|
761
|
+
}
|
|
762
|
+
return {
|
|
763
|
+
status: "limit",
|
|
764
|
+
x: found.best?.x,
|
|
765
|
+
value: found.best?.value,
|
|
766
|
+
bound,
|
|
767
|
+
tree
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
if (found.best === void 0) return {
|
|
771
|
+
status: "infeasible",
|
|
772
|
+
tree
|
|
773
|
+
};
|
|
774
|
+
return {
|
|
775
|
+
status: "optimal",
|
|
776
|
+
x: found.best.x,
|
|
777
|
+
value: found.best.value,
|
|
778
|
+
tree
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
/** This function adds a failure for each integer variable of `x` with a value that is not an integer. */
|
|
782
|
+
function checkIntegral(integer, x, name, failures) {
|
|
783
|
+
for (const j of integer) {
|
|
784
|
+
const v = x[j];
|
|
785
|
+
if (v !== void 0 && !isInteger(v)) failures.push(`${name}[${String(j)}] = ${toString(v)} is not an integer`);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
/** This function adds a failure when the value `v` is better than `limit` in the sense of the program. */
|
|
789
|
+
function checkNotBetter(s, v, limit, name, failures) {
|
|
790
|
+
if (compare(v, limit) * s > 0) failures.push(`${name} ${toString(v)} is better than ${toString(limit)}`);
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* This function examines the tree of a result: its shape, and a certificate for each leaf. With `best`, the value of each leaf
|
|
794
|
+
* is not better than `best`. Each failure goes into `failures`.
|
|
795
|
+
*/
|
|
796
|
+
function checkTree(program, tree, allowOpen, best, failures) {
|
|
797
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
798
|
+
const integer = new Set(program.integer);
|
|
799
|
+
const root = tree[0];
|
|
800
|
+
if (root === void 0 || root.parent !== void 0 || root.branch !== void 0) {
|
|
801
|
+
failures.push("node 0 is not a root with no parent and no branch");
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
const children = tree.map(() => []);
|
|
805
|
+
for (let i = 1; i < tree.length; i++) {
|
|
806
|
+
const node = tree[i];
|
|
807
|
+
if (node.parent === void 0 || !Number.isInteger(node.parent) || node.parent < 0 || node.parent >= i || node.branch === void 0) {
|
|
808
|
+
failures.push(`node ${String(i)} has no parent before it, or no branch`);
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
if (!integer.has(node.branch.variable) || !isInteger(node.branch.value)) failures.push(`node ${String(i)} branches on a variable that is not an integer variable, or at a value that is not an integer`);
|
|
812
|
+
children[node.parent]?.push(i);
|
|
813
|
+
}
|
|
814
|
+
tree.forEach((node, i) => {
|
|
815
|
+
const kids = children[i];
|
|
816
|
+
if (node.outcome === "branched") {
|
|
817
|
+
const [a, b] = kids.map((k) => tree[k].branch);
|
|
818
|
+
const down = [a, b].find((branch) => branch?.relation === "<=");
|
|
819
|
+
const up = [a, b].find((branch) => branch?.relation === ">=");
|
|
820
|
+
if (kids.length !== 2 || down === void 0 || up === void 0 || down.variable !== up.variable || !equals(add(down.value, ONE), up.value)) failures.push(`node ${String(i)} is branched, and its children are not x_j <= k and x_j >= k + 1`);
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
if (kids.length > 0) failures.push(`node ${String(i)} has children, and its outcome is ${node.outcome}`);
|
|
824
|
+
if (node.outcome === "open") {
|
|
825
|
+
if (!allowOpen) failures.push(`node ${String(i)} is open`);
|
|
826
|
+
if (best === void 0 || node.parent === void 0) return;
|
|
827
|
+
const parent = tree[node.parent]?.result;
|
|
828
|
+
if (parent?.status !== "optimal") {
|
|
829
|
+
failures.push(`node ${String(i)} is open, and its parent has no optimum`);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
const check = checkCertificate(nodeProgram(program, tree, node.parent), parent);
|
|
833
|
+
for (const failure of check.failures) failures.push(`node ${String(node.parent)}: ${failure}`);
|
|
834
|
+
checkNotBetter(s, parent.value, best, `the parent of the open node ${String(i)} has the value`, failures);
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
const result = node.result;
|
|
838
|
+
if (result === void 0) {
|
|
839
|
+
failures.push(`node ${String(i)} is a leaf with no result`);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
const check = checkCertificate(nodeProgram(program, tree, i), result);
|
|
843
|
+
for (const failure of check.failures) failures.push(`node ${String(i)}: ${failure}`);
|
|
844
|
+
if (node.outcome === "infeasible") {
|
|
845
|
+
if (result.status !== "infeasible") failures.push(`node ${String(i)} is infeasible, and its result is ${result.status}`);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
if (result.status !== "optimal") {
|
|
849
|
+
failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome}, and its result is ${result.status}`);
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
if (node.outcome === "integer") checkIntegral(program.integer, result.x, `node ${String(i)}: x`, failures);
|
|
853
|
+
if (best === void 0) failures.push(`node ${String(i)} has an optimum, and the result claims no integer point`);
|
|
854
|
+
else checkNotBetter(s, result.value, best, `node ${String(i)} has the value`, failures);
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.
|
|
859
|
+
*
|
|
860
|
+
* - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer
|
|
861
|
+
* point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its
|
|
862
|
+
* relaxation, and its value is not better than the value of the point.
|
|
863
|
+
* - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.
|
|
864
|
+
* - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.
|
|
865
|
+
* - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed
|
|
866
|
+
* leaf has a valid certificate. With a bound, each leaf and the parent of each open node have a value that is not better than the bound.
|
|
867
|
+
*/
|
|
868
|
+
function checkIntegerCertificate(program, result) {
|
|
869
|
+
const failures = [];
|
|
870
|
+
if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {
|
|
871
|
+
failures.push("a constraint row has a length that is not the count of variables");
|
|
872
|
+
return {
|
|
873
|
+
valid: false,
|
|
874
|
+
failures
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
failures.push(...integerProblems(program));
|
|
878
|
+
if (failures.length > 0) return {
|
|
879
|
+
valid: false,
|
|
880
|
+
failures
|
|
881
|
+
};
|
|
882
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
883
|
+
const point = (x, value) => {
|
|
884
|
+
checkFeasible(program, x, failures);
|
|
885
|
+
checkIntegral(program.integer, x, "x", failures);
|
|
886
|
+
if (x.length === program.objective.length && !equals(dot(program.objective, x), value)) failures.push(`the value ${toString(value)} is not c x = ${toString(dot(program.objective, x))}`);
|
|
887
|
+
};
|
|
888
|
+
if (result.status === "unbounded") {
|
|
889
|
+
failures.push(...checkCertificate(program, {
|
|
890
|
+
status: "unbounded",
|
|
891
|
+
x: result.x,
|
|
892
|
+
direction: result.direction
|
|
893
|
+
}).failures);
|
|
894
|
+
checkIntegral(program.integer, result.x, "x", failures);
|
|
895
|
+
checkIntegral(program.integer, result.direction, "direction", failures);
|
|
896
|
+
} else if (result.status === "optimal") {
|
|
897
|
+
point(result.x, result.value);
|
|
898
|
+
checkTree(program, result.tree, false, result.value, failures);
|
|
899
|
+
} else if (result.status === "infeasible") {
|
|
900
|
+
checkTree(program, result.tree, false, void 0, failures);
|
|
901
|
+
result.tree.forEach((node, i) => {
|
|
902
|
+
if (node.outcome !== "branched" && node.outcome !== "infeasible") failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome} in an infeasible result`);
|
|
903
|
+
});
|
|
904
|
+
} else {
|
|
905
|
+
if (result.x === void 0 !== (result.value === void 0)) failures.push("the limit result has a point with no value, or a value with no point");
|
|
906
|
+
if (result.x !== void 0 && result.value !== void 0) {
|
|
907
|
+
point(result.x, result.value);
|
|
908
|
+
if (result.bound === void 0) failures.push("the limit result has a point and no bound");
|
|
909
|
+
else checkNotBetter(s, result.value, result.bound, "the value", failures);
|
|
910
|
+
}
|
|
911
|
+
checkTree(program, result.tree, true, result.bound, failures);
|
|
912
|
+
}
|
|
913
|
+
return {
|
|
914
|
+
valid: failures.length === 0,
|
|
915
|
+
failures
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
export { checkCertificate, checkIntegerCertificate, columnsOf, dot, linearProgram, matrix, multiply, nullSpace, rank, rref, solve, solveIntegerProgram, solveLexicographic, solveLinearProgram, toRational, transpose, vector };
|
|
576
919
|
|
|
577
920
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/vector.ts","../src/matrix.ts","../src/program.ts","../src/simplex.ts","../src/lexicographic.ts","../src/certificate.ts"],"sourcesContent":["/**\n * Exact vectors and matrices over the rationals of `@mark1russell7/rational`.\n *\n * @packageDocumentation\n */\nimport { type Rational, add, div, fromDecimal, fromNumber, mul, rational, ZERO } from \"@mark1russell7/rational\";\n\n/** A vector of exact rationals. */\nexport type Vector = readonly Rational[];\n\n/** A matrix of exact rationals as a list of rows. Each row has the same length. */\nexport type Matrix = readonly Vector[];\n\n/** A value that `toRational` reads: a rational, a `bigint`, a JavaScript number, or a text, for example `\"3/4\"` or `\"0.25\"`. */\nexport type RationalInput = Rational | bigint | number | string;\n\n/**\n * This function gives the exact rational of an input. A number gives the decimal that JavaScript prints for it. A text is a\n * decimal or a quotient of two decimals.\n *\n * @throws {RangeError} The input is not a finite value, or the text has a zero divisor.\n */\nexport function toRational(value: RationalInput): Rational {\n if (typeof value === \"bigint\") return rational(value);\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new RangeError(`linear: ${value} is not a finite number`);\n return fromNumber(value);\n }\n if (typeof value === \"string\") {\n const slash = value.indexOf(\"/\");\n if (slash < 0) return fromDecimal(value.trim());\n return div(fromDecimal(value.slice(0, slash).trim()), fromDecimal(value.slice(slash + 1).trim()));\n }\n return value;\n}\n\n/** This function gives a vector of exact rationals from a list of inputs. */\nexport function vector(values: readonly RationalInput[]): Vector {\n return values.map(toRational);\n}\n\n/**\n * This function gives a matrix of exact rationals from a list of rows.\n *\n * @throws {RangeError} The rows do not have the same length.\n */\nexport function matrix(rows: readonly (readonly RationalInput[])[]): Matrix {\n const result = rows.map(vector);\n columnsOf(result);\n return result;\n}\n\n/**\n * This function gives the count of columns of a matrix. A matrix with no rows has 0 columns.\n *\n * @throws {RangeError} The rows do not have the same length.\n */\nexport function columnsOf(m: Matrix): number {\n const n = m[0]?.length ?? 0;\n for (const row of m) {\n if (row.length !== n) throw new RangeError(`linear: a row has ${row.length} entries, and the first row has ${n}`);\n }\n return n;\n}\n\n/**\n * This function gives the dot product of two vectors.\n *\n * @throws {RangeError} The vectors do not have the same length.\n */\nexport function dot(a: Vector, b: Vector): Rational {\n if (a.length !== b.length) throw new RangeError(`linear: the vectors have ${a.length} and ${b.length} entries`);\n let sum = ZERO;\n for (let i = 0; i < a.length; i++) sum = add(sum, mul(a[i]!, b[i]!));\n return sum;\n}\n\n/**\n * This function gives the product of a matrix and a vector.\n *\n * @throws {RangeError} The length of the vector is not the count of columns.\n */\nexport function multiply(m: Matrix, x: Vector): Vector {\n return m.map((row) => dot(row, x));\n}\n\n/** This function gives the transpose of a matrix. The argument `columns` gives the row count of the result for a matrix with no rows. */\nexport function transpose(m: Matrix, columns: number = columnsOf(m)): Matrix {\n const result: Rational[][] = [];\n for (let j = 0; j < columns; j++) result.push(m.map((row) => row[j]!));\n return result;\n}\n","/**\n * Exact elimination: the reduced row echelon form, the rank, a basis of the null space and the solution of a system.\n *\n * @packageDocumentation\n */\nimport { type Rational, inverse, mul, neg, ONE, sign, sub, ZERO } from \"@mark1russell7/rational\";\nimport { type Matrix, type Vector, columnsOf } from \"./vector.ts\";\n\n/** The reduced row echelon form of a matrix and the column of each pivot, in order. */\nexport interface RowEchelon {\n readonly matrix: Matrix;\n readonly pivots: readonly number[];\n}\n\n/**\n * This function applies Gauss-Jordan elimination to the rows in place. It takes pivots only in the columns below `limit`.\n * It gives the column of each pivot. The row of pivot `k` is row `k`.\n */\nfunction eliminate(rows: Rational[][], limit: number): number[] {\n const pivots: number[] = [];\n let r = 0;\n for (let c = 0; c < limit && r < rows.length; c++) {\n let p = r;\n while (p < rows.length && sign(rows[p]![c]!) === 0) p++;\n if (p === rows.length) continue;\n const swap = rows[r]!;\n rows[r] = rows[p]!;\n rows[p] = swap;\n const scale = inverse(rows[r]![c]!);\n const pivotRow = rows[r]!.map((v) => mul(v, scale));\n rows[r] = pivotRow;\n for (let i = 0; i < rows.length; i++) {\n const f = rows[i]![c]!;\n if (i === r || sign(f) === 0) continue;\n rows[i] = rows[i]!.map((v, j) => sub(v, mul(f, pivotRow[j]!)));\n }\n pivots.push(c);\n r++;\n }\n return pivots;\n}\n\n/**\n * This function gives the reduced row echelon form of a matrix, with exact arithmetic.\n *\n * @throws {RangeError} The rows do not have the same length.\n */\nexport function rref(m: Matrix): RowEchelon {\n const n = columnsOf(m);\n const rows = m.map((row) => [...row]);\n const pivots = eliminate(rows, n);\n return { matrix: rows, pivots };\n}\n\n/** This function gives the rank of a matrix: the count of pivots of its reduced row echelon form. */\nexport function rank(m: Matrix): number {\n return rref(m).pivots.length;\n}\n\n/**\n * This function gives a basis of the null space of a matrix: the vectors `v` with `m v = 0`. The basis has one vector for each\n * column with no pivot. That vector has 1 at its column and 0 at each other column with no pivot. The argument `columns`\n * gives the count of columns for a matrix with no rows.\n */\nexport function nullSpace(m: Matrix, columns: number = columnsOf(m)): Matrix {\n const { matrix: r, pivots } = rref(m);\n const basis: Vector[] = [];\n for (let free = 0; free < columns; free++) {\n if (pivots.includes(free)) continue;\n const v: Rational[] = new Array<Rational>(columns).fill(ZERO);\n v[free] = ONE;\n pivots.forEach((p, k) => {\n v[p] = neg(r[k]![free]!);\n });\n basis.push(v);\n }\n return basis;\n}\n\n/**\n * The result of `solve`. A system with a solution gives one solution `x` and a basis of the null space. Each solution is `x` plus a\n * combination of the basis. A system with no solution gives a certificate `y` with `y A = 0` and `y b = 1`.\n */\nexport type SolveResult =\n | { readonly status: \"solved\"; readonly x: Vector; readonly nullSpace: Matrix }\n | { readonly status: \"inconsistent\"; readonly certificate: Vector };\n\n/**\n * This function solves the system `a x = b` exactly. The matrix can be square or not, and it can have a rank below its size.\n * The solution `x` has 0 at each column with no pivot.\n *\n * @throws {RangeError} The rows do not have the same length, or `b` has a length that is not the row count.\n */\nexport function solve(a: Matrix, b: Vector, columns: number = columnsOf(a)): SolveResult {\n const m = a.length;\n if (b.length !== m) throw new RangeError(`linear: the matrix has ${m} rows, and the right side has ${b.length} entries`);\n // The augmented rows [a | b | I]. The identity part records the row operations, so a row `[0 | 1 | y]` gives the certificate.\n const rows = a.map((row, i) => [...row, b[i]!, ...Array.from({ length: m }, (_, k) => (k === i ? ONE : ZERO))]);\n const pivots = eliminate(rows, columns + 1);\n const last = pivots.length - 1;\n if (last >= 0 && pivots[last] === columns) {\n return { status: \"inconsistent\", certificate: rows[last]!.slice(columns + 1) };\n }\n const x: Rational[] = new Array<Rational>(columns).fill(ZERO);\n pivots.forEach((p, k) => {\n x[p] = rows[k]![columns]!;\n });\n return { status: \"solved\", x, nullSpace: nullSpace(a, columns) };\n}\n","/**\n * Linear programs as data, and their results with certificates.\n *\n * @packageDocumentation\n */\nimport type { Rational } from \"@mark1russell7/rational\";\nimport { type RationalInput, type Vector, toRational, vector } from \"./vector.ts\";\n\n/** The direction of an objective: `\"max\"` to maximize it, `\"min\"` to minimize it. */\nexport type Sense = \"max\" | \"min\";\n\n/** The relation of a constraint row to its right side. */\nexport type Relation = \"<=\" | \">=\" | \"=\";\n\n/** One constraint row: `coefficients · x` has the relation `relation` to `rhs`. */\nexport interface Constraint {\n readonly coefficients: Vector;\n readonly relation: Relation;\n readonly rhs: Rational;\n}\n\n/**\n * A linear program: optimize `objective · x` subject to the constraint rows and `x >= 0`. Each variable has the lower bound 0.\n * A free variable `v` is the difference of two variables `p - q`. Copy each coefficient of `v` to `p`. Put its negative on `q`.\n */\nexport interface LinearProgram {\n readonly sense: Sense;\n readonly objective: Vector;\n readonly constraints: readonly Constraint[];\n}\n\n/**\n * The result of a linear program, with its certificate.\n *\n * - `optimal`: the point `x`, its value `objective · x`, and a dual vector `dual` with one entry for each constraint row.\n * - `infeasible`: a Farkas ray `ray` with one entry for each constraint row. `checkCertificate` tells its conditions.\n * - `unbounded`: a feasible point `x` and a direction `direction`. Each point `x + t direction` with `t >= 0` is feasible, and\n * the objective improves without limit along it.\n */\nexport type LinearProgramResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly value: Rational; readonly dual: Vector }\n | { readonly status: \"infeasible\"; readonly ray: Vector }\n | { readonly status: \"unbounded\"; readonly x: Vector; readonly direction: Vector };\n\n/** One constraint row of `linearProgram`, with inputs that `toRational` reads. */\nexport interface ConstraintInput {\n readonly coefficients: readonly RationalInput[];\n readonly relation: Relation;\n readonly rhs: RationalInput;\n}\n\n/** A linear program with inputs that `toRational` reads. */\nexport interface LinearProgramInput {\n readonly sense: Sense;\n readonly objective: readonly RationalInput[];\n readonly constraints: readonly ConstraintInput[];\n}\n\n/**\n * This function makes a linear program from inputs that `toRational` reads, and examines its shape.\n *\n * @throws {RangeError} A constraint row has a length that is not the length of the objective.\n */\nexport function linearProgram(input: LinearProgramInput): LinearProgram {\n const program: LinearProgram = {\n sense: input.sense,\n objective: vector(input.objective),\n constraints: input.constraints.map((c) => ({ coefficients: vector(c.coefficients), relation: c.relation, rhs: toRational(c.rhs) })),\n };\n checkShape(program);\n return program;\n}\n\n/**\n * This function examines the shape of a program: each constraint row has one coefficient for each variable.\n *\n * @throws {RangeError} A constraint row has a length that is not the length of the objective.\n */\nexport function checkShape(program: LinearProgram): void {\n const n = program.objective.length;\n program.constraints.forEach((c, i) => {\n if (c.coefficients.length !== n) {\n throw new RangeError(`linear: constraint ${i} has ${c.coefficients.length} coefficients, and the objective has ${n}`);\n }\n });\n}\n","/**\n * The exact two-phase simplex. The rule of Bland selects each pivot, so the method ends on each program.\n *\n * @packageDocumentation\n */\nimport { type Rational, compare, div, inverse, mul, neg, ONE, sign, sub, ZERO } from \"@mark1russell7/rational\";\nimport { solve } from \"./matrix.ts\";\nimport { checkShape, type LinearProgram, type LinearProgramResult, type Relation } from \"./program.ts\";\nimport { dot } from \"./vector.ts\";\n\n/**\n * The rule that selects the entering column. `\"bland\"` takes the column with the smallest index that improves the objective.\n * `\"largest\"` takes the column with the largest reduced cost, with the smallest index on a tie. The rule `\"largest\"` can cycle\n * on a degenerate program, and the tests use it only to show that cycle.\n *\n * @internal\n */\nexport type PivotRule = \"bland\" | \"largest\";\n\n/** The program in equality form: `rows z = rhs`, `z >= 0`, with `rhs >= 0`. */\ninterface StandardForm {\n /** The original columns, then one slack or surplus column for each inequality row, then one artificial column for each row that needs one. */\n readonly rows: readonly (readonly Rational[])[];\n readonly rhs: readonly Rational[];\n /** The rows that the form multiplies by -1, so that their right side is not negative. */\n readonly flipped: readonly boolean[];\n /** The first basis: the slack column of a `<=` row, or the artificial column of the row. */\n readonly basis: readonly number[];\n /** The count of columns that are not artificial. */\n readonly structural: number;\n}\n\n/** The working tableau: the rows in the form of the current basis. */\ninterface Tableau {\n readonly rows: Rational[][];\n readonly rhs: Rational[];\n readonly basis: number[];\n}\n\nconst FLIP: Readonly<Record<Relation, Relation>> = { \"<=\": \">=\", \">=\": \"<=\", \"=\": \"=\" };\n\nfunction standardForm(program: LinearProgram): StandardForm {\n const n = program.objective.length;\n const rels = program.constraints.map((c) => (sign(c.rhs) < 0 ? FLIP[c.relation] : c.relation));\n const slacks = rels.filter((r) => r !== \"=\").length;\n const artificials = rels.filter((r) => r !== \"<=\").length;\n const structural = n + slacks;\n const total = structural + artificials;\n const rows: Rational[][] = [];\n const rhs: Rational[] = [];\n const flipped: boolean[] = [];\n const basis: number[] = [];\n let slack = n;\n let artificial = structural;\n program.constraints.forEach((c, i) => {\n const flip = sign(c.rhs) < 0;\n const row: Rational[] = new Array<Rational>(total).fill(ZERO);\n c.coefficients.forEach((v, j) => {\n row[j] = flip ? neg(v) : v;\n });\n const rel = rels[i]!;\n if (rel === \"<=\") {\n row[slack] = ONE;\n basis.push(slack++);\n } else {\n if (rel === \">=\") row[slack++] = neg(ONE);\n row[artificial] = ONE;\n basis.push(artificial++);\n }\n rows.push(row);\n rhs.push(flip ? neg(c.rhs) : c.rhs);\n flipped.push(flip);\n });\n return { rows, rhs, flipped, basis, structural };\n}\n\nfunction pivot(t: Tableau, p: number, q: number): void {\n const scale = inverse(t.rows[p]![q]!);\n const pivotRow = t.rows[p]!.map((v) => mul(v, scale));\n const pivotRhs = mul(t.rhs[p]!, scale);\n t.rows[p] = pivotRow;\n t.rhs[p] = pivotRhs;\n for (let i = 0; i < t.rows.length; i++) {\n const f = t.rows[i]![q]!;\n if (i === p || sign(f) === 0) continue;\n t.rows[i] = t.rows[i]!.map((v, j) => sub(v, mul(f, pivotRow[j]!)));\n t.rhs[i] = sub(t.rhs[i]!, mul(f, pivotRhs));\n }\n t.basis[p] = q;\n}\n\n/** This function gives the reduced cost `c_j - c_B B^-1 A_j` of each column, for a maximization. */\nfunction reducedCosts(t: Tableau, cost: readonly Rational[]): Rational[] {\n const r = [...cost];\n t.rows.forEach((row, i) => {\n const cb = cost[t.basis[i]!]!;\n if (sign(cb) === 0) return;\n for (let j = 0; j < r.length; j++) r[j] = sub(r[j]!, mul(cb, row[j]!));\n });\n return r;\n}\n\ntype Phase = { readonly kind: \"optimal\" } | { readonly kind: \"unbounded\"; readonly column: number } | { readonly kind: \"cycle\" };\n\nconst basisKey = (basis: readonly number[]): string => [...basis].sort((a, b) => a - b).join(\",\");\n\n/** This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. */\nfunction runPhase(t: Tableau, cost: readonly Rational[], allowed: number, rule: PivotRule, count: { pivots: number }): Phase {\n const seen = new Set<string>([basisKey(t.basis)]);\n for (;;) {\n const r = reducedCosts(t, cost);\n let q = -1;\n for (let j = 0; j < allowed; j++) {\n if (sign(r[j]!) <= 0) continue;\n if (rule === \"bland\") {\n q = j;\n break;\n }\n if (q < 0 || compare(r[j]!, r[q]!) > 0) q = j;\n }\n if (q < 0) return { kind: \"optimal\" };\n let p = -1;\n let best = ZERO;\n t.rows.forEach((row, i) => {\n const a = row[q]!;\n if (sign(a) <= 0) return;\n const ratio = div(t.rhs[i]!, a);\n const order = p < 0 ? -1 : compare(ratio, best);\n if (order < 0 || (order === 0 && t.basis[i]! < t.basis[p]!)) {\n p = i;\n best = ratio;\n }\n });\n if (p < 0) return { kind: \"unbounded\", column: q };\n pivot(t, p, q);\n count.pivots++;\n // A deterministic rule that meets a basis again repeats its cycle forever. The rule of Bland does not meet a basis again.\n const key = basisKey(t.basis);\n if (seen.has(key)) return { kind: \"cycle\" };\n seen.add(key);\n }\n}\n\n/** This function gives the dual of the basis in the rows of the program: the solution of `B^T y = c_B`, with the flips undone. */\nfunction dualOf(form: StandardForm, basis: readonly number[], cost: readonly Rational[]): Rational[] {\n if (basis.length === 0) return [];\n const bt = basis.map((col) => form.rows.map((row) => row[col]!));\n const solved = solve(bt, basis.map((col) => cost[col]!));\n if (solved.status !== \"solved\") throw new Error(\"linear: internal error, the basis is singular\");\n return solved.x.map((y, i) => (form.flipped[i] ? neg(y) : y));\n}\n\n/** This function gives the first `n` entries of the basic solution of the tableau. */\nfunction pointOf(t: Tableau, n: number): Rational[] {\n const x: Rational[] = new Array<Rational>(n).fill(ZERO);\n t.basis.forEach((col, i) => {\n if (col < n) x[col] = t.rhs[i]!;\n });\n return x;\n}\n\n/**\n * The run of the simplex with a pivot rule: the result, or a cycle, and the count of pivots.\n *\n * @internal\n */\nexport type SimplexRun =\n | { readonly cycled: false; readonly result: LinearProgramResult; readonly pivots: number }\n | { readonly cycled: true; readonly pivots: number };\n\n/**\n * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland.\n *\n * @internal\n */\nexport function runSimplex(program: LinearProgram, rule: PivotRule): SimplexRun {\n checkShape(program);\n const n = program.objective.length;\n const form = standardForm(program);\n const total = form.rows[0]?.length ?? n;\n const t: Tableau = { rows: form.rows.map((row) => [...row]), rhs: [...form.rhs], basis: [...form.basis] };\n const count = { pivots: 0 };\n\n // Phase 1: maximize the negative sum of the artificial columns.\n if (total > form.structural) {\n const cost = Array.from({ length: total }, (_, j) => (j >= form.structural ? neg(ONE) : ZERO));\n const phase = runPhase(t, cost, total, rule, count);\n if (phase.kind === \"cycle\") return { cycled: true, pivots: count.pivots };\n let value = ZERO;\n t.basis.forEach((col, i) => {\n value = sub(value, col >= form.structural ? t.rhs[i]! : ZERO);\n });\n if (sign(value) < 0) {\n return { cycled: false, result: { status: \"infeasible\", ray: dualOf(form, t.basis, cost) }, pivots: count.pivots };\n }\n // Each artificial column in the basis has the value 0. Move it out on a column that is not artificial, if the row has one.\n t.basis.forEach((col, i) => {\n if (col < form.structural) return;\n const j = t.rows[i]!.findIndex((v, k) => k < form.structural && sign(v) !== 0);\n if (j >= 0) pivot(t, i, j);\n });\n }\n\n // Phase 2: the objective, as a maximization. An artificial column cannot enter, and a row that keeps one is redundant.\n const max = program.sense === \"max\";\n const cost = Array.from({ length: total }, (_, j) => (j < n ? (max ? program.objective[j]! : neg(program.objective[j]!)) : ZERO));\n const phase = runPhase(t, cost, form.structural, rule, count);\n if (phase.kind === \"cycle\") return { cycled: true, pivots: count.pivots };\n const x = pointOf(t, n);\n if (phase.kind === \"unbounded\") {\n const q = phase.column;\n const direction: Rational[] = new Array<Rational>(n).fill(ZERO);\n if (q < n) direction[q] = ONE;\n t.basis.forEach((col, i) => {\n if (col < n) direction[col] = neg(t.rows[i]![q]!);\n });\n return { cycled: false, result: { status: \"unbounded\", x, direction }, pivots: count.pivots };\n }\n const dual = dualOf(form, t.basis, cost);\n return {\n cycled: false,\n result: { status: \"optimal\", x, value: dot(program.objective, x), dual: max ? dual : dual.map(neg) },\n pivots: count.pivots,\n };\n}\n\n/**\n * This function solves a linear program exactly with the two-phase simplex and the rule of Bland. The result has a certificate\n * that `checkCertificate` examines.\n *\n * @throws {RangeError} A constraint row has a length that is not the length of the objective.\n */\nexport function solveLinearProgram(program: LinearProgram): LinearProgramResult {\n const run = runSimplex(program, \"bland\");\n if (run.cycled) throw new Error(\"linear: internal error, the rule of Bland met a basis again\");\n return run.result;\n}\n\n","/**\n * Lexicographic objectives: a list of objectives, each optimized in turn while the earlier optima stay as equalities.\n *\n * @packageDocumentation\n */\nimport type { Rational } from \"@mark1russell7/rational\";\nimport type { Constraint, LinearProgram, LinearProgramResult, Sense } from \"./program.ts\";\nimport { solveLinearProgram } from \"./simplex.ts\";\nimport type { Vector } from \"./vector.ts\";\n\n/** One objective of a lexicographic program. */\nexport interface Objective {\n readonly sense: Sense;\n readonly coefficients: Vector;\n}\n\n/** One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate. */\nexport interface LexicographicStage {\n readonly program: LinearProgram;\n readonly result: LinearProgramResult;\n}\n\n/**\n * The result of `solveLexicographic`. The status `optimal` gives the last point and the optimum of each objective. The status\n * `infeasible` or `unbounded` comes from the last stage, and its result has the certificate. `checkCertificate` examines each\n * stage with its program.\n */\nexport type LexicographicResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly values: readonly Rational[]; readonly stages: readonly LexicographicStage[] }\n | { readonly status: \"infeasible\" | \"unbounded\"; readonly stages: readonly LexicographicStage[] };\n\n/**\n * This function optimizes the objectives in their order, subject to the constraint rows and `x >= 0`. Stage `k` holds the\n * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.\n * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.\n *\n * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.\n */\nexport function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[]): LexicographicResult {\n if (objectives.length === 0) throw new RangeError(\"linear: a lexicographic program needs one objective or more\");\n const stages: LexicographicStage[] = [];\n const rows: Constraint[] = [...constraints];\n const values: Rational[] = [];\n let x: Vector = [];\n for (const objective of objectives) {\n const program: LinearProgram = { sense: objective.sense, objective: objective.coefficients, constraints: [...rows] };\n const result = solveLinearProgram(program);\n stages.push({ program, result });\n if (result.status !== \"optimal\") return { status: result.status, stages };\n x = result.x;\n values.push(result.value);\n rows.push({ coefficients: objective.coefficients, relation: \"=\", rhs: result.value });\n }\n return { status: \"optimal\", x, values, stages };\n}\n","/**\n * The check of a certificate. It uses only exact arithmetic on the program and the result, and it does not trust the solver.\n *\n * @packageDocumentation\n */\nimport { type Rational, equals, mul, sign, sub, toString } from \"@mark1russell7/rational\";\nimport type { LinearProgram, LinearProgramResult, Relation } from \"./program.ts\";\nimport { dot, type Vector } from \"./vector.ts\";\n\n/** The verdict of `checkCertificate`. The list `failures` names each condition that the certificate does not meet. */\nexport interface CertificateCheck {\n readonly valid: boolean;\n readonly failures: readonly string[];\n}\n\n/** This function tells if the sign of a value obeys a relation to 0. */\nfunction holds(s: -1 | 0 | 1, relation: Relation): boolean {\n return relation === \"=\" ? s === 0 : relation === \"<=\" ? s <= 0 : s >= 0;\n}\n\n/** This function gives the column sums `y A`: entry `j` is the sum over the rows of `y_i a_ij`. */\nfunction columnSums(program: LinearProgram, y: Vector): Rational[] {\n return program.objective.map((_, j) => dot(program.constraints.map((c) => c.coefficients[j]!), y));\n}\n\n/** This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`. */\nfunction checkFeasible(program: LinearProgram, x: Vector, failures: string[]): void {\n if (x.length !== program.objective.length) {\n failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);\n return;\n }\n x.forEach((v, j) => {\n if (sign(v) < 0) failures.push(`x[${j}] = ${toString(v)} is negative`);\n });\n program.constraints.forEach((c, i) => {\n const lhs = dot(c.coefficients, x);\n if (!holds(sign(sub(lhs, c.rhs)), c.relation)) {\n failures.push(`row ${i}: ${toString(lhs)} ${c.relation} ${toString(c.rhs)} is false`);\n }\n });\n}\n\n/**\n * This function adds a failure for each multiplier with the wrong sign. With `s = 1`, a `<=` row needs a multiplier of 0 or\n * more, and a `>=` row a multiplier of 0 or less. The value `s = -1` swaps the two signs. An `=` row takes each sign.\n */\nfunction checkMultiplierSigns(program: LinearProgram, y: Vector, s: 1 | -1, name: string, failures: string[]): void {\n program.constraints.forEach((c, i) => {\n const signed = sign(y[i]!) * s;\n if ((c.relation === \"<=\" && signed < 0) || (c.relation === \">=\" && signed > 0)) {\n failures.push(`${name}[${i}] = ${toString(y[i]!)} has the wrong sign for a ${c.relation} row`);\n }\n });\n}\n\nfunction checkOptimal(program: LinearProgram, x: Vector, value: Rational, y: Vector, failures: string[]): void {\n const m = program.constraints.length;\n if (y.length !== m) failures.push(`the dual has ${y.length} entries, and the program has ${m} rows`);\n checkFeasible(program, x, failures);\n if (y.length !== m || x.length !== program.objective.length) return;\n const s = program.sense === \"max\" ? 1 : -1;\n checkMultiplierSigns(program, y, s, \"dual\", failures);\n const sums = columnSums(program, y);\n sums.forEach((sum, j) => {\n const slack = sub(sum, program.objective[j]!);\n if (sign(slack) * s < 0) failures.push(`the dual constraint of column ${j} is false: (yA)[${j}] - c[${j}] = ${toString(slack)}`);\n if (sign(mul(x[j]!, slack)) !== 0) failures.push(`complementary slackness fails at column ${j}`);\n });\n program.constraints.forEach((c, i) => {\n if (sign(mul(y[i]!, sub(dot(c.coefficients, x), c.rhs))) !== 0) failures.push(`complementary slackness fails at row ${i}`);\n });\n const primal = dot(program.objective, x);\n const dual = dot(\n program.constraints.map((c) => c.rhs),\n y,\n );\n if (!equals(primal, value)) failures.push(`the value ${toString(value)} is not c x = ${toString(primal)}`);\n if (!equals(primal, dual)) failures.push(`strong duality fails: c x = ${toString(primal)} and b y = ${toString(dual)}`);\n}\n\nfunction checkInfeasible(program: LinearProgram, y: Vector, failures: string[]): void {\n const m = program.constraints.length;\n if (y.length !== m) {\n failures.push(`the ray has ${y.length} entries, and the program has ${m} rows`);\n return;\n }\n checkMultiplierSigns(program, y, 1, \"ray\", failures);\n columnSums(program, y).forEach((sum, j) => {\n if (sign(sum) < 0) failures.push(`(yA)[${j}] = ${toString(sum)} is negative`);\n });\n const by = dot(\n program.constraints.map((c) => c.rhs),\n y,\n );\n if (sign(by) >= 0) failures.push(`b y = ${toString(by)} is not negative`);\n}\n\nfunction checkUnbounded(program: LinearProgram, x: Vector, d: Vector, failures: string[]): void {\n checkFeasible(program, x, failures);\n if (d.length !== program.objective.length) {\n failures.push(`the direction has ${d.length} entries, and the program has ${program.objective.length} variables`);\n return;\n }\n d.forEach((v, j) => {\n if (sign(v) < 0) failures.push(`direction[${j}] = ${toString(v)} is negative`);\n });\n program.constraints.forEach((c, i) => {\n const ad = dot(c.coefficients, d);\n if (!holds(sign(ad), c.relation)) failures.push(`row ${i}: the direction gives ${toString(ad)}, so it leaves the row`);\n });\n const gain = dot(program.objective, d);\n const s = program.sense === \"max\" ? 1 : -1;\n if (sign(gain) * s <= 0) failures.push(`the direction does not improve the objective: c d = ${toString(gain)}`);\n}\n\n/**\n * This function examines the certificate of a result with exact arithmetic. It does not trust the solver.\n *\n * - `optimal`: the point is feasible, the dual is feasible, `c x = b y` and complementary slackness holds. For a maximization,\n * the dual obeys `y A >= c`, `y_i >= 0` on a `<=` row and `y_i <= 0` on a `>=` row. A minimization swaps each of these signs.\n * - `infeasible`: the ray obeys `y A >= 0`, `b y < 0`, `y_i >= 0` on a `<=` row and `y_i <= 0` on a `>=` row. Then no `x >= 0`\n * meets the rows, because `0 <= y A x <= y b < 0`.\n * - `unbounded`: the point is feasible, the direction is not negative, each row keeps its relation along it, and the\n * direction improves the objective.\n */\nexport function checkCertificate(program: LinearProgram, result: LinearProgramResult): CertificateCheck {\n const failures: string[] = [];\n if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {\n failures.push(\"a constraint row has a length that is not the count of variables\");\n } else if (result.status === \"optimal\") {\n checkOptimal(program, result.x, result.value, result.dual, failures);\n } else if (result.status === \"infeasible\") {\n checkInfeasible(program, result.ray, failures);\n } else {\n checkUnbounded(program, result.x, result.direction, failures);\n }\n return { valid: failures.length === 0, failures };\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAgB,WAAW,OAAgC;CACzD,IAAI,OAAO,UAAU,UAAU,OAAO,SAAS,KAAK;CACpD,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,MAAM,IAAI,WAAW,WAAW,MAAM,wBAAwB;EAC3F,OAAO,WAAW,KAAK;CACzB;CACA,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,QAAQ,MAAM,QAAQ,GAAG;EAC/B,IAAI,QAAQ,GAAG,OAAO,YAAY,MAAM,KAAK,CAAC;EAC9C,OAAO,IAAI,YAAY,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,YAAY,MAAM,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;CAClG;CACA,OAAO;AACT;;AAGA,SAAgB,OAAO,QAA0C;CAC/D,OAAO,OAAO,IAAI,UAAU;AAC9B;;;;;;AAOA,SAAgB,OAAO,MAAqD;CAC1E,MAAM,SAAS,KAAK,IAAI,MAAM;CAC9B,UAAU,MAAM;CAChB,OAAO;AACT;;;;;;AAOA,SAAgB,UAAU,GAAmB;CAC3C,MAAM,IAAI,EAAE,EAAE,EAAE,UAAU;CAC1B,KAAK,MAAM,OAAO,GAChB,IAAI,IAAI,WAAW,GAAG,MAAM,IAAI,WAAW,qBAAqB,IAAI,OAAO,kCAAkC,GAAG;CAElH,OAAO;AACT;;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AAW,CAAC;CACrC,MAAM,IAAI,QAAQ,UAAU,QAAQ,IAAI;CACxC,IAAI,KAAK,IAAI,IAAI,KAAK,GAAG,SAAS,KAAK,uDAAuD,SAAS,IAAI,GAAG;AAChH;;;;;;;;;;;AAYA,SAAgB,iBAAiB,SAAwB,QAA+C;CACtG,MAAM,WAAqB,CAAC;CAC5B,IAAI,QAAQ,YAAY,MAAM,MAAM,EAAE,aAAa,WAAW,QAAQ,UAAU,MAAM,GACpF,SAAS,KAAK,kEAAkE;MAC3E,IAAI,OAAO,WAAW,WAC3B,aAAa,SAAS,OAAO,GAAG,OAAO,OAAO,OAAO,MAAM,QAAQ;MAC9D,IAAI,OAAO,WAAW,cAC3B,gBAAgB,SAAS,OAAO,KAAK,QAAQ;MAE7C,eAAe,SAAS,OAAO,GAAG,OAAO,WAAW,QAAQ;CAE9D,OAAO;EAAE,OAAO,SAAS,WAAW;EAAG;CAAS;AAClD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/vector.ts","../src/matrix.ts","../src/program.ts","../src/simplex.ts","../src/lexicographic.ts","../src/certificate.ts","../src/integer.ts"],"sourcesContent":["/**\n * Exact vectors and matrices over the rationals of `@mark1russell7/rational`.\n *\n * @packageDocumentation\n */\nimport { type Rational, add, div, fromDecimal, fromNumber, mul, rational, ZERO } from \"@mark1russell7/rational\";\n\n/** A vector of exact rationals. */\nexport type Vector = readonly Rational[];\n\n/** A matrix of exact rationals as a list of rows. Each row has the same length. */\nexport type Matrix = readonly Vector[];\n\n/** A value that `toRational` reads: a rational, a `bigint`, a JavaScript number, or a text, for example `\"3/4\"` or `\"0.25\"`. */\nexport type RationalInput = Rational | bigint | number | string;\n\n/**\n * This function gives the exact rational of an input. A number gives the decimal that JavaScript prints for it. A text is a\n * decimal or a quotient of two decimals.\n *\n * @throws {RangeError} The input is not a finite value, or the text has a zero divisor.\n */\nexport function toRational(value: RationalInput): Rational {\n if (typeof value === \"bigint\") return rational(value);\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new RangeError(`linear: ${value} is not a finite number`);\n return fromNumber(value);\n }\n if (typeof value === \"string\") {\n const slash = value.indexOf(\"/\");\n if (slash < 0) return fromDecimal(value.trim());\n return div(fromDecimal(value.slice(0, slash).trim()), fromDecimal(value.slice(slash + 1).trim()));\n }\n return value;\n}\n\n/** This function gives a vector of exact rationals from a list of inputs. */\nexport function vector(values: readonly RationalInput[]): Vector {\n return values.map(toRational);\n}\n\n/**\n * This function gives a matrix of exact rationals from a list of rows.\n *\n * @throws {RangeError} The rows do not have the same length.\n */\nexport function matrix(rows: readonly (readonly RationalInput[])[]): Matrix {\n const result = rows.map(vector);\n columnsOf(result);\n return result;\n}\n\n/**\n * This function gives the count of columns of a matrix. A matrix with no rows has 0 columns.\n *\n * @throws {RangeError} The rows do not have the same length.\n */\nexport function columnsOf(m: Matrix): number {\n const n = m[0]?.length ?? 0;\n for (const row of m) {\n if (row.length !== n) throw new RangeError(`linear: a row has ${row.length} entries, and the first row has ${n}`);\n }\n return n;\n}\n\n/**\n * This function gives the dot product of two vectors.\n *\n * @throws {RangeError} The vectors do not have the same length.\n */\nexport function dot(a: Vector, b: Vector): Rational {\n if (a.length !== b.length) throw new RangeError(`linear: the vectors have ${a.length} and ${b.length} entries`);\n let sum = ZERO;\n for (let i = 0; i < a.length; i++) sum = add(sum, mul(a[i]!, b[i]!));\n return sum;\n}\n\n/**\n * This function gives the product of a matrix and a vector.\n *\n * @throws {RangeError} The length of the vector is not the count of columns.\n */\nexport function multiply(m: Matrix, x: Vector): Vector {\n return m.map((row) => dot(row, x));\n}\n\n/** This function gives the transpose of a matrix. The argument `columns` gives the row count of the result for a matrix with no rows. */\nexport function transpose(m: Matrix, columns: number = columnsOf(m)): Matrix {\n const result: Rational[][] = [];\n for (let j = 0; j < columns; j++) result.push(m.map((row) => row[j]!));\n return result;\n}\n","/**\n * Exact elimination: the reduced row echelon form, the rank, a basis of the null space and the solution of a system.\n *\n * @packageDocumentation\n */\nimport { type Rational, inverse, mul, neg, ONE, sign, sub, ZERO } from \"@mark1russell7/rational\";\nimport { type Matrix, type Vector, columnsOf } from \"./vector.ts\";\n\n/** The reduced row echelon form of a matrix and the column of each pivot, in order. */\nexport interface RowEchelon {\n readonly matrix: Matrix;\n readonly pivots: readonly number[];\n}\n\n/**\n * This function applies Gauss-Jordan elimination to the rows in place. It takes pivots only in the columns below `limit`.\n * It gives the column of each pivot. The row of pivot `k` is row `k`.\n */\nfunction eliminate(rows: Rational[][], limit: number): number[] {\n const pivots: number[] = [];\n let r = 0;\n for (let c = 0; c < limit && r < rows.length; c++) {\n let p = r;\n while (p < rows.length && sign(rows[p]![c]!) === 0) p++;\n if (p === rows.length) continue;\n const swap = rows[r]!;\n rows[r] = rows[p]!;\n rows[p] = swap;\n const scale = inverse(rows[r]![c]!);\n const pivotRow = rows[r]!.map((v) => mul(v, scale));\n rows[r] = pivotRow;\n for (let i = 0; i < rows.length; i++) {\n const f = rows[i]![c]!;\n if (i === r || sign(f) === 0) continue;\n rows[i] = rows[i]!.map((v, j) => sub(v, mul(f, pivotRow[j]!)));\n }\n pivots.push(c);\n r++;\n }\n return pivots;\n}\n\n/**\n * This function gives the reduced row echelon form of a matrix, with exact arithmetic.\n *\n * @throws {RangeError} The rows do not have the same length.\n */\nexport function rref(m: Matrix): RowEchelon {\n const n = columnsOf(m);\n const rows = m.map((row) => [...row]);\n const pivots = eliminate(rows, n);\n return { matrix: rows, pivots };\n}\n\n/** This function gives the rank of a matrix: the count of pivots of its reduced row echelon form. */\nexport function rank(m: Matrix): number {\n return rref(m).pivots.length;\n}\n\n/**\n * This function gives a basis of the null space of a matrix: the vectors `v` with `m v = 0`. The basis has one vector for each\n * column with no pivot. That vector has 1 at its column and 0 at each other column with no pivot. The argument `columns`\n * gives the count of columns for a matrix with no rows.\n */\nexport function nullSpace(m: Matrix, columns: number = columnsOf(m)): Matrix {\n const { matrix: r, pivots } = rref(m);\n const basis: Vector[] = [];\n for (let free = 0; free < columns; free++) {\n if (pivots.includes(free)) continue;\n const v: Rational[] = new Array<Rational>(columns).fill(ZERO);\n v[free] = ONE;\n pivots.forEach((p, k) => {\n v[p] = neg(r[k]![free]!);\n });\n basis.push(v);\n }\n return basis;\n}\n\n/**\n * The result of `solve`. A system with a solution gives one solution `x` and a basis of the null space. Each solution is `x` plus a\n * combination of the basis. A system with no solution gives a certificate `y` with `y A = 0` and `y b = 1`.\n */\nexport type SolveResult =\n | { readonly status: \"solved\"; readonly x: Vector; readonly nullSpace: Matrix }\n | { readonly status: \"inconsistent\"; readonly certificate: Vector };\n\n/**\n * This function solves the system `a x = b` exactly. The matrix can be square or not, and it can have a rank below its size.\n * The solution `x` has 0 at each column with no pivot.\n *\n * @throws {RangeError} The rows do not have the same length, or `b` has a length that is not the row count.\n */\nexport function solve(a: Matrix, b: Vector, columns: number = columnsOf(a)): SolveResult {\n const m = a.length;\n if (b.length !== m) throw new RangeError(`linear: the matrix has ${m} rows, and the right side has ${b.length} entries`);\n // The augmented rows [a | b | I]. The identity part records the row operations, so a row `[0 | 1 | y]` gives the certificate.\n const rows = a.map((row, i) => [...row, b[i]!, ...Array.from({ length: m }, (_, k) => (k === i ? ONE : ZERO))]);\n const pivots = eliminate(rows, columns + 1);\n const last = pivots.length - 1;\n if (last >= 0 && pivots[last] === columns) {\n return { status: \"inconsistent\", certificate: rows[last]!.slice(columns + 1) };\n }\n const x: Rational[] = new Array<Rational>(columns).fill(ZERO);\n pivots.forEach((p, k) => {\n x[p] = rows[k]![columns]!;\n });\n return { status: \"solved\", x, nullSpace: nullSpace(a, columns) };\n}\n","/**\n * Linear programs as data, and their results with certificates.\n *\n * @packageDocumentation\n */\nimport type { Rational } from \"@mark1russell7/rational\";\nimport { type RationalInput, type Vector, toRational, vector } from \"./vector.ts\";\n\n/** The direction of an objective: `\"max\"` to maximize it, `\"min\"` to minimize it. */\nexport type Sense = \"max\" | \"min\";\n\n/** The relation of a constraint row to its right side. */\nexport type Relation = \"<=\" | \">=\" | \"=\";\n\n/** One constraint row: `coefficients · x` has the relation `relation` to `rhs`. */\nexport interface Constraint {\n readonly coefficients: Vector;\n readonly relation: Relation;\n readonly rhs: Rational;\n}\n\n/**\n * A linear program: optimize `objective · x` subject to the constraint rows and `x >= 0`. Each variable has the lower bound 0.\n * A free variable `v` is the difference of two variables `p - q`. Copy each coefficient of `v` to `p`. Put its negative on `q`.\n */\nexport interface LinearProgram {\n readonly sense: Sense;\n readonly objective: Vector;\n readonly constraints: readonly Constraint[];\n}\n\n/**\n * The result of a linear program, with its certificate.\n *\n * - `optimal`: the point `x`, its value `objective · x`, and a dual vector `dual` with one entry for each constraint row.\n * - `infeasible`: a Farkas ray `ray` with one entry for each constraint row. `checkCertificate` tells its conditions.\n * - `unbounded`: a feasible point `x` and a direction `direction`. Each point `x + t direction` with `t >= 0` is feasible, and\n * the objective improves without limit along it.\n */\nexport type LinearProgramResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly value: Rational; readonly dual: Vector }\n | { readonly status: \"infeasible\"; readonly ray: Vector }\n | { readonly status: \"unbounded\"; readonly x: Vector; readonly direction: Vector };\n\n/** One constraint row of `linearProgram`, with inputs that `toRational` reads. */\nexport interface ConstraintInput {\n readonly coefficients: readonly RationalInput[];\n readonly relation: Relation;\n readonly rhs: RationalInput;\n}\n\n/** A linear program with inputs that `toRational` reads. */\nexport interface LinearProgramInput {\n readonly sense: Sense;\n readonly objective: readonly RationalInput[];\n readonly constraints: readonly ConstraintInput[];\n}\n\n/**\n * This function makes a linear program from inputs that `toRational` reads, and examines its shape.\n *\n * @throws {RangeError} A constraint row has a length that is not the length of the objective.\n */\nexport function linearProgram(input: LinearProgramInput): LinearProgram {\n const program: LinearProgram = {\n sense: input.sense,\n objective: vector(input.objective),\n constraints: input.constraints.map((c) => ({ coefficients: vector(c.coefficients), relation: c.relation, rhs: toRational(c.rhs) })),\n };\n checkShape(program);\n return program;\n}\n\n/**\n * This function examines the shape of a program: each constraint row has one coefficient for each variable.\n *\n * @throws {RangeError} A constraint row has a length that is not the length of the objective.\n */\nexport function checkShape(program: LinearProgram): void {\n const n = program.objective.length;\n program.constraints.forEach((c, i) => {\n if (c.coefficients.length !== n) {\n throw new RangeError(`linear: constraint ${i} has ${c.coefficients.length} coefficients, and the objective has ${n}`);\n }\n });\n}\n","/**\n * The exact two-phase simplex. The rule of Bland selects each pivot, so the method ends on each program.\n *\n * @packageDocumentation\n */\nimport { type Rational, compare, div, inverse, mul, neg, ONE, sign, sub, ZERO } from \"@mark1russell7/rational\";\nimport { solve } from \"./matrix.ts\";\nimport { checkShape, type LinearProgram, type LinearProgramResult, type Relation } from \"./program.ts\";\nimport { dot } from \"./vector.ts\";\n\n/**\n * The rule that selects the entering column. `\"bland\"` takes the column with the smallest index that improves the objective.\n * `\"largest\"` takes the column with the largest reduced cost, with the smallest index on a tie. The rule `\"largest\"` can cycle\n * on a degenerate program, and the tests use it only to show that cycle.\n *\n * @internal\n */\nexport type PivotRule = \"bland\" | \"largest\";\n\n/** The program in equality form: `rows z = rhs`, `z >= 0`, with `rhs >= 0`. */\ninterface StandardForm {\n /** The original columns, then one slack or surplus column for each inequality row, then one artificial column for each row that needs one. */\n readonly rows: readonly (readonly Rational[])[];\n readonly rhs: readonly Rational[];\n /** The rows that the form multiplies by -1, so that their right side is not negative. */\n readonly flipped: readonly boolean[];\n /** The first basis: the slack column of a `<=` row, or the artificial column of the row. */\n readonly basis: readonly number[];\n /** The count of columns that are not artificial. */\n readonly structural: number;\n}\n\n/** The working tableau: the rows in the form of the current basis. */\ninterface Tableau {\n readonly rows: Rational[][];\n readonly rhs: Rational[];\n readonly basis: number[];\n}\n\nconst FLIP: Readonly<Record<Relation, Relation>> = { \"<=\": \">=\", \">=\": \"<=\", \"=\": \"=\" };\n\nfunction standardForm(program: LinearProgram): StandardForm {\n const n = program.objective.length;\n const rels = program.constraints.map((c) => (sign(c.rhs) < 0 ? FLIP[c.relation] : c.relation));\n const slacks = rels.filter((r) => r !== \"=\").length;\n const artificials = rels.filter((r) => r !== \"<=\").length;\n const structural = n + slacks;\n const total = structural + artificials;\n const rows: Rational[][] = [];\n const rhs: Rational[] = [];\n const flipped: boolean[] = [];\n const basis: number[] = [];\n let slack = n;\n let artificial = structural;\n program.constraints.forEach((c, i) => {\n const flip = sign(c.rhs) < 0;\n const row: Rational[] = new Array<Rational>(total).fill(ZERO);\n c.coefficients.forEach((v, j) => {\n row[j] = flip ? neg(v) : v;\n });\n const rel = rels[i]!;\n if (rel === \"<=\") {\n row[slack] = ONE;\n basis.push(slack++);\n } else {\n if (rel === \">=\") row[slack++] = neg(ONE);\n row[artificial] = ONE;\n basis.push(artificial++);\n }\n rows.push(row);\n rhs.push(flip ? neg(c.rhs) : c.rhs);\n flipped.push(flip);\n });\n return { rows, rhs, flipped, basis, structural };\n}\n\nfunction pivot(t: Tableau, p: number, q: number): void {\n const scale = inverse(t.rows[p]![q]!);\n const pivotRow = t.rows[p]!.map((v) => mul(v, scale));\n const pivotRhs = mul(t.rhs[p]!, scale);\n t.rows[p] = pivotRow;\n t.rhs[p] = pivotRhs;\n for (let i = 0; i < t.rows.length; i++) {\n const f = t.rows[i]![q]!;\n if (i === p || sign(f) === 0) continue;\n t.rows[i] = t.rows[i]!.map((v, j) => sub(v, mul(f, pivotRow[j]!)));\n t.rhs[i] = sub(t.rhs[i]!, mul(f, pivotRhs));\n }\n t.basis[p] = q;\n}\n\n/** This function gives the reduced cost `c_j - c_B B^-1 A_j` of each column, for a maximization. */\nfunction reducedCosts(t: Tableau, cost: readonly Rational[]): Rational[] {\n const r = [...cost];\n t.rows.forEach((row, i) => {\n const cb = cost[t.basis[i]!]!;\n if (sign(cb) === 0) return;\n for (let j = 0; j < r.length; j++) r[j] = sub(r[j]!, mul(cb, row[j]!));\n });\n return r;\n}\n\ntype Phase = { readonly kind: \"optimal\" } | { readonly kind: \"unbounded\"; readonly column: number } | { readonly kind: \"cycle\" };\n\nconst basisKey = (basis: readonly number[]): string => [...basis].sort((a, b) => a - b).join(\",\");\n\n/** This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. */\nfunction runPhase(t: Tableau, cost: readonly Rational[], allowed: number, rule: PivotRule, count: { pivots: number }): Phase {\n const seen = new Set<string>([basisKey(t.basis)]);\n for (;;) {\n const r = reducedCosts(t, cost);\n let q = -1;\n for (let j = 0; j < allowed; j++) {\n if (sign(r[j]!) <= 0) continue;\n if (rule === \"bland\") {\n q = j;\n break;\n }\n if (q < 0 || compare(r[j]!, r[q]!) > 0) q = j;\n }\n if (q < 0) return { kind: \"optimal\" };\n let p = -1;\n let best = ZERO;\n t.rows.forEach((row, i) => {\n const a = row[q]!;\n if (sign(a) <= 0) return;\n const ratio = div(t.rhs[i]!, a);\n const order = p < 0 ? -1 : compare(ratio, best);\n if (order < 0 || (order === 0 && t.basis[i]! < t.basis[p]!)) {\n p = i;\n best = ratio;\n }\n });\n if (p < 0) return { kind: \"unbounded\", column: q };\n pivot(t, p, q);\n count.pivots++;\n // A deterministic rule that meets a basis again repeats its cycle forever. The rule of Bland does not meet a basis again.\n const key = basisKey(t.basis);\n if (seen.has(key)) return { kind: \"cycle\" };\n seen.add(key);\n }\n}\n\n/** This function gives the dual of the basis in the rows of the program: the solution of `B^T y = c_B`, with the flips undone. */\nfunction dualOf(form: StandardForm, basis: readonly number[], cost: readonly Rational[]): Rational[] {\n if (basis.length === 0) return [];\n const bt = basis.map((col) => form.rows.map((row) => row[col]!));\n const solved = solve(bt, basis.map((col) => cost[col]!));\n if (solved.status !== \"solved\") throw new Error(\"linear: internal error, the basis is singular\");\n return solved.x.map((y, i) => (form.flipped[i] ? neg(y) : y));\n}\n\n/** This function gives the first `n` entries of the basic solution of the tableau. */\nfunction pointOf(t: Tableau, n: number): Rational[] {\n const x: Rational[] = new Array<Rational>(n).fill(ZERO);\n t.basis.forEach((col, i) => {\n if (col < n) x[col] = t.rhs[i]!;\n });\n return x;\n}\n\n/**\n * The run of the simplex with a pivot rule: the result, or a cycle, and the count of pivots.\n *\n * @internal\n */\nexport type SimplexRun =\n | { readonly cycled: false; readonly result: LinearProgramResult; readonly pivots: number }\n | { readonly cycled: true; readonly pivots: number };\n\n/**\n * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland.\n *\n * @internal\n */\nexport function runSimplex(program: LinearProgram, rule: PivotRule): SimplexRun {\n checkShape(program);\n const n = program.objective.length;\n const form = standardForm(program);\n const total = form.rows[0]?.length ?? n;\n const t: Tableau = { rows: form.rows.map((row) => [...row]), rhs: [...form.rhs], basis: [...form.basis] };\n const count = { pivots: 0 };\n\n // Phase 1: maximize the negative sum of the artificial columns.\n if (total > form.structural) {\n const cost = Array.from({ length: total }, (_, j) => (j >= form.structural ? neg(ONE) : ZERO));\n const phase = runPhase(t, cost, total, rule, count);\n if (phase.kind === \"cycle\") return { cycled: true, pivots: count.pivots };\n let value = ZERO;\n t.basis.forEach((col, i) => {\n value = sub(value, col >= form.structural ? t.rhs[i]! : ZERO);\n });\n if (sign(value) < 0) {\n return { cycled: false, result: { status: \"infeasible\", ray: dualOf(form, t.basis, cost) }, pivots: count.pivots };\n }\n // Each artificial column in the basis has the value 0. Move it out on a column that is not artificial, if the row has one.\n t.basis.forEach((col, i) => {\n if (col < form.structural) return;\n const j = t.rows[i]!.findIndex((v, k) => k < form.structural && sign(v) !== 0);\n if (j >= 0) pivot(t, i, j);\n });\n }\n\n // Phase 2: the objective, as a maximization. An artificial column cannot enter, and a row that keeps one is redundant.\n const max = program.sense === \"max\";\n const cost = Array.from({ length: total }, (_, j) => (j < n ? (max ? program.objective[j]! : neg(program.objective[j]!)) : ZERO));\n const phase = runPhase(t, cost, form.structural, rule, count);\n if (phase.kind === \"cycle\") return { cycled: true, pivots: count.pivots };\n const x = pointOf(t, n);\n if (phase.kind === \"unbounded\") {\n const q = phase.column;\n const direction: Rational[] = new Array<Rational>(n).fill(ZERO);\n if (q < n) direction[q] = ONE;\n t.basis.forEach((col, i) => {\n if (col < n) direction[col] = neg(t.rows[i]![q]!);\n });\n return { cycled: false, result: { status: \"unbounded\", x, direction }, pivots: count.pivots };\n }\n const dual = dualOf(form, t.basis, cost);\n return {\n cycled: false,\n result: { status: \"optimal\", x, value: dot(program.objective, x), dual: max ? dual : dual.map(neg) },\n pivots: count.pivots,\n };\n}\n\n/**\n * This function solves a linear program exactly with the two-phase simplex and the rule of Bland. The result has a certificate\n * that `checkCertificate` examines.\n *\n * @throws {RangeError} A constraint row has a length that is not the length of the objective.\n */\nexport function solveLinearProgram(program: LinearProgram): LinearProgramResult {\n const run = runSimplex(program, \"bland\");\n if (run.cycled) throw new Error(\"linear: internal error, the rule of Bland met a basis again\");\n return run.result;\n}\n\n","/**\n * Lexicographic objectives: a list of objectives, each optimized in turn while the earlier optima stay as equalities.\n *\n * @packageDocumentation\n */\nimport type { Rational } from \"@mark1russell7/rational\";\nimport type { Constraint, LinearProgram, LinearProgramResult, Sense } from \"./program.ts\";\nimport { solveLinearProgram } from \"./simplex.ts\";\nimport type { Vector } from \"./vector.ts\";\n\n/** One objective of a lexicographic program. */\nexport interface Objective {\n readonly sense: Sense;\n readonly coefficients: Vector;\n}\n\n/** One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate. */\nexport interface LexicographicStage {\n readonly program: LinearProgram;\n readonly result: LinearProgramResult;\n}\n\n/**\n * The result of `solveLexicographic`. The status `optimal` gives the last point and the optimum of each objective. The status\n * `infeasible` or `unbounded` comes from the last stage, and its result has the certificate. `checkCertificate` examines each\n * stage with its program.\n */\nexport type LexicographicResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly values: readonly Rational[]; readonly stages: readonly LexicographicStage[] }\n | { readonly status: \"infeasible\" | \"unbounded\"; readonly stages: readonly LexicographicStage[] };\n\n/**\n * This function optimizes the objectives in their order, subject to the constraint rows and `x >= 0`. Stage `k` holds the\n * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.\n * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.\n *\n * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.\n */\nexport function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[]): LexicographicResult {\n if (objectives.length === 0) throw new RangeError(\"linear: a lexicographic program needs one objective or more\");\n const stages: LexicographicStage[] = [];\n const rows: Constraint[] = [...constraints];\n const values: Rational[] = [];\n let x: Vector = [];\n for (const objective of objectives) {\n const program: LinearProgram = { sense: objective.sense, objective: objective.coefficients, constraints: [...rows] };\n const result = solveLinearProgram(program);\n stages.push({ program, result });\n if (result.status !== \"optimal\") return { status: result.status, stages };\n x = result.x;\n values.push(result.value);\n rows.push({ coefficients: objective.coefficients, relation: \"=\", rhs: result.value });\n }\n return { status: \"optimal\", x, values, stages };\n}\n","/**\n * The check of a certificate. It uses only exact arithmetic on the program and the result, and it does not trust the solver.\n *\n * @packageDocumentation\n */\nimport { type Rational, equals, mul, sign, sub, toString } from \"@mark1russell7/rational\";\nimport type { LinearProgram, LinearProgramResult, Relation } from \"./program.ts\";\nimport { dot, type Vector } from \"./vector.ts\";\n\n/** The verdict of `checkCertificate`. The list `failures` names each condition that the certificate does not meet. */\nexport interface CertificateCheck {\n readonly valid: boolean;\n readonly failures: readonly string[];\n}\n\n/** This function tells if the sign of a value obeys a relation to 0. */\nfunction holds(s: -1 | 0 | 1, relation: Relation): boolean {\n return relation === \"=\" ? s === 0 : relation === \"<=\" ? s <= 0 : s >= 0;\n}\n\n/** This function gives the column sums `y A`: entry `j` is the sum over the rows of `y_i a_ij`. */\nfunction columnSums(program: LinearProgram, y: Vector): Rational[] {\n return program.objective.map((_, j) => dot(program.constraints.map((c) => c.coefficients[j]!), y));\n}\n\n/**\n * This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`.\n *\n * @internal\n */\nexport function checkFeasible(program: LinearProgram, x: Vector, failures: string[]): void {\n if (x.length !== program.objective.length) {\n failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);\n return;\n }\n x.forEach((v, j) => {\n if (sign(v) < 0) failures.push(`x[${j}] = ${toString(v)} is negative`);\n });\n program.constraints.forEach((c, i) => {\n const lhs = dot(c.coefficients, x);\n if (!holds(sign(sub(lhs, c.rhs)), c.relation)) {\n failures.push(`row ${i}: ${toString(lhs)} ${c.relation} ${toString(c.rhs)} is false`);\n }\n });\n}\n\n/**\n * This function adds a failure for each multiplier with the wrong sign. With `s = 1`, a `<=` row needs a multiplier of 0 or\n * more, and a `>=` row a multiplier of 0 or less. The value `s = -1` swaps the two signs. An `=` row takes each sign.\n */\nfunction checkMultiplierSigns(program: LinearProgram, y: Vector, s: 1 | -1, name: string, failures: string[]): void {\n program.constraints.forEach((c, i) => {\n const signed = sign(y[i]!) * s;\n if ((c.relation === \"<=\" && signed < 0) || (c.relation === \">=\" && signed > 0)) {\n failures.push(`${name}[${i}] = ${toString(y[i]!)} has the wrong sign for a ${c.relation} row`);\n }\n });\n}\n\nfunction checkOptimal(program: LinearProgram, x: Vector, value: Rational, y: Vector, failures: string[]): void {\n const m = program.constraints.length;\n if (y.length !== m) failures.push(`the dual has ${y.length} entries, and the program has ${m} rows`);\n checkFeasible(program, x, failures);\n if (y.length !== m || x.length !== program.objective.length) return;\n const s = program.sense === \"max\" ? 1 : -1;\n checkMultiplierSigns(program, y, s, \"dual\", failures);\n const sums = columnSums(program, y);\n sums.forEach((sum, j) => {\n const slack = sub(sum, program.objective[j]!);\n if (sign(slack) * s < 0) failures.push(`the dual constraint of column ${j} is false: (yA)[${j}] - c[${j}] = ${toString(slack)}`);\n if (sign(mul(x[j]!, slack)) !== 0) failures.push(`complementary slackness fails at column ${j}`);\n });\n program.constraints.forEach((c, i) => {\n if (sign(mul(y[i]!, sub(dot(c.coefficients, x), c.rhs))) !== 0) failures.push(`complementary slackness fails at row ${i}`);\n });\n const primal = dot(program.objective, x);\n const dual = dot(\n program.constraints.map((c) => c.rhs),\n y,\n );\n if (!equals(primal, value)) failures.push(`the value ${toString(value)} is not c x = ${toString(primal)}`);\n if (!equals(primal, dual)) failures.push(`strong duality fails: c x = ${toString(primal)} and b y = ${toString(dual)}`);\n}\n\nfunction checkInfeasible(program: LinearProgram, y: Vector, failures: string[]): void {\n const m = program.constraints.length;\n if (y.length !== m) {\n failures.push(`the ray has ${y.length} entries, and the program has ${m} rows`);\n return;\n }\n checkMultiplierSigns(program, y, 1, \"ray\", failures);\n columnSums(program, y).forEach((sum, j) => {\n if (sign(sum) < 0) failures.push(`(yA)[${j}] = ${toString(sum)} is negative`);\n });\n const by = dot(\n program.constraints.map((c) => c.rhs),\n y,\n );\n if (sign(by) >= 0) failures.push(`b y = ${toString(by)} is not negative`);\n}\n\nfunction checkUnbounded(program: LinearProgram, x: Vector, d: Vector, failures: string[]): void {\n checkFeasible(program, x, failures);\n if (d.length !== program.objective.length) {\n failures.push(`the direction has ${d.length} entries, and the program has ${program.objective.length} variables`);\n return;\n }\n d.forEach((v, j) => {\n if (sign(v) < 0) failures.push(`direction[${j}] = ${toString(v)} is negative`);\n });\n program.constraints.forEach((c, i) => {\n const ad = dot(c.coefficients, d);\n if (!holds(sign(ad), c.relation)) failures.push(`row ${i}: the direction gives ${toString(ad)}, so it leaves the row`);\n });\n const gain = dot(program.objective, d);\n const s = program.sense === \"max\" ? 1 : -1;\n if (sign(gain) * s <= 0) failures.push(`the direction does not improve the objective: c d = ${toString(gain)}`);\n}\n\n/**\n * This function examines the certificate of a result with exact arithmetic. It does not trust the solver.\n *\n * - `optimal`: the point is feasible, the dual is feasible, `c x = b y` and complementary slackness holds. For a maximization,\n * the dual obeys `y A >= c`, `y_i >= 0` on a `<=` row and `y_i <= 0` on a `>=` row. A minimization swaps each of these signs.\n * - `infeasible`: the ray obeys `y A >= 0`, `b y < 0`, `y_i >= 0` on a `<=` row and `y_i <= 0` on a `>=` row. Then no `x >= 0`\n * meets the rows, because `0 <= y A x <= y b < 0`.\n * - `unbounded`: the point is feasible, the direction is not negative, each row keeps its relation along it, and the\n * direction improves the objective.\n */\nexport function checkCertificate(program: LinearProgram, result: LinearProgramResult): CertificateCheck {\n const failures: string[] = [];\n if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {\n failures.push(\"a constraint row has a length that is not the count of variables\");\n } else if (result.status === \"optimal\") {\n checkOptimal(program, result.x, result.value, result.dual, failures);\n } else if (result.status === \"infeasible\") {\n checkInfeasible(program, result.ray, failures);\n } else {\n checkUnbounded(program, result.x, result.direction, failures);\n }\n return { valid: failures.length === 0, failures };\n}\n","/**\n * Integer programs: branch and bound on the exact simplex. The certificate of a result is the tree of its nodes.\n *\n * @packageDocumentation\n */\nimport { type Rational, add, compare, equals, floor, gcd, isInteger, ONE, rational, toString, ZERO } from \"@mark1russell7/rational\";\nimport { type CertificateCheck, checkCertificate, checkFeasible } from \"./certificate.ts\";\nimport { checkShape, type Constraint, type LinearProgram, type LinearProgramResult } from \"./program.ts\";\nimport { solveLinearProgram } from \"./simplex.ts\";\nimport { dot, type Vector } from \"./vector.ts\";\n\n/** A linear program in which each variable of the list `integer` takes integer values only. The other variables are continuous. */\nexport interface IntegerProgram extends LinearProgram {\n /** The indices of the integer variables. */\n readonly integer: readonly number[];\n}\n\n/** The row that a node adds to the rows of its parent: `x[variable] <= value` or `x[variable] >= value`. The value is an integer. */\nexport interface Branch {\n readonly variable: number;\n readonly relation: \"<=\" | \">=\";\n readonly value: Rational;\n}\n\n/**\n * The outcome of a node of the tree.\n *\n * - `branched`: the node has two children. One child adds `x_j <= k`, and the other child adds `x_j >= k + 1`.\n * - `integer`: the relaxation of the node has an optimum with an integer value on each integer variable.\n * - `bound`: the optimum of the relaxation is not better than the best integer point that the solve found before the node.\n * - `infeasible`: the relaxation of the node has no point.\n * - `open`: the solve stopped at its limit before the node.\n */\nexport type NodeOutcome = \"branched\" | \"integer\" | \"bound\" | \"infeasible\" | \"open\";\n\n/** One node of the tree. The root is node 0. Each other node has a parent with a smaller index. */\nexport interface BranchNode {\n readonly parent: number | undefined;\n readonly branch: Branch | undefined;\n readonly outcome: NodeOutcome;\n /** The result of the relaxation of the node, with its certificate. An open node has no result. */\n readonly result: LinearProgramResult | undefined;\n}\n\n/**\n * The result of an integer program, with its certificate.\n *\n * - `optimal`: the point `x`, its value, and the tree. Each leaf proves that its integer points are not better than `x`.\n * - `infeasible`: the tree. Each leaf has a Farkas ray, so the program has no integer point.\n * - `unbounded`: an integer point `x` and a direction `direction` with an integer value on each integer variable.\n * Each point `x + t direction` with an integer `t >= 0` is an integer point, and the objective improves without limit.\n * - `limit`: the solve stopped at its limit. It gives the best integer point that it found, if any. `bound` is a bound of the\n * optimum that the tree proves. A program with an unbounded relaxation gives no bound.\n */\nexport type IntegerProgramResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly value: Rational; readonly tree: readonly BranchNode[] }\n | { readonly status: \"infeasible\"; readonly tree: readonly BranchNode[] }\n | { readonly status: \"unbounded\"; readonly x: Vector; readonly direction: Vector }\n | {\n readonly status: \"limit\";\n readonly x: Vector | undefined;\n readonly value: Rational | undefined;\n readonly bound: Rational | undefined;\n readonly tree: readonly BranchNode[];\n };\n\n/** The options of `solveIntegerProgram`. */\nexport interface IntegerOptions {\n /** The largest count of relaxations that the solve solves. The default is 10000. */\n readonly nodeLimit?: number;\n}\n\n/** A node in construction. */\ninterface WorkNode {\n readonly parent: number | undefined;\n readonly branch: Branch | undefined;\n outcome: NodeOutcome;\n result: LinearProgramResult | undefined;\n}\n\n/** The result of one search, before the solve gives its status. */\ninterface Search {\n readonly best: { readonly x: Vector; readonly value: Rational } | undefined;\n readonly nodes: readonly WorkNode[];\n /** True when the search stopped at its limit with open nodes. */\n readonly stopped: boolean;\n}\n\n/**\n * This function gives the problems of the list `integer` of a program: an index that is not an integer, or not a variable.\n *\n * @internal\n */\nexport function integerProblems(program: IntegerProgram): string[] {\n const n = program.objective.length;\n return program.integer.filter((j) => !Number.isInteger(j) || j < 0 || j >= n).map((j) => `the integer variable ${String(j)} is not a variable of the program`);\n}\n\n/**\n * This function gives the program of a node: the rows of the program, then the row of each branch on the path from the root.\n *\n * @internal\n */\nexport function nodeProgram(program: LinearProgram, tree: readonly Pick<BranchNode, \"parent\" | \"branch\">[], id: number): LinearProgram {\n const rows: Constraint[] = [];\n const n = program.objective.length;\n for (let at: number | undefined = id; at !== undefined; at = tree[at]?.parent) {\n const branch = tree[at]?.branch;\n if (branch === undefined) continue;\n const coefficients = Array.from({ length: n }, (_, j) => (j === branch.variable ? ONE : ZERO));\n rows.push({ coefficients, relation: branch.relation, rhs: branch.value });\n }\n return { ...program, constraints: [...program.constraints, ...rows.reverse()] };\n}\n\n/**\n * This function searches the tree depth first. It branches on the fractional integer variable with the smallest index, and it\n * takes the child `x_j <= k` first. With `first`, it stops at the first integer point.\n */\nfunction search(program: LinearProgram, integer: readonly number[], limit: number, first: boolean, root: LinearProgramResult): Search {\n const s = program.sense === \"max\" ? 1 : -1;\n const nodes: WorkNode[] = [{ parent: undefined, branch: undefined, outcome: \"open\", result: undefined }];\n const stack = [0];\n let best: Search[\"best\"];\n let solved = 0;\n while (stack.length > 0 && solved < limit) {\n const id = stack.pop() as number;\n const node = nodes[id] as WorkNode;\n const result = id === 0 ? root : solveLinearProgram(nodeProgram(program, nodes, id));\n solved++;\n node.result = result;\n if (result.status === \"infeasible\") {\n node.outcome = \"infeasible\";\n continue;\n }\n // A node adds rows to a program with an optimum or with the objective 0, so its relaxation is not unbounded.\n if (result.status === \"unbounded\") throw new Error(\"linear: the relaxation of a node is unbounded, and the relaxation of the root is not\");\n if (best !== undefined && compare(result.value, best.value) * s <= 0) {\n node.outcome = \"bound\";\n continue;\n }\n const j = integer.find((k) => !isInteger(result.x[k] as Rational));\n if (j === undefined) {\n node.outcome = \"integer\";\n best = { x: result.x, value: result.value };\n if (first) return { best, nodes, stopped: false };\n continue;\n }\n node.outcome = \"branched\";\n const k = floor(result.x[j] as Rational);\n nodes.push({ parent: id, branch: { variable: j, relation: \">=\", value: add(k, ONE) }, outcome: \"open\", result: undefined });\n stack.push(nodes.length - 1);\n nodes.push({ parent: id, branch: { variable: j, relation: \"<=\", value: k }, outcome: \"open\", result: undefined });\n stack.push(nodes.length - 1);\n }\n return { best, nodes, stopped: stack.length > 0 };\n}\n\n/** This function gives the direction times the least common multiple of its denominators, so each entry is an integer. */\nfunction integral(direction: Vector): Vector {\n let m = 1n;\n for (const v of direction) m = (m / gcd(m, v.d)) * v.d;\n return direction.map((v) => rational(v.n * (m / v.d)));\n}\n\n/** This function gives the frozen tree of the nodes of a search. */\nfunction treeOf(nodes: readonly WorkNode[]): BranchNode[] {\n return nodes.map(({ parent, branch, outcome, result }) => ({ parent, branch, outcome, result }));\n}\n\n/**\n * This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches\n * on the fractional integer variable with the smallest index.\n *\n * - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.\n * - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is\n * unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.\n * - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.\n *\n * @throws {RangeError} A row has a length that is not the count of variables.\n * @throws {RangeError} An integer variable is not a variable of the program.\n * @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.\n */\nexport function solveIntegerProgram(program: IntegerProgram, options: IntegerOptions = {}): IntegerProgramResult {\n checkShape(program);\n const problems = integerProblems(program);\n if (problems.length > 0) throw new RangeError(`linear: ${problems.join(\", \")}`);\n const limit = options.nodeLimit ?? 10_000;\n if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`linear: the node limit ${String(limit)} is not an integer of 1 or more`);\n const integer = [...new Set(program.integer)].sort((a, b) => a - b);\n const root = solveLinearProgram(program);\n if (root.status === \"unbounded\") {\n const zero: LinearProgram = { ...program, objective: program.objective.map(() => ZERO) };\n const found = search(zero, integer, limit, true, solveLinearProgram(zero));\n if (found.best !== undefined) return { status: \"unbounded\", x: found.best.x, direction: integral(root.direction) };\n const tree = treeOf(found.nodes);\n if (found.stopped) return { status: \"limit\", x: undefined, value: undefined, bound: undefined, tree };\n return { status: \"infeasible\", tree };\n }\n const found = search(program, integer, limit, false, root);\n const tree = treeOf(found.nodes);\n if (found.stopped) {\n const s = program.sense === \"max\" ? 1 : -1;\n let bound = found.best?.value;\n for (const node of found.nodes) {\n if (node.outcome !== \"open\" || node.parent === undefined) continue;\n const parent = found.nodes[node.parent]?.result;\n if (parent?.status === \"optimal\" && (bound === undefined || compare(parent.value, bound) * s > 0)) bound = parent.value;\n }\n return { status: \"limit\", x: found.best?.x, value: found.best?.value, bound, tree };\n }\n if (found.best === undefined) return { status: \"infeasible\", tree };\n return { status: \"optimal\", x: found.best.x, value: found.best.value, tree };\n}\n\n/** This function adds a failure for each integer variable of `x` with a value that is not an integer. */\nfunction checkIntegral(integer: readonly number[], x: Vector, name: string, failures: string[]): void {\n for (const j of integer) {\n const v = x[j];\n if (v !== undefined && !isInteger(v)) failures.push(`${name}[${String(j)}] = ${toString(v)} is not an integer`);\n }\n}\n\n/** This function adds a failure when the value `v` is better than `limit` in the sense of the program. */\nfunction checkNotBetter(s: 1 | -1, v: Rational, limit: Rational, name: string, failures: string[]): void {\n if (compare(v, limit) * s > 0) failures.push(`${name} ${toString(v)} is better than ${toString(limit)}`);\n}\n\n/**\n * This function examines the tree of a result: its shape, and a certificate for each leaf. With `best`, the value of each leaf\n * is not better than `best`. Each failure goes into `failures`.\n */\nfunction checkTree(program: IntegerProgram, tree: readonly BranchNode[], allowOpen: boolean, best: Rational | undefined, failures: string[]): void {\n const s = program.sense === \"max\" ? 1 : -1;\n const integer = new Set(program.integer);\n const root = tree[0];\n if (root === undefined || root.parent !== undefined || root.branch !== undefined) {\n failures.push(\"node 0 is not a root with no parent and no branch\");\n return;\n }\n const children = tree.map((): number[] => []);\n for (let i = 1; i < tree.length; i++) {\n const node = tree[i] as BranchNode;\n if (node.parent === undefined || !Number.isInteger(node.parent) || node.parent < 0 || node.parent >= i || node.branch === undefined) {\n failures.push(`node ${String(i)} has no parent before it, or no branch`);\n return;\n }\n if (!integer.has(node.branch.variable) || !isInteger(node.branch.value)) failures.push(`node ${String(i)} branches on a variable that is not an integer variable, or at a value that is not an integer`);\n children[node.parent]?.push(i);\n }\n tree.forEach((node, i) => {\n const kids = children[i] as number[];\n if (node.outcome === \"branched\") {\n const [a, b] = kids.map((k) => (tree[k] as BranchNode).branch as Branch);\n const down = [a, b].find((branch) => branch?.relation === \"<=\");\n const up = [a, b].find((branch) => branch?.relation === \">=\");\n if (kids.length !== 2 || down === undefined || up === undefined || down.variable !== up.variable || !equals(add(down.value, ONE), up.value)) {\n failures.push(`node ${String(i)} is branched, and its children are not x_j <= k and x_j >= k + 1`);\n }\n return;\n }\n if (kids.length > 0) failures.push(`node ${String(i)} has children, and its outcome is ${node.outcome}`);\n if (node.outcome === \"open\") {\n if (!allowOpen) failures.push(`node ${String(i)} is open`);\n if (best === undefined || node.parent === undefined) return;\n // The integer points of an open node are not better than the optimum of the relaxation of its parent.\n const parent = tree[node.parent]?.result;\n if (parent?.status !== \"optimal\") {\n failures.push(`node ${String(i)} is open, and its parent has no optimum`);\n return;\n }\n const check = checkCertificate(nodeProgram(program, tree, node.parent), parent);\n for (const failure of check.failures) failures.push(`node ${String(node.parent)}: ${failure}`);\n checkNotBetter(s, parent.value, best, `the parent of the open node ${String(i)} has the value`, failures);\n return;\n }\n const result = node.result;\n if (result === undefined) {\n failures.push(`node ${String(i)} is a leaf with no result`);\n return;\n }\n const check = checkCertificate(nodeProgram(program, tree, i), result);\n for (const failure of check.failures) failures.push(`node ${String(i)}: ${failure}`);\n if (node.outcome === \"infeasible\") {\n if (result.status !== \"infeasible\") failures.push(`node ${String(i)} is infeasible, and its result is ${result.status}`);\n return;\n }\n if (result.status !== \"optimal\") {\n failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome}, and its result is ${result.status}`);\n return;\n }\n if (node.outcome === \"integer\") checkIntegral(program.integer, result.x, `node ${String(i)}: x`, failures);\n if (best === undefined) failures.push(`node ${String(i)} has an optimum, and the result claims no integer point`);\n else checkNotBetter(s, result.value, best, `node ${String(i)} has the value`, failures);\n });\n}\n\n/**\n * This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.\n *\n * - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer\n * point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its\n * relaxation, and its value is not better than the value of the point.\n * - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.\n * - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.\n * - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed\n * leaf has a valid certificate. With a bound, each leaf and the parent of each open node have a value that is not better than the bound.\n */\nexport function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): CertificateCheck {\n const failures: string[] = [];\n if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {\n failures.push(\"a constraint row has a length that is not the count of variables\");\n return { valid: false, failures };\n }\n failures.push(...integerProblems(program));\n if (failures.length > 0) return { valid: false, failures };\n const s = program.sense === \"max\" ? 1 : -1;\n const point = (x: Vector, value: Rational): void => {\n checkFeasible(program, x, failures);\n checkIntegral(program.integer, x, \"x\", failures);\n if (x.length === program.objective.length && !equals(dot(program.objective, x), value)) failures.push(`the value ${toString(value)} is not c x = ${toString(dot(program.objective, x))}`);\n };\n if (result.status === \"unbounded\") {\n failures.push(...checkCertificate(program, { status: \"unbounded\", x: result.x, direction: result.direction }).failures);\n checkIntegral(program.integer, result.x, \"x\", failures);\n checkIntegral(program.integer, result.direction, \"direction\", failures);\n } else if (result.status === \"optimal\") {\n point(result.x, result.value);\n checkTree(program, result.tree, false, result.value, failures);\n } else if (result.status === \"infeasible\") {\n checkTree(program, result.tree, false, undefined, failures);\n result.tree.forEach((node, i) => {\n if (node.outcome !== \"branched\" && node.outcome !== \"infeasible\") failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome} in an infeasible result`);\n });\n } else {\n if ((result.x === undefined) !== (result.value === undefined)) failures.push(\"the limit result has a point with no value, or a value with no point\");\n if (result.x !== undefined && result.value !== undefined) {\n point(result.x, result.value);\n if (result.bound === undefined) failures.push(\"the limit result has a point and no bound\");\n else checkNotBetter(s, result.value, result.bound, \"the value\", failures);\n }\n checkTree(program, result.tree, true, result.bound, failures);\n }\n return { valid: failures.length === 0, failures };\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAgB,WAAW,OAAgC;CACzD,IAAI,OAAO,UAAU,UAAU,OAAO,SAAS,KAAK;CACpD,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,MAAM,IAAI,WAAW,WAAW,MAAM,wBAAwB;EAC3F,OAAO,WAAW,KAAK;CACzB;CACA,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,QAAQ,MAAM,QAAQ,GAAG;EAC/B,IAAI,QAAQ,GAAG,OAAO,YAAY,MAAM,KAAK,CAAC;EAC9C,OAAO,IAAI,YAAY,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,YAAY,MAAM,MAAM,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;CAClG;CACA,OAAO;AACT;;AAGA,SAAgB,OAAO,QAA0C;CAC/D,OAAO,OAAO,IAAI,UAAU;AAC9B;;;;;;AAOA,SAAgB,OAAO,MAAqD;CAC1E,MAAM,SAAS,KAAK,IAAI,MAAM;CAC9B,UAAU,MAAM;CAChB,OAAO;AACT;;;;;;AAOA,SAAgB,UAAU,GAAmB;CAC3C,MAAM,IAAI,EAAE,EAAE,EAAE,UAAU;CAC1B,KAAK,MAAM,OAAO,GAChB,IAAI,IAAI,WAAW,GAAG,MAAM,IAAI,WAAW,qBAAqB,IAAI,OAAO,kCAAkC,GAAG;CAElH,OAAO;AACT;;;;;;AAOA,SAAgB,IAAI,GAAW,GAAqB;CAClD,IAAI,EAAE,WAAW,EAAE,QAAQ,MAAM,IAAI,WAAW,4BAA4B,EAAE,OAAO,OAAO,EAAE,OAAO,SAAS;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G,KAAK,QAAQ;EACtD,cAAc,QAAQ,SAAS,OAAO,WAAW,aAAa,QAAQ;CACxE,OAAO,IAAI,OAAO,WAAW,WAAW;EACtC,MAAM,OAAO,GAAG,OAAO,KAAK;EAC5B,UAAU,SAAS,OAAO,MAAM,OAAO,OAAO,OAAO,QAAQ;CAC/D,OAAO,IAAI,OAAO,WAAW,cAAc;EACzC,UAAU,SAAS,OAAO,MAAM,OAAO,KAAA,GAAW,QAAQ;EAC1D,OAAO,KAAK,SAAS,MAAM,MAAM;GAC/B,IAAI,KAAK,YAAY,cAAc,KAAK,YAAY,cAAc,SAAS,KAAK,QAAQ,OAAO,CAAC,EAAE,4BAA4B,KAAK,QAAQ,yBAAyB;EACtK,CAAC;CACH,OAAO;EACL,IAAK,OAAO,MAAM,KAAA,OAAgB,OAAO,UAAU,KAAA,IAAY,SAAS,KAAK,sEAAsE;EACnJ,IAAI,OAAO,MAAM,KAAA,KAAa,OAAO,UAAU,KAAA,GAAW;GACxD,MAAM,OAAO,GAAG,OAAO,KAAK;GAC5B,IAAI,OAAO,UAAU,KAAA,GAAW,SAAS,KAAK,2CAA2C;QACpF,eAAe,GAAG,OAAO,OAAO,OAAO,OAAO,aAAa,QAAQ;EAC1E;EACA,UAAU,SAAS,OAAO,MAAM,MAAM,OAAO,OAAO,QAAQ;CAC9D;CACA,OAAO;EAAE,OAAO,SAAS,WAAW;EAAG;CAAS;AAClD"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/linear",
|
|
4
|
-
"version": "0.1.
|
|
5
|
-
"description": "Exact linear algebra and linear programs over exact rationals: solve, rank, null space, a two-phase simplex with the rule of Bland, lexicographic objectives and certificates with a check.",
|
|
4
|
+
"version": "0.1.1",
|
|
5
|
+
"description": "Exact linear algebra and linear programs over exact rationals: solve, rank, null space, a two-phase simplex with the rule of Bland, lexicographic objectives, integer programs by branch and bound, and certificates with a check.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"linear-algebra",
|
|
8
8
|
"linear-programming",
|
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
"rational",
|
|
12
12
|
"certificate",
|
|
13
13
|
"farkas",
|
|
14
|
-
"duality"
|
|
14
|
+
"duality",
|
|
15
|
+
"integer-programming",
|
|
16
|
+
"branch-and-bound"
|
|
15
17
|
],
|
|
16
18
|
"homepage": "https://github.com/mark1russell7/algebra/tree/main/packages/linear#readme",
|
|
17
19
|
"bugs": {
|
package/src/certificate.ts
CHANGED
|
@@ -23,8 +23,12 @@ function columnSums(program: LinearProgram, y: Vector): Rational[] {
|
|
|
23
23
|
return program.objective.map((_, j) => dot(program.constraints.map((c) => c.coefficients[j]!), y));
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
/**
|
|
27
|
-
function
|
|
26
|
+
/**
|
|
27
|
+
* This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`.
|
|
28
|
+
*
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
export function checkFeasible(program: LinearProgram, x: Vector, failures: string[]): void {
|
|
28
32
|
if (x.length !== program.objective.length) {
|
|
29
33
|
failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);
|
|
30
34
|
return;
|
package/src/index.ts
CHANGED
|
@@ -18,3 +18,5 @@ export type { LexicographicResult, LexicographicStage, Objective } from "./lexic
|
|
|
18
18
|
export { solveLexicographic } from "./lexicographic.ts";
|
|
19
19
|
export type { CertificateCheck } from "./certificate.ts";
|
|
20
20
|
export { checkCertificate } from "./certificate.ts";
|
|
21
|
+
export type { Branch, BranchNode, IntegerOptions, IntegerProgram, IntegerProgramResult, NodeOutcome } from "./integer.ts";
|
|
22
|
+
export { checkIntegerCertificate, solveIntegerProgram } from "./integer.ts";
|
package/src/integer.ts
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integer programs: branch and bound on the exact simplex. The certificate of a result is the tree of its nodes.
|
|
3
|
+
*
|
|
4
|
+
* @packageDocumentation
|
|
5
|
+
*/
|
|
6
|
+
import { type Rational, add, compare, equals, floor, gcd, isInteger, ONE, rational, toString, ZERO } from "@mark1russell7/rational";
|
|
7
|
+
import { type CertificateCheck, checkCertificate, checkFeasible } from "./certificate.ts";
|
|
8
|
+
import { checkShape, type Constraint, type LinearProgram, type LinearProgramResult } from "./program.ts";
|
|
9
|
+
import { solveLinearProgram } from "./simplex.ts";
|
|
10
|
+
import { dot, type Vector } from "./vector.ts";
|
|
11
|
+
|
|
12
|
+
/** A linear program in which each variable of the list `integer` takes integer values only. The other variables are continuous. */
|
|
13
|
+
export interface IntegerProgram extends LinearProgram {
|
|
14
|
+
/** The indices of the integer variables. */
|
|
15
|
+
readonly integer: readonly number[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The row that a node adds to the rows of its parent: `x[variable] <= value` or `x[variable] >= value`. The value is an integer. */
|
|
19
|
+
export interface Branch {
|
|
20
|
+
readonly variable: number;
|
|
21
|
+
readonly relation: "<=" | ">=";
|
|
22
|
+
readonly value: Rational;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The outcome of a node of the tree.
|
|
27
|
+
*
|
|
28
|
+
* - `branched`: the node has two children. One child adds `x_j <= k`, and the other child adds `x_j >= k + 1`.
|
|
29
|
+
* - `integer`: the relaxation of the node has an optimum with an integer value on each integer variable.
|
|
30
|
+
* - `bound`: the optimum of the relaxation is not better than the best integer point that the solve found before the node.
|
|
31
|
+
* - `infeasible`: the relaxation of the node has no point.
|
|
32
|
+
* - `open`: the solve stopped at its limit before the node.
|
|
33
|
+
*/
|
|
34
|
+
export type NodeOutcome = "branched" | "integer" | "bound" | "infeasible" | "open";
|
|
35
|
+
|
|
36
|
+
/** One node of the tree. The root is node 0. Each other node has a parent with a smaller index. */
|
|
37
|
+
export interface BranchNode {
|
|
38
|
+
readonly parent: number | undefined;
|
|
39
|
+
readonly branch: Branch | undefined;
|
|
40
|
+
readonly outcome: NodeOutcome;
|
|
41
|
+
/** The result of the relaxation of the node, with its certificate. An open node has no result. */
|
|
42
|
+
readonly result: LinearProgramResult | undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The result of an integer program, with its certificate.
|
|
47
|
+
*
|
|
48
|
+
* - `optimal`: the point `x`, its value, and the tree. Each leaf proves that its integer points are not better than `x`.
|
|
49
|
+
* - `infeasible`: the tree. Each leaf has a Farkas ray, so the program has no integer point.
|
|
50
|
+
* - `unbounded`: an integer point `x` and a direction `direction` with an integer value on each integer variable.
|
|
51
|
+
* Each point `x + t direction` with an integer `t >= 0` is an integer point, and the objective improves without limit.
|
|
52
|
+
* - `limit`: the solve stopped at its limit. It gives the best integer point that it found, if any. `bound` is a bound of the
|
|
53
|
+
* optimum that the tree proves. A program with an unbounded relaxation gives no bound.
|
|
54
|
+
*/
|
|
55
|
+
export type IntegerProgramResult =
|
|
56
|
+
| { readonly status: "optimal"; readonly x: Vector; readonly value: Rational; readonly tree: readonly BranchNode[] }
|
|
57
|
+
| { readonly status: "infeasible"; readonly tree: readonly BranchNode[] }
|
|
58
|
+
| { readonly status: "unbounded"; readonly x: Vector; readonly direction: Vector }
|
|
59
|
+
| {
|
|
60
|
+
readonly status: "limit";
|
|
61
|
+
readonly x: Vector | undefined;
|
|
62
|
+
readonly value: Rational | undefined;
|
|
63
|
+
readonly bound: Rational | undefined;
|
|
64
|
+
readonly tree: readonly BranchNode[];
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** The options of `solveIntegerProgram`. */
|
|
68
|
+
export interface IntegerOptions {
|
|
69
|
+
/** The largest count of relaxations that the solve solves. The default is 10000. */
|
|
70
|
+
readonly nodeLimit?: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A node in construction. */
|
|
74
|
+
interface WorkNode {
|
|
75
|
+
readonly parent: number | undefined;
|
|
76
|
+
readonly branch: Branch | undefined;
|
|
77
|
+
outcome: NodeOutcome;
|
|
78
|
+
result: LinearProgramResult | undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The result of one search, before the solve gives its status. */
|
|
82
|
+
interface Search {
|
|
83
|
+
readonly best: { readonly x: Vector; readonly value: Rational } | undefined;
|
|
84
|
+
readonly nodes: readonly WorkNode[];
|
|
85
|
+
/** True when the search stopped at its limit with open nodes. */
|
|
86
|
+
readonly stopped: boolean;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* This function gives the problems of the list `integer` of a program: an index that is not an integer, or not a variable.
|
|
91
|
+
*
|
|
92
|
+
* @internal
|
|
93
|
+
*/
|
|
94
|
+
export function integerProblems(program: IntegerProgram): string[] {
|
|
95
|
+
const n = program.objective.length;
|
|
96
|
+
return program.integer.filter((j) => !Number.isInteger(j) || j < 0 || j >= n).map((j) => `the integer variable ${String(j)} is not a variable of the program`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* This function gives the program of a node: the rows of the program, then the row of each branch on the path from the root.
|
|
101
|
+
*
|
|
102
|
+
* @internal
|
|
103
|
+
*/
|
|
104
|
+
export function nodeProgram(program: LinearProgram, tree: readonly Pick<BranchNode, "parent" | "branch">[], id: number): LinearProgram {
|
|
105
|
+
const rows: Constraint[] = [];
|
|
106
|
+
const n = program.objective.length;
|
|
107
|
+
for (let at: number | undefined = id; at !== undefined; at = tree[at]?.parent) {
|
|
108
|
+
const branch = tree[at]?.branch;
|
|
109
|
+
if (branch === undefined) continue;
|
|
110
|
+
const coefficients = Array.from({ length: n }, (_, j) => (j === branch.variable ? ONE : ZERO));
|
|
111
|
+
rows.push({ coefficients, relation: branch.relation, rhs: branch.value });
|
|
112
|
+
}
|
|
113
|
+
return { ...program, constraints: [...program.constraints, ...rows.reverse()] };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* This function searches the tree depth first. It branches on the fractional integer variable with the smallest index, and it
|
|
118
|
+
* takes the child `x_j <= k` first. With `first`, it stops at the first integer point.
|
|
119
|
+
*/
|
|
120
|
+
function search(program: LinearProgram, integer: readonly number[], limit: number, first: boolean, root: LinearProgramResult): Search {
|
|
121
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
122
|
+
const nodes: WorkNode[] = [{ parent: undefined, branch: undefined, outcome: "open", result: undefined }];
|
|
123
|
+
const stack = [0];
|
|
124
|
+
let best: Search["best"];
|
|
125
|
+
let solved = 0;
|
|
126
|
+
while (stack.length > 0 && solved < limit) {
|
|
127
|
+
const id = stack.pop() as number;
|
|
128
|
+
const node = nodes[id] as WorkNode;
|
|
129
|
+
const result = id === 0 ? root : solveLinearProgram(nodeProgram(program, nodes, id));
|
|
130
|
+
solved++;
|
|
131
|
+
node.result = result;
|
|
132
|
+
if (result.status === "infeasible") {
|
|
133
|
+
node.outcome = "infeasible";
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
// A node adds rows to a program with an optimum or with the objective 0, so its relaxation is not unbounded.
|
|
137
|
+
if (result.status === "unbounded") throw new Error("linear: the relaxation of a node is unbounded, and the relaxation of the root is not");
|
|
138
|
+
if (best !== undefined && compare(result.value, best.value) * s <= 0) {
|
|
139
|
+
node.outcome = "bound";
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const j = integer.find((k) => !isInteger(result.x[k] as Rational));
|
|
143
|
+
if (j === undefined) {
|
|
144
|
+
node.outcome = "integer";
|
|
145
|
+
best = { x: result.x, value: result.value };
|
|
146
|
+
if (first) return { best, nodes, stopped: false };
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
node.outcome = "branched";
|
|
150
|
+
const k = floor(result.x[j] as Rational);
|
|
151
|
+
nodes.push({ parent: id, branch: { variable: j, relation: ">=", value: add(k, ONE) }, outcome: "open", result: undefined });
|
|
152
|
+
stack.push(nodes.length - 1);
|
|
153
|
+
nodes.push({ parent: id, branch: { variable: j, relation: "<=", value: k }, outcome: "open", result: undefined });
|
|
154
|
+
stack.push(nodes.length - 1);
|
|
155
|
+
}
|
|
156
|
+
return { best, nodes, stopped: stack.length > 0 };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** This function gives the direction times the least common multiple of its denominators, so each entry is an integer. */
|
|
160
|
+
function integral(direction: Vector): Vector {
|
|
161
|
+
let m = 1n;
|
|
162
|
+
for (const v of direction) m = (m / gcd(m, v.d)) * v.d;
|
|
163
|
+
return direction.map((v) => rational(v.n * (m / v.d)));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** This function gives the frozen tree of the nodes of a search. */
|
|
167
|
+
function treeOf(nodes: readonly WorkNode[]): BranchNode[] {
|
|
168
|
+
return nodes.map(({ parent, branch, outcome, result }) => ({ parent, branch, outcome, result }));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches
|
|
173
|
+
* on the fractional integer variable with the smallest index.
|
|
174
|
+
*
|
|
175
|
+
* - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.
|
|
176
|
+
* - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is
|
|
177
|
+
* unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.
|
|
178
|
+
* - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.
|
|
179
|
+
*
|
|
180
|
+
* @throws {RangeError} A row has a length that is not the count of variables.
|
|
181
|
+
* @throws {RangeError} An integer variable is not a variable of the program.
|
|
182
|
+
* @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.
|
|
183
|
+
*/
|
|
184
|
+
export function solveIntegerProgram(program: IntegerProgram, options: IntegerOptions = {}): IntegerProgramResult {
|
|
185
|
+
checkShape(program);
|
|
186
|
+
const problems = integerProblems(program);
|
|
187
|
+
if (problems.length > 0) throw new RangeError(`linear: ${problems.join(", ")}`);
|
|
188
|
+
const limit = options.nodeLimit ?? 10_000;
|
|
189
|
+
if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`linear: the node limit ${String(limit)} is not an integer of 1 or more`);
|
|
190
|
+
const integer = [...new Set(program.integer)].sort((a, b) => a - b);
|
|
191
|
+
const root = solveLinearProgram(program);
|
|
192
|
+
if (root.status === "unbounded") {
|
|
193
|
+
const zero: LinearProgram = { ...program, objective: program.objective.map(() => ZERO) };
|
|
194
|
+
const found = search(zero, integer, limit, true, solveLinearProgram(zero));
|
|
195
|
+
if (found.best !== undefined) return { status: "unbounded", x: found.best.x, direction: integral(root.direction) };
|
|
196
|
+
const tree = treeOf(found.nodes);
|
|
197
|
+
if (found.stopped) return { status: "limit", x: undefined, value: undefined, bound: undefined, tree };
|
|
198
|
+
return { status: "infeasible", tree };
|
|
199
|
+
}
|
|
200
|
+
const found = search(program, integer, limit, false, root);
|
|
201
|
+
const tree = treeOf(found.nodes);
|
|
202
|
+
if (found.stopped) {
|
|
203
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
204
|
+
let bound = found.best?.value;
|
|
205
|
+
for (const node of found.nodes) {
|
|
206
|
+
if (node.outcome !== "open" || node.parent === undefined) continue;
|
|
207
|
+
const parent = found.nodes[node.parent]?.result;
|
|
208
|
+
if (parent?.status === "optimal" && (bound === undefined || compare(parent.value, bound) * s > 0)) bound = parent.value;
|
|
209
|
+
}
|
|
210
|
+
return { status: "limit", x: found.best?.x, value: found.best?.value, bound, tree };
|
|
211
|
+
}
|
|
212
|
+
if (found.best === undefined) return { status: "infeasible", tree };
|
|
213
|
+
return { status: "optimal", x: found.best.x, value: found.best.value, tree };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** This function adds a failure for each integer variable of `x` with a value that is not an integer. */
|
|
217
|
+
function checkIntegral(integer: readonly number[], x: Vector, name: string, failures: string[]): void {
|
|
218
|
+
for (const j of integer) {
|
|
219
|
+
const v = x[j];
|
|
220
|
+
if (v !== undefined && !isInteger(v)) failures.push(`${name}[${String(j)}] = ${toString(v)} is not an integer`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** This function adds a failure when the value `v` is better than `limit` in the sense of the program. */
|
|
225
|
+
function checkNotBetter(s: 1 | -1, v: Rational, limit: Rational, name: string, failures: string[]): void {
|
|
226
|
+
if (compare(v, limit) * s > 0) failures.push(`${name} ${toString(v)} is better than ${toString(limit)}`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* This function examines the tree of a result: its shape, and a certificate for each leaf. With `best`, the value of each leaf
|
|
231
|
+
* is not better than `best`. Each failure goes into `failures`.
|
|
232
|
+
*/
|
|
233
|
+
function checkTree(program: IntegerProgram, tree: readonly BranchNode[], allowOpen: boolean, best: Rational | undefined, failures: string[]): void {
|
|
234
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
235
|
+
const integer = new Set(program.integer);
|
|
236
|
+
const root = tree[0];
|
|
237
|
+
if (root === undefined || root.parent !== undefined || root.branch !== undefined) {
|
|
238
|
+
failures.push("node 0 is not a root with no parent and no branch");
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const children = tree.map((): number[] => []);
|
|
242
|
+
for (let i = 1; i < tree.length; i++) {
|
|
243
|
+
const node = tree[i] as BranchNode;
|
|
244
|
+
if (node.parent === undefined || !Number.isInteger(node.parent) || node.parent < 0 || node.parent >= i || node.branch === undefined) {
|
|
245
|
+
failures.push(`node ${String(i)} has no parent before it, or no branch`);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (!integer.has(node.branch.variable) || !isInteger(node.branch.value)) failures.push(`node ${String(i)} branches on a variable that is not an integer variable, or at a value that is not an integer`);
|
|
249
|
+
children[node.parent]?.push(i);
|
|
250
|
+
}
|
|
251
|
+
tree.forEach((node, i) => {
|
|
252
|
+
const kids = children[i] as number[];
|
|
253
|
+
if (node.outcome === "branched") {
|
|
254
|
+
const [a, b] = kids.map((k) => (tree[k] as BranchNode).branch as Branch);
|
|
255
|
+
const down = [a, b].find((branch) => branch?.relation === "<=");
|
|
256
|
+
const up = [a, b].find((branch) => branch?.relation === ">=");
|
|
257
|
+
if (kids.length !== 2 || down === undefined || up === undefined || down.variable !== up.variable || !equals(add(down.value, ONE), up.value)) {
|
|
258
|
+
failures.push(`node ${String(i)} is branched, and its children are not x_j <= k and x_j >= k + 1`);
|
|
259
|
+
}
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (kids.length > 0) failures.push(`node ${String(i)} has children, and its outcome is ${node.outcome}`);
|
|
263
|
+
if (node.outcome === "open") {
|
|
264
|
+
if (!allowOpen) failures.push(`node ${String(i)} is open`);
|
|
265
|
+
if (best === undefined || node.parent === undefined) return;
|
|
266
|
+
// The integer points of an open node are not better than the optimum of the relaxation of its parent.
|
|
267
|
+
const parent = tree[node.parent]?.result;
|
|
268
|
+
if (parent?.status !== "optimal") {
|
|
269
|
+
failures.push(`node ${String(i)} is open, and its parent has no optimum`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const check = checkCertificate(nodeProgram(program, tree, node.parent), parent);
|
|
273
|
+
for (const failure of check.failures) failures.push(`node ${String(node.parent)}: ${failure}`);
|
|
274
|
+
checkNotBetter(s, parent.value, best, `the parent of the open node ${String(i)} has the value`, failures);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const result = node.result;
|
|
278
|
+
if (result === undefined) {
|
|
279
|
+
failures.push(`node ${String(i)} is a leaf with no result`);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const check = checkCertificate(nodeProgram(program, tree, i), result);
|
|
283
|
+
for (const failure of check.failures) failures.push(`node ${String(i)}: ${failure}`);
|
|
284
|
+
if (node.outcome === "infeasible") {
|
|
285
|
+
if (result.status !== "infeasible") failures.push(`node ${String(i)} is infeasible, and its result is ${result.status}`);
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (result.status !== "optimal") {
|
|
289
|
+
failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome}, and its result is ${result.status}`);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
if (node.outcome === "integer") checkIntegral(program.integer, result.x, `node ${String(i)}: x`, failures);
|
|
293
|
+
if (best === undefined) failures.push(`node ${String(i)} has an optimum, and the result claims no integer point`);
|
|
294
|
+
else checkNotBetter(s, result.value, best, `node ${String(i)} has the value`, failures);
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.
|
|
300
|
+
*
|
|
301
|
+
* - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer
|
|
302
|
+
* point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its
|
|
303
|
+
* relaxation, and its value is not better than the value of the point.
|
|
304
|
+
* - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.
|
|
305
|
+
* - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.
|
|
306
|
+
* - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed
|
|
307
|
+
* leaf has a valid certificate. With a bound, each leaf and the parent of each open node have a value that is not better than the bound.
|
|
308
|
+
*/
|
|
309
|
+
export function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): CertificateCheck {
|
|
310
|
+
const failures: string[] = [];
|
|
311
|
+
if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {
|
|
312
|
+
failures.push("a constraint row has a length that is not the count of variables");
|
|
313
|
+
return { valid: false, failures };
|
|
314
|
+
}
|
|
315
|
+
failures.push(...integerProblems(program));
|
|
316
|
+
if (failures.length > 0) return { valid: false, failures };
|
|
317
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
318
|
+
const point = (x: Vector, value: Rational): void => {
|
|
319
|
+
checkFeasible(program, x, failures);
|
|
320
|
+
checkIntegral(program.integer, x, "x", failures);
|
|
321
|
+
if (x.length === program.objective.length && !equals(dot(program.objective, x), value)) failures.push(`the value ${toString(value)} is not c x = ${toString(dot(program.objective, x))}`);
|
|
322
|
+
};
|
|
323
|
+
if (result.status === "unbounded") {
|
|
324
|
+
failures.push(...checkCertificate(program, { status: "unbounded", x: result.x, direction: result.direction }).failures);
|
|
325
|
+
checkIntegral(program.integer, result.x, "x", failures);
|
|
326
|
+
checkIntegral(program.integer, result.direction, "direction", failures);
|
|
327
|
+
} else if (result.status === "optimal") {
|
|
328
|
+
point(result.x, result.value);
|
|
329
|
+
checkTree(program, result.tree, false, result.value, failures);
|
|
330
|
+
} else if (result.status === "infeasible") {
|
|
331
|
+
checkTree(program, result.tree, false, undefined, failures);
|
|
332
|
+
result.tree.forEach((node, i) => {
|
|
333
|
+
if (node.outcome !== "branched" && node.outcome !== "infeasible") failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome} in an infeasible result`);
|
|
334
|
+
});
|
|
335
|
+
} else {
|
|
336
|
+
if ((result.x === undefined) !== (result.value === undefined)) failures.push("the limit result has a point with no value, or a value with no point");
|
|
337
|
+
if (result.x !== undefined && result.value !== undefined) {
|
|
338
|
+
point(result.x, result.value);
|
|
339
|
+
if (result.bound === undefined) failures.push("the limit result has a point and no bound");
|
|
340
|
+
else checkNotBetter(s, result.value, result.bound, "the value", failures);
|
|
341
|
+
}
|
|
342
|
+
checkTree(program, result.tree, true, result.bound, failures);
|
|
343
|
+
}
|
|
344
|
+
return { valid: failures.length === 0, failures };
|
|
345
|
+
}
|