@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/LICENSE +21 -0
- package/README.md +70 -1
- package/build/index.d.ts +195 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +577 -0
- package/build/index.js.map +1 -0
- package/package.json +59 -4
- package/src/certificate.ts +138 -0
- package/src/index.ts +20 -0
- package/src/lexicographic.ts +55 -0
- package/src/matrix.ts +109 -0
- package/src/program.ts +86 -0
- package/src/simplex.ts +238 -0
- package/src/vector.ts +92 -0
package/package.json
CHANGED
|
@@ -1,13 +1,68 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package",
|
|
2
3
|
"name": "@mark1russell7/linear",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "Exact linear algebra and linear programs over exact rationals: solve, rank, null space, a two-phase simplex with the rule of Bland, lexicographic objectives and certificates with a check.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"linear-algebra",
|
|
8
|
+
"linear-programming",
|
|
9
|
+
"simplex",
|
|
10
|
+
"exact-arithmetic",
|
|
11
|
+
"rational",
|
|
12
|
+
"certificate",
|
|
13
|
+
"farkas",
|
|
14
|
+
"duality"
|
|
15
|
+
],
|
|
16
|
+
"homepage": "https://github.com/mark1russell7/algebra/tree/main/packages/linear#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/mark1russell7/algebra/issues"
|
|
19
|
+
},
|
|
5
20
|
"repository": {
|
|
6
21
|
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/mark1russell7/algebra.git"
|
|
22
|
+
"url": "git+https://github.com/mark1russell7/algebra.git",
|
|
23
|
+
"directory": "packages/linear"
|
|
8
24
|
},
|
|
9
25
|
"license": "MIT",
|
|
26
|
+
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
27
|
+
"type": "module",
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"main": "./build/index.js",
|
|
30
|
+
"types": "./build/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./build/index.d.ts",
|
|
34
|
+
"default": "./build/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./package.json": "./package.json"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"build",
|
|
40
|
+
"src",
|
|
41
|
+
"!src/**/*.test.ts",
|
|
42
|
+
"!src/**/*.test-helper.ts"
|
|
43
|
+
],
|
|
10
44
|
"publishConfig": {
|
|
11
45
|
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=22"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@mark1russell7/rational": "0.1.3"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@mark1russell7/cue": "^2.1.1",
|
|
55
|
+
"@types/node": "^26.6.5",
|
|
56
|
+
"@vitest/coverage-v8": "^5.0.3",
|
|
57
|
+
"fast-check": "^4.10.2",
|
|
58
|
+
"tsdown": "^0.23.4",
|
|
59
|
+
"typescript": "^7.0.2",
|
|
60
|
+
"vitest": "^5.0.3"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "tsdown",
|
|
64
|
+
"test": "vitest run",
|
|
65
|
+
"test:watch": "vitest",
|
|
66
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
|
|
12
67
|
}
|
|
13
|
-
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The check of a certificate. It uses only exact arithmetic on the program and the result, and it does not trust the solver.
|
|
3
|
+
*
|
|
4
|
+
* @packageDocumentation
|
|
5
|
+
*/
|
|
6
|
+
import { type Rational, equals, mul, sign, sub, toString } from "@mark1russell7/rational";
|
|
7
|
+
import type { LinearProgram, LinearProgramResult, Relation } from "./program.ts";
|
|
8
|
+
import { dot, type Vector } from "./vector.ts";
|
|
9
|
+
|
|
10
|
+
/** The verdict of `checkCertificate`. The list `failures` names each condition that the certificate does not meet. */
|
|
11
|
+
export interface CertificateCheck {
|
|
12
|
+
readonly valid: boolean;
|
|
13
|
+
readonly failures: readonly string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** This function tells if the sign of a value obeys a relation to 0. */
|
|
17
|
+
function holds(s: -1 | 0 | 1, relation: Relation): boolean {
|
|
18
|
+
return relation === "=" ? s === 0 : relation === "<=" ? s <= 0 : s >= 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** This function gives the column sums `y A`: entry `j` is the sum over the rows of `y_i a_ij`. */
|
|
22
|
+
function columnSums(program: LinearProgram, y: Vector): Rational[] {
|
|
23
|
+
return program.objective.map((_, j) => dot(program.constraints.map((c) => c.coefficients[j]!), y));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`. */
|
|
27
|
+
function checkFeasible(program: LinearProgram, x: Vector, failures: string[]): void {
|
|
28
|
+
if (x.length !== program.objective.length) {
|
|
29
|
+
failures.push(`the point has ${x.length} entries, and the program has ${program.objective.length} variables`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
x.forEach((v, j) => {
|
|
33
|
+
if (sign(v) < 0) failures.push(`x[${j}] = ${toString(v)} is negative`);
|
|
34
|
+
});
|
|
35
|
+
program.constraints.forEach((c, i) => {
|
|
36
|
+
const lhs = dot(c.coefficients, x);
|
|
37
|
+
if (!holds(sign(sub(lhs, c.rhs)), c.relation)) {
|
|
38
|
+
failures.push(`row ${i}: ${toString(lhs)} ${c.relation} ${toString(c.rhs)} is false`);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* This function adds a failure for each multiplier with the wrong sign. With `s = 1`, a `<=` row needs a multiplier of 0 or
|
|
45
|
+
* more, and a `>=` row a multiplier of 0 or less. The value `s = -1` swaps the two signs. An `=` row takes each sign.
|
|
46
|
+
*/
|
|
47
|
+
function checkMultiplierSigns(program: LinearProgram, y: Vector, s: 1 | -1, name: string, failures: string[]): void {
|
|
48
|
+
program.constraints.forEach((c, i) => {
|
|
49
|
+
const signed = sign(y[i]!) * s;
|
|
50
|
+
if ((c.relation === "<=" && signed < 0) || (c.relation === ">=" && signed > 0)) {
|
|
51
|
+
failures.push(`${name}[${i}] = ${toString(y[i]!)} has the wrong sign for a ${c.relation} row`);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function checkOptimal(program: LinearProgram, x: Vector, value: Rational, y: Vector, failures: string[]): void {
|
|
57
|
+
const m = program.constraints.length;
|
|
58
|
+
if (y.length !== m) failures.push(`the dual has ${y.length} entries, and the program has ${m} rows`);
|
|
59
|
+
checkFeasible(program, x, failures);
|
|
60
|
+
if (y.length !== m || x.length !== program.objective.length) return;
|
|
61
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
62
|
+
checkMultiplierSigns(program, y, s, "dual", failures);
|
|
63
|
+
const sums = columnSums(program, y);
|
|
64
|
+
sums.forEach((sum, j) => {
|
|
65
|
+
const slack = sub(sum, program.objective[j]!);
|
|
66
|
+
if (sign(slack) * s < 0) failures.push(`the dual constraint of column ${j} is false: (yA)[${j}] - c[${j}] = ${toString(slack)}`);
|
|
67
|
+
if (sign(mul(x[j]!, slack)) !== 0) failures.push(`complementary slackness fails at column ${j}`);
|
|
68
|
+
});
|
|
69
|
+
program.constraints.forEach((c, i) => {
|
|
70
|
+
if (sign(mul(y[i]!, sub(dot(c.coefficients, x), c.rhs))) !== 0) failures.push(`complementary slackness fails at row ${i}`);
|
|
71
|
+
});
|
|
72
|
+
const primal = dot(program.objective, x);
|
|
73
|
+
const dual = dot(
|
|
74
|
+
program.constraints.map((c) => c.rhs),
|
|
75
|
+
y,
|
|
76
|
+
);
|
|
77
|
+
if (!equals(primal, value)) failures.push(`the value ${toString(value)} is not c x = ${toString(primal)}`);
|
|
78
|
+
if (!equals(primal, dual)) failures.push(`strong duality fails: c x = ${toString(primal)} and b y = ${toString(dual)}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function checkInfeasible(program: LinearProgram, y: Vector, failures: string[]): void {
|
|
82
|
+
const m = program.constraints.length;
|
|
83
|
+
if (y.length !== m) {
|
|
84
|
+
failures.push(`the ray has ${y.length} entries, and the program has ${m} rows`);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
checkMultiplierSigns(program, y, 1, "ray", failures);
|
|
88
|
+
columnSums(program, y).forEach((sum, j) => {
|
|
89
|
+
if (sign(sum) < 0) failures.push(`(yA)[${j}] = ${toString(sum)} is negative`);
|
|
90
|
+
});
|
|
91
|
+
const by = dot(
|
|
92
|
+
program.constraints.map((c) => c.rhs),
|
|
93
|
+
y,
|
|
94
|
+
);
|
|
95
|
+
if (sign(by) >= 0) failures.push(`b y = ${toString(by)} is not negative`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function checkUnbounded(program: LinearProgram, x: Vector, d: Vector, failures: string[]): void {
|
|
99
|
+
checkFeasible(program, x, failures);
|
|
100
|
+
if (d.length !== program.objective.length) {
|
|
101
|
+
failures.push(`the direction has ${d.length} entries, and the program has ${program.objective.length} variables`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
d.forEach((v, j) => {
|
|
105
|
+
if (sign(v) < 0) failures.push(`direction[${j}] = ${toString(v)} is negative`);
|
|
106
|
+
});
|
|
107
|
+
program.constraints.forEach((c, i) => {
|
|
108
|
+
const ad = dot(c.coefficients, d);
|
|
109
|
+
if (!holds(sign(ad), c.relation)) failures.push(`row ${i}: the direction gives ${toString(ad)}, so it leaves the row`);
|
|
110
|
+
});
|
|
111
|
+
const gain = dot(program.objective, d);
|
|
112
|
+
const s = program.sense === "max" ? 1 : -1;
|
|
113
|
+
if (sign(gain) * s <= 0) failures.push(`the direction does not improve the objective: c d = ${toString(gain)}`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* This function examines the certificate of a result with exact arithmetic. It does not trust the solver.
|
|
118
|
+
*
|
|
119
|
+
* - `optimal`: the point is feasible, the dual is feasible, `c x = b y` and complementary slackness holds. For a maximization,
|
|
120
|
+
* 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.
|
|
121
|
+
* - `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`
|
|
122
|
+
* meets the rows, because `0 <= y A x <= y b < 0`.
|
|
123
|
+
* - `unbounded`: the point is feasible, the direction is not negative, each row keeps its relation along it, and the
|
|
124
|
+
* direction improves the objective.
|
|
125
|
+
*/
|
|
126
|
+
export function checkCertificate(program: LinearProgram, result: LinearProgramResult): CertificateCheck {
|
|
127
|
+
const failures: string[] = [];
|
|
128
|
+
if (program.constraints.some((c) => c.coefficients.length !== program.objective.length)) {
|
|
129
|
+
failures.push("a constraint row has a length that is not the count of variables");
|
|
130
|
+
} else if (result.status === "optimal") {
|
|
131
|
+
checkOptimal(program, result.x, result.value, result.dual, failures);
|
|
132
|
+
} else if (result.status === "infeasible") {
|
|
133
|
+
checkInfeasible(program, result.ray, failures);
|
|
134
|
+
} else {
|
|
135
|
+
checkUnbounded(program, result.x, result.direction, failures);
|
|
136
|
+
}
|
|
137
|
+
return { valid: failures.length === 0, failures };
|
|
138
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// @mark1russell7/linear: exact linear algebra and linear programs over the rationals of @mark1russell7/rational.
|
|
2
|
+
export type { Matrix, RationalInput, Vector } from "./vector.ts";
|
|
3
|
+
export { columnsOf, dot, matrix, multiply, toRational, transpose, vector } from "./vector.ts";
|
|
4
|
+
export type { RowEchelon, SolveResult } from "./matrix.ts";
|
|
5
|
+
export { nullSpace, rank, rref, solve } from "./matrix.ts";
|
|
6
|
+
export type {
|
|
7
|
+
Constraint,
|
|
8
|
+
ConstraintInput,
|
|
9
|
+
LinearProgram,
|
|
10
|
+
LinearProgramInput,
|
|
11
|
+
LinearProgramResult,
|
|
12
|
+
Relation,
|
|
13
|
+
Sense,
|
|
14
|
+
} from "./program.ts";
|
|
15
|
+
export { linearProgram } from "./program.ts";
|
|
16
|
+
export { solveLinearProgram } from "./simplex.ts";
|
|
17
|
+
export type { LexicographicResult, LexicographicStage, Objective } from "./lexicographic.ts";
|
|
18
|
+
export { solveLexicographic } from "./lexicographic.ts";
|
|
19
|
+
export type { CertificateCheck } from "./certificate.ts";
|
|
20
|
+
export { checkCertificate } from "./certificate.ts";
|
|
@@ -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
|
+
}
|