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
@@ -5,55 +5,79 @@
5
5
  * Defines types used within the tableau implementation:
6
6
  * - BranchCut: Bound constraint for MIP branching
7
7
  * - Branch: Node in the branch-and-bound tree
8
- * - SavedState: Tableau snapshot for backtracking
9
8
  * - OptionalObjective: Secondary objective for hierarchical optimization
10
9
  */
10
+ import type { NodeSnapshot } from "./backup";
11
11
  import type { Solution, MilpSolution } from "./solution";
12
- import type { Variable } from "../expressions";
13
- import type Model from "../model";
12
+ /** Direction of a variable bound constraint: "min" for lower bound (x >= value), "max" for upper bound (x <= value). */
14
13
  export type BoundType = "min" | "max";
14
+ /**
15
+ * A bound constraint on a variable, used during branch-and-bound.
16
+ * Each branch in the B&B tree is defined by a set of these cuts.
17
+ */
15
18
  export interface BranchCut {
19
+ /** Whether this is a lower ("min") or upper ("max") bound. */
16
20
  type: BoundType;
21
+ /** Internal index of the variable being bounded. */
17
22
  varIndex: number;
23
+ /** The bound value (e.g., ceil(x) for "min" or floor(x) for "max"). */
18
24
  value: number;
19
25
  }
26
+ /**
27
+ * A node in the branch-and-bound tree.
28
+ * Stores the LP relaxation value and all bound constraints that define this node.
29
+ */
20
30
  export interface Branch {
31
+ /** Objective value of the LP relaxation at this node (used for best-first ordering). */
21
32
  relaxedEvaluation: number;
33
+ /** Accumulated bound constraints from root to this node. */
22
34
  cuts: BranchCut[];
35
+ /** Parent LP state to warm-start from; when set, only `lastCut` needs adding. */
36
+ parentSnapshot?: NodeSnapshot | null;
37
+ /** The bound added at this node relative to its parent. */
38
+ lastCut?: BranchCut;
39
+ /** Set once the node has been taken for processing (it may sit in two queues). */
40
+ done?: boolean;
41
+ /** Index of the variable that was branched on to create this node. */
23
42
  branchVarIndex?: number;
43
+ /** Which direction the branch was taken ("up" = ceil, "down" = floor). */
24
44
  branchDirection?: "up" | "down";
45
+ /** Fractionality of the branching variable at the parent node. */
25
46
  branchFractionality?: number;
47
+ /** Parent node's objective value (for pseudocost computation). */
26
48
  parentEvaluation?: number;
27
49
  }
50
+ /**
51
+ * A secondary objective in hierarchical (priority-based) optimization.
52
+ * Lower-priority objectives are optimized only after higher-priority ones are satisfied.
53
+ */
28
54
  export interface OptionalObjective {
55
+ /** Priority level (lower number = higher priority, 0 = primary objective). */
29
56
  priority: number;
57
+ /** Reduced costs for this objective across all columns. */
30
58
  reducedCosts: number[];
59
+ /** Create an independent copy of this objective (for tableau backup). */
31
60
  copy(): OptionalObjective;
32
61
  }
62
+ /**
63
+ * Result of branching variable selection: the chosen variable's index and current value.
64
+ * Null fields indicate no fractional variable was found (solution is integral).
65
+ */
33
66
  export interface VariableValue {
67
+ /** Internal variable index, or null if no candidate found. */
34
68
  index: number | null;
69
+ /** Current fractional value of the variable, or null. */
35
70
  value: number | null;
36
71
  }
37
- export interface SavedState {
38
- width: number;
39
- height: number;
40
- nVars: number;
41
- model: Model | null;
42
- variables: Variable[];
43
- variablesPerIndex: Array<Variable | undefined>;
44
- unrestrictedVars: Record<number, boolean>;
45
- lastElementIndex: number;
46
- varIndexByRow: number[];
47
- varIndexByCol: number[];
48
- rowByVarIndex: number[];
49
- colByVarIndex: number[];
50
- availableIndexes: number[];
51
- optionalObjectives: OptionalObjective[];
52
- optionalObjectivePerPriority: Record<number, OptionalObjective>;
53
- matrix: number[][];
54
- }
72
+ /** Union type for solutions from both continuous LP and mixed-integer problems. */
55
73
  export type TableauSolution = Solution | MilpSolution;
