@mark1russell7/linear 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -61,6 +61,14 @@ A Farkas ray proves that no point is feasible: for each `x >= 0` that meets the
61
61
 
62
62
  Only the first stage can be infeasible, because each later stage keeps the optimal point of the stage before it. A later stage can be unbounded after optimal stages, because its objective is new.
63
63
 
64
+ Each stage gives `pivots`, the count of its simplex pivots. The option `{ warm: true }` keeps one tableau for all stages:
65
+
66
+ - The first stage is the cold two-phase simplex.
67
+ - After an optimal stage, each column with a reduced cost that is not 0 gets a ban. A banned column stays at 0, so each later point keeps the optimum.
68
+ - A later stage starts from the last basis. It adds no row and has no phase 1, so it uses fewer pivots.
69
+
70
+ The warm solve gives the same statuses and values as the cold solve. Each stage result passes `checkCertificate` with its recorded program. If the last objective has a tie, the point `x` can be a different optimal point. The default stays the cold solve, so the point of a tie does not change.
71
+
64
72
  ## Integer programs
65
73
 
66
74
  An `IntegerProgram` is a linear program with a list `integer` of variable indices. Each of these variables takes integer values only. The other variables stay continuous.
package/build/index.d.ts CHANGED
@@ -148,10 +148,22 @@ interface Objective {
148
148
  readonly sense: Sense;
149
149
  readonly coefficients: Vector;
150
150
  }
151
- /** One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate. */
151
+ /**
152
+ * One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate.
153
+ * The field `pivots` gives the count of simplex pivots of the stage. The count is a measure of the work of the stage.
154
+ */
152
155
  interface LexicographicStage {
153
156
  readonly program: LinearProgram;
154
157
  readonly result: LinearProgramResult;
158
+ readonly pivots?: number | undefined;
159
+ }
160
+ /**
161
+ * The options of `solveLexicographic`. With `warm: true`, the stages share one tableau. A later stage starts from the optimal
162
+ * basis of the stage before it, and it has no phase 1. The values of the stages stay the same. If the last objective has a
163
+ * tie, the point `x` can be a different optimal point. The default is `false`, and it keeps the cold solve of each stage.
164
+ */
165
+ interface LexicographicOptions {
166
+ readonly warm?: boolean | undefined;
155
167
  }
156
168
  /**
157
169
  * The result of `solveLexicographic`. The status `optimal` gives the last point and the optimum of each objective. The status
@@ -172,9 +184,11 @@ type LexicographicResult = {
172
184
  * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.
173
185
  * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.
174
186
  *
187
+ * The option `warm` keeps one tableau for all stages. Each stage result passes `checkCertificate` with its recorded program.
188
+ *
175
189
  * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.
176
190
  */
177
- export declare function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[]): LexicographicResult;
191
+ export declare function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[], options?: LexicographicOptions): LexicographicResult;
178
192
  /** The verdict of `checkCertificate`. The list `failures` names each condition that the certificate does not meet. */
179
193
  interface CertificateCheck {
180
194
  readonly valid: boolean;
@@ -280,5 +294,5 @@ export declare function solveIntegerProgram(program: IntegerProgram, options?: I
280
294
  * 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.
281
295
  */
282
296
  export declare function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): CertificateCheck;
283
- export type { Branch, BranchNode, CertificateCheck, Constraint, ConstraintInput, IntegerOptions, IntegerProgram, IntegerProgramResult, LexicographicResult, LexicographicStage, LinearProgram, LinearProgramInput, LinearProgramResult, Matrix, NodeOutcome, Objective, RationalInput, Relation, RowEchelon, Sense, SolveResult, Vector };
297
+ export type { Branch, BranchNode, CertificateCheck, Constraint, ConstraintInput, IntegerOptions, IntegerProgram, IntegerProgramResult, LexicographicOptions, LexicographicResult, LexicographicStage, LinearProgram, LinearProgramInput, LinearProgramResult, Matrix, NodeOutcome, Objective, RationalInput, Relation, RowEchelon, Sense, SolveResult, Vector };
284
298
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/vector.ts","../src/matrix.ts","../src/program.ts","../src/simplex.ts","../src/lexicographic.ts","../src/certificate.ts","../src/integer.ts"],"mappings":";;KAQY,kBAAkB;;KAGlB,kBAAkB;;KAGlB,gBAAgB;;;;;;;wBAQZ,WAAW,OAAO,gBAAgB;;wBAelC,OAAO,iBAAiB,kBAAkB;;;;;;wBAS1C,OAAO,yBAAyB,qBAAqB;;;;;;wBAWrD,UAAU,GAAG;;;;;;wBAab,IAAI,GAAG,QAAQ,GAAG,SAAS;;;;;;wBAY3B,SAAS,GAAG,QAAQ,GAAG,SAAS;;wBAKhC,UAAU,GAAG,QAAQ,mBAAiC;;UC9ErD;WACN,QAAQ;WACR;;;;;;;wBAoCK,KAAK,GAAG,SAAS;;wBAQjB,KAAK,GAAG;;;;;;wBASR,UAAU,GAAG,QAAQ,mBAAiC;;;;;KAmB1D;WACG;WAA2B,GAAG;WAAiB,WAAW;;WAC1D;WAAiC,aAAa;;;;;;;;wBAQ7C,MAAM,GAAG,QAAQ,GAAG,QAAQ,mBAAiC;;KCpFjE;;KAGA;;UAGK;WACN,cAAc;WACd,UAAU;WACV,KAAK;;;;;;UAOC;WACN,OAAO;WACP,WAAW;WACX,sBAAsB;;;;;;;;;;KAWrB;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,MAAM;;WAChF;WAA+B,KAAK;;WACpC;WAA8B,GAAG;WAAiB,WAAW;;;UAG3D;WACN,uBAAuB;WACvB,UAAU;WACV,KAAK;;;UAIC;WACN,OAAO;WACP,oBAAoB;WACpB,sBAAsB;;;;;;;wBAQjB,cAAc,OAAO,qBAAqB;;;;;;;wBCyK1C,mBAAmB,SAAS,gBAAgB;;UC7N3C;WACN,OAAO;WACP,cAAc;;;UAIR;WACN,SAAS;WACT,QAAQ;;;;;;;KAQP;WACG;WAA4B,GAAG;WAAiB,iBAAiB;WAAqB,iBAAiB;;WACvG;WAA6C,iBAAiB;;;;;;;;;wBAS7D,mBAAmB,sBAAsB,cAAc,qBAAqB,cAAc;;UC5BzF;WACN;WACA;;;;;;;;;;;;wBAqHK,iBAAiB,SAAS,eAAe,QAAQ,sBAAsB;;UCrHtE,uBAAuB;;WAE7B;;;UAIM;WACN;WACA;WACA,OAAO;;;;;;;;;;;KAYN;;UAGK;WACN;WACA,QAAQ;WACR,SAAS;;WAET,QAAQ;;;;;;;;;;;;KAaP;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,eAAe;;WACzF;WAA+B,eAAe;;WAC9C;WAA8B,GAAG;WAAiB,WAAW;;WAE7D;WACA,GAAG;WACH,OAAO;WACP,OAAO;WACP,eAAe;;;UAIb;;WAEN;;;;;;;;;;;;;;;wBAkHK,oBAAoB,SAAS,gBAAgB,UAAS,iBAAsB;;;;;;;;;;;;wBA6H5E,wBAAwB,SAAS,gBAAgB,QAAQ,uBAAuB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/vector.ts","../src/matrix.ts","../src/program.ts","../src/simplex.ts","../src/lexicographic.ts","../src/certificate.ts","../src/integer.ts"],"mappings":";;KAQY,kBAAkB;;KAGlB,kBAAkB;;KAGlB,gBAAgB;;;;;;;wBAQZ,WAAW,OAAO,gBAAgB;;wBAelC,OAAO,iBAAiB,kBAAkB;;;;;;wBAS1C,OAAO,yBAAyB,qBAAqB;;;;;;wBAWrD,UAAU,GAAG;;;;;;wBAab,IAAI,GAAG,QAAQ,GAAG,SAAS;;;;;;wBAY3B,SAAS,GAAG,QAAQ,GAAG,SAAS;;wBAKhC,UAAU,GAAG,QAAQ,mBAAiC;;UC9ErD;WACN,QAAQ;WACR;;;;;;;wBAoCK,KAAK,GAAG,SAAS;;wBAQjB,KAAK,GAAG;;;;;;wBASR,UAAU,GAAG,QAAQ,mBAAiC;;;;;KAmB1D;WACG;WAA2B,GAAG;WAAiB,WAAW;;WAC1D;WAAiC,aAAa;;;;;;;;wBAQ7C,MAAM,GAAG,QAAQ,GAAG,QAAQ,mBAAiC;;KCpFjE;;KAGA;;UAGK;WACN,cAAc;WACd,UAAU;WACV,KAAK;;;;;;UAOC;WACN,OAAO;WACP,WAAW;WACX,sBAAsB;;;;;;;;;;KAWrB;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,MAAM;;WAChF;WAA+B,KAAK;;WACpC;WAA8B,GAAG;WAAiB,WAAW;;;UAG3D;WACN,uBAAuB;WACvB,UAAU;WACV,KAAK;;;UAIC;WACN,OAAO;WACP,oBAAoB;WACpB,sBAAsB;;;;;;;wBAQjB,cAAc,OAAO,qBAAqB;;;;;;;wBC8N1C,mBAAmB,SAAS,gBAAgB;;UClR3C;WACN,OAAO;WACP,cAAc;;;;;;UAOR;WACN,SAAS;WACT,QAAQ;WACR;;;;;;;UAQM;WACN;;;;;;;KAQC;WACG;WAA4B,GAAG;WAAiB,iBAAiB;WAAqB,iBAAiB;;WACvG;WAA6C,iBAAiB;;;;;;;;;;;wBAW7D,mBAAmB,sBAAsB,cAAc,qBAAqB,aAAa,UAAS,uBAA4B;;UC3C7H;WACN;WACA;;;;;;;;;;;;wBAqHK,iBAAiB,SAAS,eAAe,QAAQ,sBAAsB;;UCrHtE,uBAAuB;;WAE7B;;;UAIM;WACN;WACA;WACA,OAAO;;;;;;;;;;;KAYN;;UAGK;WACN;WACA,QAAQ;WACR,SAAS;;WAET,QAAQ;;;;;;;;;;;;KAaP;WACG;WAA4B,GAAG;WAAiB,OAAO;WAAmB,eAAe;;WACzF;WAA+B,eAAe;;WAC9C;WAA8B,GAAG;WAAiB,WAAW;;WAE7D;WACA,GAAG;WACH,OAAO;WACP,OAAO;WACP,eAAe;;;UAIb;;WAEN;;;;;;;;;;;;;;;wBAkHK,oBAAoB,SAAS,gBAAgB,UAAS,iBAAsB;;;;;;;;;;;;wBA6H5E,wBAAwB,SAAS,gBAAgB,QAAQ,uBAAuB"}
package/build/index.js CHANGED
@@ -250,7 +250,8 @@ function standardForm(program) {
250
250
  rhs,
251
251
  flipped,
252
252
  basis,
253
- structural
253
+ structural,
254
+ total
254
255
  };
255
256
  }
