javascript-lp-solver 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +80 -12
  2. package/dist/index.browser.mjs +4797 -1314
  3. package/dist/index.browser.mjs.map +1 -1
  4. package/dist/index.cjs +4812 -1311
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.ts +765 -41
  7. package/dist/index.mjs +4812 -1311
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/solver.global.js +4797 -1314
  10. package/dist/solver.global.js.map +1 -1
  11. package/dist/types/expressions.d.ts +148 -0
  12. package/dist/types/external/lpsolve/main.d.ts +2 -7
  13. package/dist/types/external/lpsolve/reformat.d.ts +1 -6
  14. package/dist/types/external/main.d.ts +7 -0
  15. package/dist/types/implied-integers.d.ts +47 -0
  16. package/dist/types/main.d.ts +23 -7
  17. package/dist/types/model.d.ts +171 -0
  18. package/dist/types/polyopt.d.ts +21 -4
  19. package/dist/types/shims/external.d.ts +2 -6
  20. package/dist/types/solver.miplib.test.d.ts +1 -0
  21. package/dist/types/solver.netlib.test.d.ts +1 -0
  22. package/dist/types/solver.property.test.d.ts +1 -0
  23. package/dist/types/tableau/backup.d.ts +49 -0
  24. package/dist/types/tableau/bounds.d.ts +68 -0
  25. package/dist/types/tableau/bounds.test.d.ts +1 -0
  26. package/dist/types/tableau/branch-and-cut.d.ts +14 -0
  27. package/dist/types/tableau/cutting-strategies.d.ts +34 -0
  28. package/dist/types/tableau/determinism.test.d.ts +1 -0
  29. package/dist/types/tableau/dynamic-modification.d.ts +77 -11
  30. package/dist/types/tableau/enhanced-branch-and-cut.d.ts +22 -4
  31. package/dist/types/tableau/gomory.d.ts +48 -0
  32. package/dist/types/tableau/gomory.test.d.ts +1 -0
  33. package/dist/types/tableau/incremental-branch-and-cut.d.ts +24 -0
  34. package/dist/types/tableau/index.d.ts +1 -4
  35. package/dist/types/tableau/kernel.d.ts +119 -0
  36. package/dist/types/tableau/kernel.test.d.ts +1 -0
  37. package/dist/types/tableau/log.d.ts +14 -0
  38. package/dist/types/tableau/min-heap.d.ts +39 -0
  39. package/dist/types/tableau/mip-utils.d.ts +31 -55
  40. package/dist/types/tableau/mir.d.ts +65 -0
  41. package/dist/types/tableau/mir.test.d.ts +1 -0
  42. package/dist/types/tableau/presolve.d.ts +12 -10
  43. package/dist/types/tableau/pseudocosts.d.ts +42 -0
  44. package/dist/types/tableau/pseudocosts.test.d.ts +1 -0
  45. package/dist/types/tableau/root-presolve.d.ts +33 -0
  46. package/dist/types/tableau/root-presolve.test.d.ts +1 -0
  47. package/dist/types/tableau/simplex.d.ts +46 -0
  48. package/dist/types/tableau/solution.d.ts +31 -13
  49. package/dist/types/tableau/tableau.d.ts +153 -0
  50. package/dist/types/tableau/types.d.ts +45 -21
  51. package/dist/types/test-utils/problem-generator.d.ts +2 -2
  52. package/dist/types/types/solver.d.ts +119 -0
  53. package/package.json +11 -2
  54. package/scripts/ts-node-register.js +1 -1
  55. package/dist/solver.cjs.js +0 -4448
  56. package/dist/types/tableau/branching-strategies.d.ts +0 -4
  57. package/dist/types/tableau/integer-properties.d.ts +0 -4
  58. package/dist/types/tableau/lu-factorization.d.ts +0 -61
  59. package/dist/types/tableau/lu-simplex.d.ts +0 -32
  60. package/dist/types/tableau/milp-solution.d.ts +0 -7
  61. package/dist/types/tableau/parallel-branch-and-cut.d.ts +0 -39
  62. package/dist/types/tableau/sparse-matrix.d.ts +0 -98
  63. package/dist/types/tableau/sparse-simplex.d.ts +0 -30
  64. package/dist/types/types/api.d.ts +0 -5
  65. package/dist/types/wasm/index.d.ts +0 -42
  66. /package/dist/types/{tableau/sparse-matrix.test.d.ts → implied-integers.test.d.ts} +0 -0
package/dist/index.d.ts CHANGED
@@ -13,72 +13,216 @@
13
13
  * These classes support the fluent API: model.smallerThan(10).addTerm(2, x)
14
14
  */
15
15
 
16
+ /**
17
+ * Priority level for hierarchical optimization.
18
+ * Numeric values represent custom priority levels (lower = higher priority).
19
+ * String values map to predefined levels: "required" (0), "strong" (1), "medium" (2), "weak" (3).
20
+ */
16
21
  type Priority = number | "required" | "strong" | "medium" | "weak";
22
+ /**
23
+ * A continuous decision variable in the optimization problem.
24
+ *
25
+ * Variables represent quantities the solver can adjust. Each variable has
26
+ * an objective coefficient (`cost`), a solution `value`, and a `priority`
27
+ * level for hierarchical optimization.
28
+ */
17
29
  declare class Variable$1 {
30
+ /** Unique string identifier (used in solution output). */
18
31
  id: string;
32
+ /** Objective function coefficient. */
19
33
  cost: number;
34
+ /** Internal index in the tableau's variable/column arrays. */
20
35
  index: number;
36
+ /** Current solution value (set after solving). */
21
37
  value: number;
38
+ /** Priority level for hierarchical optimization (0 = primary objective). */
22
39
  priority: number;
40
+ /** Whether this variable is restricted to integer values. */
23
41
  isInteger?: true;
42
+ /** Whether this is a slack variable (internal, not a decision variable). */
24
43
  isSlack?: true;
44
+ /**
45
+ * @param id - Unique identifier for this variable.
46
+ * @param cost - Objective function coefficient.
47
+ * @param index - Internal tableau index.
48
+ * @param priority - Priority level for hierarchical optimization.
49
+ */
25
50
  constructor(id: string, cost: number, index: number, priority: number);
26
51
  }
52
+ /**
53
+ * A decision variable restricted to integer values.
54
+ * The branch-and-cut algorithm ensures integrality in the final solution.
55
+ */
27
56
  declare class IntegerVariable extends Variable$1 {
28
57
  isInteger: true;
29
58
  constructor(id: string, cost: number, index: number, priority: number);
30
59
  }
60
+ /**
61
+ * An internal variable added to convert inequality constraints to equalities.
62
+ * Slack variables have zero cost and priority and are excluded from solution output.
63
+ */
31
64
  declare class SlackVariable extends Variable$1 {
32
65
  isSlack: true;
66
+ /**
67
+ * @param id - Identifier (typically "s" + index).
68
+ * @param index - Internal tableau index.
69
+ */
33
70
  constructor(id: string, index: number);
34
71
  }
72
+ /**
73
+ * A single term in a linear expression: a variable multiplied by a coefficient.
74
+ */
35
75
  declare class Term$1 {
76
+ /** The variable in this term. */
36
77
  variable: Variable$1;
78
+ /** The scalar multiplier for the variable. */
37
79
  coefficient: number;
38
80
  constructor(variable: Variable$1, coefficient: number);
39
81
  }
40
82
  type RelaxationModel = Model & {
41
83
  addVariable(cost: number, id: string, isInteger?: boolean, isUnrestricted?: boolean, priority?: number): Variable$1;
42
84
  };