74
+ /**
75
+ * A flat map of variable IDs to their solution values.
76
+ * Used as an intermediate format before constructing the final SolveResult.
77
+ */
56
78
  export interface TableauSolutionSet {
79
+ /** Variable values keyed by variable ID. */
57
80
  [variable: string]: number | undefined;
81
+ /** The objective function value for this solution. */
58
82
  result?: number;
59
83
  }
@@ -34,8 +34,8 @@ export interface GeneratedProblem {
34
34
  equal?: number;
35
35
  }>;
36
36
  variables: Record<string, Record<string, number>>;
37
- ints?: Record<string, number>;
38
- binaries?: Record<string, number>;
37
+ ints?: Record<string, 1>;
38
+ binaries?: Record<string, 1>;
39
39
  }
40
40
  /**
41
41
  * Generate a random LP problem (continuous variables only)
@@ -9,80 +9,199 @@
9
9
  * - ConstraintBound: Constraint specification
10
10
  * - Variable, Term, Constraint: Expression types
11
11
  */
12
+ /** Direction for single-objective optimization. */
12
13
  export type ObjectiveDirection = "max" | "min";
14
+ /** Constraint relation type when specified as a string shorthand. */
13
15
  export type ConstraintRelation = "min" | "max" | "equal";
16
+ /**
17
+ * Configuration options passed to the solver to control algorithm behavior.
18
+ *
19
+ * These can be specified at the top level of the model or nested under `options`.
20
+ * The `options` object takes precedence over top-level properties.
21
+ */
14
22
  export interface SolveOptions {
23
+ /** Optimality tolerance for branch-and-cut. Stops early when incumbent is within this fraction of the bound. */
15
24
  tolerance?: number;
25
+ /** Maximum solve time in milliseconds. The solver returns the best solution found so far when exceeded. */
16
26
  timeout?: number;
27
+ /** Enable Mixed Integer Rounding cuts to tighten LP relaxations during branch-and-cut. */
17
28
  useMIRCuts?: boolean;
29
+ /** If true, abort when a pivot cycle is detected (prevents infinite loops on degenerate problems). */
18
30
  exitOnCycles?: boolean;
31
+ /** If true, store all integer-feasible solutions found during branch-and-cut (not just the best). */
19
32
  keep_solutions?: boolean;
33
+ /** Node selection strategy for branch-and-bound tree exploration. */
20
34
  nodeSelection?: "best-first" | "depth-first" | "hybrid";
35
+ /** Variable selection (branching) strategy for choosing which fractional variable to branch on. */
21
36
  branching?: "most-fractional" | "pseudocost" | "strong";
37
+ /** Enable preprocessing reductions (variable fixing, bound tightening, redundant constraint removal). */
22
38
  presolve?: boolean;
39
+ /** Use incremental state management for branch-and-bound (experimental; stores checkpoints to avoid full restores). */
23
40
  useIncremental?: boolean;
24
41
  }
42
+ /**
43
+ * Specifies bounds for a constraint in the JSON model format.
44
+ *
45
+ * A constraint can have a lower bound (`min`), upper bound (`max`), or equality (`equal`).
46
+ * Soft constraints can specify `weight` and `priority` for relaxation.
47
+ */
25
48
  export interface ConstraintBound {
49
+ /** Lower bound: the constraint sum must be >= this value. */
26
50
  min?: number;
51
+ /** Upper bound: the constraint sum must be <= this value. */
27
52
  max?: number;
53
+ /** Equality: the constraint sum must equal this value exactly. */
28
54
  equal?: number;
55
+ /** Relaxation weight for soft constraints. Higher weight = harder to violate. */
29
56
  weight?: number;
57
+ /** Relaxation priority level. "required" constraints cannot be violated. */
30
58
  priority?: number | "required" | "strong" | "medium" | "weak";
31
59
  }
60
+ /**
61
+ * Maps constraint names to the variable's coefficient in each constraint.
62
+ * Also includes the objective attribute coefficient.
63
+ */
32
64
  export interface VariableCoefficients {
33
65
  [constraintName: string]: number;
34
66
  }
