@mark1russell7/linear 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js ADDED
@@ -0,0 +1,577 @@
1
+ import { ONE, ZERO, add, compare, div, equals, fromDecimal, fromNumber, inverse, 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
+ /** This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`. */
481
+ function checkFeasible(program, x, failures) {
482
+ if (x.length !== program.objective.length) {
483
+ failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);
484
+ return;
485
+ }
486
+ x.forEach((v, j) => {
487
+ if (sign(v) < 0) failures.push(`x[${j}] = ${toString(v)} is negative`);
488
+ });
489
+ program.constraints.forEach((c, i) => {
490
+ const lhs = dot(c.coefficients, x);
491
+ if (!holds(sign(sub(lhs, c.rhs)), c.relation)) failures.push(`row ${i}: ${toString(lhs)} ${c.relation} ${toString(c.rhs)} is false`);
492
+ });
493
+ }
494
+ /**
495
+ * This function adds a failure for each multiplier with the wrong sign. With `s = 1`, a `<=` row needs a multiplier of 0 or
496
+ * more, and a `>=` row a multiplier of 0 or less. The value `s = -1` swaps the two signs. An `=` row takes each sign.
497
+ */
498
+ function checkMultiplierSigns(program, y, s, name, failures) {
499
+ program.constraints.forEach((c, i) => {
500
+ const signed = sign(y[i]) * s;
501
+ 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`);
502
+ });
503
+ }
504
+ function checkOptimal(program, x, value, y, failures) {
505
+ const m = program.constraints.length;
506
+ if (y.length !== m) failures.push(`the dual has ${y.length} entries, and the program has ${m} rows`);
507
+ checkFeasible(program, x, failures);
508
+ if (y.length !== m || x.length !== program.objective.length) return;
509
+ const s = program.sense === "max" ? 1 : -1;
510
+ checkMultiplierSigns(program, y, s, "dual", failures);
511
+ columnSums(program, y).forEach((sum, j) => {
512
+ const slack = sub(sum, program.objective[j]);
513
+ if (sign(slack) * s < 0) failures.push(`the dual constraint of column ${j} is false: (yA)[${j}] - c[${j}] = ${toString(slack)}`);
514
+ if (sign(mul(x[j], slack)) !== 0) failures.push(`complementary slackness fails at column ${j}`);
515
+ });
516
+ program.constraints.forEach((c, i) => {
517
+ if (sign(mul(y[i], sub(dot(c.coefficients, x), c.rhs))) !== 0) failures.push(`complementary slackness fails at row ${i}`);
518
+ });
519
+ const primal = dot(program.objective, x);
520
+ const dual = dot(program.constraints.map((c) => c.rhs), y);
521
+ if (!equals(primal, value)) failures.push(`the value ${toString(value)} is not c x = ${toString(primal)}`);
522
+ if (!equals(primal, dual)) failures.push(`strong duality fails: c x = ${toString(primal)} and b y = ${toString(dual)}`);
523
+ }
524
+ function checkInfeasible(program, y, failures) {
525
+ const m = program.constraints.length;
526
+ if (y.length !== m) {
527
+ failures.push(`the ray has ${y.length} entries, and the program has ${m} rows`);
528
+ return;
529
+ }
530
+ checkMultiplierSigns(program, y, 1, "ray", failures);
531
+ columnSums(program, y).forEach((sum, j) => {
532
+ if (sign(sum) < 0) failures.push(`(yA)[${j}] = ${toString(sum)} is negative`);
533
+ });
534
+ const by = dot(program.constraints.map((c) => c.rhs), y);
535
+ if (sign(by) >= 0) failures.push(`b y = ${toString(by)} is not negative`);
536
+ }
537
+ function checkUnbounded(program, x, d, failures) {
538
+ checkFeasible(program, x, failures);
539
+ if (d.length !== program.objective.length) {
540
+ failures.push(`the direction has ${d.length} entries, and the program has ${program.objective.length} variables`);
541
+ return;
542
+ }
543
+ d.forEach((v, j) => {
544
+ if (sign(v) < 0) failures.push(`direction[${j}] = ${toString(v)} is negative`);
545
+ });
546
+ program.constraints.forEach((c, i) => {
547
+ const ad = dot(c.coefficients, d);
548
+ if (!holds(sign(ad), c.relation)) failures.push(`row ${i}: the direction gives ${toString(ad)}, so it leaves the row`);
549
+ });
550
+ const gain = dot(program.objective, d);
551
+ const s = program.sense === "max" ? 1 : -1;
552
+ if (sign(gain) * s <= 0) failures.push(`the direction does not improve the objective: c d = ${toString(gain)}`);
553
+ }
554
+ /**
555
+ * This function examines the certificate of a result with exact arithmetic. It does not trust the solver.
556
+ *
557
+ * - `optimal`: the point is feasible, the dual is feasible, `c x = b y` and complementary slackness holds. For a maximization,
558
+ * 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.
559
+ * - `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`
560
+ * meets the rows, because `0 <= y A x <= y b < 0`.
561
+ * - `unbounded`: the point is feasible, the direction is not negative, each row keeps its relation along it, and the
562
+ * direction improves the objective.
563
+ */
564
+ function checkCertificate(program, result) {
565
+ const failures = [];
566
+ 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");
567
+ else if (result.status === "optimal") checkOptimal(program, result.x, result.value, result.dual, failures);
568
+ else if (result.status === "infeasible") checkInfeasible(program, result.ray, failures);
569
+ else checkUnbounded(program, result.x, result.direction, failures);
570
+ return {
571
+ valid: failures.length === 0,
572
+ failures
573
+ };
574
+ }
575
+ export { checkCertificate, columnsOf, dot, linearProgram, matrix, multiply, nullSpace, rank, rref, solve, solveLexicographic, solveLinearProgram, toRational, transpose, vector };
576
+
577
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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;;;;;;A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