@ohtaman/washi 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -34
- package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
- package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
- package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
- package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
- package/dist/browser/solvers/highs.js +1414 -0
- package/dist/browser/washi.js +1090 -1473
- package/dist/browser/washi.min.js +4 -4
- package/dist/lib/solvers/glpk.js +34 -32
- package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
- package/dist/lib/solvers/highs.js +410 -0
- package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
- package/dist/lib/solvers/pumpkin-worker.js +1 -1
- package/dist/lib/solvers/pumpkin.js +247 -1146
- package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
- package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
- package/dist/lib/solvers/z3.js +125 -123
- package/dist/lib/washi.js +2426 -1340
- package/dist/types/index.d.ts +1 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +0 -1
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +6 -7
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/solvers/index.d.ts +2 -1
- package/dist/types/modeler/solvers/index.d.ts.map +1 -1
- package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
- package/docs/examples/diet-sensitivity.md +33 -14
- package/docs/examples/ecommerce-coupons.md +17 -9
- package/docs/examples/index.md +34 -30
- package/docs/examples/knapsack.md +11 -5
- package/docs/examples/portfolio-qp.md +21 -8
- package/docs/examples/production.md +10 -5
- package/docs/examples/project-scheduling.md +25 -12
- package/docs/examples/shift-scheduling.md +27 -19
- package/docs/examples/smt-security.md +27 -12
- package/docs/examples/transportation.md +23 -13
- package/docs/examples/traveling-salesperson.md +34 -22
- package/docs/examples/unsat-core.md +27 -15
- package/docs/examples/vehicle-routing.md +74 -28
- package/docs/getting-started/ai-agents.md +129 -90
- package/docs/getting-started/coding-agents.md +60 -41
- package/docs/getting-started/cross-origin.md +27 -14
- package/docs/getting-started/index.md +23 -16
- package/docs/getting-started/runtimes.md +70 -40
- package/docs/guide/constraint-programming.md +74 -44
- package/docs/guide/constraints.md +71 -39
- package/docs/guide/decomposition.md +72 -42
- package/docs/guide/expressions.md +79 -48
- package/docs/guide/formulation-tips.md +46 -27
- package/docs/guide/objectives.md +55 -31
- package/docs/guide/unsat-core.md +56 -53
- package/docs/guide/variables.md +61 -28
- package/docs/solvers/custom-solver.md +155 -119
- package/docs/solvers/glpk.md +58 -17
- package/docs/solvers/highs.md +115 -43
- package/docs/solvers/index.md +33 -26
- package/docs/solvers/pumpkin.md +71 -63
- package/docs/solvers/z3.md +63 -25
- package/llms-full.txt +1623 -953
- package/llms.txt +125 -93
- package/package.json +29 -22
- package/skills/washi/SKILL.md +43 -22
- package/README.ja.md +0 -248
- package/README.zh-CN.md +0 -248
- package/dist/browser/solvers/pumpkin.min.js +0 -1
- package/dist/lib/registry-dx7x4e5c.js +0 -1694
- /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
- /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
- /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
- /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
- /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
- /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
- /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
- /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
- /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
- /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
- /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
|
|
4
|
-
In WaSHI,
|
|
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
|
-
|
|
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
|
-
|
|
37
|
-
-
|
|
38
|
-
-
|
|
39
|
-
-
|
|
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
|
-
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
##
|
|
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
|
|
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)
|
|
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
|
|
97
|
-
console.log("Looked-up dual:", m.constraints.get("wood")?.dual); // number | null
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
> **
|
|
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`**:
|
|
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
|
|
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
|
|
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** |
|
|
182
|
-
| **Primary Use Case** | MIP optimization models
|
|
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
|
|
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
|
|
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
|
|
228
|
+
m.constraint(expr`${roomA} != ${roomB}`, "diff_room"); // native on Pumpkin/Z3, single-binary MIP on HiGHS/GLPK
|
|
201
229
|
```
|
|
202
230
|
|
|
203
|
-
Expressions
|
|
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
|
|
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 |
|
|
243
|
+
| Predicate | Meaning | HiGHS / GLPK | Pumpkin | Z3 |
|
|
212
244
|
| :--- | :--- | :--- | :--- | :--- |
|
|
213
|
-
| `distinct(...args)` |
|
|
214
|
-
| `disjoint(tasks)` |
|
|
215
|
-
| `cumulative(tasks, capacity)` |
|
|
216
|
-
| `allowed(vars, tuples)` |
|
|
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
|
|
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
|
|
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
|
-
|
|
|
5
|
+
| Method | WaSHI API | When to use |
|
|
6
6
|
| :--- | :--- | :--- |
|
|
7
|
-
| **Column Generation**
|
|
8
|
-
| **Benders Decomposition**
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
//
|
|
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
|
|
50
|
-
const dualB = demandB
|
|
51
|
-
const dualC = demandC
|
|
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
|
|
92
|
+
### Example: Pricing with Plain TypeScript (`getDual`)
|
|
75
93
|
|
|
76
|
-
|
|
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
|
|
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)`
|
|
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
|
|
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 (
|
|
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
|
|
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("
|
|
184
|
+
console.log("Master values:", result.values);
|
|
161
185
|
```
|
|
162
186
|
|
|
163
|
-
> [!
|
|
164
|
-
>
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
250
|
-
|
|
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
|
|
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 &
|
|
293
|
+
## Related Examples & Tips
|
|
263
294
|
|
|
264
|
-
-
|
|
265
|
-
|
|
266
|
-
|
|
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)
|