67
+ /**
68
+ * JSON model definition format for specifying optimization problems.
69
+ *
70
+ * This is the primary input format for `solver.Solve()`. It defines the objective,
71
+ * constraints, and variables in a declarative JSON structure.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * const model: Model = {
76
+ * optimize: "profit",
77
+ * opType: "max",
78
+ * constraints: {
79
+ * wood: { max: 300 },
80
+ * labor: { max: 110 }
81
+ * },
82
+ * variables: {
83
+ * table: { wood: 30, labor: 5, profit: 1200 },
84
+ * chair: { wood: 20, labor: 10, profit: 1000 }
85
+ * },
86
+ * ints: { table: true, chair: true }
87
+ * };
88
+ * ```
89
+ */
35
90
  export interface Model {
91
+ /** Optional model name for identification/debugging. */
36
92
  name?: string;
93
+ /** Attribute name to optimize, or a map of attribute names to directions for multi-objective. */
37
94
  optimize: string | Record<string, ObjectiveDirection>;
95
+ /** Optimization direction (ignored when `optimize` is a multi-objective map). */
38
96
  opType?: ObjectiveDirection;
97
+ /** Map of constraint names to their bound specifications. */
39
98
  constraints: Record<string, ConstraintBound | ConstraintRelation>;
99
+ /** Map of variable names to their constraint coefficients. */
40
100
  variables: Record<string, VariableCoefficients>;
101
+ /** Variables restricted to integer values. */
41
102
  ints?: Record<string, boolean | 0 | 1>;
103
+ /** Variables restricted to 0 or 1 (automatically implies an upper bound of 1). */
42
104
  binaries?: Record<string, boolean | 0 | 1>;
105
+ /** Variables that may take negative values (by default, all variables are non-negative). */
43
106
  unrestricted?: Record<string, boolean | 0 | 1>;
107
+ /** Shorthand for `options.tolerance`. */
44
108
  tolerance?: number;
109
+ /** Shorthand for `options.timeout`. */
45
110
  timeout?: number;
111
+ /** Solver configuration options. */
46
112
  options?: SolveOptions;
113
+ /** Configuration for delegating to an external solver process (e.g., lp_solve). */
47
114
  external?: {
115
+ /** Name of the external solver to use (e.g., "lpsolve"). */
48
116
  solver: string;
49
117
  [key: string]: unknown;
50
118
  };
51
119
  }
120
+ /**
121
+ * A decision variable in the optimization problem.
122
+ * Represents a quantity the solver can adjust to optimize the objective.
123
+ */
52
124
  export interface Variable {
125
+ /** Unique identifier for this variable. */
53
126
  id: string;
127
+ /** Objective function coefficient (contribution to the objective per unit). */
54
128
  cost: number;
129
+ /** Internal index in the tableau's variable arrays. */
55
130
  index: number;
131
+ /** Current value assigned by the solver. */
56
132
  value: number;
133
+ /** Priority level for hierarchical optimization (0 = primary objective). */
57
134
  priority: number;
135
+ /** Whether this variable must take an integer value. */
58
136
  isInteger?: boolean;
137
+ /** Whether this is a slack variable introduced for constraint conversion. */
59
138
  isSlack?: boolean;
60
139
  }
140
+ /**
141
+ * A variable-coefficient pair representing one term in a linear expression.
142
+ */
61
143
  export interface Term {
144
+ /** The variable this term references. */
62
145
  variable: Variable;
146
+ /** The coefficient multiplying the variable. */
63
147
  coefficient: number;
64
148
  }
149
+ /**
150
+ * A linear constraint in the optimization problem.
151
+ * Represents a linear inequality or equality over decision variables.
152
+ */
65
153
  export interface Constraint {
154
+ /** Slack variable added to convert inequality to equality for the tableau. */
66
155
  slack: Variable;
156
+ /** Internal index for the constraint in the tableau. */
67
157
  index: number;
158
+ /** Reference to the parent Model. */
68
159
  model: unknown;
160
+ /** Right-hand side value of the constraint. */
69
161
  rhs: number;
162
+ /** If true, constraint is <= (upper bound); if false, >= (lower bound). */
70
163
  isUpperBound: boolean;
164
+ /** All terms on the left-hand side of the constraint. */
71
165
  terms: Term[];
166
+ /** Fast lookup of terms by variable index. */
72
167
  termsByVarIndex: Record<number, Term>;
168
+ /** Relaxation variable for soft constraints (null if hard constraint). */
73
169
  relaxation: Variable | null;
74
170
  }
171
+ /**
172
+ * A wrapped numeric value, used internally for expression building.
173
+ */
75
174
  export interface Numeral {
175
+ /** The numeric value. */
76
176
  value: number;
77
177
  }
