@ohtaman/washi 0.8.0 → 0.8.1

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 (81) hide show
  1. package/README.ja.md +22 -24
  2. package/README.md +20 -22
  3. package/README.zh-CN.md +25 -27
  4. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  5. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  6. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  7. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  8. package/dist/browser/solvers/highs.js +1414 -0
  9. package/dist/browser/washi.js +1090 -1473
  10. package/dist/browser/washi.min.js +4 -4
  11. package/dist/lib/solvers/glpk.js +34 -32
  12. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  13. package/dist/lib/solvers/highs.js +410 -0
  14. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  15. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  16. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  17. package/dist/lib/solvers/pumpkin.js +247 -1146
  18. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  19. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  20. package/dist/lib/solvers/z3.js +125 -123
  21. package/dist/lib/washi.js +2426 -1340
  22. package/dist/types/index.d.ts +1 -2
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/modeler/index.d.ts +0 -1
  25. package/dist/types/modeler/index.d.ts.map +1 -1
  26. package/dist/types/modeler/model.d.ts +6 -7
  27. package/dist/types/modeler/model.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/index.d.ts +2 -1
  29. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  31. package/docs/examples/diet-sensitivity.md +33 -14
  32. package/docs/examples/ecommerce-coupons.md +17 -9
  33. package/docs/examples/index.md +34 -30
  34. package/docs/examples/knapsack.md +11 -5
  35. package/docs/examples/portfolio-qp.md +21 -8
  36. package/docs/examples/production.md +10 -5
  37. package/docs/examples/project-scheduling.md +25 -12
  38. package/docs/examples/shift-scheduling.md +27 -19
  39. package/docs/examples/smt-security.md +27 -12
  40. package/docs/examples/transportation.md +23 -13
  41. package/docs/examples/traveling-salesperson.md +34 -22
  42. package/docs/examples/unsat-core.md +27 -15
  43. package/docs/examples/vehicle-routing.md +74 -28
  44. package/docs/getting-started/ai-agents.md +129 -90
  45. package/docs/getting-started/coding-agents.md +60 -41
  46. package/docs/getting-started/cross-origin.md +27 -14
  47. package/docs/getting-started/index.md +23 -16
  48. package/docs/getting-started/runtimes.md +70 -40
  49. package/docs/guide/constraint-programming.md +74 -44
  50. package/docs/guide/constraints.md +71 -39
  51. package/docs/guide/decomposition.md +72 -42
  52. package/docs/guide/expressions.md +79 -48
  53. package/docs/guide/formulation-tips.md +46 -27
  54. package/docs/guide/objectives.md +55 -31
  55. package/docs/guide/unsat-core.md +56 -53
  56. package/docs/guide/variables.md +61 -28
  57. package/docs/solvers/custom-solver.md +155 -119
  58. package/docs/solvers/glpk.md +58 -17
  59. package/docs/solvers/highs.md +115 -43
  60. package/docs/solvers/index.md +33 -26
  61. package/docs/solvers/pumpkin.md +71 -63
  62. package/docs/solvers/z3.md +63 -25
  63. package/llms-full.txt +1623 -953
  64. package/llms.txt +125 -93
  65. package/package.json +29 -20
  66. package/skills/washi/SKILL.md +43 -22
  67. package/dist/browser/solvers/pumpkin.min.js +0 -1
  68. package/dist/lib/registry-dx7x4e5c.js +0 -1694
  69. /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
  70. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  71. /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
  72. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  73. /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
  74. /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
  75. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  76. /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
  77. /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
  78. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  79. /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
  80. /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
  81. /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
@@ -1,7 +1,7 @@
1
1
  # Constraints (`m.constraint` & `m.indicator`)
2
2
 
3
- Constraints restrict the feasible solution space of your mathematical or logical model.
4
- In WaSHI, both linear arithmetic constraints and propositional logic formulas are registered using **`m.constraint()`**:
3
+ Constraints define the rules that every valid solution must satisfy.
4
+ In WaSHI, linear arithmetic constraints, logical rules, and CP global constraints are all registered with `m.constraint()`:
5
5
 
6
6
  ```typescript
7
7
  m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood_limit");
@@ -11,7 +11,7 @@ m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood_limit");
11
11
 
12
12
  ## Algebraic Linear Constraints (`expr`)
13
13
 
14
- The `expr` tagged template literal allows writing equations and inequalities with standard mathematical notation:
14
+ Use the `expr` tagged template literal to write linear equations and inequalities in standard algebraic notation:
15
15
 
16
16
  ```typescript
17
17
  import { Model, expr } from "@ohtaman/washi";
@@ -33,13 +33,16 @@ m.constraint(expr`${x} + ${y} == 30`, "exact_quota");
33
33
  `m.constraint()` returns the registered `Constraint` (or `BoolExpr` for logical formulas), or an array when passed a batch array.
34
34
 
35
35
  ### Supported Comparison Operators
