@mark1russell7/linear 0.0.0-stage → 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 +71 -2
- 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 +65 -3
- 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/src/simplex.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The exact two-phase simplex. The rule of Bland selects each pivot, so the method ends on each program.
|
|
3
|
+
*
|
|
4
|
+
* @packageDocumentation
|
|
5
|
+
*/
|
|
6
|
+
import { type Rational, compare, div, inverse, mul, neg, ONE, sign, sub, ZERO } from "@mark1russell7/rational";
|
|
7
|
+
import { solve } from "./matrix.ts";
|
|
8
|
+
import { checkShape, type LinearProgram, type LinearProgramResult, type Relation } from "./program.ts";
|
|
9
|
+
import { dot } from "./vector.ts";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The rule that selects the entering column. `"bland"` takes the column with the smallest index that improves the objective.
|
|
13
|
+
* `"largest"` takes the column with the largest reduced cost, with the smallest index on a tie. The rule `"largest"` can cycle
|
|
14
|
+
* on a degenerate program, and the tests use it only to show that cycle.
|
|
15
|
+
*
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
export type PivotRule = "bland" | "largest";
|
|
19
|
+
|
|
20
|
+
/** The program in equality form: `rows z = rhs`, `z >= 0`, with `rhs >= 0`. */
|
|
21
|
+
interface StandardForm {
|
|
22
|
+
/** The original columns, then one slack or surplus column for each inequality row, then one artificial column for each row that needs one. */
|
|
23
|
+
readonly rows: readonly (readonly Rational[])[];
|
|
24
|
+
readonly rhs: readonly Rational[];
|
|
25
|
+
/** The rows that the form multiplies by -1, so that their right side is not negative. */
|
|
26
|
+
readonly flipped: readonly boolean[];
|
|
27
|
+
/** The first basis: the slack column of a `<=` row, or the artificial column of the row. */
|
|
28
|
+
readonly basis: readonly number[];
|
|
29
|
+
/** The count of columns that are not artificial. */
|
|
30
|
+
readonly structural: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The working tableau: the rows in the form of the current basis. */
|
|
34
|
+
interface Tableau {
|
|
35
|
+
readonly rows: Rational[][];
|
|
36
|
+
readonly rhs: Rational[];
|
|
37
|
+
readonly basis: number[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const FLIP: Readonly<Record<Relation, Relation>> = { "<=": ">=", ">=": "<=", "=": "=" };
|
|
41
|
+
|
|
42
|
+
function standardForm(program: LinearProgram): StandardForm {
|
|
43
|
+
const n = program.objective.length;
|
|
44
|
+
const rels = program.constraints.map((c) => (sign(c.rhs) < 0 ? FLIP[c.relation] : c.relation));
|
|
45
|
+
const slacks = rels.filter((r) => r !== "=").length;
|
|
46
|
+
const artificials = rels.filter((r) => r !== "<=").length;
|
|
47
|
+
const structural = n + slacks;
|
|
48
|
+
const total = structural + artificials;
|
|
49
|
+
const rows: Rational[][] = [];
|
|
50
|
+
const rhs: Rational[] = [];
|
|
51
|
+
const flipped: boolean[] = [];
|
|
52
|
+
const basis: number[] = [];
|
|
53
|
+
let slack = n;
|
|
54
|
+
let artificial = structural;
|
|
55
|
+
program.constraints.forEach((c, i) => {
|
|
56
|
+
const flip = sign(c.rhs) < 0;
|
|
57
|
+
const row: Rational[] = new Array<Rational>(total).fill(ZERO);
|
|
58
|
+
c.coefficients.forEach((v, j) => {
|
|
59
|
+
row[j] = flip ? neg(v) : v;
|
|
60
|
+
});
|
|
61
|
+
const rel = rels[i]!;
|
|
62
|
+
if (rel === "<=") {
|
|
63
|
+
row[slack] = ONE;
|
|
64
|
+
basis.push(slack++);
|
|
65
|
+
} else {
|
|
66
|
+
if (rel === ">=") row[slack++] = neg(ONE);
|
|
67
|
+
row[artificial] = ONE;
|
|
68
|
+
basis.push(artificial++);
|
|
69
|
+
}
|
|
70
|
+
rows.push(row);
|
|
71
|
+
rhs.push(flip ? neg(c.rhs) : c.rhs);
|
|
72
|
+
flipped.push(flip);
|
|
73
|
+
});
|
|
74
|
+
return { rows, rhs, flipped, basis, structural };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function pivot(t: Tableau, p: number, q: number): void {
|
|
78
|
+
const scale = inverse(t.rows[p]![q]!);
|
|
79
|
+
const pivotRow = t.rows[p]!.map((v) => mul(v, scale));
|
|
80
|
+
const pivotRhs = mul(t.rhs[p]!, scale);
|
|
81
|
+
t.rows[p] = pivotRow;
|
|
82
|
+
t.rhs[p] = pivotRhs;
|
|
83
|
+
for (let i = 0; i < t.rows.length; i++) {
|
|
84
|
+
const f = t.rows[i]![q]!;
|
|
85
|
+
if (i === p || sign(f) === 0) continue;
|
|
86
|
+
t.rows[i] = t.rows[i]!.map((v, j) => sub(v, mul(f, pivotRow[j]!)));
|
|
87
|
+
t.rhs[i] = sub(t.rhs[i]!, mul(f, pivotRhs));
|
|
88
|
+
}
|
|
89
|
+
t.basis[p] = q;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** This function gives the reduced cost `c_j - c_B B^-1 A_j` of each column, for a maximization. */
|
|
93
|
+
function reducedCosts(t: Tableau, cost: readonly Rational[]): Rational[] {
|
|
94
|
+
const r = [...cost];
|
|
95
|
+
t.rows.forEach((row, i) => {
|
|
96
|
+
const cb = cost[t.basis[i]!]!;
|
|
97
|
+
if (sign(cb) === 0) return;
|
|
98
|
+
for (let j = 0; j < r.length; j++) r[j] = sub(r[j]!, mul(cb, row[j]!));
|
|
99
|
+
});
|
|
100
|
+
return r;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
type Phase = { readonly kind: "optimal" } | { readonly kind: "unbounded"; readonly column: number } | { readonly kind: "cycle" };
|
|
104
|
+
|
|
105
|
+
const basisKey = (basis: readonly number[]): string => [...basis].sort((a, b) => a - b).join(",");
|
|
106
|
+
|
|
107
|
+
/** This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. */
|
|
108
|
+
function runPhase(t: Tableau, cost: readonly Rational[], allowed: number, rule: PivotRule, count: { pivots: number }): Phase {
|
|
109
|
+
const seen = new Set<string>([basisKey(t.basis)]);
|
|
110
|
+
for (;;) {
|
|
111
|
+
const r = reducedCosts(t, cost);
|
|
112
|
+
let q = -1;
|
|
113
|
+
for (let j = 0; j < allowed; j++) {
|
|
114
|
+
if (sign(r[j]!) <= 0) continue;
|
|
115
|
+
if (rule === "bland") {
|
|
116
|
+
q = j;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
if (q < 0 || compare(r[j]!, r[q]!) > 0) q = j;
|
|
120
|
+
}
|
|
121
|
+
if (q < 0) return { kind: "optimal" };
|
|
122
|
+
let p = -1;
|
|
123
|
+
let best = ZERO;
|
|
124
|
+
t.rows.forEach((row, i) => {
|
|
125
|
+
const a = row[q]!;
|
|
126
|
+
if (sign(a) <= 0) return;
|
|
127
|
+
const ratio = div(t.rhs[i]!, a);
|
|
128
|
+
const order = p < 0 ? -1 : compare(ratio, best);
|
|
129
|
+
if (order < 0 || (order === 0 && t.basis[i]! < t.basis[p]!)) {
|
|
130
|
+
p = i;
|
|
131
|
+
best = ratio;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
if (p < 0) return { kind: "unbounded", column: q };
|
|
135
|
+
pivot(t, p, q);
|
|
136
|
+
count.pivots++;
|
|
137
|
+
// A deterministic rule that meets a basis again repeats its cycle forever. The rule of Bland does not meet a basis again.
|
|
138
|
+
const key = basisKey(t.basis);
|
|
139
|
+
if (seen.has(key)) return { kind: "cycle" };
|
|
140
|
+
seen.add(key);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 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. */
|
|
145
|
+
function dualOf(form: StandardForm, basis: readonly number[], cost: readonly Rational[]): Rational[] {
|
|
146
|
+
if (basis.length === 0) return [];
|
|
147
|
+
const bt = basis.map((col) => form.rows.map((row) => row[col]!));
|
|
148
|
+
const solved = solve(bt, basis.map((col) => cost[col]!));
|
|
149
|
+
if (solved.status !== "solved") throw new Error("linear: internal error, the basis is singular");
|
|
150
|
+
return solved.x.map((y, i) => (form.flipped[i] ? neg(y) : y));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** This function gives the first `n` entries of the basic solution of the tableau. */
|
|
154
|
+
function pointOf(t: Tableau, n: number): Rational[] {
|
|
155
|
+
const x: Rational[] = new Array<Rational>(n).fill(ZERO);
|
|
156
|
+
t.basis.forEach((col, i) => {
|
|
157
|
+
if (col < n) x[col] = t.rhs[i]!;
|
|
158
|
+
});
|
|
159
|
+
return x;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The run of the simplex with a pivot rule: the result, or a cycle, and the count of pivots.
|
|
164
|
+
*
|
|
165
|
+
* @internal
|
|
166
|
+
*/
|
|
167
|
+
export type SimplexRun =
|
|
168
|
+
| { readonly cycled: false; readonly result: LinearProgramResult; readonly pivots: number }
|
|
169
|
+
| { readonly cycled: true; readonly pivots: number };
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland.
|
|
173
|
+
*
|
|
174
|
+
* @internal
|
|
175
|
+
*/
|
|
176
|
+
export function runSimplex(program: LinearProgram, rule: PivotRule): SimplexRun {
|
|
177
|
+
checkShape(program);
|
|
178
|
+
const n = program.objective.length;
|
|
179
|
+
const form = standardForm(program);
|
|
180
|
+
const total = form.rows[0]?.length ?? n;
|
|
181
|
+
const t: Tableau = { rows: form.rows.map((row) => [...row]), rhs: [...form.rhs], basis: [...form.basis] };
|
|
182
|
+
const count = { pivots: 0 };
|
|
183
|
+
|
|
184
|
+
// Phase 1: maximize the negative sum of the artificial columns.
|
|
185
|
+
if (total > form.structural) {
|
|
186
|
+
const cost = Array.from({ length: total }, (_, j) => (j >= form.structural ? neg(ONE) : ZERO));
|
|
187
|
+
const phase = runPhase(t, cost, total, rule, count);
|
|
188
|
+
if (phase.kind === "cycle") return { cycled: true, pivots: count.pivots };
|
|
189
|
+
let value = ZERO;
|
|
190
|
+
t.basis.forEach((col, i) => {
|
|
191
|
+
value = sub(value, col >= form.structural ? t.rhs[i]! : ZERO);
|
|
192
|
+
});
|
|
193
|
+
if (sign(value) < 0) {
|
|
194
|
+
return { cycled: false, result: { status: "infeasible", ray: dualOf(form, t.basis, cost) }, pivots: count.pivots };
|
|
195
|
+
}
|
|
196
|
+
// 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.
|
|
197
|
+
t.basis.forEach((col, i) => {
|
|
198
|
+
if (col < form.structural) return;
|
|
199
|
+
const j = t.rows[i]!.findIndex((v, k) => k < form.structural && sign(v) !== 0);
|
|
200
|
+
if (j >= 0) pivot(t, i, j);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Phase 2: the objective, as a maximization. An artificial column cannot enter, and a row that keeps one is redundant.
|
|
205
|
+
const max = program.sense === "max";
|
|
206
|
+
const cost = Array.from({ length: total }, (_, j) => (j < n ? (max ? program.objective[j]! : neg(program.objective[j]!)) : ZERO));
|
|
207
|
+
const phase = runPhase(t, cost, form.structural, rule, count);
|
|
208
|
+
if (phase.kind === "cycle") return { cycled: true, pivots: count.pivots };
|
|
209
|
+
const x = pointOf(t, n);
|
|
210
|
+
if (phase.kind === "unbounded") {
|
|
211
|
+
const q = phase.column;
|
|
212
|
+
const direction: Rational[] = new Array<Rational>(n).fill(ZERO);
|
|
213
|
+
if (q < n) direction[q] = ONE;
|
|
214
|
+
t.basis.forEach((col, i) => {
|
|
215
|
+
if (col < n) direction[col] = neg(t.rows[i]![q]!);
|
|
216
|
+
});
|
|
217
|
+
return { cycled: false, result: { status: "unbounded", x, direction }, pivots: count.pivots };
|
|
218
|
+
}
|
|
219
|
+
const dual = dualOf(form, t.basis, cost);
|
|
220
|
+
return {
|
|
221
|
+
cycled: false,
|
|
222
|
+
result: { status: "optimal", x, value: dot(program.objective, x), dual: max ? dual : dual.map(neg) },
|
|
223
|
+
pivots: count.pivots,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* This function solves a linear program exactly with the two-phase simplex and the rule of Bland. The result has a certificate
|
|
229
|
+
* that `checkCertificate` examines.
|
|
230
|
+
*
|
|
231
|
+
* @throws {RangeError} A constraint row has a length that is not the length of the objective.
|
|
232
|
+
*/
|
|
233
|
+
export function solveLinearProgram(program: LinearProgram): LinearProgramResult {
|
|
234
|
+
const run = runSimplex(program, "bland");
|
|
235
|
+
if (run.cycled) throw new Error("linear: internal error, the rule of Bland met a basis again");
|
|
236
|
+
return run.result;
|
|
237
|
+
}
|
|
238
|
+
|
package/src/vector.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact vectors and matrices over the rationals of `@mark1russell7/rational`.
|
|
3
|
+
*
|
|
4
|
+
* @packageDocumentation
|
|
5
|
+
*/
|
|
6
|
+
import { type Rational, add, div, fromDecimal, fromNumber, mul, rational, ZERO } from "@mark1russell7/rational";
|
|
7
|
+
|
|
8
|
+
/** A vector of exact rationals. */
|
|
9
|
+
export type Vector = readonly Rational[];
|
|
10
|
+
|
|
11
|
+
/** A matrix of exact rationals as a list of rows. Each row has the same length. */
|
|
12
|
+
export type Matrix = readonly Vector[];
|
|
13
|
+
|
|
14
|
+
/** A value that `toRational` reads: a rational, a `bigint`, a JavaScript number, or a text, for example `"3/4"` or `"0.25"`. */
|
|
15
|
+
export type RationalInput = Rational | bigint | number | string;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* This function gives the exact rational of an input. A number gives the decimal that JavaScript prints for it. A text is a
|
|
19
|
+
* decimal or a quotient of two decimals.
|
|
20
|
+
*
|
|
21
|
+
* @throws {RangeError} The input is not a finite value, or the text has a zero divisor.
|
|
22
|
+
*/
|
|
23
|
+
export function toRational(value: RationalInput): Rational {
|
|
24
|
+
if (typeof value === "bigint") return rational(value);
|
|
25
|
+
if (typeof value === "number") {
|
|
26
|
+
if (!Number.isFinite(value)) throw new RangeError(`linear: ${value} is not a finite number`);
|
|
27
|
+
return fromNumber(value);
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "string") {
|
|
30
|
+
const slash = value.indexOf("/");
|
|
31
|
+
if (slash < 0) return fromDecimal(value.trim());
|
|
32
|
+
return div(fromDecimal(value.slice(0, slash).trim()), fromDecimal(value.slice(slash + 1).trim()));
|
|
33
|
+
}
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** This function gives a vector of exact rationals from a list of inputs. */
|
|
38
|
+
export function vector(values: readonly RationalInput[]): Vector {
|
|
39
|
+
return values.map(toRational);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* This function gives a matrix of exact rationals from a list of rows.
|
|
44
|
+
*
|
|
45
|
+
* @throws {RangeError} The rows do not have the same length.
|
|
46
|
+
*/
|
|
47
|
+
export function matrix(rows: readonly (readonly RationalInput[])[]): Matrix {
|
|
48
|
+
const result = rows.map(vector);
|
|
49
|
+
columnsOf(result);
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* This function gives the count of columns of a matrix. A matrix with no rows has 0 columns.
|
|
55
|
+
*
|
|
56
|
+
* @throws {RangeError} The rows do not have the same length.
|
|
57
|
+
*/
|
|
58
|
+
export function columnsOf(m: Matrix): number {
|
|
59
|
+
const n = m[0]?.length ?? 0;
|
|
60
|
+
for (const row of m) {
|
|
61
|
+
if (row.length !== n) throw new RangeError(`linear: a row has ${row.length} entries, and the first row has ${n}`);
|
|
62
|
+
}
|
|
63
|
+
return n;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* This function gives the dot product of two vectors.
|
|
68
|
+
*
|
|
69
|
+
* @throws {RangeError} The vectors do not have the same length.
|
|
70
|
+
*/
|
|
71
|
+
export function dot(a: Vector, b: Vector): Rational {
|
|
72
|
+
if (a.length !== b.length) throw new RangeError(`linear: the vectors have ${a.length} and ${b.length} entries`);
|
|
73
|
+
let sum = ZERO;
|
|
74
|
+
for (let i = 0; i < a.length; i++) sum = add(sum, mul(a[i]!, b[i]!));
|
|
75
|
+
return sum;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* This function gives the product of a matrix and a vector.
|
|
80
|
+
*
|
|
81
|
+
* @throws {RangeError} The length of the vector is not the count of columns.
|
|
82
|
+
*/
|
|
83
|
+
export function multiply(m: Matrix, x: Vector): Vector {
|
|
84
|
+
return m.map((row) => dot(row, x));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** This function gives the transpose of a matrix. The argument `columns` gives the row count of the result for a matrix with no rows. */
|
|
88
|
+
export function transpose(m: Matrix, columns: number = columnsOf(m)): Matrix {
|
|
89
|
+
const result: Rational[][] = [];
|
|
90
|
+
for (let j = 0; j < columns; j++) result.push(m.map((row) => row[j]!));
|
|
91
|
+
return result;
|
|
92
|
+
}
|