178
+ /**
179
+ * Simplified solution object returned by `solver.Solve()`.
180
+ *
181
+ * Contains feasibility status, optimal objective value, and the values
182
+ * of all non-zero decision variables as dynamic properties.
183
+ */
78
184
  export interface SolveResult {
185
+ /** Whether a feasible solution was found. */
79
186
  feasible: boolean;
187
+ /** Optimal objective function value (0 if infeasible). */
80
188
  result: number;
189
+ /** Whether the problem is bounded. False indicates unbounded objective. */
81
190
  bounded?: boolean;
191
+ /** Whether the solution satisfies all integrality constraints. */
82
192
  isIntegral?: boolean;
193
+ /** Decision variable values (only non-zero variables are included). */
83
194
  [variable: string]: number | boolean | undefined;
84
195
  }
85
196
  export type { ExternalSolvers, ExternalSolverModule } from "../external/main";
197
+ /**
198
+ * Type-safe solution access with known variable names.
199
+ * Extends SolveResult to provide typed access to specific variable values.
200
+ *
201
+ * @typeParam TVariable - Union of variable name string literals.
202
+ */
86
203
  export type Solution<TVariable extends string = string> = SolveResult & Record<TVariable, number | undefined>;
204
+ /** The full Solver class API type (useful for dependency injection). */
87
205
  export type SolverAPI = typeof import("../main").default;
206
+ /** Alias for backwards compatibility with older API consumers. */
88
207
  export type ModelDefinition = Model;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "javascript-lp-solver",
3
3
  "description": "Easy to use, JSON oriented Linear Programming and Mixed Int. Programming Solver",
4
- "version": "1.0.1",
4
+ "version": "1.1.0",
5
5
  "private": false,
6
6
  "authors": [
7
7
  "Justin W. Wolcott <justin.w.wolcott@gmail.com>"
@@ -42,19 +42,23 @@
42
42
  "@typescript-eslint/eslint-plugin": "8.2.0",
43
43
  "@typescript-eslint/parser": "8.2.0",
44
44
  "@vitest/coverage-v8": "^4.0.16",
45
+ "dependency-cruiser": "^17.3.7",
45
46
  "eslint": "9.6.0",
46
47
  "eslint-config-prettier": "9.1.0",
47
48
  "eslint-plugin-unicorn": "55.0.0",
48
- "mocha": "10.7.3",
49
+ "knip": "^5.82.1",
50
+ "lefthook": "^2.0.14",
49
51
  "prettier": "3.4.2",
50
52
  "rollup": "4.22.4",
51
53
  "rollup-plugin-dts": "6.1.1",
52
54
  "ts-node": "10.9.2",
55
+ "tslib": "^2.8.1",
53
56
  "typedoc": "0.27.6",
54
57
  "typescript": "5.5.4",
55
58
  "vitest": "^4.0.16"
56
59
  },
57
60
  "scripts": {
61
+ "prepare": "lefthook install",
58
62
  "build": "tsc -p tsconfig.build.json --declaration --emitDeclarationOnly --outDir dist/types && rollup -c",
59
63
  "lint": "ESLINT_USE_FLAT_CONFIG=false eslint .",
60
64
  "lint:fix": "ESLINT_USE_FLAT_CONFIG=false eslint . --fix",
@@ -63,11 +67,16 @@
63
67
  "typecheck": "tsc --noEmit",
64
68
  "docs": "typedoc",
65
69
  "prepublishOnly": "npm run build",
70
+ "knip": "knip",
71
+ "deps": "depcruise src --config .dependency-cruiser.cjs",
72
+ "deps:graph": "depcruise src --config .dependency-cruiser.cjs --output-type dot | dot -T svg > dependency-graph.svg",
73
+ "quality": "npm run lint && npm run knip && npm run deps && npm run test:coverage",
66
74
  "test": "vitest run",
67
75
  "test:unit": "vitest run",
68
76
  "test:watch": "vitest",
69
77
  "test:coverage": "vitest run --coverage",
70
78
  "test:stress": "vitest run src/solver.stress.test.ts",
79
+ "perf:ratchet": "node -r ./scripts/ts-node-register.js scripts/perf-ratchet.ts",
71
80
  "profile": "node -r ./scripts/ts-node-register.js scripts/profile.ts",
72
81
  "release": "npm run format:check && npm run lint && npm test && npm run build"
73
82
  },
@@ -13,7 +13,7 @@ try {
13
13
  let ts;
14
14
  try {
15
15
  ts = require("typescript");
16
- } catch (tsError) {
16
+ } catch (_tsError) {
17
17
  const nvmTypescriptPath = path.join(
18
18
  path.dirname(process.execPath),
19
19
  "..",