36
- - `<=`: Upper bound constraint
37
- - `>=`: Lower bound constraint
38
- - `==` or `=`: Exact equality constraint
39
- - `<`, `>`, `!=`: Discrete strict inequality / disequality constraints (integer-valued expressions only; see [Discrete Comparisons](#discrete-comparisons))
36
+
37
+ - `<=`: Upper-bound inequality.
38
+ - `>=`: Lower-bound inequality.
39
+ - `==` or `=`: Exact equality.
40
+ - `<`, `>`, `!=`: Strict inequality and not-equal constraints for integer-valued expressions only (see [Discrete Comparisons](#discrete-comparisons)).
40
41
 
41
42
  ### Batch Registration
42
- Pass an array of constraints to `m.constraint([...])` to register them transactionally in a single call:
43
+
44
+ Pass an array of constraints to `m.constraint([...])` to register them atomically.
45
+ If any item in the array is invalid, none of them are added:
43
46
 
44
47
  ```typescript
45
48
  m.constraint([expr`${x} <= 10`, expr`${y} <= 20`]);
@@ -56,15 +59,16 @@ m.constraint(expr`${x} + ${y} <= 100`, "budget_cap");
56
59
  ```
57
60
 
58
61
  ### Why Name Constraints?
59
- 1. **Model Inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain these descriptive names (sanitized if needed) so you can inspect the generated formulation.
60
- 2. **Conflict Diagnosis (`conflicts` / `unsatCore`)**: When constraints contradict each other, `m.check()` returns the conflicting constraint names (via built-in HiGHS elastic relaxation, bundled Pumpkin `unsatCore`, or Z3 `unsatCore`).
61
- 3. **Direct Lookup (`m.constraints.get()`)**: Retrieve any registered constraint by name after solving to inspect its `dual` or `slack` value.
62
+
63
+ 1. **Model inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain your constraint names so you can audit the generated formulation.
64
+ 2. **Conflict diagnosis (`conflicts` / `unsatCore`)**: When constraints contradict each other, `m.check()` reports the conflicting constraint names.
65
+ 3. **Direct lookup (`m.constraints.get()`)**: After solving, fetch any named constraint to read its `dual` or `slack` value.
62
66
 
63
67
  ---
64
68
 
65
- ## Aggregated Constraints (`sum` & `dot`)
69
+ ## Constraints with Sums & Dot Products (`sum` & `dot`)
66
70
 
67
- Use `sum(...)` and `dot(..., ...)` directly inside `expr` to express linear aggregations over arrays and dictionaries cleanly:
71
+ Use `sum(...)` and `dot(..., ...)` directly inside `expr` to express linear aggregations over arrays and dictionaries:
68
72
 
69
73
  ```typescript
70
74
  import { Model, expr } from "@ohtaman/washi";
@@ -85,7 +89,13 @@ m.constraint(expr`dot(${weights}, ${selected}) <= 25`, "capacity_limit");
85
89
 
86
90
  ## Dual Values, Shadow Prices & Lookups
87
91
 
88
- For continuous Linear Programming (LP) problems, query the shadow price (`dual`) and surplus (`slack`) on each constraint (returned by `m.constraint()` or looked up via `m.constraints.get()`):
92
+ For continuous Linear Programming (LP) models—or LP relaxations solved via `m.relax()`—on HiGHS, each linear constraint exposes two sensitivity properties (GLPK populates `dual` only and leaves `slack` as `null`):
93
+
94
+ - **`dual` (shadow price)**: The marginal signed change in the optimal objective value per unit increase in the constraint's right-hand side (while the optimal basis remains unchanged).
95
+ - **`slack`**: Defined as `rhs - lhs` at the optimal solution (`>= 0` for `<=` constraints, `<= 0` for `>=` constraints, and `0` when the constraint is tight).
96
+
97
+ Both properties have type `number | null`.
98
+ They are `null` before solving, when no optimal LP solution is found, on MIP models solved with `m.solve()`, and on CP, SMT, and logical constraints.
89
99
 
90
100
  ```typescript
91
101
  const woodConstraint = m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
@@ -93,8 +103,8 @@ const woodConstraint = m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
93
103
  await m.solve();
94
104
 
95
105
  console.log("Shadow price (dual):", woodConstraint.dual);
96
- console.log("Slack surplus:", woodConstraint.slack);
97
- console.log("Looked-up dual:", m.constraints.get("wood")?.dual); // number | null (null for MIP, CP, or logical constraints)
106
+ console.log("Slack:", woodConstraint.slack);
107
+ console.log("Looked-up dual:", m.constraints.get("wood")?.dual); // number | null
98
108
  console.log("Total constraints:", m.constraints.size);
99
109
  ```
100
110
 
@@ -102,7 +112,11 @@ console.log("Total constraints:", m.constraints.size);
102
112
 
103
113
  ## Conditional / Indicator Constraints (`m.indicator`)
104
114
 
105
- When a linear constraint should only take effect when a binary decision variable (`m.binary()`) equals `1` (or `0`), use `m.indicator()`:
115
+ Use `m.indicator()` when a linear constraint should only apply if a binary variable (`m.binary()`) equals `activeValue` (`1` by default, or `0`).
116
+ In MIP formulations, this conditional rule is encoded via the **Big-M method**.
117
+ For example, $a^\top x \le b + M(1 - y)$ enforces $a^\top x \le b$ when $y = 1$, and relaxes it with a large constant $M$ when $y = 0$.
118
+
119
+ The target constraint must be linear with `<=`, `>=`, or `==`—discrete `!=`, nonlinear atoms (`max`, `min`, `abs`, `at`), and referencing `binVar` inside the constrained expression are rejected:
106
120
 
107
121
  ```typescript
108
122
  const useDiscount = m.binary("use_discount");
@@ -118,15 +132,18 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
118
132
 
119
133
  ### Safe Automatic Big-M Derivation & Bounds
120
134
 
121
- When `options.M` is omitted, WaSHI automatically derives a minimal valid Big-M value from finite variable bounds (`lb` and `ub`):
122
- - For `<=` constraints, variables with positive coefficients require finite upper bounds (`ub`), and negative coefficients require finite lower bounds (`lb`).
123
- - For `>=` constraints, variables with positive coefficients require finite lower bounds (`lb`), and negative coefficients require finite upper bounds (`ub`).
124
- - For `==` constraints, bounds are derived separately for both the `<=` and `>=` directions (generating `name_le` and `name_ge`).
135
+ When `options.M` is omitted, WaSHI computes the smallest valid Big-M from finite variable bounds (`lb` and `ub`):
125
136
 
126
- If any referenced variable lacks the required finite bound, `m.indicator()` throws an error prompting for finite bounds or an explicit `options.M`.
137
+ - For `<=` constraints, positive coefficients require finite `ub` and negative coefficients require finite `lb`.
138
+ - For `>=` constraints, positive coefficients require finite `lb` and negative coefficients require finite `ub`.
139
+ - For `==` constraints, WaSHI derives bounds for both directions separately, creating `name_le` and `name_ge`.
140
+
141
+ If any referenced variable lacks a required finite bound, `m.indicator()` throws an error asking for finite bounds or an explicit `options.M`.
127
142
 
128
143
  > [!NOTE]
129
- > **Native Indicator Lowering on Pumpkin & Z3**: When `options.M` is omitted, `m.indicator()` still returns Big-M-linearized `Constraint[]` rows (so `m.toLpString()`, HiGHS, and GLPK stay identical and backward compatible) while annotating those rows so **Pumpkin** lowers natively via `implied_by` and **Z3** lowers natively via `ctx.Implies` without Big-M numerical degradation. Mutating a returned row clears that metadata so subsequent edits take effect directly.
144
+ > **How `m.indicator()` works across MIP, CP, and SMT solvers**: When `options.M` is omitted, `m.indicator()` returns an array of Big-M linear `Constraint` objects (`Constraint[]`) that also carry a native-indicator annotation.
145
+ > HiGHS, GLPK, and `m.toLpString()` use the Big-M inequalities directly, while Pumpkin and Z3 read the annotation to solve the implication natively without Big-M numerical issues or weak relaxations.
146
+ > If you later mutate any returned `Constraint` object, WaSHI clears that annotation so your direct edits take effect across every solver.
130
147
 
131
148
  ### Explicit `M` Override
132
149
 
@@ -140,13 +157,20 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
140
157
  ```
141
158
 
142
159
  > [!TIP]
143
- > **Prefer Finite Variable Bounds Over Arbitrary Large `M`**: An $M$ value that is too small can cut off valid feasible solutions, whereas an excessively large $M$ (e.g., $10^9$) degrades numerical conditioning in MIP solvers. Setting realistic `lb` and `ub` bounds on variables lets WaSHI compute the tightest safe Big-M automatically.
160
+ > **Prefer Finite Variable Bounds Over Arbitrary Large `M`**: Too small an $M$ can cut off valid solutions, while an excessively large $M$ (such as `1e9`) weakens LP relaxations and harms MIP numerical stability.
161
+ > Setting realistic `lb` and `ub` bounds lets WaSHI compute the tightest safe Big-M automatically.
144
162
 
145
163
  ---
146
164
 
147
165
  ## Propositional Logic & SMT Constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`)
148
166
 
149
- WaSHI provides first-class logical operators to combine propositional boolean variables (`m.bool()`) and linear constraints (`Constraint`). Logical formulas are solved natively by **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`, for bounded integer & boolean models) and **Z3** (`@ohtaman/washi/solvers/z3`), and automatically linearized to 0-1 MIP constraints on **HiGHS** and **GLPK**:
167
+ WaSHI provides first-class logical operators that combine `BoolVar` variables from `m.bool()` with linear `Constraint` objects.
168
+ Pumpkin (`{ solver: "pumpkin" }`, bundled with zero extra imports) and Z3 (`import "@ohtaman/washi/solvers/z3"`) solve these formulas natively, while HiGHS and GLPK automatically linearize them into 0-1 MIP constraints.
169
+
170
+ > [!IMPORTANT]
171
+ > **Solver Preconditions**:
172
+ > - **Pumpkin**: Every numeric variable must be `Integer` or `Binary` with finite `lb` and `ub`.
173
+ > - **Z3**: Requires the optional dependency `z3-solver` (`npm install z3-solver`). In browsers, Z3 also requires `COOP`/`COEP` response headers for `SharedArrayBuffer`.
150
174
 
151
175
  ```typescript
152
176
  import { Model, expr, and, or, not, implies, xor } from "@ohtaman/washi";
@@ -170,7 +194,8 @@ m.constraint(
170
194
  m.constraint(and(or(isAdmin, hasMfa), not(xor(isAdmin, hasMfa))), "policy");
171
195
  ```
172
196
 
173
- All named constraints—both linear `Constraint`s and logical/CP `LogicalConstraint`s (`{ kind: "logical", name, expr, dual: null, slack: null }`)—are stored uniformly in `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`) and can be looked up by name via `m.constraints.get(name)`.
197
+ All registered constraints (including auto-named ones) are stored in `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`) and can be looked up with `m.constraints.get(name)`.
198
+ Logical and CP entries use the shape `{ kind: "logical", name, expr, dual: null, slack: null }`.
174
199
 
175
200
  ### Choosing Between `m.indicator()` and `implies()`
176
201
 
@@ -178,17 +203,20 @@ All named constraints—both linear `Constraint`s and logical/CP `LogicalConstra
178
203
  | :--- | :--- | :--- |
179
204
  | **Trigger variable** | Numeric `Binary` variable (`m.binary()`) | `BoolVar` (`m.bool()`), `BoolOp`, or `Constraint` |
180
205
  | **Consequent** | Linear `Constraint` (`<=`, `>=`, `==`) | `BoolVar`, `BoolOp`, or linear `Constraint` |
181
- | **Target Solvers** | **All MIP/LP solvers** (HiGHS, GLPK via Big-M; Pumpkin/Z3 natively when `M` omitted) | **All solvers** (HiGHS and GLPK via automatic 0-1 MIP linearization, Pumpkin and Z3 natively) |
182
- | **Primary Use Case** | MIP optimization models with arithmetic binary variables (`m.solve()`) | Logical rule systems and SMT feasibility (`m.check()`) |
206
+ | **Target Solvers** | All solvers (Big-M on HiGHS/GLPK; native on Pumpkin/Z3 when `M` is omitted) | All solvers (automatic 0-1 MIP on HiGHS/GLPK; native on Pumpkin/Z3) |
207
+ | **Primary Use Case** | MIP optimization models using numeric binary variables | Logical rule systems and SMT feasibility checks |
183
208
 
184
209
  > [!NOTE]
185
- > **Comparison Constraints in Negated Positions (`implies` Antecedents, `not`, `xor`)**: Linear comparison constraints whose referenced variables are all `Integer` or `Binary` with integer coefficients and integer right-hand sides (plus required finite bounds for Big-M indicators, such as ``implies(expr`${clearance} >= 4`, hasMfa)`` above) are linearized automatically on **HiGHS** and **GLPK** via exact $\pm 1$ integer shifts ($\neg(a^\top x \le b) \iff a^\top x \ge b + 1$, and $a^\top x \ne b \iff a^\top x \le b - 1 \lor a^\top x \ge b + 1$), and solved natively on **Pumpkin** and **Z3**. When a comparison constraint containing `Continuous` variables or non-integer coefficients/thresholds appears in a negated position, MIP `solve()` / `check()` throws an error because strict-inequality negation forms an open half-space—use `{ solver: "z3" }`, or write an explicit closed-tolerance disjunction such as ``or(expr`... >= ... + eps`, ...)`` or an `m.bool()` proposition.
210
+ > **Negating Comparison Constraints (arguments of `not` or `xor`, or the condition of `implies`)**:
211
+ > - **Integer expressions**: Negations such as $\neg(x \le 5)$ are converted automatically to $x \ge 6$ on HiGHS and GLPK, and handled natively on Pumpkin and Z3.
212
+ > - **`Continuous` or decimal expressions**: HiGHS and GLPK reject negated continuous comparisons because strict `<` and `>` cannot form closed linear inequalities. Use `{ solver: "z3" }` or model the condition with `m.bool()`.
186
213
 
187
214
  ---
188
215
 
189
216
  ## Discrete Comparisons (`!=`, `<`, `>`)
190
217
 
191
- WaSHI supports discrete comparisons `!=`, `<`, and `>` in `expr` (and fluent `.ne()`, `.lt()`, `.gt()` on `Var`, `LinExpr`, and `QuadExpr`) strictly for **integer-valued expressions** (`Integer` or `Binary` variables with safe-integer coefficients and constants):
218
+ WaSHI supports `!=`, `<`, and `>` inside `expr` as well as via `.ne()`, `.lt()`, and `.gt()` on `Var`, `LinExpr`, and `QuadExpr`.
219
+ These operators apply strictly to **integer-valued expressions**—expressions built from `Integer` or `Binary` variables with safe-integer coefficients and constants:
192
220
 
193
221
  ```typescript
194
222
  const rankA = m.integer("rankA", { lb: 1, ub: 4 });
@@ -197,23 +225,27 @@ const roomA = m.integer("roomA", { lb: 1, ub: 3 });
197
225
  const roomB = m.integer("roomB", { lb: 1, ub: 3 });
198
226
 
199
227
  m.constraint(expr`${rankA} < ${rankB}`, "strict_order"); // lowered via rankA - rankB <= -1
200
- m.constraint(expr`${roomA} != ${roomB}`, "diff_room"); // native not_equals on Pumpkin, neq on Z3, single-binary MIP on HiGHS/GLPK
228
+ m.constraint(expr`${roomA} != ${roomB}`, "diff_room"); // native on Pumpkin/Z3, single-binary MIP on HiGHS/GLPK
201
229
  ```
202
230
 
203
- Expressions involving `Continuous` variables or fractional numbers in `!=`, `<`, or `>` are rejected immediately because open inequalities ($x < b$, $x \ne b$) are not closed polyhedra on continuous domains.
231
+ Expressions containing `Continuous` variables or decimal constants are rejected immediately for `!=`, `<`, and `>`.
232
+ Over real numbers, strict inequalities define open sets—for example, maximizing $x$ subject to $x < 5$ has no optimal real solution.
233
+ LP and MIP solvers therefore require closed inequalities ($\le$, $\ge$, $=$) so an optimum is well-defined.
204
234
 
205
235
  ---
206
236
 
207
237
  ## CP Global Constraints (`distinct`, `disjoint`, `cumulative`, `allowed`)
208
238
 
209
- WaSHI provides backend-agnostic Constraint Programming predicates returning composable `BoolExpr` objects (combinable with `and`, `or`, `not`, `implies`, `xor`). For interval scheduling, symmetry breaking, and solver modeling patterns with **Pumpkin**, see the dedicated [Constraint Programming (CP) Modeling Guide](./constraint-programming.md).
239
+ WaSHI provides backend-agnostic Constraint Programming **global constraints**—higher-level predicates over groups of variables that return composable `BoolExpr` objects.
240
+ They combine freely with `and`, `or`, `not`, `implies`, and `xor`.
241
+ For interval scheduling, symmetry breaking, and Pumpkin modeling patterns, see the [Constraint Programming (CP) Modeling Guide](./constraint-programming.md).
210
242
 
211
- | Predicate | Semantics | HiGHS / GLPK | Pumpkin | Z3 |
243
+ | Predicate | Meaning | HiGHS / GLPK | Pumpkin | Z3 |
212
244
  | :--- | :--- | :--- | :--- | :--- |
213
- | `distinct(...args)` | Pairwise `a != b` across integer expressions / 1D–2D containers (`AllDifferent`) | Pairwise `!=` MIP | `all_different` | `ctx.Distinct` |
214
- | `disjoint(tasks)` | Non-overlapping intervals `[start, start + duration)` on unary resource (`NoOverlap` / `Disjunctive`; `duration >= 0` integer; duration-0 only at boundaries) | Pairwise binary precedence + Big-M | `disjunctive_strict` (Vilím edge-finding) | Pairwise `Or` disjunctions |
215
- | `cumulative(tasks, capacity)` | Resource usage $\le$ `capacity` across all time points (`duration >= 0`, `demand >= 0` integer) | Time-indexed MIP (throws horizon guard error above 5,000 span / 25,000 pulse vars recommending `{ solver: "pumpkin" }`) | Native `cumulative` time-table filtering | Start-event load assertions |
216
- | `allowed(vars, tuples)` | Tuple `(vars[0], ...) in tuples` (`Table` / `AllowedAssignments`; use `not(allowed(...))` for forbidden tuples) | Tuple selector binaries (`not` emits 0-binary cuts on 2-valued vars) | `table` / `negative_table` | Tuple `Or` / `And` |
245
+ | `distinct(...args)` | All values are pairwise different (`!=`) | Pairwise `!=` MIP | Native `all_different` | Native `Distinct` |
246
+ | `disjoint(tasks)` | Tasks `[start, start + duration)` do not overlap | Pairwise ordering + Big-M | Native non-overlap | Pairwise `Or` |
247
+ | `cumulative(tasks, capacity)` | Total demand $\le$ `capacity` at every moment | Time-indexed MIP (errors above 5,000 steps / 25,000 vars) | Native `cumulative` | Event-point load |
248
+ | `allowed(vars, tuples)` | Values match a row in `tuples` (`not(allowed(...))` forbids them) | Tuple selector binaries | Native table | Tuple `Or` / `And` |
217
249
 
218
250
  ```typescript
219
251
  import { Model, expr, distinct, disjoint, cumulative, allowed, not, minimize } from "@ohtaman/washi";
@@ -230,4 +262,4 @@ m.objective(minimize(expr`${s[0]} + ${s[1]}`));
230
262
  ```
231
263
 
232
264
  > [!TIP]
233
- > For modeling techniques such as **soft constraints with slack variables** and **symmetry breaking**, see [Formulation Patterns & Optimization Tips](./formulation-tips.md#_3-constraint-design-numerical-conditioning).
265
+ > For **soft constraints with slack variables** and **symmetry breaking**, see [Formulation Patterns & Optimization Tips](./formulation-tips.md#_3-constraint-design-numerical-conditioning).
@@ -1,31 +1,49 @@
1
1
  # Decomposition Methods (`solveColumnGeneration` & `solveBenders`)
2
2
 
3
- When monolithic Mixed-Integer Programming (MIP) models have exponentially many candidate patterns or large multi-stage subproblems, WaSHI provides two high-level decomposition orchestrators—`master.solveColumnGeneration()` and `master.solveBenders()`—along with low-level primitives for dual inspection and dynamic model updates.
3
+ When a single LP or MIP model has too many columns to enumerate upfront, or splits naturally into two decision stages, WaSHI provides two decomposition helpers:
4
4
 
5
- | Decomposition Method | WaSHI Orchestrator | Typical Use Case |
5
+ | Method | WaSHI API | When to use |
6
6
  | :--- | :--- | :--- |
7
- | **Column Generation** *(Dantzig-Wolfe)* | [`master.solveColumnGeneration()`](#column-generation-solvecolumngeneration) | Models with exponentially many patterns, routes, or schedules (e.g., Cutting Stock, Vehicle Routing, Crew Rostering). |
8
- | **Benders Decomposition** *(and Lazy Cuts)* | [`master.solveBenders()`](#benders-decomposition-solvebenders) | Two-stage or complicating-variable problems (e.g., Facility Location + Dispatch, Stochastic Planning, TSP Subtour Elimination). |
7
+ | **Column Generation** | [`master.solveColumnGeneration()`](#column-generation-solvecolumngeneration) | Models with exponentially many patterns, routes, or shifts (Cutting Stock, VRP, Crew Rostering). |
8
+ | **Benders Decomposition** | [`master.solveBenders()`](#benders-decomposition-solvebenders) | Two-stage problems (Facility Location + Dispatch) or lazy constraints added on demand (TSP Subtour Elimination). |
9
+
10
+ Both helpers are also exported as standalone functions—`solveColumnGeneration({ master, ... })` and `solveBenders({ master, ... })`—alongside the `Model` methods.
9
11
 
10
12
  ---
11
13
 
12
14
  ## Column Generation (`solveColumnGeneration`)
13
15
 
14
- `master.solveColumnGeneration(options)` starts from a **Restricted Master Problem (RMP)** containing an initial feasible subset of columns and executes the column generation loop:
15
- 1. Solves the continuous LP relaxation of the master problem via `master.relax()`.
16
- 2. Invokes your `pricing` callback with the current dual shadow prices (`duals`, `getDual`).
17
- 3. Evaluates candidate columns (`ColumnProposal` or `ColumnProposal[]`), dynamically injecting those with improving reduced costs ($\bar{c} = \text{cost} - \sum_i \pi_i a_i < 0$ when minimizing).
18
- 4. Repeats until `pricing` returns `null` / `[]` or no column improves the objective beyond `reducedCostTolerance`.
19
- 5. Optionally solves the final master model as a MIP (`finalizeAsMIP: true`, the default) to obtain an integer solution over all generated columns.
16
+ Column Generation solves large linear and integer models whose variables (columns) are too numerous to enumerate upfront.
17
+ It splits the problem into two parts:
18
+
19
+ - **Restricted Master Problem (RMP)**: The master `Model`, initialized with a small feasible subset of columns.
20
+ - **Pricing Subproblem**: A callback (`pricing`) that reads the RMP's LP dual values and searches for a new column that improves the objective.
21
+
22
+ Each call to `master.solveColumnGeneration()` runs this loop:
23
+
24
+ 1. Solves the LP relaxation of the RMP (`master.relax()`) to obtain each constraint's **dual value** (shadow price).
25
+ 2. Passes those duals (`duals`, `getDual`) to your `pricing` callback.
26
+ 3. Checks whether each returned `ColumnProposal` improves the objective beyond `reducedCostTolerance` using its **reduced cost** (computed automatically as $\bar{c} = \text{cost} - \sum_i \pi_i a_i$ when `reducedCost` is omitted).
27
+ 4. Adds any improving column ($\bar{c} < -\varepsilon$ when minimizing, or $\bar{c} > \varepsilon$ when maximizing, with $\varepsilon$ = `reducedCostTolerance`). The loop repeats until `pricing` returns `null` / `[]`, no improving column remains, or `maxIterations` is reached.
28
+ 5. Optionally solves the final RMP with all generated columns as an integer program (`finalizeAsMIP: true`, enabled by default).
29
+
30
+ > [!IMPORTANT]
31
+ > **Preconditions & Guarantees**:
32
+ > - **Feasible & bounded initial RMP**: Starting columns (or penalized artificial slacks) must make the initial LP relaxation feasible and bounded so a finite optimum and valid duals exist.
33
+ > - **LP-dual solver required**: Requires HiGHS or GLPK; Pumpkin and Z3 do not produce LP duals.
34
+ > - **Price-and-Branch heuristic**: `finalizeAsMIP: true` solves one MIP over root-LP columns only—fast and practical, but not exact Branch-and-Price.
35
+
36
+ ### Example: Pricing with a Subproblem `Model`
20
37
 
21
- ### Pricing with a WaSHI Subproblem Model
38
+ In the Cutting Stock problem below, the RMP starts with three single-item patterns and the pricing subproblem solves a knapsack model to find better roll patterns.
39
+ Because `solveColumnGeneration()` checks reduced cost automatically, `pricing` can simply return the best pattern found by the subproblem:
22
40
 
23
41
  ```typescript
24
42
  import { Model, expr, minimize, maximize } from "@ohtaman/washi";
25
43
 
26
44
  const rollWidth = 100;
27
45
 
28
- // 1. Restricted Master Problem (RMP) with simple single-item initial patterns
46
+ // 1. Master problem: start with simple single-item cutting patterns
29
47
  const master = new Model("CuttingStockMaster");
30
48
  const pA = master.integer("init_A", { lb: 0 }); // 2 of A (width 45) per roll
31
49
  const pB = master.integer("init_B", { lb: 0 }); // 2 of B (width 36) per roll
@@ -39,16 +57,16 @@ const demandC = master.constraint(expr`6 * ${pC} >= 20`, "demand_C");
39
57
  // 2. Run Column Generation
40
58
  const result = await master.solveColumnGeneration({
41
59
  finalizeAsMIP: true,
42
- pricing: async () => {
43
- // Knapsack pricing subproblem: find a pattern maximizing total dual value
60
+ pricing: async ({ getDual }) => {
61
+ // Subproblem: find a valid roll pattern maximizing total dual value
44
62
  const sub = new Model("KnapsackPricing");
45
63
  const aA = sub.integer("a_A", { lb: 0, ub: 2 });
46
64
  const aB = sub.integer("a_B", { lb: 0, ub: 2 });
47
65
  const aC = sub.integer("a_C", { lb: 0, ub: 6 });
48
66
 
49
- const dualA = demandA.dual ?? 0;
50
- const dualB = demandB.dual ?? 0;
51
- const dualC = demandC.dual ?? 0;
67
+ const dualA = getDual(demandA);
68
+ const dualB = getDual(demandB);
69
+ const dualC = getDual(demandC);
52
70
  sub.objective(maximize(expr`${dualA} * ${aA} + ${dualB} * ${aB} + ${dualC} * ${aC}`));
53
71
  sub.constraint(expr`45 * ${aA} + 36 * ${aB} + 16 * ${aC} <= ${rollWidth}`);
54
72
 
@@ -71,9 +89,10 @@ console.log("Iterations:", result.iterations);
71
89
  console.log("Columns added:", result.columnsAdded);
72
90
  ```
73
91
 
74
- ### Pricing with a Custom Algorithm (`getDual`)
92
+ ### Example: Pricing with Plain TypeScript (`getDual`)
75
93
 
76
- Because `pricing` is a standard callback receiving `PricingContext`, you can also solve the pricing problem directly in TypeScript (e.g., via combinatorial search, dynamic programming, or shortest-path routines) instead of constructing a subproblem `Model`:
94
+ You do not need to build a subproblem `Model` inside `pricing`.
95
+ You can run any TypeScript algorithm—such as dynamic programming or a search loop—using `getDual(constraintName)`:
77
96
 
78
97
  ```typescript
79
98
  const customResult = await master.solveColumnGeneration({
@@ -84,7 +103,7 @@ const customResult = await master.solveColumnGeneration({
84
103
  const dB = getDual("demand_B");
85
104
  const dC = getDual("demand_C");
86
105
 
87
- // Search feasible patterns (45*aA + 36*aB + 16*aC <= rollWidth) for negative reduced cost (1 - dualSum < -1e-6)
106
+ // Search for a pattern with negative reduced cost (1 - dualSum < -1e-6)
88
107
  let bestDualSum = 1 + 1e-6;
89
108
  let best: { demand_A: number; demand_B: number; demand_C: number } | null = null;
90
109
  for (let aA = 0; 45 * aA <= rollWidth; aA++) {
@@ -107,11 +126,16 @@ const customResult = await master.solveColumnGeneration({
107
126
 
108
127
  ## Benders Decomposition (`solveBenders`)
109
128
 
110
- `master.solveBenders(options)` partitions a problem into a **Master Problem** (holding first-stage or complicating variables) and a **Subproblem** evaluated at each master candidate solution to generate **Optimality Cuts** or **Feasibility Cuts**.
129
+ `master.solveBenders(options)` splits a problem into a **master problem** for first-stage decisions and a **subproblem** for second-stage evaluation.
130
+ On each iteration, the subproblem evaluates the master's candidate solution and `solveBenders()` adds the resulting linear constraints (**cuts**) back to the master:
131
+
132
+ - **Optimality cut (`kind: "optimality"`)**: Tightens the master's estimate (`theta`) of the subproblem objective when the candidate is feasible but its true second-stage cost exceeds the estimate (for minimization; for maximization, tightens the upper bound when the true value is lower).
133
+ - **Feasibility cut (`kind: "feasibility"`)**: Rules out a master candidate when the subproblem is infeasible or violates a lazy structural rule (such as a disconnected TSP subtour).
111
134
 
112
135
  ### Automatic Cut Generation (`sub.link()`)
113
136
 
114
- Return a continuous LP subproblem `Model` from `subproblem` and declare cross-model constraints via `sub.link(...)`. WaSHI automatically manages the auxiliary cost estimator variable $\theta$, substitutes master candidate values, extracts subproblem duals, and adds Benders cuts until convergence:
137
+ Return a continuous LP subproblem `Model` from `subproblem` and connect it to master variables using `sub.link(...)`.
138
+ WaSHI manages the cost estimator `theta`, substitutes current master values, extracts duals from the LP subproblem, and adds optimality cuts until the bound gap falls within `gapTolerance`:
115
139
 
116
140
  ```typescript
117
141
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -121,11 +145,11 @@ const master = new Model("FacilityMaster");
121
145
  const y1 = master.binary("open_F1");
122
146
  const y2 = master.binary("open_F2");
123
147
 
124
- // Fixed opening costs (theta for operational subproblem cost is managed automatically)
148
+ // Fixed opening costs (operational cost estimator theta is added automatically)
125
149
  master.objective(minimize(expr`100 * ${y1} + 120 * ${y2}`));
126
150
  master.constraint(expr`50 * ${y1} + 60 * ${y2} >= 75`, "total_capacity_floor");
127
151
 
128
- // 2. Solve with automatic Benders cut generation
152
+ // 2. Solve with automatic Benders cuts
129
153
  const result = await master.solveBenders({
130
154
  gapTolerance: 1e-4,
131
155
  subproblem: () => {
@@ -157,15 +181,19 @@ const result = await master.solveBenders({
157
181
 
158
182
  console.log("Optimal total cost:", result.objectiveValue); // 390
159
183
  console.log("Cuts added:", result.cutsAdded);
160
- console.log("Open facilities:", result.values);
184
+ console.log("Master values:", result.values);
161
185
  ```
162
186
 
163
- > [!NOTE]
164
- > **`theta` Lower Bound for Negative Subproblem Objectives**: When `sub.link(...)` is used without an explicit `theta` variable, WaSHI injects `__benders_theta` with default `lb: 0` (assuming non-negative subproblem costs). If your subproblem objective can take negative values (e.g., rebate or profit terms), declare `const theta = master.continuous("theta", { lb: -1e6 })`, include `+ ${theta}` in `master.objective(...)`, and pass `{ theta }` in `solveBenders(options)`.
187
+ > [!IMPORTANT]
188
+ > **Preconditions for Automatic `sub.link()` Mode**:
189
+ > - **Optimality cuts only**: Throws if any master candidate makes the LP subproblem infeasible. Add master feasibility guards (like `total_capacity_floor`) or use manual `kind: "feasibility"` cuts.
190
+ > - **Explicit `theta` for `Maximize` or negative costs**: Auto-`theta` assumes a `Minimize` master with `lb: 0`. For `Maximize` or negative subproblem objectives, declare `theta` on `master` with appropriate bounds, include it in `master.objective()`, and pass `{ theta }`.
191
+ > - **LP-dual solver required**: Requires HiGHS or GLPK to solve the continuous LP subproblem.
165
192
 
166
193
  ### Manual Cut Generation (`BendersCut` / Lazy Constraints)
167
194
 
168
- For combinatorial separation (such as lazy subtour elimination) or custom analytical cuts, return one `BendersCut` object, an array `BendersCut[]`, or `null` when converged:
195
+ For custom cuts, feasibility cuts, or lazy constraints (such as TSP subtour elimination), return a `BendersCut`, a `BendersCut[]`, or `null` when converged.
196
+ When returning an optimality cut, pass the **total evaluated objective** (first-stage objective *excluding* `theta`, plus the actual subproblem objective) in `subproblemObjective` so WaSHI can compare it against the master's bound to compute the optimality gap:
169
197
 
170
198
  ```typescript
171
199
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -202,10 +230,11 @@ console.log(result.objectiveValue); // 70 (y = 1, theta = 30)
202
230
 
203
231
  ## Low-Level Primitives (Custom Loops)
204
232
 
205
- The two orchestrators above are built on four lower-level primitives that you can also call directly when writing your own cutting-plane or column-generation loops:
233
+ If you want to build your own decomposition loop instead of using the helpers above, WaSHI exposes four building blocks:
206
234
 
207
235
  ### 1. Constraint Duals (`c.dual`)
208
- After solving a continuous linear program (LP), read the shadow price (marginal impact on the objective per unit change in RHS) of each constraint:
236
+
237
+ After solving a continuous LP, read each constraint's dual value (shadow price):
209
238
 
210
239
  ```typescript
211
240
  import { Model, expr, maximize } from "@ohtaman/washi";
@@ -218,21 +247,22 @@ m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
218
247
  const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
219
248
  await m.solve();
220
249
 
221
- console.log(c.dual); // Dual value / shadow price
250
+ console.log(c.dual); // Dual value / shadow price
222
251
  console.log(m.solution?.duals.capacity); // Lookup by constraint name
223
252
  ```
224
253
 
225
254
  ### 2. Continuous LP Relaxation (`m.relax()`)
226
- `m.relax()` temporarily relaxes all `Integer` and `Binary` variables to continuous variables within their `[lb, ub]` bounds and solves the LP relaxation so constraint duals are populated:
255
+
256
+ `m.relax()` temporarily relaxes all `Integer` variables to continuous `[lb, ub]` and `Binary` variables to `[0, 1]`, then solves the LP so dual values are available:
227
257
 
228
258
  ```typescript
229
- // Solves the continuous LP relaxation and populates m.solution.duals
230
259
  const status = await m.relax();
231
260
  console.log("LP relaxation bound:", m.objectiveValue);
232
261
  ```
233
262
 
234
263
  ### 3. Dynamic Column Injection (`m.column()`)
235
- Create a new decision variable, set its objective coefficient, and attach its non-zero coefficients to existing named constraints in a single call:
264
+
265
+ Add a new variable, set its objective coefficient, and attach it to existing named constraints in one call:
236
266
 
237
267
  ```typescript
238
268
  const col = m.column({
@@ -246,22 +276,22 @@ const col = m.column({
246
276
  });
247
277
  ```
248
278
 
249
- ### 4. Dynamic Constraint Term Updates (`c.addTerm()` / `c.setTerm()`)
250
- Increment or overwrite the coefficient of a variable inside an existing linear constraint:
279
+ ### 4. Dynamic Constraint Updates (`c.addTerm()` / `c.setTerm()`)
280
+
281
+ Add to (introducing the variable if not yet present) or overwrite a variable's coefficient in an existing linear constraint:
251
282
 
252
283
  ```typescript
253
284
  const extra = m.continuous("extra", { lb: 0 });
254
285
  const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
255
286
 
256
- budget.addTerm(extra, 5); // Adds +5 * extra to the LHS
287
+ budget.addTerm(extra, 5); // Adds +5 * extra to the left-hand side
257
288
  budget.setTerm(extra, 0); // Setting 0 removes extra from the constraint
258
289
  ```
259
290
 
260
291
  ---
261
292
 
262
- ## Related Examples & Formulation Tips
293
+ ## Related Examples & Tips
263
294
 
264
- - **Full Decomposition Walkthroughs**:
265
- - [Vehicle Routing Problem (`solveColumnGeneration`)](../examples/vehicle-routing.md)
266
- - [Traveling Salesperson Problem (`solveBenders` lazy subtour elimination)](../examples/traveling-salesperson.md)
267
- - **Formulation Tips**: See [Formulation Patterns & Optimization Tips](./formulation-tips.md#_5-decomposition-formulation-tips) for Set Covering (`>= 1`) vs. Set Partitioning (`== 1`), Price-and-Branch (`finalizeAsMIP`), and multi-cut separation.
295
+ - [Vehicle Routing Problem (`solveColumnGeneration`)](../examples/vehicle-routing.md)
296
+ - [Traveling Salesperson Problem (`solveBenders` lazy subtour elimination)](../examples/traveling-salesperson.md)
297
+ - [Formulation Patterns & Tips](./formulation-tips.md#_5-decomposition-formulation-tips)