@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/src/integer.ts ADDED
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Integer programs: branch and bound on the exact simplex. The certificate of a result is the tree of its nodes.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import { type Rational, add, compare, equals, floor, gcd, isInteger, ONE, rational, toString, ZERO } from "@mark1russell7/rational";
7
+ import { type CertificateCheck, checkCertificate, checkFeasible } from "./certificate.ts";
8
+ import { checkShape, type Constraint, type LinearProgram, type LinearProgramResult } from "./program.ts";
9
+ import { solveLinearProgram } from "./simplex.ts";
10
+ import { dot, type Vector } from "./vector.ts";
11
+
12
+ /** A linear program in which each variable of the list `integer` takes integer values only. The other variables are continuous. */
13
+ export interface IntegerProgram extends LinearProgram {
14
+ /** The indices of the integer variables. */
15
+ readonly integer: readonly number[];
16
+ }
17
+
18
+ /** The row that a node adds to the rows of its parent: `x[variable] <= value` or `x[variable] >= value`. The value is an integer. */
19
+ export interface Branch {
20
+ readonly variable: number;
21
+ readonly relation: "<=" | ">=";
22
+ readonly value: Rational;
23
+ }
24
+
25
+ /**
26
+ * The outcome of a node of the tree.
27
+ *
28
+ * - `branched`: the node has two children. One child adds `x_j <= k`, and the other child adds `x_j >= k + 1`.
29
+ * - `integer`: the relaxation of the node has an optimum with an integer value on each integer variable.
30
+ * - `bound`: the optimum of the relaxation is not better than the best integer point that the solve found before the node.
31
+ * - `infeasible`: the relaxation of the node has no point.
32
+ * - `open`: the solve stopped at its limit before the node.
33
+ */
34
+ export type NodeOutcome = "branched" | "integer" | "bound" | "infeasible" | "open";
35
+
36
+ /** One node of the tree. The root is node 0. Each other node has a parent with a smaller index. */
37
+ export interface BranchNode {
38
+ readonly parent: number | undefined;
39
+ readonly branch: Branch | undefined;
40
+ readonly outcome: NodeOutcome;
41
+ /** The result of the relaxation of the node, with its certificate. An open node has no result. */
42
+ readonly result: LinearProgramResult | undefined;
43
+ }
44
+
45
+ /**
46
+ * The result of an integer program, with its certificate.
47
+ *
48
+ * - `optimal`: the point `x`, its value, and the tree. Each leaf proves that its integer points are not better than `x`.
49
+ * - `infeasible`: the tree. Each leaf has a Farkas ray, so the program has no integer point.
50
+ * - `unbounded`: an integer point `x` and a direction `direction` with an integer value on each integer variable.
51
+ * Each point `x + t direction` with an integer `t >= 0` is an integer point, and the objective improves without limit.
52
+ * - `limit`: the solve stopped at its limit. It gives the best integer point that it found, if any. `bound` is a bound of the
53
+ * optimum that the tree proves. A program with an unbounded relaxation gives no bound.
54
+ */
55
+ export type IntegerProgramResult =
56
+ | { readonly status: "optimal"; readonly x: Vector; readonly value: Rational; readonly tree: readonly BranchNode[] }
57
+ | { readonly status: "infeasible"; readonly tree: readonly BranchNode[] }
58
+ | { readonly status: "unbounded"; readonly x: Vector; readonly direction: Vector }
59
+ | {
60
+ readonly status: "limit";
61
+ readonly x: Vector | undefined;
62
+ readonly value: Rational | undefined;
63
+ readonly bound: Rational | undefined;
64
+ readonly tree: readonly BranchNode[];
65
+ };
66
+
67
+ /** The options of `solveIntegerProgram`. */
68
+ export interface IntegerOptions {
69
+ /** The largest count of relaxations that the solve solves. The default is 10000. */
70
+ readonly nodeLimit?: number;
71
+ }
72
+
73
+ /** A node in construction. */
74
+ interface WorkNode {
75
+ readonly parent: number | undefined;
76
+ readonly branch: Branch | undefined;
77
+ outcome: NodeOutcome;
78
+ result: LinearProgramResult | undefined;
79
+ }
80
+
81
+ /** The result of one search, before the solve gives its status. */
82
+ interface Search {
83
+ readonly best: { readonly x: Vector; readonly value: Rational } | undefined;
84
+ readonly nodes: readonly WorkNode[];
85
+ /** True when the search stopped at its limit with open nodes. */
86
+ readonly stopped: boolean;
87
+ }
88
+
89
+ /**
90
+ * This function gives the problems of the list `integer` of a program: an index that is not an integer, or not a variable.
91
+ *
92
+ * @internal
93
+ */
94
+ export function integerProblems(program: IntegerProgram): string[] {
95
+ const n = program.objective.length;
96
+ return program.integer.filter((j) => !Number.isInteger(j) || j < 0 || j >= n).map((j) => `the integer variable ${String(j)} is not a variable of the program`);
97
+ }
98
+
99
+ /**
100
+ * This function gives the program of a node: the rows of the program, then the row of each branch on the path from the root.
101
+ *
102
+ * @internal
103
+ */
104
+ export function nodeProgram(program: LinearProgram, tree: readonly Pick<BranchNode, "parent" | "branch">[], id: number): LinearProgram {
105
+ const rows: Constraint[] = [];
106
+ const n = program.objective.length;
107
+ for (let at: number | undefined = id; at !== undefined; at = tree[at]?.parent) {
108
+ const branch = tree[at]?.branch;
109
+ if (branch === undefined) continue;
110
+ const coefficients = Array.from({ length: n }, (_, j) => (j === branch.variable ? ONE : ZERO));
111
+ rows.push({ coefficients, relation: branch.relation, rhs: branch.value });
112
+ }
113
+ return { ...program, constraints: [...program.constraints, ...rows.reverse()] };
114
+ }
115
+
116
+ /**
117
+ * This function searches the tree depth first. It branches on the fractional integer variable with the smallest index, and it
118
+ * takes the child `x_j <= k` first. With `first`, it stops at the first integer point.
119
+ */
120
+ function search(program: LinearProgram, integer: readonly number[], limit: number, first: boolean, root: LinearProgramResult): Search {
121
+ const s = program.sense === "max" ? 1 : -1;
122
+ const nodes: WorkNode[] = [{ parent: undefined, branch: undefined, outcome: "open", result: undefined }];
123
+ const stack = [0];
124
+ let best: Search["best"];
125
+ let solved = 0;
126
+ while (stack.length > 0 && solved < limit) {
127
+ const id = stack.pop() as number;
128
+ const node = nodes[id] as WorkNode;
129
+ const result = id === 0 ? root : solveLinearProgram(nodeProgram(program, nodes, id));
130
+ solved++;
131
+ node.result = result;
132
+ if (result.status === "infeasible") {
133
+ node.outcome = "infeasible";
134
+ continue;
135
+ }
136
+ // A node adds rows to a program with an optimum or with the objective 0, so its relaxation is not unbounded.
137
+ if (result.status === "unbounded") throw new Error("linear: the relaxation of a node is unbounded, and the relaxation of the root is not");
138
+ if (best !== undefined && compare(result.value, best.value) * s <= 0) {
139
+ node.outcome = "bound";
140
+ continue;
141
+ }
142
+ const j = integer.find((k) => !isInteger(result.x[k] as Rational));
143
+ if (j === undefined) {
144
+ node.outcome = "integer";
145
+ best = { x: result.x, value: result.value };
146
+ if (first) return { best, nodes, stopped: false };
147
+ continue;
148
+ }
149
+ node.outcome = "branched";
150
+ const k = floor(result.x[j] as Rational);
151
+ nodes.push({ parent: id, branch: { variable: j, relation: ">=", value: add(k, ONE) }, outcome: "open", result: undefined });
152
+ stack.push(nodes.length - 1);
153
+ nodes.push({ parent: id, branch: { variable: j, relation: "<=", value: k }, outcome: "open", result: undefined });
154
+ stack.push(nodes.length - 1);
155
+ }
156
+ return { best, nodes, stopped: stack.length > 0 };
157
+ }
158
+
159
+ /** This function gives the direction times the least common multiple of its denominators, so each entry is an integer. */
160
+ function integral(direction: Vector): Vector {
161
+ let m = 1n;
162
+ for (const v of direction) m = (m / gcd(m, v.d)) * v.d;
163
+ return direction.map((v) => rational(v.n * (m / v.d)));
164
+ }
165
+
166
+ /** This function gives the frozen tree of the nodes of a search. */
167
+ function treeOf(nodes: readonly WorkNode[]): BranchNode[] {
168
+ return nodes.map(({ parent, branch, outcome, result }) => ({ parent, branch, outcome, result }));
169
+ }
170
+
171
+ /**
172
+ * This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches
173
+ * on the fractional integer variable with the smallest index.
174
+ *
175
+ * - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.
176
+ * - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is
177
+ * unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.
178
+ * - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.
179
+ *
180
+ * @throws {RangeError} A row has a length that is not the count of variables.
181
+ * @throws {RangeError} An integer variable is not a variable of the program.
182
+ * @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.
183
+ */
184
+ export function solveIntegerProgram(program: IntegerProgram, options: IntegerOptions = {}): IntegerProgramResult {
185
+ checkShape(program);
186
+ const problems = integerProblems(program);
187
+ if (problems.length > 0) throw new RangeError(`linear: ${problems.join(", ")}`);
188
+ const limit = options.nodeLimit ?? 10_000;
189
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`linear: the node limit ${String(limit)} is not an integer of 1 or more`);
190
+ const integer = [...new Set(program.integer)].sort((a, b) => a - b);
191
+ const root = solveLinearProgram(program);
192
+ if (root.status === "unbounded") {
193
+ const zero: LinearProgram = { ...program, objective: program.objective.map(() => ZERO) };
194
+ const found = search(zero, integer, limit, true, solveLinearProgram(zero));
195
+ if (found.best !== undefined) return { status: "unbounded", x: found.best.x, direction: integral(root.direction) };
196
+ const tree = treeOf(found.nodes);
197
+ if (found.stopped) return { status: "limit", x: undefined, value: undefined, bound: undefined, tree };
198
+ return { status: "infeasible", tree };
199
+ }
200
+ const found = search(program, integer, limit, false, root);
201
+ const tree = treeOf(found.nodes);
202
+ if (found.stopped) {
203
+ const s = program.sense === "max" ? 1 : -1;
204
+ let bound = found.best?.value;
205
+ for (const node of found.nodes) {
206
+ if (node.outcome !== "open" || node.parent === undefined) continue;
207
+ const parent = found.nodes[node.parent]?.result;
208
+ if (parent?.status === "optimal" && (bound === undefined || compare(parent.value, bound) * s > 0)) bound = parent.value;
209
+ }
210
+ return { status: "limit", x: found.best?.x, value: found.best?.value, bound, tree };
211
+ }
212
+ if (found.best === undefined) return { status: "infeasible", tree };
213
+ return { status: "optimal", x: found.best.x, value: found.best.value, tree };
214
+ }
215
+
216
+ /** This function adds a failure for each integer variable of `x` with a value that is not an integer. */
217
+ function checkIntegral(integer: readonly number[], x: Vector, name: string, failures: string[]): void {
218
+ for (const j of integer) {
219
+ const v = x[j];
220
+ if (v !== undefined && !isInteger(v)) failures.push(`${name}[${String(j)}] = ${toString(v)} is not an integer`);
221
+ }
222
+ }
223
+
224
+ /** This function adds a failure when the value `v` is better than `limit` in the sense of the program. */
225
+ function checkNotBetter(s: 1 | -1, v: Rational, limit: Rational, name: string, failures: string[]): void {
226
+ if (compare(v, limit) * s > 0) failures.push(`${name} ${toString(v)} is better than ${toString(limit)}`);
227
+ }
228
+
229
+ /**
230
+ * This function examines the tree of a result: its shape, and a certificate for each leaf. With `best`, the value of each leaf
231
+ * is not better than `best`. Each failure goes into `failures`.
232
+ */
233
+ function checkTree(program: IntegerProgram, tree: readonly BranchNode[], allowOpen: boolean, best: Rational | undefined, failures: string[]): void {
234
+ const s = program.sense === "max" ? 1 : -1;
235
+ const integer = new Set(program.integer);
236
+ const root = tree[0];
237
+ if (root === undefined || root.parent !== undefined || root.branch !== undefined) {
238
+ failures.push("node 0 is not a root with no parent and no branch");
239
+ return;
240
+ }
241
+ const children = tree.map((): number[] => []);
242
+ for (let i = 1; i < tree.length; i++) {
243
+ const node = tree[i] as BranchNode;
244
+ if (node.parent === undefined || !Number.isInteger(node.parent) || node.parent < 0 || node.parent >= i || node.branch === undefined) {
245
+ failures.push(`node ${String(i)} has no parent before it, or no branch`);
246
+ return;
247
+ }
248
+ if (!integer.has(node.branch.variable) || !isInteger(node.branch.value)) failures.push(`node ${String(i)} branches on a variable that is not an integer variable, or at a value that is not an integer`);
249
+ children[node.parent]?.push(i);
250
+ }
251
+ tree.forEach((node, i) => {
252
+ const kids = children[i] as number[];
253
+ if (node.outcome === "branched") {
254
+ const [a, b] = kids.map((k) => (tree[k] as BranchNode).branch as Branch);
255
+ const down = [a, b].find((branch) => branch?.relation === "<=");
256
+ const up = [a, b].find((branch) => branch?.relation === ">=");
257
+ if (kids.length !== 2 || down === undefined || up === undefined || down.variable !== up.variable || !equals(add(down.value, ONE), up.value)) {
258
+ failures.push(`node ${String(i)} is branched, and its children are not x_j <= k and x_j >= k + 1`);
259
+ }
260
+ return;
261
+ }
262
+ if (kids.length > 0) failures.push(`node ${String(i)} has children, and its outcome is ${node.outcome}`);
263
+ if (node.outcome === "open") {
264
+ if (!allowOpen) failures.push(`node ${String(i)} is open`);
265
+ if (best === undefined || node.parent === undefined) return;
266
+ // The integer points of an open node are not better than the optimum of the relaxation of its parent.
267
+ const parent = tree[node.parent]?.result;
268
+ if (parent?.status !== "optimal") {
269
+ failures.push(`node ${String(i)} is open, and its parent has no optimum`);
270
+ return;
271
+ }
272
+ const check = checkCertificate(nodeProgram(program, tree, node.parent), parent);
273
+ for (const failure of check.failures) failures.push(`node ${String(node.parent)}: ${failure}`);
274
+ checkNotBetter(s, parent.value, best, `the parent of the open node ${String(i)} has the value`, failures);
275
+ return;
276
+ }
277
+ const result = node.result;
278
+ if (result === undefined) {
279
+ failures.push(`node ${String(i)} is a leaf with no result`);
280
+ return;
281
+ }
282
+ const check = checkCertificate(nodeProgram(program, tree, i), result);
283
+ for (const failure of check.failures) failures.push(`node ${String(i)}: ${failure}`);
284
+ if (node.outcome === "infeasible") {
285
+ if (result.status !== "infeasible") failures.push(`node ${String(i)} is infeasible, and its result is ${result.status}`);
286
+ return;
287
+ }
288
+ if (result.status !== "optimal") {
289
+ failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome}, and its result is ${result.status}`);
290
+ return;
291
+ }
292
+ if (node.outcome === "integer") checkIntegral(program.integer, result.x, `node ${String(i)}: x`, failures);
293
+ if (best === undefined) failures.push(`node ${String(i)} has an optimum, and the result claims no integer point`);
294
+ else checkNotBetter(s, result.value, best, `node ${String(i)} has the value`, failures);
295
+ });
296
+ }
297
+
298
+ /**
299
+ * This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.
300
+ *
301
+ * - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer
302
+ * point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its
303
+ * relaxation, and its value is not better than the value of the point.
304
+ * - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.
305
+ * - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.
306
+ * - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed
307
+ * leaf has a valid certificate. With a bound, each leaf and the parent of each open node have a value that is not better than the bound.
308
+ */
309
+ export function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): CertificateCheck {
310
+ const failures: string[] = [];
311
+ if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {
312
+ failures.push("a constraint row has a length that is not the count of variables");
313
+ return { valid: false, failures };
314
+ }
315
+ failures.push(...integerProblems(program));
316
+ if (failures.length > 0) return { valid: false, failures };
317
+ const s = program.sense === "max" ? 1 : -1;
318
+ const point = (x: Vector, value: Rational): void => {
319
+ checkFeasible(program, x, failures);
320
+ checkIntegral(program.integer, x, "x", failures);
321
+ if (x.length === program.objective.length && !equals(dot(program.objective, x), value)) failures.push(`the value ${toString(value)} is not c x = ${toString(dot(program.objective, x))}`);
322
+ };
323
+ if (result.status === "unbounded") {
324
+ failures.push(...checkCertificate(program, { status: "unbounded", x: result.x, direction: result.direction }).failures);
325
+ checkIntegral(program.integer, result.x, "x", failures);
326
+ checkIntegral(program.integer, result.direction, "direction", failures);
327
+ } else if (result.status === "optimal") {
328
+ point(result.x, result.value);
329
+ checkTree(program, result.tree, false, result.value, failures);
330
+ } else if (result.status === "infeasible") {
331
+ checkTree(program, result.tree, false, undefined, failures);
332
+ result.tree.forEach((node, i) => {
333
+ if (node.outcome !== "branched" && node.outcome !== "infeasible") failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome} in an infeasible result`);
334
+ });
335
+ } else {
336
+ if ((result.x === undefined) !== (result.value === undefined)) failures.push("the limit result has a point with no value, or a value with no point");
337
+ if (result.x !== undefined && result.value !== undefined) {
338
+ point(result.x, result.value);
339
+ if (result.bound === undefined) failures.push("the limit result has a point and no bound");
340
+ else checkNotBetter(s, result.value, result.bound, "the value", failures);
341
+ }
342
+ checkTree(program, result.tree, true, result.bound, failures);
343
+ }
344
+ return { valid: failures.length === 0, failures };
345
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Lexicographic objectives: a list of objectives, each optimized in turn while the earlier optima stay as equalities.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import type { Rational } from "@mark1russell7/rational";
7
+ import type { Constraint, LinearProgram, LinearProgramResult, Sense } from "./program.ts";
8
+ import { solveLinearProgram } from "./simplex.ts";
9
+ import type { Vector } from "./vector.ts";
10
+
11
+ /** One objective of a lexicographic program. */
12
+ export interface Objective {
13
+ readonly sense: Sense;
14
+ readonly coefficients: Vector;
15
+ }
16
+
17
+ /** One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate. */
18
+ export interface LexicographicStage {
19
+ readonly program: LinearProgram;
20
+ readonly result: LinearProgramResult;
21
+ }
22
+
23
+ /**
24
+ * The result of `solveLexicographic`. The status `optimal` gives the last point and the optimum of each objective. The status
25
+ * `infeasible` or `unbounded` comes from the last stage, and its result has the certificate. `checkCertificate` examines each
26
+ * stage with its program.
27
+ */
28
+ export type LexicographicResult =
29
+ | { readonly status: "optimal"; readonly x: Vector; readonly values: readonly Rational[]; readonly stages: readonly LexicographicStage[] }
30
+ | { readonly status: "infeasible" | "unbounded"; readonly stages: readonly LexicographicStage[] };
31
+
32
+ /**
33
+ * This function optimizes the objectives in their order, subject to the constraint rows and `x >= 0`. Stage `k` holds the
34
+ * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.
35
+ * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.
36
+ *
37
+ * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.
38
+ */
39
+ export function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[]): LexicographicResult {
40
+ if (objectives.length === 0) throw new RangeError("linear: a lexicographic program needs one objective or more");
41
+ const stages: LexicographicStage[] = [];
42
+ const rows: Constraint[] = [...constraints];
43
+ const values: Rational[] = [];
44
+ let x: Vector = [];
45
+ for (const objective of objectives) {
46
+ const program: LinearProgram = { sense: objective.sense, objective: objective.coefficients, constraints: [...rows] };
47
+ const result = solveLinearProgram(program);
48
+ stages.push({ program, result });
49
+ if (result.status !== "optimal") return { status: result.status, stages };
50
+ x = result.x;
51
+ values.push(result.value);
52
+ rows.push({ coefficients: objective.coefficients, relation: "=", rhs: result.value });
53
+ }
54
+ return { status: "optimal", x, values, stages };
55
+ }
package/src/matrix.ts ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Exact elimination: the reduced row echelon form, the rank, a basis of the null space and the solution of a system.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import { type Rational, inverse, mul, neg, ONE, sign, sub, ZERO } from "@mark1russell7/rational";
7
+ import { type Matrix, type Vector, columnsOf } from "./vector.ts";
8
+
9
+ /** The reduced row echelon form of a matrix and the column of each pivot, in order. */
10
+ export interface RowEchelon {
11
+ readonly matrix: Matrix;
12
+ readonly pivots: readonly number[];
13
+ }
14
+
15
+ /**
16
+ * This function applies Gauss-Jordan elimination to the rows in place. It takes pivots only in the columns below `limit`.
17
+ * It gives the column of each pivot. The row of pivot `k` is row `k`.
18
+ */
19
+ function eliminate(rows: Rational[][], limit: number): number[] {
20
+ const pivots: number[] = [];
21
+ let r = 0;
22
+ for (let c = 0; c < limit && r < rows.length; c++) {
23
+ let p = r;
24
+ while (p < rows.length && sign(rows[p]![c]!) === 0) p++;
25
+ if (p === rows.length) continue;
26
+ const swap = rows[r]!;
27
+ rows[r] = rows[p]!;
28
+ rows[p] = swap;
29
+ const scale = inverse(rows[r]![c]!);
30
+ const pivotRow = rows[r]!.map((v) => mul(v, scale));
31
+ rows[r] = pivotRow;
32
+ for (let i = 0; i < rows.length; i++) {
33
+ const f = rows[i]![c]!;
34
+ if (i === r || sign(f) === 0) continue;
35
+ rows[i] = rows[i]!.map((v, j) => sub(v, mul(f, pivotRow[j]!)));
36
+ }
37
+ pivots.push(c);
38
+ r++;
39
+ }
40
+ return pivots;
41
+ }
42
+
43
+ /**
44
+ * This function gives the reduced row echelon form of a matrix, with exact arithmetic.
45
+ *
46
+ * @throws {RangeError} The rows do not have the same length.
47
+ */
48
+ export function rref(m: Matrix): RowEchelon {
49
+ const n = columnsOf(m);
50
+ const rows = m.map((row) => [...row]);
51
+ const pivots = eliminate(rows, n);
52
+ return { matrix: rows, pivots };
53
+ }
54
+
55
+ /** This function gives the rank of a matrix: the count of pivots of its reduced row echelon form. */
56
+ export function rank(m: Matrix): number {
57
+ return rref(m).pivots.length;
58
+ }
59
+
60
+ /**
61
+ * 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
62
+ * column with no pivot. That vector has 1 at its column and 0 at each other column with no pivot. The argument `columns`
63
+ * gives the count of columns for a matrix with no rows.
64
+ */
65
+ export function nullSpace(m: Matrix, columns: number = columnsOf(m)): Matrix {
66
+ const { matrix: r, pivots } = rref(m);
67
+ const basis: Vector[] = [];
68
+ for (let free = 0; free < columns; free++) {
69
+ if (pivots.includes(free)) continue;
70
+ const v: Rational[] = new Array<Rational>(columns).fill(ZERO);
71
+ v[free] = ONE;
72
+ pivots.forEach((p, k) => {
73
+ v[p] = neg(r[k]![free]!);
74
+ });
75
+ basis.push(v);
76
+ }
77
+ return basis;
78
+ }
79
+
80
+ /**
81
+ * 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
82
+ * combination of the basis. A system with no solution gives a certificate `y` with `y A = 0` and `y b = 1`.
83
+ */
84
+ export type SolveResult =
85
+ | { readonly status: "solved"; readonly x: Vector; readonly nullSpace: Matrix }
86
+ | { readonly status: "inconsistent"; readonly certificate: Vector };
87
+
88
+ /**
89
+ * 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.
90
+ * The solution `x` has 0 at each column with no pivot.
91
+ *
92
+ * @throws {RangeError} The rows do not have the same length, or `b` has a length that is not the row count.
93
+ */
94
+ export function solve(a: Matrix, b: Vector, columns: number = columnsOf(a)): SolveResult {
95
+ const m = a.length;
96
+ if (b.length !== m) throw new RangeError(`linear: the matrix has ${m} rows, and the right side has ${b.length} entries`);
97
+ // The augmented rows [a | b | I]. The identity part records the row operations, so a row `[0 | 1 | y]` gives the certificate.
98
+ const rows = a.map((row, i) => [...row, b[i]!, ...Array.from({ length: m }, (_, k) => (k === i ? ONE : ZERO))]);
99
+ const pivots = eliminate(rows, columns + 1);
100
+ const last = pivots.length - 1;
101
+ if (last >= 0 && pivots[last] === columns) {
102
+ return { status: "inconsistent", certificate: rows[last]!.slice(columns + 1) };
103
+ }
104
+ const x: Rational[] = new Array<Rational>(columns).fill(ZERO);
105
+ pivots.forEach((p, k) => {
106
+ x[p] = rows[k]![columns]!;
107
+ });
108
+ return { status: "solved", x, nullSpace: nullSpace(a, columns) };
109
+ }
package/src/program.ts ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Linear programs as data, and their results with certificates.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import type { Rational } from "@mark1russell7/rational";
7
+ import { type RationalInput, type Vector, toRational, vector } from "./vector.ts";
8
+
9
+ /** The direction of an objective: `"max"` to maximize it, `"min"` to minimize it. */
10
+ export type Sense = "max" | "min";
11
+
12
+ /** The relation of a constraint row to its right side. */
13
+ export type Relation = "<=" | ">=" | "=";
14
+
15
+ /** One constraint row: `coefficients · x` has the relation `relation` to `rhs`. */
16
+ export interface Constraint {
17
+ readonly coefficients: Vector;
18
+ readonly relation: Relation;
19
+ readonly rhs: Rational;
20
+ }
21
+
22
+ /**
23
+ * A linear program: optimize `objective · x` subject to the constraint rows and `x >= 0`. Each variable has the lower bound 0.
24
+ * A free variable `v` is the difference of two variables `p - q`. Copy each coefficient of `v` to `p`. Put its negative on `q`.
25
+ */
26
+ export interface LinearProgram {
27
+ readonly sense: Sense;
28
+ readonly objective: Vector;
29
+ readonly constraints: readonly Constraint[];
30
+ }
31
+
32
+ /**
33
+ * The result of a linear program, with its certificate.
34
+ *
35
+ * - `optimal`: the point `x`, its value `objective · x`, and a dual vector `dual` with one entry for each constraint row.
36
+ * - `infeasible`: a Farkas ray `ray` with one entry for each constraint row. `checkCertificate` tells its conditions.
37
+ * - `unbounded`: a feasible point `x` and a direction `direction`. Each point `x + t direction` with `t >= 0` is feasible, and
38
+ * the objective improves without limit along it.
39
+ */
40
+ export type LinearProgramResult =
41
+ | { readonly status: "optimal"; readonly x: Vector; readonly value: Rational; readonly dual: Vector }
42
+ | { readonly status: "infeasible"; readonly ray: Vector }
43
+ | { readonly status: "unbounded"; readonly x: Vector; readonly direction: Vector };
44
+
45
+ /** One constraint row of `linearProgram`, with inputs that `toRational` reads. */
46
+ export interface ConstraintInput {
47
+ readonly coefficients: readonly RationalInput[];
48
+ readonly relation: Relation;
49
+ readonly rhs: RationalInput;
50
+ }
51
+
52
+ /** A linear program with inputs that `toRational` reads. */
53
+ export interface LinearProgramInput {
54
+ readonly sense: Sense;
55
+ readonly objective: readonly RationalInput[];
56
+ readonly constraints: readonly ConstraintInput[];
57
+ }
58
+
59
+ /**
60
+ * This function makes a linear program from inputs that `toRational` reads, and examines its shape.
61
+ *
62
+ * @throws {RangeError} A constraint row has a length that is not the length of the objective.
63
+ */
64
+ export function linearProgram(input: LinearProgramInput): LinearProgram {
65
+ const program: LinearProgram = {
66
+ sense: input.sense,
67
+ objective: vector(input.objective),
68
+ constraints: input.constraints.map((c) => ({ coefficients: vector(c.coefficients), relation: c.relation, rhs: toRational(c.rhs) })),
69
+ };
70
+ checkShape(program);
71
+ return program;
72
+ }
73
+
74
+ /**
75
+ * This function examines the shape of a program: each constraint row has one coefficient for each variable.
76
+ *
77
+ * @throws {RangeError} A constraint row has a length that is not the length of the objective.
78
+ */
79
+ export function checkShape(program: LinearProgram): void {
80
+ const n = program.objective.length;
81
+ program.constraints.forEach((c, i) => {
82
+ if (c.coefficients.length !== n) {
83
+ throw new RangeError(`linear: constraint ${i} has ${c.coefficients.length} coefficients, and the objective has ${n}`);
84
+ }
85
+ });
86
+ }