85
+ /**
86
+ * A linear inequality constraint: sum(terms) <= rhs (upper bound) or sum(terms) >= rhs (lower bound).
87
+ *
88
+ * Constraints are created via `model.smallerThan()` or `model.greaterThan()` and populated
89
+ * with terms via the fluent `addTerm()` method. Internally, the constraint is stored
90
+ * in standard form with a slack variable.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * // x + 2y <= 10
95
+ * const c = model.smallerThan(10);
96
+ * c.addTerm(1, x).addTerm(2, y);
97
+ * ```
98
+ */
43
99
  declare class Constraint$1 {
100
+ /** Slack variable converting this inequality to an equality for the tableau. */
44
101
  slack: SlackVariable;
102
+ /** Internal constraint index in the tableau. */
45
103
  index: number;
104
+ /** Reference to the parent model (used for dynamic coefficient updates). */
46
105
  model: RelaxationModel;
106
+ /** Right-hand side value. */
47
107
  rhs: number;
108
+ /** If true, this is a <= constraint; if false, a >= constraint. */
48
109
  isUpperBound: boolean;
110
+ /** All terms on the left-hand side. */
49
111
  terms: Term$1[];
112
+ /** Fast lookup of terms by variable index for coefficient updates. */
50
113
  termsByVarIndex: Record<number, Term$1>;
114
+ /** Relaxation variable for soft constraint violation (null if hard). */
51
115
  relaxation: Variable$1 | null;
116
+ /**
117
+ * @param rhs - Right-hand side value.
118
+ * @param isUpperBound - True for <= constraint, false for >=.
119
+ * @param index - Internal index assigned by the tableau.
120
+ * @param model - Parent model for registering coefficient updates.
121
+ */
52
122
  constructor(rhs: number, isUpperBound: boolean, index: number, model: RelaxationModel);
123
+ /**
124
+ * Add a term (coefficient * variable) to this constraint.
125
+ * If the variable already has a term, the coefficients are summed.
126
+ *
127
+ * @param coefficient - Scalar multiplier for the variable.
128
+ * @param variable - The decision variable.
129
+ * @returns This constraint for method chaining.
130
+ */
53
131
  addTerm(coefficient: number, variable: Variable$1): this;
132
+ /** @deprecated Not yet implemented. Placeholder for future term removal. */
54
133
  removeTerm(_term: Term$1): this;
134
+ /**
135
+ * Update the right-hand side value of this constraint.
136
+ * Propagates the change to the tableau if already initialized.
137
+ *
138
+ * @param newRhs - New RHS value.
139
+ * @returns This constraint for method chaining.
140
+ */
55
141
  setRightHandSide(newRhs: number): this;
142
+ /**
143
+ * Set the coefficient of a variable in this constraint.
144
+ * Creates a new term if the variable doesn't already appear.
145
+ *
146
+ * @param newCoefficient - The new coefficient value.
147
+ * @param variable - The variable whose coefficient to set.
148
+ * @returns This constraint for chaining, or void if the variable has no index.
149
+ */
56
150
  setVariableCoefficient(newCoefficient: number, variable: Variable$1): this | void;
151
+ /**
152
+ * Make this constraint "soft" by adding a relaxation variable.
153
+ * Violation of the constraint incurs a penalty in the objective.
154
+ *
155
+ * @param weight - Cost per unit of violation (default: 1).
156
+ * @param priority - Priority level for hierarchical optimization.
157
+ */
57
158
  relax(weight?: number, priority?: Priority): void;
159
+ /**
160
+ * Apply a relaxation variable to this constraint.
161
+ * Adds the variable with coefficient +1 (lower bound) or -1 (upper bound).
162
+ */
58
163
  _relax(relaxationVariable: Variable$1 | null): void;
59
164
  }
165
+ /**
166
+ * An equality constraint represented as two paired inequalities (upper + lower bound).
167
+ *
168
+ * Created via `model.equal(rhs)`. Operations like `addTerm()` and `relax()` are
169
+ * delegated to both underlying constraints simultaneously.
170
+ */
60
171
  declare class Equality {
172
+ /** The <= constraint (sum <= rhs). */
61
173
  upperBound: Constraint$1;
174
+ /** The >= constraint (sum >= rhs). */
62
175
  lowerBound: Constraint$1;
176
+ /** Reference to the parent model. */
63
177
  model: RelaxationModel;
178
+ /** Right-hand side value (same for both bounds). */
64
179
  rhs: number;
180
+ /** Shared relaxation variable (null if hard constraint). */
65
181
  relaxation: Variable$1 | null;
182
+ /** Type discriminator for distinguishing Equality from Constraint. */
66
183
  isEquality: true;
67
184
  constructor(constraintUpper: Constraint$1, constraintLower: Constraint$1);
185
+ /**
186
+ * Add a term to both sides of the equality.
187
+ * @param coefficient - Scalar multiplier.
188
+ * @param variable - The decision variable.
189
+ * @returns This equality for method chaining.
190
+ */
68
191
  addTerm(coefficient: number, variable: Variable$1): this;
192
+ /** @deprecated Not yet implemented. Placeholder for future term removal. */
69
193
  removeTerm(_term: Term$1): this;
194
+ /**
195
+ * Update the RHS value for both inequality constraints.
196
+ * @param rhs - New right-hand side value.
197
+ */
70
198
  setRightHandSide(rhs: number): void;
199
+ /**
200
+ * Make this equality constraint soft by adding a shared relaxation variable to both bounds.
201
+ * @param weight - Cost per unit of violation.
202
+ * @param priority - Priority level for hierarchical optimization.
203
+ */
71
204
  relax(weight?: number, priority?: Priority): void;
72
205
  }
206
+ /**
207
+ * A wrapped numeric constant, used for expression building APIs.
208
+ */
73
209
  declare class Numeral$1 {
210
+ /** The numeric value. */
74
211
  value: number;
75
212
  constructor(value: number);
76
213
  }
77
214
 
215
+ /**
216
+ * Interface for an external solver integration module.
217
+ * Each module provides at least a `solve` method for delegating to an external process.
218
+ */
78
219
  interface ExternalSolverModule {
220
+ /** Convert a JSON model to the external solver's input format. */
79
221
  reformat?: (model: Model$1) => unknown;
222
+ /** Solve the model using the external solver process. */
80
223
  solve: (model: Model$1) => Promise<unknown>;
81
224
  }
225
+ /** Registry of available external solver modules keyed by solver name. */
82
226
  type ExternalSolvers = Record<string, ExternalSolverModule>;
83
227
 
84
228
  /**
@@ -92,151 +236,374 @@ type ExternalSolvers = Record<string, ExternalSolverModule>;
92
236
  * - ConstraintBound: Constraint specification
93
237
  * - Variable, Term, Constraint: Expression types
94
238
  */
239
+ /** Direction for single-objective optimization. */
95
240
  type ObjectiveDirection = "max" | "min";
241
+ /** Constraint relation type when specified as a string shorthand. */
96
242
  type ConstraintRelation = "min" | "max" | "equal";