256
257
  function pivot(t, p, q) {
@@ -278,14 +279,17 @@ function reducedCosts(t, cost) {
278
279
  return r;
279
280
  }
280
281
  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) {
282
+ /**
283
+ * This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. A column with the
284
+ * entry `true` in `banned` cannot enter.
285
+ */
286
+ function runPhase(t, cost, allowed, rule, count, banned = []) {
283
287
  const seen = /* @__PURE__ */ new Set([basisKey(t.basis)]);
284
288
  for (;;) {
285
289
  const r = reducedCosts(t, cost);
286
290
  let q = -1;
287
291
  for (let j = 0; j < allowed; j++) {
288
- if (sign(r[j]) <= 0) continue;
292
+ if (banned[j] === true || sign(r[j]) <= 0) continue;
289
293
  if (rule === "bland") {
290
294
  q = j;
291
295
  break;
@@ -331,71 +335,96 @@ function pointOf(t, n) {
331
335
  });
332
336
  return x;
333
337
  }
338
+ /** This function gives the cost of a phase 2 as a maximization: the objective, or its negative for `"min"`, and 0 on the other columns. */
339
+ function phaseTwoCost(sense, objective, total) {
340
+ const max = sense === "max";
341
+ return Array.from({ length: total }, (_, j) => j < objective.length ? max ? objective[j] : neg(objective[j]) : ZERO);
342
+ }
343
+ /** This function gives the result of an unbounded phase 2: the basic point and the direction of the entering column `q`. */
344
+ function unboundedResult(t, n, q) {
345
+ const direction = new Array(n).fill(ZERO);
346
+ if (q < n) direction[q] = ONE;
347
+ t.basis.forEach((col, i) => {
348
+ if (col < n) direction[col] = neg(t.rows[i][q]);
349
+ });
350
+ return {
351
+ status: "unbounded",
352
+ x: pointOf(t, n),
353
+ direction
354
+ };
355
+ }
356
+ /** This function makes the standard form and the tableau, and it does phase 1. Each pivot adds 1 to `count`. */
357
+ function phaseOne(program, rule, count) {
358
+ const form = standardForm(program);
359
+ const t = {
360
+ rows: form.rows.map((row) => [...row]),
361
+ rhs: [...form.rhs],
362
+ basis: [...form.basis]
363
+ };
364
+ if (form.total === form.structural) return {
365
+ kind: "ready",
366
+ form,
367
+ t
368
+ };
369
+ const cost = Array.from({ length: form.total }, (_, j) => j >= form.structural ? neg(ONE) : ZERO);
370
+ if (runPhase(t, cost, form.total, rule, count).kind === "cycle") return { kind: "cycle" };
371
+ let value = ZERO;
372
+ t.basis.forEach((col, i) => {
373
+ value = sub(value, col >= form.structural ? t.rhs[i] : ZERO);
374
+ });
375
+ if (sign(value) < 0) return {
376
+ kind: "infeasible",
377
+ ray: dualOf(form, t.basis, cost)
378
+ };
379
+ t.basis.forEach((col, i) => {
380
+ if (col < form.structural) return;
381
+ const j = t.rows[i].findIndex((v, k) => k < form.structural && sign(v) !== 0);
382
+ if (j < 0) return;
383
+ pivot(t, i, j);
384
+ count.pivots++;
385
+ });
386
+ return {
387
+ kind: "ready",
388
+ form,
389
+ t
390
+ };
391
+ }
334
392
  /**
335
- * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland.
393
+ * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland. The count of
394
+ * pivots includes the pivots that move an artificial column out of the basis after phase 1.
336
395
  *
337
396
  * @internal
338
397
  */
339
398
  function runSimplex(program, rule) {
340
399
  checkShape(program);
341
400
  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
401
  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);
402
+ const start = phaseOne(program, rule, count);
403
+ if (start.kind === "cycle") return {
404
+ cycled: true,
405
+ pivots: count.pivots
406
+ };
407
+ if (start.kind === "infeasible") return {
408
+ cycled: false,
409
+ result: {
410
+ status: "infeasible",
411
+ ray: start.ray
412
+ },
413
+ pivots: count.pivots
414
+ };
415
+ const { form, t } = start;
416
+ const cost = phaseTwoCost(program.sense, program.objective, form.total);
376
417
  const phase = runPhase(t, cost, form.structural, rule, count);
377
418
  if (phase.kind === "cycle") return {
378
419
  cycled: true,
379
420
  pivots: count.pivots
380
421
  };
422
+ if (phase.kind === "unbounded") return {
423
+ cycled: false,
424
+ result: unboundedResult(t, n, phase.column),
425
+ pivots: count.pivots
426
+ };
381
427
  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
428
  const dual = dualOf(form, t.basis, cost);
400
429
  return {
401
430
  cycled: false,
@@ -403,21 +432,142 @@ function runSimplex(program, rule) {
403
432
  status: "optimal",
404
433
  x,
405
434
  value: dot(program.objective, x),
406
- dual: max ? dual : dual.map(neg)
435
+ dual: program.sense === "max" ? dual : dual.map(neg)
407
436
  },
408
437
  pivots: count.pivots
409
438
  };
410
439
  }
411
440
  /**
441
+ * This function solves a program with the rule of Bland, and it gives the count of pivots with the result.
442
+ *
443
+ * @internal
444
+ */
445
+ function solveCounted(program) {
446
+ const run = runSimplex(program, "bland");
447
+ if (run.cycled) throw new Error("linear: internal error, the rule of Bland met a basis again");
448
+ return {
449
+ result: run.result,
450
+ pivots: run.pivots
451
+ };
452
+ }
453
+ /**
412
454
  * This function solves a linear program exactly with the two-phase simplex and the rule of Bland. The result has a certificate
413
455
  * that `checkCertificate` examines.
414
456
  *
415
457
  * @throws {RangeError} A constraint row has a length that is not the length of the objective.
416
458
  */
417
459
  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;
460
+ return solveCounted(program).result;
461
+ }
462
+ /**
463
+ * This function gives the dual of a warm stage for its recorded program: the constraint rows, then one row `c_i x = v_i` for
464
+ * each earlier objective.
465
+ *
466
+ * The reduced costs `s` of the stage start as those of its cost. From the last earlier stage to the
467
+ * first, the function adds `M_i` times the cost of stage `i`. The value `M_i` is the smallest that makes `s_j <= 0` at each
468
+ * column that stage `i` banned. A column that stage `i` did not ban has the reduced cost 0 for objective `i`, so the step
469
+ * does not change it. At the end, `s <= 0` at each column that is not artificial. Thus the sum of the costs has a feasible
470
+ * dual at the basis.
471
+ */
472
+ function warmDual(form, t, sense, cost, earlier) {
473
+ let s = reducedCosts(t, cost);
474
+ let combined = [...cost];
475
+ const multipliers = new Array(earlier.length).fill(ZERO);
476
+ for (let i = earlier.length - 1; i >= 0; i--) {
477
+ const stage = earlier[i];
478
+ const r = reducedCosts(t, stage.cost);
479
+ let m = ZERO;
480
+ for (const j of stage.banned) {
481
+ if (sign(s[j]) <= 0 || sign(r[j]) >= 0) continue;
482
+ const need = div(s[j], neg(r[j]));
483
+ if (compare(need, m) > 0) m = need;
484
+ }
485
+ if (sign(m) === 0) continue;
486
+ multipliers[i] = m;
487
+ s = s.map((v, j) => add(v, mul(m, r[j])));
488
+ combined = combined.map((v, j) => add(v, mul(m, stage.cost[j])));
489
+ }
490
+ const dual = [...dualOf(form, t.basis, combined), ...multipliers.map((m, i) => earlier[i].sense === "max" ? neg(m) : m)];
491
+ return sense === "max" ? dual : dual.map(neg);
492
+ }
493
+ /**
494
+ * This function starts a warm lexicographic solve. The first stage is the cold two-phase simplex. After an optimal stage, each
495
+ * column with a reduced cost that is not 0 gets a ban. A banned column cannot enter in a later stage, so it stays at 0.
496
+ *
497
+ * Then each point of a later stage keeps each earlier optimum, because `c z = v + sum r_j z_j` at the basis. A later stage
498
+ * does only phase 2 from the current basis. It adds no row and has no phase 1.
499
+ *
500
+ * @internal
501
+ */
502
+ function warmStages(constraints) {
503
+ let ready;
504
+ let stopped = false;
505
+ const banned = [];
506
+ const earlier = [];
507
+ const stage = (sense, objective) => {
508
+ const n = objective.length;
509
+ const count = { pivots: 0 };
510
+ if (stopped) throw new Error("linear: internal error, a warm stage after a stage with no optimum");
511
+ let current = ready;
512
+ if (current === void 0) {
513
+ const start = phaseOne({
514
+ sense,
515
+ objective,
516
+ constraints
517
+ }, "bland", count);
518
+ if (start.kind === "cycle") throw new Error("linear: internal error, the rule of Bland met a basis again");
519
+ if (start.kind === "infeasible") {
520
+ stopped = true;
521
+ return {
522
+ result: {
523
+ status: "infeasible",
524
+ ray: start.ray
525
+ },
526
+ pivots: count.pivots
527
+ };
528
+ }
529
+ current = {
530
+ form: start.form,
531
+ t: start.t
532
+ };
533
+ ready = current;
534
+ }
535
+ const { form, t } = current;
536
+ const cost = phaseTwoCost(sense, objective, form.total);
537
+ const phase = runPhase(t, cost, form.structural, "bland", count, banned);
538
+ if (phase.kind === "cycle") throw new Error("linear: internal error, the rule of Bland met a basis again");
539
+ if (phase.kind === "unbounded") {
540
+ stopped = true;
541
+ return {
542
+ result: unboundedResult(t, n, phase.column),
543
+ pivots: count.pivots
544
+ };
545
+ }
546
+ const x = pointOf(t, n);
547
+ const dual = warmDual(form, t, sense, cost, earlier);
548
+ const r = reducedCosts(t, cost);
549
+ const now = [];
550
+ for (let j = 0; j < form.structural; j++) {
551
+ if (banned[j] === true || sign(r[j]) === 0) continue;
552
+ banned[j] = true;
553
+ now.push(j);
554
+ }
555
+ earlier.push({
556
+ cost,
557
+ sense,
558
+ banned: now
559
+ });
560
+ return {
561
+ result: {
562
+ status: "optimal",
563
+ x,
564
+ value: dot(objective, x),
565
+ dual
566
+ },
567
+ pivots: count.pivots
568
+ };
569
+ };
570
+ return { stage };
421
571
  }
422
572
  // src/lexicographic.ts
423
573
  /**
@@ -425,10 +575,13 @@ function solveLinearProgram(program) {
425
575
  * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.
426
576
  * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.
427
577
  *
578
+ * The option `warm` keeps one tableau for all stages. Each stage result passes `checkCertificate` with its recorded program.
579
+ *
428
580
  * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.
429
581
  */
430
- function solveLexicographic(constraints, objectives) {
582
+ function solveLexicographic(constraints, objectives, options = {}) {
431
583
  if (objectives.length === 0) throw new RangeError("linear: a lexicographic program needs one objective or more");
584
+ const warm = options.warm === true ? warmStages(constraints) : void 0;
432
585
  const stages = [];
433
586
  const rows = [...constraints];
434
587
  const values = [];
@@ -439,10 +592,12 @@ function solveLexicographic(constraints, objectives) {
439
592
  objective: objective.coefficients,
440
593
  constraints: [...rows]
441
594
  };
442
- const result = solveLinearProgram(program);
595
+ if (warm !== void 0) checkShape(program);
596
+ const { result, pivots } = warm === void 0 ? solveCounted(program) : warm.stage(objective.sense, objective.coefficients);
443
597
  stages.push({
444
598
  program,
445
- result
599
+ result,
600
+ pivots
446
601
  });
447
602
  if (result.status !== "optimal") return {
448
603
  status: result.status,
@@ -1 +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","../src/integer.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/**\n * This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`.\n *\n * @internal\n */\nexport function 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","/**\n * Integer programs: branch and bound on the exact simplex. The certificate of a result is the tree of its nodes.\n *\n * @packageDocumentation\n */\nimport { type Rational, add, compare, equals, floor, gcd, isInteger, ONE, rational, toString, ZERO } from \"@mark1russell7/rational\";\nimport { type CertificateCheck, checkCertificate, checkFeasible } from \"./certificate.ts\";\nimport { checkShape, type Constraint, type LinearProgram, type LinearProgramResult } from \"./program.ts\";\nimport { solveLinearProgram } from \"./simplex.ts\";\nimport { dot, type Vector } from \"./vector.ts\";\n\n/** A linear program in which each variable of the list `integer` takes integer values only. The other variables are continuous. */\nexport interface IntegerProgram extends LinearProgram {\n /** The indices of the integer variables. */\n readonly integer: readonly number[];\n}\n\n/** The row that a node adds to the rows of its parent: `x[variable] <= value` or `x[variable] >= value`. The value is an integer. */\nexport interface Branch {\n readonly variable: number;\n readonly relation: \"<=\" | \">=\";\n readonly value: Rational;\n}\n\n/**\n * The outcome of a node of the tree.\n *\n * - `branched`: the node has two children. One child adds `x_j <= k`, and the other child adds `x_j >= k + 1`.\n * - `integer`: the relaxation of the node has an optimum with an integer value on each integer variable.\n * - `bound`: the optimum of the relaxation is not better than the best integer point that the solve found before the node.\n * - `infeasible`: the relaxation of the node has no point.\n * - `open`: the solve stopped at its limit before the node.\n */\nexport type NodeOutcome = \"branched\" | \"integer\" | \"bound\" | \"infeasible\" | \"open\";\n\n/** One node of the tree. The root is node 0. Each other node has a parent with a smaller index. */\nexport interface BranchNode {\n readonly parent: number | undefined;\n readonly branch: Branch | undefined;\n readonly outcome: NodeOutcome;\n /** The result of the relaxation of the node, with its certificate. An open node has no result. */\n readonly result: LinearProgramResult | undefined;\n}\n\n/**\n * The result of an integer program, with its certificate.\n *\n * - `optimal`: the point `x`, its value, and the tree. Each leaf proves that its integer points are not better than `x`.\n * - `infeasible`: the tree. Each leaf has a Farkas ray, so the program has no integer point.\n * - `unbounded`: an integer point `x` and a direction `direction` with an integer value on each integer variable.\n * Each point `x + t direction` with an integer `t >= 0` is an integer point, and the objective improves without limit.\n * - `limit`: the solve stopped at its limit. It gives the best integer point that it found, if any. `bound` is a bound of the\n * optimum that the tree proves. A program with an unbounded relaxation gives no bound.\n */\nexport type IntegerProgramResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly value: Rational; readonly tree: readonly BranchNode[] }\n | { readonly status: \"infeasible\"; readonly tree: readonly BranchNode[] }\n | { readonly status: \"unbounded\"; readonly x: Vector; readonly direction: Vector }\n | {\n readonly status: \"limit\";\n readonly x: Vector | undefined;\n readonly value: Rational | undefined;\n readonly bound: Rational | undefined;\n readonly tree: readonly BranchNode[];\n };\n\n/** The options of `solveIntegerProgram`. */\nexport interface IntegerOptions {\n /** The largest count of relaxations that the solve solves. The default is 10000. */\n readonly nodeLimit?: number;\n}\n\n/** A node in construction. */\ninterface WorkNode {\n readonly parent: number | undefined;\n readonly branch: Branch | undefined;\n outcome: NodeOutcome;\n result: LinearProgramResult | undefined;\n}\n\n/** The result of one search, before the solve gives its status. */\ninterface Search {\n readonly best: { readonly x: Vector; readonly value: Rational } | undefined;\n readonly nodes: readonly WorkNode[];\n /** True when the search stopped at its limit with open nodes. */\n readonly stopped: boolean;\n}\n\n/**\n * This function gives the problems of the list `integer` of a program: an index that is not an integer, or not a variable.\n *\n * @internal\n */\nexport function integerProblems(program: IntegerProgram): string[] {\n const n = program.objective.length;\n 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`);\n}\n\n/**\n * 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.\n *\n * @internal\n */\nexport function nodeProgram(program: LinearProgram, tree: readonly Pick<BranchNode, \"parent\" | \"branch\">[], id: number): LinearProgram {\n const rows: Constraint[] = [];\n const n = program.objective.length;\n for (let at: number | undefined = id; at !== undefined; at = tree[at]?.parent) {\n const branch = tree[at]?.branch;\n if (branch === undefined) continue;\n const coefficients = Array.from({ length: n }, (_, j) => (j === branch.variable ? ONE : ZERO));\n rows.push({ coefficients, relation: branch.relation, rhs: branch.value });\n }\n return { ...program, constraints: [...program.constraints, ...rows.reverse()] };\n}\n\n/**\n * This function searches the tree depth first. It branches on the fractional integer variable with the smallest index, and it\n * takes the child `x_j <= k` first. With `first`, it stops at the first integer point.\n */\nfunction search(program: LinearProgram, integer: readonly number[], limit: number, first: boolean, root: LinearProgramResult): Search {\n const s = program.sense === \"max\" ? 1 : -1;\n const nodes: WorkNode[] = [{ parent: undefined, branch: undefined, outcome: \"open\", result: undefined }];\n const stack = [0];\n let best: Search[\"best\"];\n let solved = 0;\n while (stack.length > 0 && solved < limit) {\n const id = stack.pop() as number;\n const node = nodes[id] as WorkNode;\n const result = id === 0 ? root : solveLinearProgram(nodeProgram(program, nodes, id));\n solved++;\n node.result = result;\n if (result.status === \"infeasible\") {\n node.outcome = \"infeasible\";\n continue;\n }\n // A node adds rows to a program with an optimum or with the objective 0, so its relaxation is not unbounded.\n if (result.status === \"unbounded\") throw new Error(\"linear: the relaxation of a node is unbounded, and the relaxation of the root is not\");\n if (best !== undefined && compare(result.value, best.value) * s <= 0) {\n node.outcome = \"bound\";\n continue;\n }\n const j = integer.find((k) => !isInteger(result.x[k] as Rational));\n if (j === undefined) {\n node.outcome = \"integer\";\n best = { x: result.x, value: result.value };\n if (first) return { best, nodes, stopped: false };\n continue;\n }\n node.outcome = \"branched\";\n const k = floor(result.x[j] as Rational);\n nodes.push({ parent: id, branch: { variable: j, relation: \">=\", value: add(k, ONE) }, outcome: \"open\", result: undefined });\n stack.push(nodes.length - 1);\n nodes.push({ parent: id, branch: { variable: j, relation: \"<=\", value: k }, outcome: \"open\", result: undefined });\n stack.push(nodes.length - 1);\n }\n return { best, nodes, stopped: stack.length > 0 };\n}\n\n/** This function gives the direction times the least common multiple of its denominators, so each entry is an integer. */\nfunction integral(direction: Vector): Vector {\n let m = 1n;\n for (const v of direction) m = (m / gcd(m, v.d)) * v.d;\n return direction.map((v) => rational(v.n * (m / v.d)));\n}\n\n/** This function gives the frozen tree of the nodes of a search. */\nfunction treeOf(nodes: readonly WorkNode[]): BranchNode[] {\n return nodes.map(({ parent, branch, outcome, result }) => ({ parent, branch, outcome, result }));\n}\n\n/**\n * This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches\n * on the fractional integer variable with the smallest index.\n *\n * - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.\n * - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is\n * unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.\n * - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.\n *\n * @throws {RangeError} A row has a length that is not the count of variables.\n * @throws {RangeError} An integer variable is not a variable of the program.\n * @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.\n */\nexport function solveIntegerProgram(program: IntegerProgram, options: IntegerOptions = {}): IntegerProgramResult {\n checkShape(program);\n const problems = integerProblems(program);\n if (problems.length > 0) throw new RangeError(`linear: ${problems.join(\", \")}`);\n const limit = options.nodeLimit ?? 10_000;\n if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`linear: the node limit ${String(limit)} is not an integer of 1 or more`);\n const integer = [...new Set(program.integer)].sort((a, b) => a - b);\n const root = solveLinearProgram(program);\n if (root.status === \"unbounded\") {\n const zero: LinearProgram = { ...program, objective: program.objective.map(() => ZERO) };\n const found = search(zero, integer, limit, true, solveLinearProgram(zero));\n if (found.best !== undefined) return { status: \"unbounded\", x: found.best.x, direction: integral(root.direction) };\n const tree = treeOf(found.nodes);\n if (found.stopped) return { status: \"limit\", x: undefined, value: undefined, bound: undefined, tree };\n return { status: \"infeasible\", tree };\n }\n const found = search(program, integer, limit, false, root);\n const tree = treeOf(found.nodes);\n if (found.stopped) {\n const s = program.sense === \"max\" ? 1 : -1;\n let bound = found.best?.value;\n for (const node of found.nodes) {\n if (node.outcome !== \"open\" || node.parent === undefined) continue;\n const parent = found.nodes[node.parent]?.result;\n if (parent?.status === \"optimal\" && (bound === undefined || compare(parent.value, bound) * s > 0)) bound = parent.value;\n }\n return { status: \"limit\", x: found.best?.x, value: found.best?.value, bound, tree };\n }\n if (found.best === undefined) return { status: \"infeasible\", tree };\n return { status: \"optimal\", x: found.best.x, value: found.best.value, tree };\n}\n\n/** This function adds a failure for each integer variable of `x` with a value that is not an integer. */\nfunction checkIntegral(integer: readonly number[], x: Vector, name: string, failures: string[]): void {\n for (const j of integer) {\n const v = x[j];\n if (v !== undefined && !isInteger(v)) failures.push(`${name}[${String(j)}] = ${toString(v)} is not an integer`);\n }\n}\n\n/** This function adds a failure when the value `v` is better than `limit` in the sense of the program. */\nfunction checkNotBetter(s: 1 | -1, v: Rational, limit: Rational, name: string, failures: string[]): void {\n if (compare(v, limit) * s > 0) failures.push(`${name} ${toString(v)} is better than ${toString(limit)}`);\n}\n\n/**\n * This function examines the tree of a result: its shape, and a certificate for each leaf. With `best`, the value of each leaf\n * is not better than `best`. Each failure goes into `failures`.\n */\nfunction checkTree(program: IntegerProgram, tree: readonly BranchNode[], allowOpen: boolean, best: Rational | undefined, failures: string[]): void {\n const s = program.sense === \"max\" ? 1 : -1;\n const integer = new Set(program.integer);\n const root = tree[0];\n if (root === undefined || root.parent !== undefined || root.branch !== undefined) {\n failures.push(\"node 0 is not a root with no parent and no branch\");\n return;\n }\n const children = tree.map((): number[] => []);\n for (let i = 1; i < tree.length; i++) {\n const node = tree[i] as BranchNode;\n if (node.parent === undefined || !Number.isInteger(node.parent) || node.parent < 0 || node.parent >= i || node.branch === undefined) {\n failures.push(`node ${String(i)} has no parent before it, or no branch`);\n return;\n }\n 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`);\n children[node.parent]?.push(i);\n }\n tree.forEach((node, i) => {\n const kids = children[i] as number[];\n if (node.outcome === \"branched\") {\n const [a, b] = kids.map((k) => (tree[k] as BranchNode).branch as Branch);\n const down = [a, b].find((branch) => branch?.relation === \"<=\");\n const up = [a, b].find((branch) => branch?.relation === \">=\");\n if (kids.length !== 2 || down === undefined || up === undefined || down.variable !== up.variable || !equals(add(down.value, ONE), up.value)) {\n failures.push(`node ${String(i)} is branched, and its children are not x_j <= k and x_j >= k + 1`);\n }\n return;\n }\n if (kids.length > 0) failures.push(`node ${String(i)} has children, and its outcome is ${node.outcome}`);\n if (node.outcome === \"open\") {\n if (!allowOpen) failures.push(`node ${String(i)} is open`);\n if (best === undefined || node.parent === undefined) return;\n // The integer points of an open node are not better than the optimum of the relaxation of its parent.\n const parent = tree[node.parent]?.result;\n if (parent?.status !== \"optimal\") {\n failures.push(`node ${String(i)} is open, and its parent has no optimum`);\n return;\n }\n const check = checkCertificate(nodeProgram(program, tree, node.parent), parent);\n for (const failure of check.failures) failures.push(`node ${String(node.parent)}: ${failure}`);\n checkNotBetter(s, parent.value, best, `the parent of the open node ${String(i)} has the value`, failures);\n return;\n }\n const result = node.result;\n if (result === undefined) {\n failures.push(`node ${String(i)} is a leaf with no result`);\n return;\n }\n const check = checkCertificate(nodeProgram(program, tree, i), result);\n for (const failure of check.failures) failures.push(`node ${String(i)}: ${failure}`);\n if (node.outcome === \"infeasible\") {\n if (result.status !== \"infeasible\") failures.push(`node ${String(i)} is infeasible, and its result is ${result.status}`);\n return;\n }\n if (result.status !== \"optimal\") {\n failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome}, and its result is ${result.status}`);\n return;\n }\n if (node.outcome === \"integer\") checkIntegral(program.integer, result.x, `node ${String(i)}: x`, failures);\n if (best === undefined) failures.push(`node ${String(i)} has an optimum, and the result claims no integer point`);\n else checkNotBetter(s, result.value, best, `node ${String(i)} has the value`, failures);\n });\n}\n\n/**\n * This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.\n *\n * - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer\n * point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its\n * relaxation, and its value is not better than the value of the point.\n * - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.\n * - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.\n * - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed\n * 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.\n */\nexport function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): 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 return { valid: false, failures };\n }\n failures.push(...integerProblems(program));\n if (failures.length > 0) return { valid: false, failures };\n const s = program.sense === \"max\" ? 1 : -1;\n const point = (x: Vector, value: Rational): void => {\n checkFeasible(program, x, failures);\n checkIntegral(program.integer, x, \"x\", failures);\n 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))}`);\n };\n if (result.status === \"unbounded\") {\n failures.push(...checkCertificate(program, { status: \"unbounded\", x: result.x, direction: result.direction }).failures);\n checkIntegral(program.integer, result.x, \"x\", failures);\n checkIntegral(program.integer, result.direction, \"direction\", failures);\n } else if (result.status === \"optimal\") {\n point(result.x, result.value);\n checkTree(program, result.tree, false, result.value, failures);\n } else if (result.status === \"infeasible\") {\n checkTree(program, result.tree, false, undefined, failures);\n result.tree.forEach((node, i) => {\n if (node.outcome !== \"branched\" && node.outcome !== \"infeasible\") failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome} in an infeasible result`);\n });\n } else {\n if ((result.x === undefined) !== (result.value === undefined)) failures.push(\"the limit result has a point with no value, or a value with no point\");\n if (result.x !== undefined && result.value !== undefined) {\n point(result.x, result.value);\n if (result.bound === undefined) failures.push(\"the limit result has a point and no bound\");\n else checkNotBetter(s, result.value, result.bound, \"the value\", failures);\n }\n checkTree(program, result.tree, true, result.bound, 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;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O,OAAO,OAAO,OAAO,aAAa,QAAQ;EAC1E;EACA,UAAU,SAAS,OAAO,MAAM,MAAM,OAAO,OAAO,QAAQ;CAC9D;CACA,OAAO;EAAE,OAAO,SAAS,WAAW;EAAG;CAAS;AAClD"}
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","../src/integer.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, add, compare, div, inverse, mul, neg, ONE, sign, sub, ZERO } from \"@mark1russell7/rational\";\nimport { solve } from \"./matrix.ts\";\nimport { checkShape, type Constraint, type LinearProgram, type LinearProgramResult, type Relation, type Sense } from \"./program.ts\";\nimport { dot, type Vector } 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 /** The count of all columns. */\n readonly total: 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, total };\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/**\n * This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. A column with the\n * entry `true` in `banned` cannot enter.\n */\nfunction runPhase(\n t: Tableau,\n cost: readonly Rational[],\n allowed: number,\n rule: PivotRule,\n count: { pivots: number },\n banned: readonly boolean[] = [],\n): 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 (banned[j] === true || 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/** This function gives the cost of a phase 2 as a maximization: the objective, or its negative for `\"min\"`, and 0 on the other columns. */\nfunction phaseTwoCost(sense: Sense, objective: Vector, total: number): Rational[] {\n const max = sense === \"max\";\n return Array.from({ length: total }, (_, j) => (j < objective.length ? (max ? objective[j]! : neg(objective[j]!)) : ZERO));\n}\n\n/** This function gives the result of an unbounded phase 2: the basic point and the direction of the entering column `q`. */\nfunction unboundedResult(t: Tableau, n: number, q: number): LinearProgramResult {\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 { status: \"unbounded\", x: pointOf(t, n), direction };\n}\n\n/** The end of phase 1: the tableau of a feasible basis, the Farkas ray of an infeasible program, or a cycle. */\ntype Start =\n | { readonly kind: \"ready\"; readonly form: StandardForm; readonly t: Tableau }\n | { readonly kind: \"infeasible\"; readonly ray: Rational[] }\n | { readonly kind: \"cycle\" };\n\n/** This function makes the standard form and the tableau, and it does phase 1. Each pivot adds 1 to `count`. */\nfunction phaseOne(program: LinearProgram, rule: PivotRule, count: { pivots: number }): Start {\n const form = standardForm(program);\n const t: Tableau = { rows: form.rows.map((row) => [...row]), rhs: [...form.rhs], basis: [...form.basis] };\n if (form.total === form.structural) return { kind: \"ready\", form, t };\n // Phase 1: maximize the negative sum of the artificial columns.\n const cost = Array.from({ length: form.total }, (_, j) => (j >= form.structural ? neg(ONE) : ZERO));\n const phase = runPhase(t, cost, form.total, rule, count);\n if (phase.kind === \"cycle\") return { kind: \"cycle\" };\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) return { kind: \"infeasible\", ray: dualOf(form, t.basis, cost) };\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) return;\n pivot(t, i, j);\n count.pivots++;\n });\n return { kind: \"ready\", form, t };\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. The count of\n * pivots includes the pivots that move an artificial column out of the basis after phase 1.\n *\n * @internal\n */\nexport function runSimplex(program: LinearProgram, rule: PivotRule): SimplexRun {\n checkShape(program);\n const n = program.objective.length;\n const count = { pivots: 0 };\n const start = phaseOne(program, rule, count);\n if (start.kind === \"cycle\") return { cycled: true, pivots: count.pivots };\n if (start.kind === \"infeasible\") return { cycled: false, result: { status: \"infeasible\", ray: start.ray }, pivots: count.pivots };\n const { form, t } = start;\n\n // Phase 2: the objective, as a maximization. An artificial column cannot enter, and a row that keeps one is redundant.\n const cost = phaseTwoCost(program.sense, program.objective, form.total);\n const phase = runPhase(t, cost, form.structural, rule, count);\n if (phase.kind === \"cycle\") return { cycled: true, pivots: count.pivots };\n if (phase.kind === \"unbounded\") return { cycled: false, result: unboundedResult(t, n, phase.column), pivots: count.pivots };\n const x = pointOf(t, 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: program.sense === \"max\" ? dual : dual.map(neg) },\n pivots: count.pivots,\n };\n}\n\n/**\n * The result of one solve and the count of its pivots.\n *\n * @internal\n */\nexport interface CountedResult {\n readonly result: LinearProgramResult;\n readonly pivots: number;\n}\n\n/**\n * This function solves a program with the rule of Bland, and it gives the count of pivots with the result.\n *\n * @internal\n */\nexport function solveCounted(program: LinearProgram): CountedResult {\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 { result: run.result, pivots: run.pivots };\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 return solveCounted(program).result;\n}\n\n/** One optimal stage of a warm solve: its cost as a maximization, its sense and the columns that it banned. */\ninterface WarmEarlier {\n readonly cost: readonly Rational[];\n readonly sense: Sense;\n readonly banned: readonly number[];\n}\n\n/**\n * The stages of a warm lexicographic solve on one tableau. Each call of `stage` optimizes the next objective, and it gives the\n * result of the stage program and the count of pivots. Use `stage` again only after an optimal stage.\n *\n * @internal\n */\nexport interface WarmStages {\n readonly stage: (sense: Sense, objective: Vector) => CountedResult;\n}\n\n/**\n * This function gives the dual of a warm stage for its recorded program: the constraint rows, then one row `c_i x = v_i` for\n * each earlier objective.\n *\n * The reduced costs `s` of the stage start as those of its cost. From the last earlier stage to the\n * first, the function adds `M_i` times the cost of stage `i`. The value `M_i` is the smallest that makes `s_j <= 0` at each\n * column that stage `i` banned. A column that stage `i` did not ban has the reduced cost 0 for objective `i`, so the step\n * does not change it. At the end, `s <= 0` at each column that is not artificial. Thus the sum of the costs has a feasible\n * dual at the basis.\n */\nfunction warmDual(form: StandardForm, t: Tableau, sense: Sense, cost: readonly Rational[], earlier: readonly WarmEarlier[]): Rational[] {\n let s = reducedCosts(t, cost);\n let combined = [...cost];\n const multipliers: Rational[] = new Array<Rational>(earlier.length).fill(ZERO);\n for (let i = earlier.length - 1; i >= 0; i--) {\n const stage = earlier[i]!;\n const r = reducedCosts(t, stage.cost);\n let m = ZERO;\n for (const j of stage.banned) {\n if (sign(s[j]!) <= 0 || sign(r[j]!) >= 0) continue;\n const need = div(s[j]!, neg(r[j]!));\n if (compare(need, m) > 0) m = need;\n }\n if (sign(m) === 0) continue;\n multipliers[i] = m;\n s = s.map((v, j) => add(v, mul(m, r[j]!)));\n combined = combined.map((v, j) => add(v, mul(m, stage.cost[j]!)));\n }\n // The cost of stage i is g_i c_i, with g_i = 1 for \"max\" and -1 for \"min\". Its row c_i x = v_i takes the multiplier -g_i M_i.\n const dual = [...dualOf(form, t.basis, combined), ...multipliers.map((m, i) => (earlier[i]!.sense === \"max\" ? neg(m) : m))];\n return sense === \"max\" ? dual : dual.map(neg);\n}\n\n/**\n * This function starts a warm lexicographic solve. The first stage is the cold two-phase simplex. After an optimal stage, each\n * column with a reduced cost that is not 0 gets a ban. A banned column cannot enter in a later stage, so it stays at 0.\n *\n * Then each point of a later stage keeps each earlier optimum, because `c z = v + sum r_j z_j` at the basis. A later stage\n * does only phase 2 from the current basis. It adds no row and has no phase 1.\n *\n * @internal\n */\nexport function warmStages(constraints: readonly Constraint[]): WarmStages {\n let ready: { readonly form: StandardForm; readonly t: Tableau } | undefined;\n let stopped = false;\n const banned: boolean[] = [];\n const earlier: WarmEarlier[] = [];\n const stage = (sense: Sense, objective: Vector): CountedResult => {\n const n = objective.length;\n const count = { pivots: 0 };\n if (stopped) throw new Error(\"linear: internal error, a warm stage after a stage with no optimum\");\n let current = ready;\n if (current === undefined) {\n const start = phaseOne({ sense, objective, constraints }, \"bland\", count);\n if (start.kind === \"cycle\") throw new Error(\"linear: internal error, the rule of Bland met a basis again\");\n if (start.kind === \"infeasible\") {\n stopped = true;\n return { result: { status: \"infeasible\", ray: start.ray }, pivots: count.pivots };\n }\n current = { form: start.form, t: start.t };\n ready = current;\n }\n const { form, t } = current;\n const cost = phaseTwoCost(sense, objective, form.total);\n const phase = runPhase(t, cost, form.structural, \"bland\", count, banned);\n if (phase.kind === \"cycle\") throw new Error(\"linear: internal error, the rule of Bland met a basis again\");\n if (phase.kind === \"unbounded\") {\n stopped = true;\n return { result: unboundedResult(t, n, phase.column), pivots: count.pivots };\n }\n const x = pointOf(t, n);\n const dual = warmDual(form, t, sense, cost, earlier);\n const r = reducedCosts(t, cost);\n const now: number[] = [];\n for (let j = 0; j < form.structural; j++) {\n if (banned[j] === true || sign(r[j]!) === 0) continue;\n banned[j] = true;\n now.push(j);\n }\n earlier.push({ cost, sense, banned: now });\n return { result: { status: \"optimal\", x, value: dot(objective, x), dual }, pivots: count.pivots };\n };\n return { stage };\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 { checkShape, type Constraint, type LinearProgram, type LinearProgramResult, type Sense } from \"./program.ts\";\nimport { solveCounted, warmStages } 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/**\n * One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate.\n * The field `pivots` gives the count of simplex pivots of the stage. The count is a measure of the work of the stage.\n */\nexport interface LexicographicStage {\n readonly program: LinearProgram;\n readonly result: LinearProgramResult;\n readonly pivots?: number | undefined;\n}\n\n/**\n * The options of `solveLexicographic`. With `warm: true`, the stages share one tableau. A later stage starts from the optimal\n * basis of the stage before it, and it has no phase 1. The values of the stages stay the same. If the last objective has a\n * tie, the point `x` can be a different optimal point. The default is `false`, and it keeps the cold solve of each stage.\n */\nexport interface LexicographicOptions {\n readonly warm?: boolean | undefined;\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 * The option `warm` keeps one tableau for all stages. Each stage result passes `checkCertificate` with its recorded program.\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[], options: LexicographicOptions = {}): LexicographicResult {\n if (objectives.length === 0) throw new RangeError(\"linear: a lexicographic program needs one objective or more\");\n const warm = options.warm === true ? warmStages(constraints) : undefined;\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 if (warm !== undefined) checkShape(program);\n const { result, pivots } = warm === undefined ? solveCounted(program) : warm.stage(objective.sense, objective.coefficients);\n stages.push({ program, result, pivots });\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/**\n * This function adds a failure for each constraint row that `x` breaks, and for each negative entry of `x`.\n *\n * @internal\n */\nexport function 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","/**\n * Integer programs: branch and bound on the exact simplex. The certificate of a result is the tree of its nodes.\n *\n * @packageDocumentation\n */\nimport { type Rational, add, compare, equals, floor, gcd, isInteger, ONE, rational, toString, ZERO } from \"@mark1russell7/rational\";\nimport { type CertificateCheck, checkCertificate, checkFeasible } from \"./certificate.ts\";\nimport { checkShape, type Constraint, type LinearProgram, type LinearProgramResult } from \"./program.ts\";\nimport { solveLinearProgram } from \"./simplex.ts\";\nimport { dot, type Vector } from \"./vector.ts\";\n\n/** A linear program in which each variable of the list `integer` takes integer values only. The other variables are continuous. */\nexport interface IntegerProgram extends LinearProgram {\n /** The indices of the integer variables. */\n readonly integer: readonly number[];\n}\n\n/** The row that a node adds to the rows of its parent: `x[variable] <= value` or `x[variable] >= value`. The value is an integer. */\nexport interface Branch {\n readonly variable: number;\n readonly relation: \"<=\" | \">=\";\n readonly value: Rational;\n}\n\n/**\n * The outcome of a node of the tree.\n *\n * - `branched`: the node has two children. One child adds `x_j <= k`, and the other child adds `x_j >= k + 1`.\n * - `integer`: the relaxation of the node has an optimum with an integer value on each integer variable.\n * - `bound`: the optimum of the relaxation is not better than the best integer point that the solve found before the node.\n * - `infeasible`: the relaxation of the node has no point.\n * - `open`: the solve stopped at its limit before the node.\n */\nexport type NodeOutcome = \"branched\" | \"integer\" | \"bound\" | \"infeasible\" | \"open\";\n\n/** One node of the tree. The root is node 0. Each other node has a parent with a smaller index. */\nexport interface BranchNode {\n readonly parent: number | undefined;\n readonly branch: Branch | undefined;\n readonly outcome: NodeOutcome;\n /** The result of the relaxation of the node, with its certificate. An open node has no result. */\n readonly result: LinearProgramResult | undefined;\n}\n\n/**\n * The result of an integer program, with its certificate.\n *\n * - `optimal`: the point `x`, its value, and the tree. Each leaf proves that its integer points are not better than `x`.\n * - `infeasible`: the tree. Each leaf has a Farkas ray, so the program has no integer point.\n * - `unbounded`: an integer point `x` and a direction `direction` with an integer value on each integer variable.\n * Each point `x + t direction` with an integer `t >= 0` is an integer point, and the objective improves without limit.\n * - `limit`: the solve stopped at its limit. It gives the best integer point that it found, if any. `bound` is a bound of the\n * optimum that the tree proves. A program with an unbounded relaxation gives no bound.\n */\nexport type IntegerProgramResult =\n | { readonly status: \"optimal\"; readonly x: Vector; readonly value: Rational; readonly tree: readonly BranchNode[] }\n | { readonly status: \"infeasible\"; readonly tree: readonly BranchNode[] }\n | { readonly status: \"unbounded\"; readonly x: Vector; readonly direction: Vector }\n | {\n readonly status: \"limit\";\n readonly x: Vector | undefined;\n readonly value: Rational | undefined;\n readonly bound: Rational | undefined;\n readonly tree: readonly BranchNode[];\n };\n\n/** The options of `solveIntegerProgram`. */\nexport interface IntegerOptions {\n /** The largest count of relaxations that the solve solves. The default is 10000. */\n readonly nodeLimit?: number;\n}\n\n/** A node in construction. */\ninterface WorkNode {\n readonly parent: number | undefined;\n readonly branch: Branch | undefined;\n outcome: NodeOutcome;\n result: LinearProgramResult | undefined;\n}\n\n/** The result of one search, before the solve gives its status. */\ninterface Search {\n readonly best: { readonly x: Vector; readonly value: Rational } | undefined;\n readonly nodes: readonly WorkNode[];\n /** True when the search stopped at its limit with open nodes. */\n readonly stopped: boolean;\n}\n\n/**\n * This function gives the problems of the list `integer` of a program: an index that is not an integer, or not a variable.\n *\n * @internal\n */\nexport function integerProblems(program: IntegerProgram): string[] {\n const n = program.objective.length;\n 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`);\n}\n\n/**\n * 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.\n *\n * @internal\n */\nexport function nodeProgram(program: LinearProgram, tree: readonly Pick<BranchNode, \"parent\" | \"branch\">[], id: number): LinearProgram {\n const rows: Constraint[] = [];\n const n = program.objective.length;\n for (let at: number | undefined = id; at !== undefined; at = tree[at]?.parent) {\n const branch = tree[at]?.branch;\n if (branch === undefined) continue;\n const coefficients = Array.from({ length: n }, (_, j) => (j === branch.variable ? ONE : ZERO));\n rows.push({ coefficients, relation: branch.relation, rhs: branch.value });\n }\n return { ...program, constraints: [...program.constraints, ...rows.reverse()] };\n}\n\n/**\n * This function searches the tree depth first. It branches on the fractional integer variable with the smallest index, and it\n * takes the child `x_j <= k` first. With `first`, it stops at the first integer point.\n */\nfunction search(program: LinearProgram, integer: readonly number[], limit: number, first: boolean, root: LinearProgramResult): Search {\n const s = program.sense === \"max\" ? 1 : -1;\n const nodes: WorkNode[] = [{ parent: undefined, branch: undefined, outcome: \"open\", result: undefined }];\n const stack = [0];\n let best: Search[\"best\"];\n let solved = 0;\n while (stack.length > 0 && solved < limit) {\n const id = stack.pop() as number;\n const node = nodes[id] as WorkNode;\n const result = id === 0 ? root : solveLinearProgram(nodeProgram(program, nodes, id));\n solved++;\n node.result = result;\n if (result.status === \"infeasible\") {\n node.outcome = \"infeasible\";\n continue;\n }\n // A node adds rows to a program with an optimum or with the objective 0, so its relaxation is not unbounded.\n if (result.status === \"unbounded\") throw new Error(\"linear: the relaxation of a node is unbounded, and the relaxation of the root is not\");\n if (best !== undefined && compare(result.value, best.value) * s <= 0) {\n node.outcome = \"bound\";\n continue;\n }\n const j = integer.find((k) => !isInteger(result.x[k] as Rational));\n if (j === undefined) {\n node.outcome = \"integer\";\n best = { x: result.x, value: result.value };\n if (first) return { best, nodes, stopped: false };\n continue;\n }\n node.outcome = \"branched\";\n const k = floor(result.x[j] as Rational);\n nodes.push({ parent: id, branch: { variable: j, relation: \">=\", value: add(k, ONE) }, outcome: \"open\", result: undefined });\n stack.push(nodes.length - 1);\n nodes.push({ parent: id, branch: { variable: j, relation: \"<=\", value: k }, outcome: \"open\", result: undefined });\n stack.push(nodes.length - 1);\n }\n return { best, nodes, stopped: stack.length > 0 };\n}\n\n/** This function gives the direction times the least common multiple of its denominators, so each entry is an integer. */\nfunction integral(direction: Vector): Vector {\n let m = 1n;\n for (const v of direction) m = (m / gcd(m, v.d)) * v.d;\n return direction.map((v) => rational(v.n * (m / v.d)));\n}\n\n/** This function gives the frozen tree of the nodes of a search. */\nfunction treeOf(nodes: readonly WorkNode[]): BranchNode[] {\n return nodes.map(({ parent, branch, outcome, result }) => ({ parent, branch, outcome, result }));\n}\n\n/**\n * This function solves an integer program with branch and bound on the exact simplex. The search goes depth first. It branches\n * on the fractional integer variable with the smallest index.\n *\n * - A relaxation with an optimum starts the search for the optimum. Each node with no better optimum than the best point is a leaf.\n * - An unbounded relaxation starts a search for one integer point with the objective 0. When it finds a point, the program is\n * unbounded: the program has rational rows, so its integer points have the unbounded directions of its relaxation.\n * - The search can go on with no end, for example on a line with no integer point. The limit `nodeLimit` stops it.\n *\n * @throws {RangeError} A row has a length that is not the count of variables.\n * @throws {RangeError} An integer variable is not a variable of the program.\n * @throws {RangeError} The option `nodeLimit` is not an integer of 1 or more.\n */\nexport function solveIntegerProgram(program: IntegerProgram, options: IntegerOptions = {}): IntegerProgramResult {\n checkShape(program);\n const problems = integerProblems(program);\n if (problems.length > 0) throw new RangeError(`linear: ${problems.join(\", \")}`);\n const limit = options.nodeLimit ?? 10_000;\n if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`linear: the node limit ${String(limit)} is not an integer of 1 or more`);\n const integer = [...new Set(program.integer)].sort((a, b) => a - b);\n const root = solveLinearProgram(program);\n if (root.status === \"unbounded\") {\n const zero: LinearProgram = { ...program, objective: program.objective.map(() => ZERO) };\n const found = search(zero, integer, limit, true, solveLinearProgram(zero));\n if (found.best !== undefined) return { status: \"unbounded\", x: found.best.x, direction: integral(root.direction) };\n const tree = treeOf(found.nodes);\n if (found.stopped) return { status: \"limit\", x: undefined, value: undefined, bound: undefined, tree };\n return { status: \"infeasible\", tree };\n }\n const found = search(program, integer, limit, false, root);\n const tree = treeOf(found.nodes);\n if (found.stopped) {\n const s = program.sense === \"max\" ? 1 : -1;\n let bound = found.best?.value;\n for (const node of found.nodes) {\n if (node.outcome !== \"open\" || node.parent === undefined) continue;\n const parent = found.nodes[node.parent]?.result;\n if (parent?.status === \"optimal\" && (bound === undefined || compare(parent.value, bound) * s > 0)) bound = parent.value;\n }\n return { status: \"limit\", x: found.best?.x, value: found.best?.value, bound, tree };\n }\n if (found.best === undefined) return { status: \"infeasible\", tree };\n return { status: \"optimal\", x: found.best.x, value: found.best.value, tree };\n}\n\n/** This function adds a failure for each integer variable of `x` with a value that is not an integer. */\nfunction checkIntegral(integer: readonly number[], x: Vector, name: string, failures: string[]): void {\n for (const j of integer) {\n const v = x[j];\n if (v !== undefined && !isInteger(v)) failures.push(`${name}[${String(j)}] = ${toString(v)} is not an integer`);\n }\n}\n\n/** This function adds a failure when the value `v` is better than `limit` in the sense of the program. */\nfunction checkNotBetter(s: 1 | -1, v: Rational, limit: Rational, name: string, failures: string[]): void {\n if (compare(v, limit) * s > 0) failures.push(`${name} ${toString(v)} is better than ${toString(limit)}`);\n}\n\n/**\n * This function examines the tree of a result: its shape, and a certificate for each leaf. With `best`, the value of each leaf\n * is not better than `best`. Each failure goes into `failures`.\n */\nfunction checkTree(program: IntegerProgram, tree: readonly BranchNode[], allowOpen: boolean, best: Rational | undefined, failures: string[]): void {\n const s = program.sense === \"max\" ? 1 : -1;\n const integer = new Set(program.integer);\n const root = tree[0];\n if (root === undefined || root.parent !== undefined || root.branch !== undefined) {\n failures.push(\"node 0 is not a root with no parent and no branch\");\n return;\n }\n const children = tree.map((): number[] => []);\n for (let i = 1; i < tree.length; i++) {\n const node = tree[i] as BranchNode;\n if (node.parent === undefined || !Number.isInteger(node.parent) || node.parent < 0 || node.parent >= i || node.branch === undefined) {\n failures.push(`node ${String(i)} has no parent before it, or no branch`);\n return;\n }\n 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`);\n children[node.parent]?.push(i);\n }\n tree.forEach((node, i) => {\n const kids = children[i] as number[];\n if (node.outcome === \"branched\") {\n const [a, b] = kids.map((k) => (tree[k] as BranchNode).branch as Branch);\n const down = [a, b].find((branch) => branch?.relation === \"<=\");\n const up = [a, b].find((branch) => branch?.relation === \">=\");\n if (kids.length !== 2 || down === undefined || up === undefined || down.variable !== up.variable || !equals(add(down.value, ONE), up.value)) {\n failures.push(`node ${String(i)} is branched, and its children are not x_j <= k and x_j >= k + 1`);\n }\n return;\n }\n if (kids.length > 0) failures.push(`node ${String(i)} has children, and its outcome is ${node.outcome}`);\n if (node.outcome === \"open\") {\n if (!allowOpen) failures.push(`node ${String(i)} is open`);\n if (best === undefined || node.parent === undefined) return;\n // The integer points of an open node are not better than the optimum of the relaxation of its parent.\n const parent = tree[node.parent]?.result;\n if (parent?.status !== \"optimal\") {\n failures.push(`node ${String(i)} is open, and its parent has no optimum`);\n return;\n }\n const check = checkCertificate(nodeProgram(program, tree, node.parent), parent);\n for (const failure of check.failures) failures.push(`node ${String(node.parent)}: ${failure}`);\n checkNotBetter(s, parent.value, best, `the parent of the open node ${String(i)} has the value`, failures);\n return;\n }\n const result = node.result;\n if (result === undefined) {\n failures.push(`node ${String(i)} is a leaf with no result`);\n return;\n }\n const check = checkCertificate(nodeProgram(program, tree, i), result);\n for (const failure of check.failures) failures.push(`node ${String(i)}: ${failure}`);\n if (node.outcome === \"infeasible\") {\n if (result.status !== \"infeasible\") failures.push(`node ${String(i)} is infeasible, and its result is ${result.status}`);\n return;\n }\n if (result.status !== \"optimal\") {\n failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome}, and its result is ${result.status}`);\n return;\n }\n if (node.outcome === \"integer\") checkIntegral(program.integer, result.x, `node ${String(i)}: x`, failures);\n if (best === undefined) failures.push(`node ${String(i)} has an optimum, and the result claims no integer point`);\n else checkNotBetter(s, result.value, best, `node ${String(i)} has the value`, failures);\n });\n}\n\n/**\n * This function examines the certificate of the result of an integer program with exact arithmetic. It does not trust the solver.\n *\n * - `optimal`: the point is feasible, its integer variables are integers, and its value is `c x`. The tree covers each integer\n * point: each branched node has the children `x_j <= k` and `x_j >= k + 1`. Each leaf has a valid certificate of its\n * relaxation, and its value is not better than the value of the point.\n * - `infeasible`: the tree covers each integer point, and each leaf has a Farkas ray.\n * - `unbounded`: the point and the direction meet the conditions of `checkCertificate`, and their integer variables are integers.\n * - `limit`: the point, if any, meets the conditions of an optimum. The tree has the shape of a tree of branches, and each closed\n * 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.\n */\nexport function checkIntegerCertificate(program: IntegerProgram, result: IntegerProgramResult): 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 return { valid: false, failures };\n }\n failures.push(...integerProblems(program));\n if (failures.length > 0) return { valid: false, failures };\n const s = program.sense === \"max\" ? 1 : -1;\n const point = (x: Vector, value: Rational): void => {\n checkFeasible(program, x, failures);\n checkIntegral(program.integer, x, \"x\", failures);\n 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))}`);\n };\n if (result.status === \"unbounded\") {\n failures.push(...checkCertificate(program, { status: \"unbounded\", x: result.x, direction: result.direction }).failures);\n checkIntegral(program.integer, result.x, \"x\", failures);\n checkIntegral(program.integer, result.direction, \"direction\", failures);\n } else if (result.status === \"optimal\") {\n point(result.x, result.value);\n checkTree(program, result.tree, false, result.value, failures);\n } else if (result.status === \"infeasible\") {\n checkTree(program, result.tree, false, undefined, failures);\n result.tree.forEach((node, i) => {\n if (node.outcome !== \"branched\" && node.outcome !== \"infeasible\") failures.push(`node ${String(i)} is a leaf of the outcome ${node.outcome} in an infeasible result`);\n });\n } else {\n if ((result.x === undefined) !== (result.value === undefined)) failures.push(\"the limit result has a point with no value, or a value with no point\");\n if (result.x !== undefined && result.value !== undefined) {\n point(result.x, result.value);\n if (result.bound === undefined) failures.push(\"the limit result has a point and no bound\");\n else checkNotBetter(s, result.value, result.bound, \"the value\", failures);\n }\n checkTree(program, result.tree, true, result.bound, failures);\n }\n return { valid: failures.length === 0, failures };\n}\n"],"mappings":";;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S,KAAK,sEAAsE;EACnJ,IAAI,OAAO,MAAM,KAAA,KAAa,OAAO,UAAU,KAAA,GAAW;GACxD,MAAM,OAAO,GAAG,OAAO,KAAK;GAC5B,IAAI,OAAO,UAAU,KAAA,GAAW,SAAS,KAAK,2CAA2C;QACpF,eAAe,GAAG,OAAO,OAAO,OAAO,OAAO,aAAa,QAAQ;EAC1E;EACA,UAAU,SAAS,OAAO,MAAM,MAAM,OAAO,OAAO,QAAQ;CAC9D;CACA,OAAO;EAAE,OAAO,SAAS,WAAW;EAAG;CAAS;AAClD"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/linear",
4
- "version": "0.1.2",
4
+ "version": "0.1.3",
5
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, integer programs by branch and bound, and certificates with a check.",
6
6
  "keywords": [
7
7
  "linear-algebra",
package/src/index.ts CHANGED
@@ -14,7 +14,7 @@ export type {
14
14
  } from "./program.ts";
15
15
  export { linearProgram } from "./program.ts";
16
16
  export { solveLinearProgram } from "./simplex.ts";
17
- export type { LexicographicResult, LexicographicStage, Objective } from "./lexicographic.ts";
17
+ export type { LexicographicOptions, LexicographicResult, LexicographicStage, Objective } from "./lexicographic.ts";
18
18
  export { solveLexicographic } from "./lexicographic.ts";
19
19
  export type { CertificateCheck } from "./certificate.ts";
20
20
  export { checkCertificate } from "./certificate.ts";
@@ -4,8 +4,8 @@
4
4
  * @packageDocumentation
5
5
  */
6
6
  import type { Rational } from "@mark1russell7/rational";
7
- import type { Constraint, LinearProgram, LinearProgramResult, Sense } from "./program.ts";
8
- import { solveLinearProgram } from "./simplex.ts";
7
+ import { checkShape, type Constraint, type LinearProgram, type LinearProgramResult, type Sense } from "./program.ts";
8
+ import { solveCounted, warmStages } from "./simplex.ts";
9
9
  import type { Vector } from "./vector.ts";
10
10
 
11
11
  /** One objective of a lexicographic program. */
@@ -14,10 +14,23 @@ export interface Objective {
14
14
  readonly coefficients: Vector;
15
15
  }
16
16
 
17
- /** One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate. */
17
+ /**
18
+ * One stage of a lexicographic solve: its program, with the earlier optima as equality rows, and its result with a certificate.
19
+ * The field `pivots` gives the count of simplex pivots of the stage. The count is a measure of the work of the stage.
20
+ */
18
21
  export interface LexicographicStage {
19
22
  readonly program: LinearProgram;
20
23
  readonly result: LinearProgramResult;
24
+ readonly pivots?: number | undefined;
25
+ }
26
+
27
+ /**
28
+ * The options of `solveLexicographic`. With `warm: true`, the stages share one tableau. A later stage starts from the optimal
29
+ * basis of the stage before it, and it has no phase 1. The values of the stages stay the same. If the last objective has a
30
+ * tie, the point `x` can be a different optimal point. The default is `false`, and it keeps the cold solve of each stage.
31
+ */
32
+ export interface LexicographicOptions {
33
+ readonly warm?: boolean | undefined;
21
34
  }
22
35
 
23
36
  /**
@@ -34,18 +47,22 @@ export type LexicographicResult =
34
47
  * optimum of each earlier objective as an equality row. The function stops at the first stage with no optimum.
35
48
  * Only the first stage can be infeasible. A later stage can be unbounded after optimal stages, because its objective is new.
36
49
  *
50
+ * The option `warm` keeps one tableau for all stages. Each stage result passes `checkCertificate` with its recorded program.
51
+ *
37
52
  * @throws {RangeError} The list of objectives is empty, or a row has a length that is not the length of the first objective.
38
53
  */
39
- export function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[]): LexicographicResult {
54
+ export function solveLexicographic(constraints: readonly Constraint[], objectives: readonly Objective[], options: LexicographicOptions = {}): LexicographicResult {
40
55
  if (objectives.length === 0) throw new RangeError("linear: a lexicographic program needs one objective or more");
56
+ const warm = options.warm === true ? warmStages(constraints) : undefined;
41
57
  const stages: LexicographicStage[] = [];
42
58
  const rows: Constraint[] = [...constraints];
43
59
  const values: Rational[] = [];
44
60
  let x: Vector = [];
45
61
  for (const objective of objectives) {
46
62
  const program: LinearProgram = { sense: objective.sense, objective: objective.coefficients, constraints: [...rows] };
47
- const result = solveLinearProgram(program);
48
- stages.push({ program, result });
63
+ if (warm !== undefined) checkShape(program);
64
+ const { result, pivots } = warm === undefined ? solveCounted(program) : warm.stage(objective.sense, objective.coefficients);
65
+ stages.push({ program, result, pivots });
49
66
  if (result.status !== "optimal") return { status: result.status, stages };
50
67
  x = result.x;
51
68
  values.push(result.value);
package/src/simplex.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * @packageDocumentation
5
5
  */
6
- import { type Rational, compare, div, inverse, mul, neg, ONE, sign, sub, ZERO } from "@mark1russell7/rational";
6
+ import { type Rational, add, compare, div, inverse, mul, neg, ONE, sign, sub, ZERO } from "@mark1russell7/rational";
7
7
  import { solve } from "./matrix.ts";
8
- import { checkShape, type LinearProgram, type LinearProgramResult, type Relation } from "./program.ts";
9
- import { dot } from "./vector.ts";
8
+ import { checkShape, type Constraint, type LinearProgram, type LinearProgramResult, type Relation, type Sense } from "./program.ts";
9
+ import { dot, type Vector } from "./vector.ts";
10
10
 
11
11
  /**
12
12
  * The rule that selects the entering column. `"bland"` takes the column with the smallest index that improves the objective.
@@ -28,6 +28,8 @@ interface StandardForm {
28
28
  readonly basis: readonly number[];
29
29
  /** The count of columns that are not artificial. */
30
30
  readonly structural: number;
31
+ /** The count of all columns. */
32
+ readonly total: number;
31
33
  }
32
34
 
33
35
  /** The working tableau: the rows in the form of the current basis. */
@@ -71,7 +73,7 @@ function standardForm(program: LinearProgram): StandardForm {
71
73
  rhs.push(flip ? neg(c.rhs) : c.rhs);
72
74
  flipped.push(flip);
73
75
  });
74
- return { rows, rhs, flipped, basis, structural };
76
+ return { rows, rhs, flipped, basis, structural, total };
75
77
  }
76
78
 
77
79
  function pivot(t: Tableau, p: number, q: number): void {
@@ -104,14 +106,24 @@ type Phase = { readonly kind: "optimal" } | { readonly kind: "unbounded"; readon
104
106
 
105
107
  const basisKey = (basis: readonly number[]): string => [...basis].sort((a, b) => a - b).join(",");
106
108
 
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
+ /**
110
+ * This function maximizes `cost · z` from the current basis. Only the columns below `allowed` can enter. A column with the
111
+ * entry `true` in `banned` cannot enter.
112
+ */
113
+ function runPhase(
114
+ t: Tableau,
115
+ cost: readonly Rational[],
116
+ allowed: number,
117
+ rule: PivotRule,
118
+ count: { pivots: number },
119
+ banned: readonly boolean[] = [],
120
+ ): Phase {
109
121
  const seen = new Set<string>([basisKey(t.basis)]);
110
122
  for (;;) {
111
123
  const r = reducedCosts(t, cost);
112
124
  let q = -1;
113
125
  for (let j = 0; j < allowed; j++) {
114
- if (sign(r[j]!) <= 0) continue;
126
+ if (banned[j] === true || sign(r[j]!) <= 0) continue;
115
127
  if (rule === "bland") {
116
128
  q = j;
117
129
  break;
@@ -159,6 +171,53 @@ function pointOf(t: Tableau, n: number): Rational[] {
159
171
  return x;
160
172
  }
161
173
 
174
+ /** This function gives the cost of a phase 2 as a maximization: the objective, or its negative for `"min"`, and 0 on the other columns. */
175
+ function phaseTwoCost(sense: Sense, objective: Vector, total: number): Rational[] {
176
+ const max = sense === "max";
177
+ return Array.from({ length: total }, (_, j) => (j < objective.length ? (max ? objective[j]! : neg(objective[j]!)) : ZERO));
178
+ }
179
+
180
+ /** This function gives the result of an unbounded phase 2: the basic point and the direction of the entering column `q`. */
181
+ function unboundedResult(t: Tableau, n: number, q: number): LinearProgramResult {
182
+ const direction: Rational[] = new Array<Rational>(n).fill(ZERO);
183
+ if (q < n) direction[q] = ONE;
184
+ t.basis.forEach((col, i) => {
185
+ if (col < n) direction[col] = neg(t.rows[i]![q]!);
186
+ });
187
+ return { status: "unbounded", x: pointOf(t, n), direction };
188
+ }
189
+
190
+ /** The end of phase 1: the tableau of a feasible basis, the Farkas ray of an infeasible program, or a cycle. */
191
+ type Start =
192
+ | { readonly kind: "ready"; readonly form: StandardForm; readonly t: Tableau }
193
+ | { readonly kind: "infeasible"; readonly ray: Rational[] }
194
+ | { readonly kind: "cycle" };
195
+
196
+ /** This function makes the standard form and the tableau, and it does phase 1. Each pivot adds 1 to `count`. */
197
+ function phaseOne(program: LinearProgram, rule: PivotRule, count: { pivots: number }): Start {
198
+ const form = standardForm(program);
199
+ const t: Tableau = { rows: form.rows.map((row) => [...row]), rhs: [...form.rhs], basis: [...form.basis] };
200
+ if (form.total === form.structural) return { kind: "ready", form, t };
201
+ // Phase 1: maximize the negative sum of the artificial columns.
202
+ const cost = Array.from({ length: form.total }, (_, j) => (j >= form.structural ? neg(ONE) : ZERO));
203
+ const phase = runPhase(t, cost, form.total, rule, count);
204
+ if (phase.kind === "cycle") return { kind: "cycle" };
205
+ let value = ZERO;
206
+ t.basis.forEach((col, i) => {
207
+ value = sub(value, col >= form.structural ? t.rhs[i]! : ZERO);
208
+ });
209
+ if (sign(value) < 0) return { kind: "infeasible", ray: dualOf(form, t.basis, cost) };
210
+ // 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.
211
+ t.basis.forEach((col, i) => {
212
+ if (col < form.structural) return;
213
+ const j = t.rows[i]!.findIndex((v, k) => k < form.structural && sign(v) !== 0);
214
+ if (j < 0) return;
215
+ pivot(t, i, j);
216
+ count.pivots++;
217
+ });
218
+ return { kind: "ready", form, t };
219
+ }
220
+
162
221
  /**
163
222
  * The run of the simplex with a pivot rule: the result, or a cycle, and the count of pivots.
164
223
  *
@@ -169,61 +228,55 @@ export type SimplexRun =
169
228
  | { readonly cycled: true; readonly pivots: number };
170
229
 
171
230
  /**
172
- * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland.
231
+ * This function solves a program with a pivot rule. The public `solveLinearProgram` uses the rule of Bland. The count of
232
+ * pivots includes the pivots that move an artificial column out of the basis after phase 1.
173
233
  *
174
234
  * @internal
175
235
  */
176
236
  export function runSimplex(program: LinearProgram, rule: PivotRule): SimplexRun {
177
237
  checkShape(program);
178
238
  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
239
  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
- }
240
+ const start = phaseOne(program, rule, count);
241
+ if (start.kind === "cycle") return { cycled: true, pivots: count.pivots };
242
+ if (start.kind === "infeasible") return { cycled: false, result: { status: "infeasible", ray: start.ray }, pivots: count.pivots };
243
+ const { form, t } = start;
203
244
 
204
245
  // 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));
246
+ const cost = phaseTwoCost(program.sense, program.objective, form.total);
207
247
  const phase = runPhase(t, cost, form.structural, rule, count);
208
248
  if (phase.kind === "cycle") return { cycled: true, pivots: count.pivots };
249
+ if (phase.kind === "unbounded") return { cycled: false, result: unboundedResult(t, n, phase.column), pivots: count.pivots };
209
250
  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
251
  const dual = dualOf(form, t.basis, cost);
220
252
  return {
221
253
  cycled: false,
222
- result: { status: "optimal", x, value: dot(program.objective, x), dual: max ? dual : dual.map(neg) },
254
+ result: { status: "optimal", x, value: dot(program.objective, x), dual: program.sense === "max" ? dual : dual.map(neg) },
223
255
  pivots: count.pivots,
224
256
  };
225
257
  }
226
258
 
259
+ /**
260
+ * The result of one solve and the count of its pivots.
261
+ *
262
+ * @internal
263
+ */
264
+ export interface CountedResult {
265
+ readonly result: LinearProgramResult;
266
+ readonly pivots: number;
267
+ }
268
+
269
+ /**
270
+ * This function solves a program with the rule of Bland, and it gives the count of pivots with the result.
271
+ *
272
+ * @internal
273
+ */
274
+ export function solveCounted(program: LinearProgram): CountedResult {
275
+ const run = runSimplex(program, "bland");
276
+ if (run.cycled) throw new Error("linear: internal error, the rule of Bland met a basis again");
277
+ return { result: run.result, pivots: run.pivots };
278
+ }
279
+
227
280
  /**
228
281
  * This function solves a linear program exactly with the two-phase simplex and the rule of Bland. The result has a certificate
229
282
  * that `checkCertificate` examines.
@@ -231,8 +284,107 @@ export function runSimplex(program: LinearProgram, rule: PivotRule): SimplexRun
231
284
  * @throws {RangeError} A constraint row has a length that is not the length of the objective.
232
285
  */
233
286
  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;
287
+ return solveCounted(program).result;
288
+ }
289
+
290
+ /** One optimal stage of a warm solve: its cost as a maximization, its sense and the columns that it banned. */
291
+ interface WarmEarlier {
292
+ readonly cost: readonly Rational[];
293
+ readonly sense: Sense;
294
+ readonly banned: readonly number[];
295
+ }
296
+
297
+ /**
298
+ * The stages of a warm lexicographic solve on one tableau. Each call of `stage` optimizes the next objective, and it gives the
299
+ * result of the stage program and the count of pivots. Use `stage` again only after an optimal stage.
300
+ *
301
+ * @internal
302
+ */
303
+ export interface WarmStages {
304
+ readonly stage: (sense: Sense, objective: Vector) => CountedResult;
305
+ }
306
+
307
+ /**
308
+ * This function gives the dual of a warm stage for its recorded program: the constraint rows, then one row `c_i x = v_i` for
309
+ * each earlier objective.
310
+ *
311
+ * The reduced costs `s` of the stage start as those of its cost. From the last earlier stage to the
312
+ * first, the function adds `M_i` times the cost of stage `i`. The value `M_i` is the smallest that makes `s_j <= 0` at each
313
+ * column that stage `i` banned. A column that stage `i` did not ban has the reduced cost 0 for objective `i`, so the step
314
+ * does not change it. At the end, `s <= 0` at each column that is not artificial. Thus the sum of the costs has a feasible
315
+ * dual at the basis.
316
+ */
317
+ function warmDual(form: StandardForm, t: Tableau, sense: Sense, cost: readonly Rational[], earlier: readonly WarmEarlier[]): Rational[] {
318
+ let s = reducedCosts(t, cost);
319
+ let combined = [...cost];
320
+ const multipliers: Rational[] = new Array<Rational>(earlier.length).fill(ZERO);
321
+ for (let i = earlier.length - 1; i >= 0; i--) {
322
+ const stage = earlier[i]!;
323
+ const r = reducedCosts(t, stage.cost);
324
+ let m = ZERO;
325
+ for (const j of stage.banned) {
326
+ if (sign(s[j]!) <= 0 || sign(r[j]!) >= 0) continue;
327
+ const need = div(s[j]!, neg(r[j]!));
328
+ if (compare(need, m) > 0) m = need;
329
+ }
330
+ if (sign(m) === 0) continue;
331
+ multipliers[i] = m;
332
+ s = s.map((v, j) => add(v, mul(m, r[j]!)));
333
+ combined = combined.map((v, j) => add(v, mul(m, stage.cost[j]!)));
334
+ }
335
+ // The cost of stage i is g_i c_i, with g_i = 1 for "max" and -1 for "min". Its row c_i x = v_i takes the multiplier -g_i M_i.
336
+ const dual = [...dualOf(form, t.basis, combined), ...multipliers.map((m, i) => (earlier[i]!.sense === "max" ? neg(m) : m))];
337
+ return sense === "max" ? dual : dual.map(neg);
237
338
  }
238
339
 
340
+ /**
341
+ * This function starts a warm lexicographic solve. The first stage is the cold two-phase simplex. After an optimal stage, each
342
+ * column with a reduced cost that is not 0 gets a ban. A banned column cannot enter in a later stage, so it stays at 0.
343
+ *
344
+ * Then each point of a later stage keeps each earlier optimum, because `c z = v + sum r_j z_j` at the basis. A later stage
345
+ * does only phase 2 from the current basis. It adds no row and has no phase 1.
346
+ *
347
+ * @internal
348
+ */
349
+ export function warmStages(constraints: readonly Constraint[]): WarmStages {
350
+ let ready: { readonly form: StandardForm; readonly t: Tableau } | undefined;
351
+ let stopped = false;
352
+ const banned: boolean[] = [];
353
+ const earlier: WarmEarlier[] = [];
354
+ const stage = (sense: Sense, objective: Vector): CountedResult => {
355
+ const n = objective.length;
356
+ const count = { pivots: 0 };
357
+ if (stopped) throw new Error("linear: internal error, a warm stage after a stage with no optimum");
358
+ let current = ready;
359
+ if (current === undefined) {
360
+ const start = phaseOne({ sense, objective, constraints }, "bland", count);
361
+ if (start.kind === "cycle") throw new Error("linear: internal error, the rule of Bland met a basis again");
362
+ if (start.kind === "infeasible") {
363
+ stopped = true;
364
+ return { result: { status: "infeasible", ray: start.ray }, pivots: count.pivots };
365
+ }
366
+ current = { form: start.form, t: start.t };
367
+ ready = current;
368
+ }
369
+ const { form, t } = current;
370
+ const cost = phaseTwoCost(sense, objective, form.total);
371
+ const phase = runPhase(t, cost, form.structural, "bland", count, banned);
372
+ if (phase.kind === "cycle") throw new Error("linear: internal error, the rule of Bland met a basis again");
373
+ if (phase.kind === "unbounded") {
374
+ stopped = true;
375
+ return { result: unboundedResult(t, n, phase.column), pivots: count.pivots };
376
+ }
377
+ const x = pointOf(t, n);
378
+ const dual = warmDual(form, t, sense, cost, earlier);
379
+ const r = reducedCosts(t, cost);
380
+ const now: number[] = [];
381
+ for (let j = 0; j < form.structural; j++) {
382
+ if (banned[j] === true || sign(r[j]!) === 0) continue;
383
+ banned[j] = true;
384
+ now.push(j);
385
+ }
386
+ earlier.push({ cost, sense, banned: now });
387
+ return { result: { status: "optimal", x, value: dot(objective, x), dual }, pivots: count.pivots };
388
+ };
389
+ return { stage };
390
+ }