@mark1russell7/linear 0.0.0-stage → 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/build/index.js ADDED
@@ -0,0 +1,920 @@
1
+ import { ONE, ZERO, add, compare, div, equals, floor, fromDecimal, fromNumber, gcd, inverse, isInteger, mul, neg, rational, sign, sub, toString } from "@mark1russell7/rational";
2
+ // src/vector.ts
3
+ /**
4
+ * Exact vectors and matrices over the rationals of `@mark1russell7/rational`.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ /**
9
+ * This function gives the exact rational of an input. A number gives the decimal that JavaScript prints for it. A text is a
10
+ * decimal or a quotient of two decimals.
11
+ *
12
+ * @throws {RangeError} The input is not a finite value, or the text has a zero divisor.
13
+ */
14
+ function toRational(value) {
15
+ if (typeof value === "bigint") return rational(value);
16
+ if (typeof value === "number") {
17
+ if (!Number.isFinite(value)) throw new RangeError(`linear: ${value} is not a finite number`);
18
+ return fromNumber(value);
19
+ }
20
+ if (typeof value === "string") {
21
+ const slash = value.indexOf("/");
22
+ if (slash < 0) return fromDecimal(value.trim());
23
+ return div(fromDecimal(value.slice(0, slash).trim()), fromDecimal(value.slice(slash + 1).trim()));
24
+ }
25
+ return value;
26
+ }
27
+ /** This function gives a vector of exact rationals from a list of inputs. */
28
+ function vector(values) {
29
+ return values.map(toRational);
30
+ }
31
+ /**
32
+ * This function gives a matrix of exact rationals from a list of rows.
33
+ *
34
+ * @throws {RangeError} The rows do not have the same length.
35
+ */
36
+ function matrix(rows) {
37
+ const result = rows.map(vector);
38
+ columnsOf(result);
39
+ return result;
40
+ }
41
+ /**
42
+ * This function gives the count of columns of a matrix. A matrix with no rows has 0 columns.
43
+ *
44
+ * @throws {RangeError} The rows do not have the same length.
45
+ */
46
+ function columnsOf(m) {
47
+ const n = m[0]?.length ?? 0;
48
+ for (const row of m) if (row.length !== n) throw new RangeError(`linear: a row has ${row.length} entries, and the first row has ${n}`);
49
+ return n;
50
+ }
51
+ /**
52
+ * This function gives the dot product of two vectors.
53
+ *
54
+ * @throws {RangeError} The vectors do not have the same length.
55
+ */
56
+ function dot(a, b) {
57
+ if (a.length !== b.length) throw new RangeError(`linear: the vectors have ${a.length} and ${b.length} entries`);
58
+ let sum = ZERO;
59
+ for (let i = 0; i < a.length; i++) sum = add(sum, mul(a[i], b[i]));
60
+ return sum;
61
+ }
62
+ /**
63
+ * This function gives the product of a matrix and a vector.
64
+ *
65
+ * @throws {RangeError} The length of the vector is not the count of columns.
66
+ */
67
+ function multiply(m, x) {
68
+ return m.map((row) => dot(row, x));
69
+ }
70
+ /** This function gives the transpose of a matrix. The argument `columns` gives the row count of the result for a matrix with no rows. */
71
+ function transpose(m, columns = columnsOf(m)) {
72
+ const result = [];
73
+ for (let j = 0; j < columns; j++) result.push(m.map((row) => row[j]));
74
+ return result;
75
+ }
76
+ // src/matrix.ts
77
+ /**
78
+ * Exact elimination: the reduced row echelon form, the rank, a basis of the null space and the solution of a system.
79
+ *
80
+ * @packageDocumentation
81
+ */
82
+ /**
83
+ * This function applies Gauss-Jordan elimination to the rows in place. It takes pivots only in the columns below `limit`.
84
+ * It gives the column of each pivot. The row of pivot `k` is row `k`.
85
+ */
86
+ function eliminate(rows, limit) {
87
+ const pivots = [];
88
+ let r = 0;
89
+ for (let c = 0; c < limit && r < rows.length; c++) {
90
+ let p = r;
91
+ while (p < rows.length && sign(rows[p][c]) === 0) p++;
92
+ if (p === rows.length) continue;
93
+ const swap = rows[r];
94
+ rows[r] = rows[p];
95
+ rows[p] = swap;
96
+ const scale = inverse(rows[r][c]);
97
+ const pivotRow = rows[r].map((v) => mul(v, scale));
98
+ rows[r] = pivotRow;
99
+ for (let i = 0; i < rows.length; i++) {
100
+ const f = rows[i][c];
101
+ if (i === r || sign(f) === 0) continue;
102
+ rows[i] = rows[i].map((v, j) => sub(v, mul(f, pivotRow[j])));
103
+ }
104
+ pivots.push(c);
105
+ r++;
106
+ }
107
+ return pivots;
108
+ }
109
+ /**
110
+ * This function gives the reduced row echelon form of a matrix, with exact arithmetic.
111
+ *
112
+ * @throws {RangeError} The rows do not have the same length.
113
+ */
114
+ function rref(m) {
115
+ const n = columnsOf(m);
116
+ const rows = m.map((row) => [...row]);
117
+ return {
118
+ matrix: rows,
119
+ pivots: eliminate(rows, n)
120
+ };
121
+ }
122
+ /** This function gives the rank of a matrix: the count of pivots of its reduced row echelon form. */
123
+ function rank(m) {
124
+ return rref(m).pivots.length;
125
+ }
126
+ /**
127
+ * 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
128
+ * column with no pivot. That vector has 1 at its column and 0 at each other column with no pivot. The argument `columns`
129
+ * gives the count of columns for a matrix with no rows.
130
+ */
131
+ function nullSpace(m, columns = columnsOf(m)) {
132
+ const { matrix: r, pivots } = rref(m);
133
+ const basis = [];
134
+ for (let free = 0; free < columns; free++) {
135
+ if (pivots.includes(free)) continue;
136
+ const v = new Array(columns).fill(ZERO);
137
+ v[free] = ONE;
138
+ pivots.forEach((p, k) => {
139
+ v[p] = neg(r[k][free]);
140
+ });
141
+ basis.push(v);
142
+ }
143
+ return basis;
144
+ }
145
+ /**
146
+ * 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.
147
+ * The solution `x` has 0 at each column with no pivot.
148
+ *
149
+ * @throws {RangeError} The rows do not have the same length, or `b` has a length that is not the row count.
150
+ */
151
+ function solve(a, b, columns = columnsOf(a)) {
152
+ const m = a.length;
153
+ if (b.length !== m) throw new RangeError(`linear: the matrix has ${m} rows, and the right side has ${b.length} entries`);
154
+ const rows = a.map((row, i) => [
155
+ ...row,
156
+ b[i],
157
+ ...Array.from({ length: m }, (_, k) => k === i ? ONE : ZERO)
158
+ ]);
159
+ const pivots = eliminate(rows, columns + 1);
160
+ const last = pivots.length - 1;
161
+ if (last >= 0 && pivots[last] === columns) return {
162
+ status: "inconsistent",
163
+ certificate: rows[last].slice(columns + 1)
164
+ };
165
+ const x = new Array(columns).fill(ZERO);
166
+ pivots.forEach((p, k) => {
167
+ x[p] = rows[k][columns];
168
+ });
169
+ return {
170
+ status: "solved",
171
+ x,
172
+ nullSpace: nullSpace(a, columns)
173
+ };
174
+ }
175
+ // src/program.ts
176
+ /**
177
+ * This function makes a linear program from inputs that `toRational` reads, and examines its shape.
178
+ *
179
+ * @throws {RangeError} A constraint row has a length that is not the length of the objective.
180
+ */
181
+ function linearProgram(input) {
182
+ const program = {
183
+ sense: input.sense,
184
+ objective: vector(input.objective),
185
+ constraints: input.constraints.map((c) => ({
186
+ coefficients: vector(c.coefficients),
187
+ relation: c.relation,
188
+ rhs: toRational(c.rhs)
189
+ }))
190
+ };
191
+ checkShape(program);
192
+ return program;
193
+ }
194
+ /**
195
+ * This function examines the shape of a program: each constraint row has one coefficient for each variable.
196
+ *
197
+ * @throws {RangeError} A constraint row has a length that is not the length of the objective.
198
+ */
199
+ function checkShape(program) {
200
+ const n = program.objective.length;
201
+ program.constraints.forEach((c, i) => {
202
+ if (c.coefficients.length !== n) throw new RangeError(`linear: constraint ${i} has ${c.coefficients.length} coefficients, and the objective has ${n}`);
203
+ });
204
+ }
205
+ // src/simplex.ts
206
+ /**
207
+ * The exact two-phase simplex. The rule of Bland selects each pivot, so the method ends on each program.
208
+ *
209
+ * @packageDocumentation
210
+ */
211
+ const FLIP = {
212
+ "<=": ">=",
213
+ ">=": "<=",
214
+ "=": "="
215
+ };
216
+ function standardForm(program) {
217
+ const n = program.objective.length;
218
+ const rels = program.constraints.map((c) => sign(c.rhs) < 0 ? FLIP[c.relation] : c.relation);
219
+ const slacks = rels.filter((r) => r !== "=").length;
220
+ const artificials = rels.filter((r) => r !== "<=").length;
221
+ const structural = n + slacks;
222
+ const total = structural + artificials;
223
+ const rows = [];
224
+ const rhs = [];
225
+ const flipped = [];
226
+ const basis = [];
227
+ let slack = n;
228
+ let artificial = structural;
229
+ program.constraints.forEach((c, i) => {
230
+ const flip = sign(c.rhs) < 0;
231
+ const row = new Array(total).fill(ZERO);
232
+ c.coefficients.forEach((v, j) => {
233
+ row[j] = flip ? neg(v) : v;
234
+ });
235
+ const rel = rels[i];
236
+ if (rel === "<=") {
237
+ row[slack] = ONE;
238
+ basis.push(slack++);
239
+ } else {
240
+ if (rel === ">=") row[slack++] = neg(ONE);
241
+ row[artificial] = ONE;
242
+ basis.push(artificial++);
243
+ }
244
+ rows.push(row);
245
+ rhs.push(flip ? neg(c.rhs) : c.rhs);
246
+ flipped.push(flip);
247
+ });
248
+ return {
249
+ rows,
250
+ rhs,
251
+ flipped,
252
+ basis,
253
+ structural
254
+ };
255
+ }
256
+ function pivot(t, p, q) {
257
+ const scale = inverse(t.rows[p][q]);
258
+ const pivotRow = t.rows[p].map((v) => mul(v, scale));
259
+ const pivotRhs = mul(t.rhs[p], scale);
260
+ t.rows[p] = pivotRow;
261
+ t.rhs[p] = pivotRhs;
262
+ for (let i = 0; i < t.rows.length; i++) {
263
+ const f = t.rows[i][q];
264
+ if (i === p || sign(f) === 0) continue;
265
+ t.rows[i] = t.rows[i].map((v, j) => sub(v, mul(f, pivotRow[j])));
266
+ t.rhs[i] = sub(t.rhs[i], mul(f, pivotRhs));
267
+ }
268
+ t.basis[p] = q;
269
+ }
270
+ /** This function gives the reduced cost `c_j - c_B B^-1 A_j` of each column, for a maximization. */
271
+ function reducedCosts(t, cost) {
272
+ const r = [...cost];
273
+ t.rows.forEach((row, i) => {
274
+ const cb = cost[t.basis[i]];
275
+ if (sign(cb) === 0) return;
276
+ for (let j = 0; j < r.length; j++) r[j] = sub(r[j], mul(cb, row[j]));
277
+ });
278
+ return r;
279
+ }
280
+ const basisKey = (basis) => [...basis].sort((a, b) => a - b).join(",");
281
+ /** This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. */
282
+ function runPhase(t, cost, allowed, rule, count) {
283
+ const seen = /* @__PURE__ */ new Set([basisKey(t.basis)]);
284
+ for (;;) {
285
+ const r = reducedCosts(t, cost);
286
+ let q = -1;
287
+ for (let j = 0; j < allowed; j++) {
288
+ if (sign(r[j]) <= 0) continue;
289
+ if (rule === "bland") {
290
+ q = j;
291
+ break;
292
+ }
293
+ if (q < 0 || compare(r[j], r[q]) > 0) q = j;
294
+ }
295
+ if (q < 0) return { kind: "optimal" };
296
+ let p = -1;
297
+ let best = ZERO;
298
+ t.rows.forEach((row, i) => {
299
+ const a = row[q];
300
+ if (sign(a) <= 0) return;
301
+ const ratio = div(t.rhs[i], a);
302
+ const order = p < 0 ? -1 : compare(ratio, best);
303
+ if (order < 0 || order === 0 && t.basis[i] < t.basis[p]) {
304
+ p = i;
305
+ best = ratio;
306
+ }
307
+ });
308
+ if (p < 0) return {
309
+ kind: "unbounded",
310
+ column: q
311
+ };
312
+ pivot(t, p, q);
313
+ count.pivots++;
314
+ const key = basisKey(t.basis);
315
+ if (seen.has(key)) return { kind: "cycle" };
316
+ seen.add(key);
317
+ }
318
+ }
319
+ /** 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. */
320
+ function dualOf(form, basis, cost) {
321
+ if (basis.length === 0) return [];
322
+ const solved = solve(basis.map((col) => form.rows.map((row) => row[col])), basis.map((col) => cost[col]));
323
+ if (solved.status !== "solved") throw new Error("linear: internal error, the basis is singular");
324
+ return solved.x.map((y, i) => form.flipped[i] ? neg(y) : y);
325
+ }
326
+ /** This function gives the first `n` entries of the basic solution of the tableau. */
327
+ function pointOf(t, n) {
328
+ const x = new Array(n).fill(ZERO);
329
+ t.basis.forEach((col, i) => {
330
+ if (col < n) x[col] = t.rhs[i];
331
+ });
332
+ return x;
333
+ }
334
+ /**
335
+ * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland.
336
+ *
337
+ * @internal
338
+ */
339
+ function runSimplex(program, rule) {
340
+ checkShape(program);
341
+ const n = program.objective.length;
342
+ const form = standardForm(program);
343
+ const total = form.rows[0]?.length ?? n;
344
+ const t = {
345
+ rows: form.rows.map((row) => [...row]),
346
+ rhs: [...form.rhs],
347
+ basis: [...form.basis]
348
+ };
349
+ const count = { pivots: 0 };
350
+ if (total > form.structural) {
351
+ const cost = Array.from({ length: total }, (_, j) => j >= form.structural ? neg(ONE) : ZERO);
352
+ if (runPhase(t, cost, total, rule, count).kind === "cycle") return {
353
+ cycled: true,
354
+ pivots: count.pivots
355
+ };
356
+ let value = ZERO;
357
+ t.basis.forEach((col, i) => {
358
+ value = sub(value, col >= form.structural ? t.rhs[i] : ZERO);
359
+ });
360
+ if (sign(value) < 0) return {
361
+ cycled: false,
362
+ result: {
363
+ status: "infeasible",
364
+ ray: dualOf(form, t.basis, cost)
365
+ },
366
+ pivots: count.pivots
367
+ };
368
+ t.basis.forEach((col, i) => {
369
+ if (col < form.structural) return;
370
+ const j = t.rows[i].findIndex((v, k) => k < form.structural && sign(v) !== 0);
371
+ if (j >= 0) pivot(t, i, j);
372
+ });
373
+ }
374
+ const max = program.sense === "max";
375
+ const cost = Array.from({ length: total }, (_, j) => j < n ? max ? program.objective[j] : neg(program.objective[j]) : ZERO);
376
+ const phase = runPhase(t, cost, form.structural, rule, count);
377
+ if (phase.kind === "cycle") return {
378
+ cycled: true,
379
+ pivots: count.pivots
380
+ };
381
+ const x = pointOf(t, n);
382
+ if (phase.kind === "unbounded") {
383
+ const q = phase.column;
384
+ const direction = new Array(n).fill(ZERO);
385
+ if (q < n) direction[q] = ONE;
386
+ t.basis.forEach((col, i) => {
387
+ if (col < n) direction[col] = neg(t.rows[i][q]);
388
+ });
389
+ return {
390
+ cycled: false,
391
+ result: {
392
+ status: "unbounded",
393
+ x,
394
+ direction
395
+ },
396
+ pivots: count.pivots
397
+ };
398
+ }
399
+ const dual = dualOf(form, t.basis, cost);
400
+ return {
401
+ cycled: false,
402
+ result: {
403
+ status: "optimal",
404
+ x,
405
+ value: dot(program.objective, x),
406
+ dual: max ? dual : dual.map(neg)
407
+ },
408
+ pivots: count.pivots
409
+ };
410
+ }
411
+ /**
412
+ * This function solves a linear program exactly with the two-phase simplex and the rule of Bland. The result has a certificate
413
+ * that `checkCertificate` examines.
414
+ *
415
+ * @throws {RangeError} A constraint row has a length that is not the length of the objective.
416
+ */
417
+ function solveLinearProgram(program) {
418
+ const run = runSimplex(program, "bland");
419
+ if (run.cycled) throw new Error("linear: internal error, the rule of Bland met a basis again");
420
+ return run.result;
421
+ }
422
+ // src/lexicographic.ts
423
+ /**
424
+ * This function optimizes the objectives in their order, subject to the constraint rows and `x >= 0`. Stage `k` holds the
425
+ * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.
426
+ * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.
427
+ *
428
+ * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.
429
+ */
430
+ function solveLexicographic(constraints, objectives) {
431
+ if (objectives.length === 0) throw new RangeError("linear: a lexicographic program needs one objective or more");
432
+ const stages = [];
433
+ const rows = [...constraints];
434
+ const values = [];
435
+ let x = [];
436
+ for (const objective of objectives) {
437
+ const program = {
438
+ sense: objective.sense,
439
+ objective: objective.coefficients,
440
+ constraints: [...rows]
441
+ };
442
+ const result = solveLinearProgram(program);
443
+ stages.push({
444
+ program,
445
+ result
446
+ });
447
+ if (result.status !== "optimal") return {
448
+ status: result.status,
449
+ stages
450
+ };
451
+ x = result.x;
452
+ values.push(result.value);
453
+ rows.push({
454
+ coefficients: objective.coefficients,
455
+ relation: "=",
456
+ rhs: result.value
457
+ });
458
+ }
459
+ return {
460
+ status: "optimal",
461
+ x,
462
+ values,
463
+ stages
464
+ };
465
+ }
466
+ // src/certificate.ts
467
+ /**
468
+ * The check of a certificate. It uses only exact arithmetic on the program and the result, and it does not trust the solver.
469
+ *
470
+ * @packageDocumentation
471
+ */
472
+ /** This function tells if the sign of a value obeys a relation to 0. */
473
+ function holds(s, relation) {
474
+ return relation === "=" ? s === 0 : relation === "<=" ? s <= 0 : s >= 0;
475
+ }
476
+ /** This function gives the column sums `y A`: entry `j` is the sum over the rows of `y_i a_ij`. */
477
+ function columnSums(program, y) {
478
+ return program.objective.map((_, j) => dot(program.constraints.map((c) => c.coefficients[j]), y));
479
+ }
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
+ */
485
+ function checkFeasible(program, x, failures) {
486
+ if (x.length !== program.objective.length) {
487
+ failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);
488
+ return;
489
+ }
490
+ x.forEach((v, j) => {
491
+ if (sign(v) < 0) failures.push(`x[${j}] = ${toString(v)} is negative`);
492
+ });
493
+ program.constraints.forEach((c, i) => {
494
+ const lhs = dot(c.coefficients, x);
495
+ if (!holds(sign(sub(lhs, c.rhs)), c.relation)) failures.push(`row ${i}: ${toString(lhs)} ${c.relation} ${toString(c.rhs)} is false`);
496
+ });
497
+ }
498
+ /**
499
+ * This function adds a failure for each multiplier with the wrong sign. With `s = 1`, a `<=` row needs a multiplier of 0 or
500
+ * more, and a `>=` row a multiplier of 0 or less. The value `s = -1` swaps the two signs. An `=` row takes each sign.
501
+ */
502
+ function checkMultiplierSigns(program, y, s, name, failures) {
503
+ program.constraints.forEach((c, i) => {
504
+ const signed = sign(y[i]) * s;
505
+ if (c.relation === "<=" && signed < 0 || c.relation === ">=" && signed > 0) failures.push(`${name}[${i}] = ${toString(y[i])} has the wrong sign for a ${c.relation} row`);
506
+ });
507
+ }
508
+ function checkOptimal(program, x, value, y, failures) {
509
+ const m = program.constraints.length;
510
+ if (y.length !== m) failures.push(`the dual has ${y.length} entries, and the program has ${m} rows`);
511
+ checkFeasible(program, x, failures);
512
+ if (y.length !== m || x.length !== program.objective.length) return;
513
+ const s = program.sense === "max" ? 1 : -1;
514
+ checkMultiplierSigns(program, y, s, "dual", failures);
515
+ columnSums(program, y).forEach((sum, j) => {
516
+ const slack = sub(sum, program.objective[j]);
517
+ if (sign(slack) * s < 0) failures.push(`the dual constraint of column ${j} is false: (yA)[${j}] - c[${j}] = ${toString(slack)}`);
518
+ if (sign(mul(x[j], slack)) !== 0) failures.push(`complementary slackness fails at column ${j}`);
519
+ });
520
+ program.constraints.forEach((c, i) => {
521
+ if (sign(mul(y[i], sub(dot(c.coefficients, x), c.rhs))) !== 0) failures.push(`complementary slackness fails at row ${i}`);
522
+ });
523
+ const primal = dot(program.objective, x);
524
+ const dual = dot(program.constraints.map((c) => c.rhs), y);
525
+ if (!equals(primal, value)) failures.push(`the value ${toString(value)} is not c x = ${toString(primal)}`);
526
+ if (!equals(primal, dual)) failures.push(`strong duality fails: c x = ${toString(primal)} and b y = ${toString(dual)}`);
527
+ }
528
+ function checkInfeasible(program, y, failures) {
529
+ const m = program.constraints.length;
530
+ if (y.length !== m) {
531
+ failures.push(`the ray has ${y.length} entries, and the program has ${m} rows`);
532
+ return;
533
+ }
534
+ checkMultiplierSigns(program, y, 1, "ray", failures);
535
+ columnSums(program, y).forEach((sum, j) => {
536
+ if (sign(sum) < 0) failures.push(`(yA)[${j}] = ${toString(sum)} is negative`);
537
+ });
538
+ const by = dot(program.constraints.map((c) => c.rhs), y);
539
+ if (sign(by) >= 0) failures.push(`b y = ${toString(by)} is not negative`);
540
+ }
541
+ function checkUnbounded(program, x, d, failures) {
542
+ checkFeasible(program, x, failures);
543
+ if (d.length !== program.objective.length) {
544
+ failures.push(`the direction has ${d.length} entries, and the program has ${program.objective.length} variables`);
545
+ return;
546
+ }
547
+ d.forEach((v, j) => {
548
+ if (sign(v) < 0) failures.push(`direction[${j}] = ${toString(v)} is negative`);
549
+ });
550
+ program.constraints.forEach((c, i) => {
551
+ const ad = dot(c.coefficients, d);
552
+ if (!holds(sign(ad), c.relation)) failures.push(`row ${i}: the direction gives ${toString(ad)}, so it leaves the row`);
553
+ });
554
+ const gain = dot(program.objective, d);
555
+ const s = program.sense === "max" ? 1 : -1;
556
+ if (sign(gain) * s <= 0) failures.push(`the direction does not improve the objective: c d = ${toString(gain)}`);
557
+ }
558
+ /**
559
+ * This function examines the certificate of a result with exact arithmetic. It does not trust the solver.
560
+ *
561
+ * - `optimal`: the point is feasible, the dual is feasible, `c x = b y` and complementary slackness holds. For a maximization,
562
+ * 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.
563
+ * - `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`
564
+ * meets the rows, because `0 <= y A x <= y b < 0`.
565
+ * - `unbounded`: the point is feasible, the direction is not negative, each row keeps its relation along it, and the
566
+ * direction improves the objective.
567
+ */
568
+ function checkCertificate(program, result) {
569
+ const failures = [];
570
+ if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) failures.push("a constraint row has a length that is not the count of variables");
571
+ else if (result.status === "optimal") checkOptimal(program, result.x, result.value, result.dual, failures);
572
+ else if (result.status === "infeasible") checkInfeasible(program, result.ray, failures);
573
+ else checkUnbounded(program, result.x, result.direction, failures);
574
+ return {
575
+ valid: failures.length === 0,
576
+ failures
577
+ };
578
+ }
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 };
919
+
920
+ //# sourceMappingURL=index.js.map