243
+ /**
244
+ * Configuration options passed to the solver to control algorithm behavior.
245
+ *
246
+ * These can be specified at the top level of the model or nested under `options`.
247
+ * The `options` object takes precedence over top-level properties.
248
+ */
97
249
  interface SolveOptions {
250
+ /** Optimality tolerance for branch-and-cut. Stops early when incumbent is within this fraction of the bound. */
98
251
  tolerance?: number;
252
+ /** Maximum solve time in milliseconds. The solver returns the best solution found so far when exceeded. */
99
253
  timeout?: number;
254
+ /** Enable Mixed Integer Rounding cuts to tighten LP relaxations during branch-and-cut. */
100
255
  useMIRCuts?: boolean;
256
+ /** If true, abort when a pivot cycle is detected (prevents infinite loops on degenerate problems). */
101
257
  exitOnCycles?: boolean;
258
+ /** If true, store all integer-feasible solutions found during branch-and-cut (not just the best). */
102
259
  keep_solutions?: boolean;
260
+ /** Node selection strategy for branch-and-bound tree exploration. */
103
261
  nodeSelection?: "best-first" | "depth-first" | "hybrid";
262
+ /** Variable selection (branching) strategy for choosing which fractional variable to branch on. */
104
263
  branching?: "most-fractional" | "pseudocost" | "strong";
264
+ /** Enable preprocessing reductions (variable fixing, bound tightening, redundant constraint removal). */
105
265
  presolve?: boolean;
266
+ /** Use incremental state management for branch-and-bound (experimental; stores checkpoints to avoid full restores). */
106
267
  useIncremental?: boolean;
107
268
  }
269
+ /**
270
+ * Specifies bounds for a constraint in the JSON model format.
271
+ *
272
+ * A constraint can have a lower bound (`min`), upper bound (`max`), or equality (`equal`).
273
+ * Soft constraints can specify `weight` and `priority` for relaxation.
274
+ */
108
275
  interface ConstraintBound {
276
+ /** Lower bound: the constraint sum must be >= this value. */
109
277
  min?: number;
278
+ /** Upper bound: the constraint sum must be <= this value. */
110
279
  max?: number;
280
+ /** Equality: the constraint sum must equal this value exactly. */
111
281
  equal?: number;
282
+ /** Relaxation weight for soft constraints. Higher weight = harder to violate. */
112
283
  weight?: number;
284
+ /** Relaxation priority level. "required" constraints cannot be violated. */
113
285
  priority?: number | "required" | "strong" | "medium" | "weak";
114
286
  }
287
+ /**
288
+ * Maps constraint names to the variable's coefficient in each constraint.
289
+ * Also includes the objective attribute coefficient.
290
+ */
115
291
  interface VariableCoefficients {
116
292
  [constraintName: string]: number;
117
293
  }
294
+ /**
295
+ * JSON model definition format for specifying optimization problems.
296
+ *
297
+ * This is the primary input format for `solver.Solve()`. It defines the objective,
298
+ * constraints, and variables in a declarative JSON structure.
299
+ *
300
+ * @example
301
+ * ```ts
302
+ * const model: Model = {
303
+ * optimize: "profit",
304
+ * opType: "max",
305
+ * constraints: {
306
+ * wood: { max: 300 },
307
+ * labor: { max: 110 }
308
+ * },
309
+ * variables: {
310
+ * table: { wood: 30, labor: 5, profit: 1200 },
311
+ * chair: { wood: 20, labor: 10, profit: 1000 }
312
+ * },
313
+ * ints: { table: true, chair: true }
314
+ * };
315
+ * ```
316
+ */
118
317
  interface Model$1 {
318
+ /** Optional model name for identification/debugging. */
119
319
  name?: string;
320
+ /** Attribute name to optimize, or a map of attribute names to directions for multi-objective. */
120
321
  optimize: string | Record<string, ObjectiveDirection>;
322
+ /** Optimization direction (ignored when `optimize` is a multi-objective map). */
121
323
  opType?: ObjectiveDirection;
324
+ /** Map of constraint names to their bound specifications. */
122
325
  constraints: Record<string, ConstraintBound | ConstraintRelation>;
326
+ /** Map of variable names to their constraint coefficients. */
123
327
  variables: Record<string, VariableCoefficients>;
328
+ /** Variables restricted to integer values. */
124
329
  ints?: Record<string, boolean | 0 | 1>;
330
+ /** Variables restricted to 0 or 1 (automatically implies an upper bound of 1). */
125
331
  binaries?: Record<string, boolean | 0 | 1>;
332
+ /** Variables that may take negative values (by default, all variables are non-negative). */
126
333
  unrestricted?: Record<string, boolean | 0 | 1>;
334
+ /** Shorthand for `options.tolerance`. */
127
335
  tolerance?: number;
336
+ /** Shorthand for `options.timeout`. */
128
337
  timeout?: number;
338
+ /** Solver configuration options. */
129
339
  options?: SolveOptions;
340
+ /** Configuration for delegating to an external solver process (e.g., lp_solve). */
130
341
  external?: {
342
+ /** Name of the external solver to use (e.g., "lpsolve"). */
131
343
  solver: string;
132
344
  [key: string]: unknown;
133
345
  };
134
346
  }
347
+ /**
348
+ * A decision variable in the optimization problem.
349
+ * Represents a quantity the solver can adjust to optimize the objective.
350
+ */
135
351
  interface Variable {
352
+ /** Unique identifier for this variable. */
136
353
  id: string;
354
+ /** Objective function coefficient (contribution to the objective per unit). */
137
355
  cost: number;
356
+ /** Internal index in the tableau's variable arrays. */
138
357
  index: number;
358
+ /** Current value assigned by the solver. */
139
359
  value: number;
360
+ /** Priority level for hierarchical optimization (0 = primary objective). */
140
361
  priority: number;
362
+ /** Whether this variable must take an integer value. */
141
363
  isInteger?: boolean;
364
+ /** Whether this is a slack variable introduced for constraint conversion. */
142
365
  isSlack?: boolean;
143
366
  }
367
+ /**
368
+ * A variable-coefficient pair representing one term in a linear expression.
369
+ */
144
370
  interface Term {
371
+ /** The variable this term references. */
145
372
  variable: Variable;
373
+ /** The coefficient multiplying the variable. */
146
374
  coefficient: number;
147
375
  }
376
+ /**
377
+ * A linear constraint in the optimization problem.
378
+ * Represents a linear inequality or equality over decision variables.
379
+ */
148
380
  interface Constraint {
381
+ /** Slack variable added to convert inequality to equality for the tableau. */
149
382
  slack: Variable;
383
+ /** Internal index for the constraint in the tableau. */
150
384
  index: number;
385
+ /** Reference to the parent Model. */
151
386
  model: unknown;
387
+ /** Right-hand side value of the constraint. */
152
388
  rhs: number;
389
+ /** If true, constraint is <= (upper bound); if false, >= (lower bound). */
153
390
  isUpperBound: boolean;
391
+ /** All terms on the left-hand side of the constraint. */
154
392
  terms: Term[];
393
+ /** Fast lookup of terms by variable index. */
155
394
  termsByVarIndex: Record<number, Term>;
395
+ /** Relaxation variable for soft constraints (null if hard constraint). */
156
396
  relaxation: Variable | null;
157
397
  }
398
+ /**
399
+ * A wrapped numeric value, used internally for expression building.
400
+ */
158
401
  interface Numeral {
402
+ /** The numeric value. */
159
403
  value: number;
160
404
  }
405
+ /**
406
+ * Simplified solution object returned by `solver.Solve()`.
407
+ *
408
+ * Contains feasibility status, optimal objective value, and the values
409
+ * of all non-zero decision variables as dynamic properties.
410
+ */
161
411
  interface SolveResult {
412
+ /** Whether a feasible solution was found. */
162
413
  feasible: boolean;
414
+ /** Optimal objective function value (0 if infeasible). */
163
415
  result: number;
416
+ /** Whether the problem is bounded. False indicates unbounded objective. */
164
417
  bounded?: boolean;
418
+ /** Whether the solution satisfies all integrality constraints. */
165
419
  isIntegral?: boolean;
420
+ /** Decision variable values (only non-zero variables are included). */
166
421
  [variable: string]: number | boolean | undefined;
167
422
  }
168
423
 
424
+ /**
425
+ * Type-safe solution access with known variable names.
426
+ * Extends SolveResult to provide typed access to specific variable values.
427
+ *
428
+ * @typeParam TVariable - Union of variable name string literals.
429
+ */
169
430
  type Solution$1<TVariable extends string = string> = SolveResult & Record<TVariable, number | undefined>;
431
+ /** The full Solver class API type (useful for dependency injection). */
170
432
  type SolverAPI = typeof solver;
433
+ /** Alias for backwards compatibility with older API consumers. */
171
434
  type ModelDefinition = Model$1;
172
435
 
173
436
  /**
174
- * @file src/tableau/types.ts
175
- * @description Internal type definitions for the tableau module
437
+ * @file src/tableau/bounds.ts
438
+ * @description Column bounds for the tableau (upper-bounding technique)
176
439
  *
177
- * Defines types used within the tableau implementation:
178
- * - BranchCut: Bound constraint for MIP branching
179
- * - Branch: Node in the branch-and-bound tree
180
- * - SavedState: Tableau snapshot for backtracking
181
- * - OptionalObjective: Secondary objective for hierarchical optimization
440
+ * Every variable keeps the classic "nonbasic means stored value 0" invariant
441
+ * by storing an affine image of itself:
442
+ *
443
+ * x = offset + sign * s, 0 <= s <= range, sign in {+1, -1}
444
+ *
445
+ * A variable resting at its lower bound has sign +1 and offset = lb; one
446
+ * resting at its upper bound is complemented (sign -1, offset = ub). Changing
447
+ * a bound is a substitution s = alpha + beta * s' applied to the tableau
448
+ * (Dantzig 1955; Chvátal, "Linear Programming", ch. 8), so pivots and the
449
+ * existing phase logic need no knowledge of bounds beyond the range check.
450
+ *
451
+ * Every tableau row, including the cost row, has the form
452
+ * basic = rhs - sum(a_c * s_c) over nonbasic columns c,
453
+ * so substitutions apply uniformly to all rows.
182
454
  */
183
455
 
184
- type BoundType = "min" | "max";
185
- interface BranchCut {
186
- type: BoundType;
187
- varIndex: number;
188
- value: number;
189
- }
190
- interface OptionalObjective {
191
- priority: number;
192
- reducedCosts: number[];
193
- copy(): OptionalObjective;
194
- }
195
- interface VariableValue {
196
- index: number | null;
197
- value: number | null;
198
- }
199
- type TableauSolution = Solution | MilpSolution;
200
- interface TableauSolutionSet {
201
- [variable: string]: number | undefined;
202
- result?: number;
456
+ /** State captured with snapshots and saved tableaux. */
457
+ interface BoundState {
458
+ hasBounds: boolean;
459
+ offset: Float64Array;
460
+ sign: Float64Array;
461
+ range: Float64Array;
462
+ lower: Float64Array;
463
+ upper: Float64Array;
203
464
  }
204
465
 
205
466
  /**
206
- * @file src/tableau/solution.ts
207
- * @description Solution classes for LP and MIP results
467
+ * @file src/tableau/backup.ts
468
+ * @description Tableau state backup and restoration
208
469
  *
209
- * Provides solution containers for optimization results:
210
- * - Solution: Base class for continuous LP problems
211
- * - MilpSolution: Extended class for mixed-integer problems
470
+ * Provides functions to snapshot and restore tableau state during
471
+ * branch-and-bound exploration. Essential for backtracking when
472
+ * a branch is pruned or found infeasible.
212
473
  *
213
- * Solutions include feasibility status, objective value, and variable values.
474
+ * Functions are designed to be bound to a Tableau instance via `this`.
214
475
  */
215
476
 
477
+ /**
478
+ * Lightweight copy of the LP state at a branch-and-cut node: the live rows
479
+ * of the matrix plus the basis bookkeeping. Variables, model and optional
480
+ * objectives are shared with the tableau and not captured.
481
+ */
482
+ interface NodeSnapshot {
483
+ matrix: Float64Array;
484
+ height: number;
485
+ nVars: number;
486
+ lastElementIndex: number;
487
+ varIndexByRow: number[];
488
+ varIndexByCol: number[];
489
+ rowByVarIndex: number[];
490
+ colByVarIndex: number[];
491
+ availableIndexes: number[];
492
+ bounds: BoundState | null;
493
+ }
494
+
216
495
  /**
217
496
  * Represents a solution to a linear programming problem.
497
+ *
498
+ * Contains the feasibility status, objective value, and provides a method
499
+ * to extract variable values from the tableau's current state.
218
500
  */
219
501
  declare class Solution {
502
+ /** Whether the solver found a feasible solution. */
220
503
  feasible: boolean;
504
+ /** Optimal objective function value (in the model's original direction). */
221
505
  evaluation: number;
506
+ /** Whether the problem is bounded (false = unbounded objective). */
222
507
  bounded: boolean;
508
+ /** Reference to the source tableau (used by generateSolutionSet). */
223
509
  _tableau: Tableau;
510
+ /** Cached variable-to-value mapping (populated by generateSolutionSet). */
224
511
  solutionSet: TableauSolutionSet;
512
+ /**
513
+ * @param tableau - The solved tableau containing variable values.
514
+ * @param evaluation - Objective value (already sign-corrected for min/max).
515
+ * @param feasible - Whether a feasible solution exists.
516
+ * @param bounded - Whether the objective is bounded.
517
+ */
225
518
  constructor(tableau: Tableau, evaluation: number, feasible: boolean, bounded: boolean);
226
519
  /**
227
- * Generate the solution set mapping variable IDs to their values.
520
+ * Extract variable values from the tableau's current state.
521
+ *
522
+ * Iterates over all basic variables, skipping slack variables, and
523
+ * rounds values to the tableau's precision to avoid floating-point noise.
524
+ *
525
+ * @returns A map from variable ID to its solution value.
228
526
  */
229
527
  generateSolutionSet(): TableauSolutionSet;
230
528
  }
231
529
  /**
232
530
  * Represents a solution to a mixed-integer programming problem.
233
- * Extends Solution with branch-and-cut iteration tracking.
531
+ *
532
+ * Extends the base Solution with the number of branch-and-cut iterations
533
+ * performed, which is useful for performance analysis and debugging.
234
534
  */
235
535
  declare class MilpSolution extends Solution {
536
+ /** Number of branch-and-cut iterations (nodes explored) to find this solution. */
236
537
  iter: number;
538
+ /**
539
+ * @param tableau - The solved tableau.
540
+ * @param evaluation - Objective value.
541
+ * @param feasible - Whether an integer-feasible solution was found.
542
+ * @param bounded - Whether the problem is bounded.
543
+ * @param branchAndCutIterations - Number of B&C nodes explored.
544
+ */
237
545
  constructor(tableau: Tableau, evaluation: number, feasible: boolean, bounded: boolean, branchAndCutIterations: number);
238
546
  }
239
547
 
548
+ /**
549
+ * @file src/tableau/types.ts
550
+ * @description Internal type definitions for the tableau module
551
+ *
552
+ * Defines types used within the tableau implementation:
553
+ * - BranchCut: Bound constraint for MIP branching
554
+ * - Branch: Node in the branch-and-bound tree
555
+ * - OptionalObjective: Secondary objective for hierarchical optimization
556
+ */
557
+
558
+ /** Direction of a variable bound constraint: "min" for lower bound (x >= value), "max" for upper bound (x <= value). */
559
+ type BoundType = "min" | "max";
560
+ /**
561
+ * A bound constraint on a variable, used during branch-and-bound.
562
+ * Each branch in the B&B tree is defined by a set of these cuts.
563
+ */
564
+ interface BranchCut {
565
+ /** Whether this is a lower ("min") or upper ("max") bound. */
566
+ type: BoundType;
567
+ /** Internal index of the variable being bounded. */
568
+ varIndex: number;
569
+ /** The bound value (e.g., ceil(x) for "min" or floor(x) for "max"). */
570
+ value: number;
571
+ }
572
+ /**
573
+ * A secondary objective in hierarchical (priority-based) optimization.
574
+ * Lower-priority objectives are optimized only after higher-priority ones are satisfied.
575
+ */
576
+ interface OptionalObjective {
577
+ /** Priority level (lower number = higher priority, 0 = primary objective). */
578
+ priority: number;
579
+ /** Reduced costs for this objective across all columns. */
580
+ reducedCosts: number[];
581
+ /** Create an independent copy of this objective (for tableau backup). */
582
+ copy(): OptionalObjective;
583
+ }
584
+ /**
585
+ * Result of branching variable selection: the chosen variable's index and current value.
586
+ * Null fields indicate no fractional variable was found (solution is integral).
587
+ */
588
+ interface VariableValue {
589
+ /** Internal variable index, or null if no candidate found. */
590
+ index: number | null;
591
+ /** Current fractional value of the variable, or null. */
592
+ value: number | null;
593
+ }
594
+ /** Union type for solutions from both continuous LP and mixed-integer problems. */
595
+ type TableauSolution = Solution | MilpSolution;
596
+ /**
597
+ * A flat map of variable IDs to their solution values.
598
+ * Used as an intermediate format before constructing the final SolveResult.
599
+ */
600
+ interface TableauSolutionSet {
601
+ /** Variable values keyed by variable ID. */
602
+ [variable: string]: number | undefined;
603
+ /** The objective function value for this solution. */
604
+ result?: number;
605
+ }
606
+
240
607
  /**
241
608
  * @file src/tableau/presolve.ts
242
609
  * @description Problem preprocessing for LP/MIP
@@ -250,17 +617,29 @@ declare class MilpSolution extends Solution {
250
617
  * Based on techniques from COIN-OR CBC, CPLEX, and Gurobi.
251
618
  */
252
619
 
620
+ /**
621
+ * Results from the presolve preprocessing phase.
622
+ * Contains all reductions discovered and an infeasibility flag.
623
+ */
253
624
  interface PresolveResult {
625
+ /** Variables proven to have a unique feasible value. */
254
626
  fixedVariables: Map<Variable$1, number>;
627
+ /** Constraints proven to be redundant (always satisfied). */
255
628
  removedConstraints: Set<Constraint$1>;
629
+ /** Variables with tightened lower/upper bounds from constraint analysis. */
256
630
  tightenedBounds: Map<Variable$1, {
257
631
  lower?: number;
258
632
  upper?: number;
259
633
  }>;
634
+ /** Set to true if preprocessing proves the problem has no feasible solution. */
260
635
  isInfeasible: boolean;
636
+ /** Summary statistics of reductions applied. */
261
637
  stats: {
638
+ /** Number of variables fixed to a constant value. */
262
639
  variablesFixed: number;
640
+ /** Number of constraints removed as redundant. */
263
641
  constraintsRemoved: number;
642
+ /** Number of variable bounds tightened. */
264
643
  boundsTightened: number;
265
644
  };
266
645
  }
@@ -279,96 +658,350 @@ interface PresolveResult {
279
658
  * Tableau representation used by the simplex algorithm.
280
659
  */
281
660
 
661
+ /**
662
+ * High-level representation of an optimization problem.
663
+ *
664
+ * Provides a programmatic API for building LP/MIP problems:
665
+ * - Add variables with costs, integer constraints, and priorities
666
+ * - Define constraints (<=, >=, =) with coefficients
667
+ * - Load problems from JSON model definitions
668
+ * - Dynamically modify models after initialization
669
+ *
670
+ * The Model converts high-level definitions into the internal Tableau
671
+ * representation used by the simplex algorithm.
672
+ *
673
+ * @example
674
+ * ```ts
675
+ * const model = new Model();
676
+ * const x = model.addVariable(3, "x");
677
+ * const y = model.addVariable(5, "y");
678
+ * model.smallerThan(10).addTerm(1, x).addTerm(2, y);
679
+ * const solution = model.solve();
680
+ * ```
681
+ */
282
682
  declare class Model {
683
+ /** The underlying simplex tableau. */
283
684
  tableau: Tableau;
685
+ /** Optional model name for identification. */
284
686
  name?: string;
687
+ /** All decision variables in insertion order. */
285
688
  variables: Variable$1[];
689
+ /** Subset of variables with integrality constraints. */
286
690
  integerVariables: IntegerVariable[];
691
+ /** Set of variable indices that may take negative values. */
287
692
  unrestrictedVariables: Record<number, boolean>;
693
+ /** Column bounds (from single-variable JSON constraints and binaries), applied by the tableau. */
694
+ columnBounds: Map<Variable$1, {
695
+ lb: number;
696
+ ub: number;
697
+ }>;
698
+ /**
699
+ * Continuous variables integral at some optimum once the integers are
700
+ * fixed (implied-integers.ts). Used only to recognize an integral
701
+ * objective, never for branching.
702
+ */
703
+ integralContinuous: Set<string>;
704
+ /**
705
+ * Continuous variables treated as integer because they are implied
706
+ * integer (implied-integers.ts). Cut separators may treat them as
707
+ * continuous again (relaxing integrality keeps cuts valid).
708
+ */
709
+ impliedIntegers: Set<string>;
710
+ /** Bounds collected by id while loading JSON, before variables exist. */
711
+ private pendingColumnBounds;
712
+ /** Whether binaries get a column bound instead of an upper-bound row. */
713
+ private binariesAsColumnBounds;
714
+ /** All constraints in insertion order. */
288
715
  constraints: Constraint$1[];
716
+ /** Current number of constraints. */
289
717
  nConstraints: number;
718
+ /** Current number of variables. */
290
719
  nVariables: number;
720
+ /** True for minimization, false for maximization. */
291
721
  isMinimization: boolean;
722
+ /** Whether the tableau has been initialized from this model. */
292
723
  tableauInitialized: boolean;
724
+ /** Counter for generating unique relaxation variable IDs. */
293
725
  relaxationIndex: number;
726
+ /** Whether MIR cuts are enabled for branch-and-cut. */
294
727
  useMIRCuts: boolean;
728
+ /** Whether to detect and abort on simplex pivot cycles. */
295
729
  checkForCycles: boolean;
730
+ /** Diagnostic messages collected during solving. */
296
731
  messages: unknown[];
732
+ /** Optimality tolerance for early termination in B&C. */
297
733
  tolerance?: number;
734
+ /** Maximum solve time in milliseconds. */
298
735
  timeout?: number;
736
+ /** Whether to store all integer-feasible solutions found during B&C. */
299
737
  keep_solutions?: boolean;
738
+ /** All integer-feasible solutions found (if keep_solutions is true). */
300
739
  solutions?: TableauSolutionSet[];
740
+ /** Pool of recycled variable/constraint indices. */
301
741
  availableIndexes: number[];
742
+ /** Next fresh index to allocate. */
302
743
  lastElementIndex: number;
744
+ /** Whether to apply preprocessing reductions before solving. */
303
745
  usePresolve: boolean;
746
+ /** Whether the user explicitly configured presolve behavior. */
747
+ presolveExplicitlyConfigured: boolean;
748
+ /** Cached presolve results (null if not yet applied). */
304
749
  presolveResult: PresolveResult | null;
750
+ /**
751
+ * @param precision - Numerical tolerance for the tableau (default: 1e-8).
752
+ * @param name - Optional model name.
753
+ * @param branchAndCutService - Custom B&C strategy for MIP solving.
754
+ */
305
755
  constructor(precision?: number, name?: string, branchAndCutService?: BranchAndCutService);
756
+ /** Set the optimization direction to minimization. */
306
757
  minimize(): this;
758
+ /** Set the optimization direction to maximization. */
307
759
  maximize(): this;
760
+ /** Allocate a new element index, reusing from pool if available. */
308
761
  _getNewElementIndex(): number;
762
+ /** Register a constraint with the model and propagate to tableau if initialized. */
309
763
  _addConstraint(constraint: Constraint$1): void;
764
+ /**
765
+ * Create a <= (upper bound) constraint.
766
+ * @param rhs - The upper bound value.
767
+ * @returns The new constraint (add terms via .addTerm()).
768
+ */
310
769
  smallerThan(rhs: number): Constraint$1;
770
+ /**
771
+ * Create a >= (lower bound) constraint.
772
+ * @param rhs - The lower bound value.
773
+ * @returns The new constraint (add terms via .addTerm()).
774
+ */
311
775
  greaterThan(rhs: number): Constraint$1;
776
+ /**
777
+ * Create an equality constraint (implemented as paired upper + lower bounds).
778
+ * @param rhs - The equality value.
779
+ * @returns An Equality wrapping both bounds (add terms via .addTerm()).
780
+ */
312
781
  equal(rhs: number): Equality;
782
+ /**
783
+ * Add a decision variable to the model.
784
+ *
785
+ * @param cost - Objective function coefficient (default: 0).
786
+ * @param id - Unique identifier (default: auto-generated).
787
+ * @param isInteger - If true, the variable is restricted to integer values.
788
+ * @param isUnrestricted - If true, the variable may be negative.
789
+ * @param priority - Priority level for hierarchical optimization.
790
+ * @returns The newly created Variable instance.
791
+ */
313
792
  addVariable(cost?: number | null, id?: string | null, isInteger?: boolean, isUnrestricted?: boolean, priority?: Priority | null): Variable$1;
793
+ /** Remove a single constraint from the model and propagate to tableau. */
314
794
  _removeConstraint(constraint: Constraint$1): void;
795
+ /**
796
+ * Remove a constraint or equality from the model.
797
+ * For equalities, removes both the upper and lower bound constraints.
798
+ *
799
+ * @param constraint - The Constraint or Equality to remove.
800
+ * @returns This model for chaining.
801
+ */
315
802
  removeConstraint(constraint: Constraint$1 | Equality): this;
803
+ /**
804
+ * Remove a variable from the model.
805
+ * @param variable - The variable to remove.
806
+ * @returns This model for chaining, or void if variable not found.
807
+ */
316
808
  removeVariable(variable: Variable$1): this | void;
809
+ /**
810
+ * Update a constraint's RHS in the live tableau.
811
+ * @param constraint - The constraint to update.
812
+ * @param difference - Amount to subtract from the current RHS.
813
+ */
317
814
  updateRightHandSide(constraint: Constraint$1, difference: number): this;
815
+ /**
816
+ * Update a variable's coefficient in a constraint in the live tableau.
817
+ * @param constraint - The constraint being modified.
818
+ * @param variable - The variable whose coefficient is changing.
819
+ * @param difference - Amount to add to the current coefficient.
820
+ */
318
821
  updateConstraintCoefficient(constraint: Constraint$1, variable: Variable$1, difference: number): this;
822
+ /**
823
+ * Change a variable's objective coefficient.
824
+ * @param cost - New objective coefficient value.
825
+ * @param variable - The variable to update.
826
+ */
319
827
  setCost(cost: number, variable: Variable$1): this;
828
+ /**
829
+ * Load a problem from the JSON model definition format.
830
+ *
831
+ * Parses constraints, variables, integer/binary flags, and solver options
832
+ * from the JSON structure. Supports equality constraints (via paired bounds),
833
+ * soft constraints (weight/priority), and binary variable upper bounds.
834
+ *
835
+ * @param jsonModel - The JSON model definition.
836
+ * @returns This model for chaining.
837
+ */
320
838
  loadJson(jsonModel: Model$1): this;
839
+ /**
840
+ * Find JSON constraints that touch a single variable and can become
841
+ * column bounds instead of tableau rows (HiGHS and other solvers do this
842
+ * in presolve; here it shrinks the dense tableau). Records the bounds in
843
+ * pendingColumnBounds (by variable id) and returns the constraint ids to
844
+ * skip. Disabled whenever something still reads raw tableau rows: MIR
845
+ * cuts, the enhanced/incremental branch-and-cut services, soft
846
+ * constraints, or unrestricted integer variables.
847
+ */
848
+ private collectColumnBounds;
849
+ /** @returns The number of integer-constrained variables in this model. */
321
850
  getNumberOfIntegerVariables(): number;
851
+ /**
852
+ * Solve the optimization problem.
853
+ *
854
+ * Applies presolve reductions (if enabled), initializes the tableau,
855
+ * and runs simplex (for LP) or branch-and-cut (for MIP).
856
+ *
857
+ * @returns The solution with objective value and variable assignments.
858
+ */
322
859
  solve(): TableauSolution;
323
860
  /**
324
861
  * Apply presolve reductions to the model.
325
862
  * Sets fixed variable values and removes redundant constraints.
326
863
  */
327
864
  private applyPresolveReductions;
865
+ private shouldRunPresolve;
866
+ /** @returns Whether the last solve found a feasible solution. */
328
867
  isFeasible(): boolean;
868
+ /** Snapshot the current tableau state for later restoration. */
329
869
  save(): void;
870
+ /** Restore the tableau to the previously saved state. */
330
871
  restore(): void;
872
+ /**
873
+ * Enable or disable Mixed Integer Rounding cuts.
874
+ * @param useMIRCuts - Whether to apply MIR cuts during branch-and-cut.
875
+ */
331
876
  activateMIRCuts(useMIRCuts: boolean): void;
877
+ /**
878
+ * Enable or disable cycle detection in the simplex algorithm.
879
+ * @param debugCheckForCycles - Whether to check for pivot cycles.
880
+ */
332
881
  debug(debugCheckForCycles: boolean): void;
882
+ /** Print the tableau to console for debugging. */
333
883
  log(message: unknown): Tableau;
334
884
  }
335
885
 
886
+ /**
887
+ * Core simplex tableau data structure.
888
+ *
889
+ * Stores the LP problem in matrix form (Float64Array for numerical precision)
890
+ * and provides methods for simplex operations, branch-and-cut, and dynamic
891
+ * model modification. Each row represents a basic variable; each column
892
+ * represents a non-basic variable. The first row is the cost (objective) row;
893
+ * the first column is the RHS column.
894
+ *
895
+ * This class delegates its method implementations to separate modules
896
+ * (simplex, cutting-strategies, backup, etc.) for maintainability.
897
+ */
336
898
  declare class Tableau {
899
+ /** The model this tableau was built from (null until setModel is called). */
337
900
  model: Model | null;
901
+ /** Flat row-major matrix storage. Element at (row, col) is matrix[row * width + col]. */
338
902
  matrix: Float64Array;
903
+ /** Number of columns (non-basic variables + RHS column). */
339
904
  width: number;
905
+ /** Number of rows (basic variables + cost row). */
340
906
  height: number;
907
+ /** Row index of the objective function (always 0). */
341
908
  costRowIndex: number;
909
+ /** Column index of the RHS values (always 0). */
342
910
  rhsColumn: number;
911
+ /** Lookup table: internal variable index -> Variable object. */
343
912
  variablesPerIndex: Array<Variable$1 | undefined>;
913
+ /** Set of variable indices that are unrestricted (may be negative). */
344
914
  unrestrictedVars: Record<number, boolean>;
915
+ /** Whether the current solution is feasible. Set to false by phase 1 if no BFS found. */
345
916
  feasible: boolean;
917
+ /** Current objective function value (negated internally for minimization). */
346
918
  evaluation: number;
919
+ /** Total simplex iterations performed across all phases. */
347
920
  simplexIters: number;
921
+ /** Maps row index -> variable index of the basic variable in that row. */
348
922
  varIndexByRow: number[];
923
+ /** Maps column index -> variable index of the non-basic variable in that column. */
349
924
  varIndexByCol: number[];
925
+ /** Maps variable index -> row index (-1 if non-basic). */
350
926
  rowByVarIndex: number[];
927
+ /** Maps variable index -> column index (-1 if basic). */
351
928
  colByVarIndex: number[];
929
+ /** Numerical precision tolerance for integrality and zero comparisons. */
352
930
  precision: number;
931
+ /** Secondary objectives sorted by priority (for hierarchical optimization). */
353
932
  optionalObjectives: OptionalObjective[];
933
+ /** Lookup: priority level -> optional objective. */
354
934
  objectivesByPriority: Record<number, OptionalObjective>;
935
+ /** Alias for objectivesByPriority (legacy compatibility). */
355
936
  optionalObjectivePerPriority: Record<number, OptionalObjective>;
937
+ /** Saved tableau state for branch-and-cut restoration. */
356
938
  savedState: Tableau | null;
939
+ /** Pivots performed so far (deterministic work measure for branch-and-cut). */
940
+ pivotCount: number;
941
+ /**
942
+ * When positive, a dual phase 1 from a dual-feasible basis stops after
943
+ * this many iterations and reports its objective (a valid bound) with
944
+ * iterationLimited set. Used by strong branching, which only needs bounds.
945
+ */
946
+ dualIterationLimit: number;
947
+ /** Whether the last simplex() stopped at dualIterationLimit. */
948
+ iterationLimited: boolean;
949
+ /**
950
+ * Row equilibration factor per constraint (indexed by the constraint's
951
+ * slack variable index; absent means 1). Each constraint row is stored
952
+ * multiplied by a power of two that brings its largest coefficient near
953
+ * 1, so the slack is measured on a comparable scale to the structurals
954
+ * and the fixed tolerances mean the same thing on every row.
955
+ */
956
+ rowScale: Float64Array;
957
+ /** True once any column bound has been set (see bounds.ts). */
958
+ hasBounds: boolean;
959
+ /** A column bound from the model had an empty range (lb > ub). */
960
+ hasEmptyColumnBound: boolean;
961
+ /**
962
+ * Per variable index (dense, allocated on first use; see bounds.ts):
963
+ * x = boundOffset + boundSign * stored, stored in [0, boundRange],
964
+ * actual bounds [boundLower, boundUpper].
965
+ */
966
+ boundOffset: Float64Array;
967
+ boundSign: Float64Array;
968
+ boundRange: Float64Array;
969
+ boundLower: Float64Array;
970
+ boundUpper: Float64Array;
971
+ /** Pool of recycled variable/constraint indices. */
357
972
  availableIndexes: number[];
973
+ /** Next fresh index to assign (when pool is empty). */
358
974
  lastElementIndex: number;
975
+ /** All decision variables in column order. */
359
976
  variables: Variable$1[];
977
+ /** Total number of variable/constraint indices allocated. */
360
978
  nVars: number;
979
+ /** Whether the problem is bounded (set to false if unbounded ray detected). */
361
980
  bounded: boolean;
981
+ /** Index of the unbounded variable (if bounded is false). */
362
982
  unboundedVarIndex: number | null;
983
+ /** Number of B&B nodes explored in the last branchAndCut call. */
363
984
  branchAndCutIterations: number;
985
+ /** Best possible objective value (LP relaxation at root). */
364
986
  bestPossibleEval: number;
987
+ /** Set to true when the current solution satisfies all integrality constraints. */
365
988
  __isIntegral?: boolean;
989
+ /** Starting column for partial pricing sweep in phase 2. */
366
990
  pricingBatchStart: number;
991
+ /** Batch size for partial pricing (0 = auto-compute based on problem size). */
367
992
  pricingBatchSize: number;
993
+ /** The branch-and-cut strategy used for MIP solving. */
368
994
  readonly branchAndCutService: BranchAndCutService;
995
+ /**
996
+ * @param precision - Numerical tolerance for zero/integrality tests (default: 1e-8).
997
+ * @param branchAndCutService - Custom B&C strategy (default: basic best-first).
998
+ */
369
999
  constructor(precision?: number, branchAndCutService?: BranchAndCutService);
1000
+ /** Run two-phase simplex to find the optimal LP solution. */
370
1001
  simplex(): this;
1002
+ /** Phase 1: Find a basic feasible solution. @returns Pivot iteration count. */
371
1003
  phase1(): number;
1004
+ /** Phase 2: Optimize the objective. @returns Pivot iteration count. */
372
1005
  phase2(): number;
373
1006
  /**
374
1007
  * Dual simplex for warm-starting after adding bound constraints.
@@ -376,41 +1009,110 @@ declare class Tableau {
376
1009
  * @returns Number of iterations, or -1 if dual infeasible
377
1010
  */
378
1011
  dualSimplex(): number;
1012
+ /**
1013
+ * Perform a single simplex pivot.
1014
+ * @param pivotRowIndex - Row of the leaving variable.
1015
+ * @param pivotColumnIndex - Column of the entering variable.
1016
+ */
379
1017
  pivot(pivotRowIndex: number, pivotColumnIndex: number): void;
1018
+ /** Detect pivot cycles in a history of (leaving, entering) pairs. */
380
1019
  checkForCycles(varIndexes: Array<[number, number]>): number[];
1020
+ /** Count how many integer variables currently have integral values. */
381
1021
  countIntegerValues(): number;
1022
+ /** Check if all integer variables have integral values within precision. */
382
1023
  isIntegral(): boolean;
1024
+ /**
1025
+ * Compute sum of fractionalities of integer variables.
1026
+ * @param ignoreIntegerValues - If true, skip variables that are already integral.
1027
+ * @returns Total fractional volume (0 = all integral).
1028
+ */
383
1029
  computeFractionalVolume(ignoreIntegerValues?: boolean): number;
1030
+ /** Add bound constraints and grow the tableau as needed. */
384
1031
  addCutConstraints(branchingCuts: BranchCut[]): void;
1032
+ /** Apply MIR cuts to all fractional integer rows. */
385
1033
  applyMIRCuts(): void;
1034
+ /** Add a lower-bound MIR cut from the given row. @returns True if cut was added. */
386
1035
  addLowerBoundMIRCut(rowIndex: number): boolean;
1036
+ /** Add an upper-bound MIR cut from the given row. @returns True if cut was added. */
387
1037
  addUpperBoundMIRCut(rowIndex: number): boolean;
1038
+ /** Find the integer variable with the most fractional current value. */
388
1039
  getMostFractionalVar(): VariableValue;
1040
+ /** Find the fractional integer variable with the lowest objective cost. */
389
1041
  getFractionalVarWithLowestCost(): VariableValue;
1042
+ /** Pivot a variable into the basis. @returns Its new row index. */
390
1043
  putInBase(varIndex: number): number;
1044
+ /** Pivot a variable out of the basis. @returns Its new column index. */
391
1045
  takeOutOfBase(varIndex: number): number;
1046
+ /** Read variable values from the matrix into Variable.value. */
392
1047
  updateVariableValues(): void;
1048
+ /** Update a constraint's RHS in the active tableau. */
393
1049
  updateRightHandSide(constraint: Constraint$1, difference: number): void;
1050
+ /** Update a variable's coefficient in a constraint. */
394
1051
  updateConstraintCoefficient(constraint: Constraint$1, variable: Variable$1, difference: number): void;
1052
+ /** Update a variable's objective coefficient. */
395
1053
  updateCost(variable: Variable$1, difference: number): void;
1054
+ /** Add a new constraint row to the tableau. */
396
1055
  addConstraint(constraint: Constraint$1): void;
1056
+ /** Remove a constraint row from the tableau. */
397
1057
  removeConstraint(constraint: Constraint$1): void;
1058
+ /** Add a new variable column to the tableau. */
398
1059
  addVariable(variable: Variable$1): void;
1060
+ /** Remove a variable column from the tableau. */
399
1061
  removeVariable(variable: Variable$1): void;
1062
+ /** Create a deep copy of this tableau's mutable state. */
400
1063
  copy(): Tableau;
1064
+ /** Snapshot the current state for later restoration. */
401
1065
  save(): void;
1066
+ /** Restore the tableau to its previously saved state. */
402
1067
  restore(): void;
1068
+ /** Capture the current node's LP state (see backup.snapshot). */
1069
+ snapshot(reuse?: NodeSnapshot | null): NodeSnapshot;
1070
+ /** Load a node LP state captured by snapshot(). */
1071
+ loadSnapshot(snap: NodeSnapshot): void;
1072
+ /** Print the tableau matrix to console for debugging. */
403
1073
  log(message: unknown): this;
1074
+ /** Apply branch cuts and re-solve the LP relaxation. */
404
1075
  applyCuts(branchingCuts: BranchCut[]): void;
1076
+ /** Run branch-and-cut to find an integer-optimal solution. */
405
1077
  branchAndCut(): void;
1078
+ /**
1079
+ * Solve the problem: run B&C for MIP or simplex for LP, then extract the solution.
1080
+ * @returns The complete solution object.
1081
+ */
406
1082
  solve(): TableauSolution;
1083
+ /** Build a Solution or MilpSolution from the current tableau state. */
407
1084
  getSolution(): TableauSolution;
1085
+ /**
1086
+ * Register or update a secondary (optional) objective at the given priority.
1087
+ * @param priority - Priority level (lower = optimized first).
1088
+ * @param column - Column index for the reduced cost entry.
1089
+ * @param cost - Reduced cost value for this variable in this objective.
1090
+ */
408
1091
  setOptionalObjective(priority: number, column: number, cost: number): void;
1092
+ /**
1093
+ * Allocate and initialize the tableau's matrix and index arrays.
1094
+ * Called by setModel; should not be called directly.
1095
+ *
1096
+ * @param width - Number of columns (variables + 1).
1097
+ * @param height - Number of rows (constraints + 1).
1098
+ * @param variables - All decision variables.
1099
+ * @param unrestrictedVars - Set of unrestricted variable indices.
1100
+ */
409
1101
  initialize(width: number, height: number, variables: Variable$1[], unrestrictedVars: Record<number, boolean>): void;
1102
+ /** Populate the matrix with objective coefficients and constraint data from the model. */
410
1103
  _resetMatrix(): void;
1104
+ /**
1105
+ * Initialize the tableau from a Model instance.
1106
+ * Allocates the matrix and populates it with the model's data.
1107
+ * @param model - The optimization model to load.
1108
+ * @returns This tableau for chaining.
1109
+ */
411
1110
  setModel(model: Model): this;
1111
+ /** Allocate a new variable/constraint index (reuses from pool if available). */
412
1112
  getNewElementIndex(): number;
1113
+ /** Compute the fraction of non-zero entries in the matrix (for sparsity analysis). */
413
1114
  density(): number;
1115
+ /** Read the objective value from the matrix, round to precision, and store in this.evaluation. */
414
1116
  setEvaluation(): void;
415
1117
  }
416
1118
 
@@ -429,30 +1131,52 @@ declare class Tableau {
429
1131
  * - Early termination via tolerance
430
1132
  */
431
1133
 
1134
+ /**
1135
+ * Interface for branch-and-cut solver services.
1136
+ * Implementations provide the strategy for exploring the B&B tree.
1137
+ */
432
1138
  interface BranchAndCutService {
1139
+ /** Apply bound cuts and re-solve the LP relaxation. */
433
1140
  applyCuts(tableau: Tableau, branchingCuts: BranchCut[]): void;
1141
+ /** Run the full branch-and-cut algorithm to find an integer-optimal solution. */
434
1142
  branchAndCut(tableau: Tableau): void;
435
1143
  }
436
1144
 
437
1145
  /**
438
1146
  * Main solver class providing the public API for solving optimization problems.
1147
+ *
1148
+ * Typically used as a singleton (exported as `solver` from this module).
1149
+ * Orchestrates model parsing, validation, simplex/B&C solving, and
1150
+ * multi-objective optimization.
1151
+ *
1152
+ * @example
1153
+ * ```ts
1154
+ * import solver from "javascript-lp-solver";
1155
+ * const result = solver.Solve({ optimize: "profit", opType: "max", ... });
1156
+ * ```
439
1157
  */
440
1158
  declare class Solver {
1159
+ /** Model class constructor for programmatic model building. */
441
1160
  Model: typeof Model;
1161
+ /** Tableau class constructor (advanced: for direct tableau manipulation). */
442
1162
  Tableau: typeof Tableau;
1163
+ /** Constraint class constructor. */
443
1164
  Constraint: typeof Constraint$1;
1165
+ /** Variable class constructor. */
444
1166
  Variable: typeof Variable$1;
1167
+ /** Numeral class constructor. */
445
1168
  Numeral: typeof Numeral$1;
1169
+ /** Term class constructor. */
446
1170
  Term: typeof Term$1;
1171
+ /** Registry of external solver integrations (e.g., lp_solve). */
447
1172
  External: ExternalSolvers;
448
- ReformatLP: (model: any) => string | {
449
- opType: string;
450
- optimize: string;
451
- constraints: {};
452
- variables: {};
453
- };
1173
+ /** LP format conversion utility for external solvers. */
1174
+ ReformatLP: (model: object | string | string[]) => object | string;
1175
+ /** Default branch-and-cut service instance. */
454
1176
  branchAndCutService: BranchAndCutService;
1177
+ /** Convenience method to run branch-and-cut on a tableau. */
455
1178
  branchAndCut: (tableau: Tableau) => void;
1179
+ /** Reference to the most recently solved Model instance (useful for post-solve inspection). */
456
1180
  lastSolvedModel: Model | null;
457
1181
  /**
458
1182
  * Select the appropriate branch-and-cut service based on model options.
@@ -472,7 +1196,7 @@ declare class Solver {
472
1196
  * @param validate - If true, run model through validation functions
473
1197
  * @returns Solution object or simplified result with variable values
474
1198
  */
475
- Solve<TVariable extends string = string>(model: Model$1 | Model, precision?: number, full?: boolean, validate?: boolean): SolveResult | unknown;
1199
+ Solve<_TVariable extends string = string>(model: Model$1 | Model, precision?: number, full?: boolean, validate?: boolean): SolveResult | unknown;
476
1200
  /**
477
1201
  * Delegate solving to an external solver (e.g., lp_solve).
478
1202
  */