@ohtaman/washi 0.7.0 → 0.8.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.
- package/README.ja.md +58 -19
- package/README.md +58 -19
- package/README.zh-CN.md +58 -19
- package/THIRD_PARTY_LICENSES.md +34 -1
- package/dist/browser/__vite-browser-external-rTVKos2U.js +7 -0
- package/dist/browser/browser-runtime-AG5QFtKf.js +2021 -0
- package/dist/browser/highs-worker.js +26 -11
- package/dist/browser/highs.wasm +0 -0
- package/dist/browser/{loader-DewlSho8.js → loader-i3FnqMes.js} +183 -149
- package/dist/browser/solvers/glpk.js +289 -238
- package/dist/browser/solvers/glpk.min.js +1 -1
- package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
- package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
- package/dist/browser/solvers/pumpkin-worker.js +45 -0
- package/dist/browser/solvers/pumpkin.js +1777 -0
- package/dist/browser/solvers/pumpkin.min.js +1 -0
- package/dist/browser/solvers/pumpkin.wasm +0 -0
- package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/browser/solvers/z3.js +1600 -1335
- package/dist/browser/solvers/z3.min.js +2 -2
- package/dist/browser/washi.js +3374 -1377
- package/dist/browser/washi.min.js +5 -3
- package/dist/lib/__vite-browser-external-oLchLuMx.js +7 -0
- package/dist/lib/highs-browser-runtime.js +1846 -1618
- package/dist/lib/highs-runtime.js +16 -2
- package/dist/lib/highs-worker.js +26 -11
- package/dist/lib/highs.wasm +0 -0
- package/dist/lib/{loader-BZUQNvh4.js → loader-CDpPXN_F.js} +138 -116
- package/dist/lib/registry-dx7x4e5c.js +1694 -0
- package/dist/lib/rolldown-runtime-DtPi1Y-2.js +13 -0
- package/dist/lib/solvers/glpk.js +161 -121
- package/dist/lib/solvers/pumpkin-assets.js +1 -0
- package/dist/lib/solvers/pumpkin-loader-Ow74Fa1B.js +311 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
- package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
- package/dist/lib/solvers/pumpkin-worker.js +45 -0
- package/dist/lib/solvers/pumpkin.js +1767 -0
- package/dist/lib/solvers/pumpkin.wasm +0 -0
- package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/lib/solvers/z3.js +486 -306
- package/dist/lib/washi.js +2563 -1154
- package/dist/types/decomposition/benders.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/boolean-expr.d.ts +137 -29
- package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
- package/dist/types/modeler/constraint.d.ts +40 -4
- package/dist/types/modeler/constraint.d.ts.map +1 -1
- package/dist/types/modeler/expression.d.ts +129 -2
- package/dist/types/modeler/expression.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +4 -5
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/linearizer.d.ts +11 -2
- package/dist/types/modeler/linearizer.d.ts.map +1 -1
- package/dist/types/modeler/lp-writer.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +85 -124
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/parser.d.ts.map +1 -1
- package/dist/types/modeler/quad-expr.d.ts +8 -2
- package/dist/types/modeler/quad-expr.d.ts.map +1 -1
- package/dist/types/modeler/solution-validator.d.ts +12 -12
- package/dist/types/modeler/solution-validator.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
- package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
- package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
- package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
- package/dist/types/modeler/solvers/mock.d.ts +2 -3
- package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
- package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
- package/dist/types/modeler/solvers/types.d.ts +7 -9
- package/dist/types/modeler/solvers/types.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
- package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
- package/dist/types/modeler/types.d.ts +12 -15
- package/dist/types/modeler/types.d.ts.map +1 -1
- package/dist/types/modeler/validation.d.ts +26 -2
- package/dist/types/modeler/validation.d.ts.map +1 -1
- package/dist/types/modeler/variable.d.ts +9 -5
- package/dist/types/modeler/variable.d.ts.map +1 -1
- package/docs/examples/index.md +6 -1
- package/docs/examples/project-scheduling.md +106 -0
- package/docs/examples/shift-scheduling.md +3 -0
- package/docs/examples/smt-security.md +1 -0
- package/docs/examples/traveling-salesperson.md +1 -1
- package/docs/examples/unsat-core.md +3 -2
- package/docs/getting-started/ai-agents.md +94 -25
- package/docs/getting-started/coding-agents.md +158 -0
- package/docs/getting-started/cross-origin.md +2 -2
- package/docs/getting-started/index.md +40 -41
- package/docs/getting-started/runtimes.md +42 -18
- package/docs/guide/constraint-programming.md +141 -0
- package/docs/guide/constraints.md +64 -14
- package/docs/guide/decomposition.md +59 -59
- package/docs/guide/expressions.md +42 -10
- package/docs/guide/formulation-tips.md +6 -6
- package/docs/guide/objectives.md +65 -62
- package/docs/guide/unsat-core.md +36 -27
- package/docs/guide/variables.md +30 -17
- package/docs/solvers/custom-solver.md +18 -13
- package/docs/solvers/highs.md +18 -23
- package/docs/solvers/index.md +12 -6
- package/docs/solvers/pumpkin.md +163 -0
- package/docs/solvers/z3.md +2 -2
- package/llms-full.txt +944 -314
- package/llms.txt +43 -22
- package/package.json +38 -11
- package/skills/washi/SKILL.md +79 -27
- package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
- package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
- package/docs/ja/getting-started/ai-agents.md +0 -280
- package/docs/zh/getting-started/ai-agents.md +0 -280
|
@@ -8,7 +8,7 @@ WaSHI runs across JavaScript and TypeScript runtimes—from Node.js, Bun, and De
|
|
|
8
8
|
|
|
9
9
|
### Node.js
|
|
10
10
|
|
|
11
|
-
WaSHI supports Node.js (v18+) out of the box with standard ECMAScript Modules (ESM).
|
|
11
|
+
WaSHI supports Node.js (v18+) out of the box with standard ECMAScript Modules (ESM). Both the built-in HiGHS WebAssembly binary and the bundled Pumpkin WebAssembly binary (`@ohtaman/washi/solvers/pumpkin`) are loaded directly from the installed package:
|
|
12
12
|
|
|
13
13
|
```typescript
|
|
14
14
|
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
@@ -75,10 +75,10 @@ export async function runOptimization() {
|
|
|
75
75
|
}
|
|
76
76
|
```
|
|
77
77
|
|
|
78
|
-
Because both the modeler and solver run on WebAssembly, the static output of `vite build` (or your bundler's production build) can be deployed directly to **GitHub Pages, Cloudflare Pages, Vercel, or Netlify** with no backend server required. (
|
|
78
|
+
Because both the modeler and solver run on WebAssembly, the static output of `vite build` (or your bundler's production build) can be deployed directly to **GitHub Pages, Cloudflare Pages, Vercel, or Netlify** with no backend server required. (Bundled **HiGHS** and **Pumpkin**, as well as **GLPK**, require no special HTTP headers; if you use Z3 in the browser, see [Cross-Origin Isolation](./cross-origin.md).)
|
|
79
79
|
|
|
80
80
|
#### Background Web Worker Execution (Default)
|
|
81
|
-
In browsers, HiGHS automatically
|
|
81
|
+
In browsers, both **HiGHS** and **Pumpkin** automatically run inside dedicated **Web Workers** so LP/MIP/QP/CP solves never freeze the main UI thread, animations, or user input, while enabling real-time progress events (`onProgress`) and cancellation (`AbortSignal`).
|
|
82
82
|
|
|
83
83
|
If your environment prohibits Web Workers or you explicitly want main-thread execution, pass `useWorker: false`:
|
|
84
84
|
|
|
@@ -86,18 +86,20 @@ If your environment prohibits Web Workers or you explicitly want main-thread exe
|
|
|
86
86
|
await m.solve({ useWorker: false });
|
|
87
87
|
```
|
|
88
88
|
|
|
89
|
-
#### Customizing
|
|
90
|
-
By default, WaSHI resolves `highs.wasm` relative to the bundle (`new URL("./highs.wasm", import.meta.url)`). It **never** makes implicit requests to external CDNs (`jsdelivr`, `unpkg`, etc.).
|
|
89
|
+
#### Customizing WASM Asset URLs
|
|
90
|
+
By default, WaSHI resolves `highs.wasm` and `pumpkin.wasm` relative to the bundle (`new URL("./highs.wasm", import.meta.url)` / `new URL("./pumpkin.wasm", import.meta.url)`). It **never** makes implicit requests to external CDNs (`jsdelivr`, `unpkg`, etc.).
|
|
91
91
|
|
|
92
|
-
If your bundler or static server hosts `.wasm` files under a custom path, configure the URL globally or per solve:
|
|
92
|
+
If your bundler or static server hosts `.wasm` files under a custom path, configure the URL globally or per solve/check:
|
|
93
93
|
|
|
94
94
|
```typescript
|
|
95
95
|
import { setHighsWasmUrl } from "@ohtaman/washi";
|
|
96
|
+
import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
|
|
96
97
|
|
|
97
98
|
// Option A: Configure globally before solving
|
|
98
99
|
setHighsWasmUrl("/assets/wasm/highs.wasm");
|
|
100
|
+
setPumpkinWasmUrl("/assets/wasm/pumpkin.wasm");
|
|
99
101
|
|
|
100
|
-
// Option B: Configure per solve call
|
|
102
|
+
// Option B: Configure per solve / check call
|
|
101
103
|
await m.solve({ wasmUrl: "/assets/wasm/highs.wasm" });
|
|
102
104
|
```
|
|
103
105
|
|
|
@@ -133,6 +135,24 @@ export default function OptimizerComponent() {
|
|
|
133
135
|
}
|
|
134
136
|
```
|
|
135
137
|
|
|
138
|
+
### Desktop & Mobile WebView Apps (Tauri / Capacitor / PWA)
|
|
139
|
+
|
|
140
|
+
Standard Vite frontends bundle and run **HiGHS** and **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`) completely offline inside **Tauri** (`tauri://localhost` / `http://tauri.localhost`), **Capacitor** mobile WebViews, and offline **PWAs** with no native C/C++ solver compilation.
|
|
141
|
+
|
|
142
|
+
In `tauri.conf.json`, allow WebAssembly compilation (`'wasm-unsafe-eval'` in `script-src`) and Web Workers (`worker-src 'self' blob:`), or pass `{ useWorker: false }`:
|
|
143
|
+
|
|
144
|
+
```json
|
|
145
|
+
{
|
|
146
|
+
"app": {
|
|
147
|
+
"security": {
|
|
148
|
+
"csp": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:"
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Bundled **HiGHS** and **Pumpkin** are recommended over **Z3** in desktop and mobile WebViews because they do not require `SharedArrayBuffer` or `COOP`/`COEP` headers.
|
|
155
|
+
|
|
136
156
|
---
|
|
137
157
|
|
|
138
158
|
## 📦 Browser ESM (`<script type="module">`)
|
|
@@ -142,10 +162,11 @@ Without a bundler, you can import the pre-built browser ESM module directly from
|
|
|
142
162
|
```html
|
|
143
163
|
<script type="module">
|
|
144
164
|
// From an npm CDN (or "./dist/browser/washi.js" when self-hosted):
|
|
145
|
-
import { Model, expr, maximize } from "https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
146
|
-
//
|
|
147
|
-
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
148
|
-
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
165
|
+
import { Model, expr, maximize } from "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.js";
|
|
166
|
+
// Bundled / optional solver plugins:
|
|
167
|
+
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin.js";
|
|
168
|
+
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/glpk.js";
|
|
169
|
+
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/z3.js";
|
|
149
170
|
|
|
150
171
|
const m = new Model("BrowserESM");
|
|
151
172
|
const x = m.integer("x", { lb: 0, ub: 100 });
|
|
@@ -180,10 +201,11 @@ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a stan
|
|
|
180
201
|
<pre id="output">Solving...</pre>
|
|
181
202
|
|
|
182
203
|
<!-- Core WaSHI + HiGHS (MIT) via CDN (or "./dist/browser/washi.min.js" when self-hosted) -->
|
|
183
|
-
<script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
184
|
-
<!--
|
|
185
|
-
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
186
|
-
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
204
|
+
<script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.min.js"></script>
|
|
205
|
+
<!-- Bundled / optional plugins (auto-register on window.Washi): -->
|
|
206
|
+
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin.min.js"></script> -->
|
|
207
|
+
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/glpk.min.js"></script> -->
|
|
208
|
+
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/z3.min.js"></script> -->
|
|
187
209
|
|
|
188
210
|
<script>
|
|
189
211
|
(async () => {
|
|
@@ -211,7 +233,8 @@ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a stan
|
|
|
211
233
|
```
|
|
212
234
|
|
|
213
235
|
> [!NOTE]
|
|
214
|
-
>
|
|
236
|
+
> - **Cross-origin CDN workers**: On standard web origins (`https://` / `http://`), browsers block direct `new Worker("https://cdn...")`, so WaSHI automatically bridges cross-origin workers via a lightweight ES module `Blob` bootstrap (`import "https://..."`).
|
|
237
|
+
> - **Opening local `.html` files directly (`file://`)**: CDN-loaded `washi.min.js` and `solvers/pumpkin.min.js` work directly when opening a local `.html` via `file://` (double-click, no local server)—on opaque effective origins (`window.origin === "null"`, such as `file:` URLs or `sandbox="allow-scripts"` `<iframe>` embeds without `allow-same-origin`), WaSHI automatically runs HiGHS and Pumpkin on the main thread when `useWorker` is omitted. Self-hosted local `.wasm` files (blocked on `file://` by browser `fetch()` CORS rules) and **Z3** (`COOP`/`COEP`) require serving over `http://` or `https://`.
|
|
215
238
|
|
|
216
239
|
---
|
|
217
240
|
|
|
@@ -221,12 +244,13 @@ WaSHI never phones home or falls back to public CDNs. To self-host in an air-gap
|
|
|
221
244
|
|
|
222
245
|
1. **Copy Static Assets**: Serve the files from `node_modules/@ohtaman/washi/dist/browser/` on your own origin:
|
|
223
246
|
- `washi.js` / `washi.min.js`, `highs.wasm`, and `highs-worker.js`
|
|
247
|
+
- Bundled Pumpkin: `solvers/pumpkin.js` / `solvers/pumpkin.min.js`, `solvers/pumpkin.wasm`, `solvers/pumpkin-worker.js` (plus `solvers/pumpkin-*.js` chunks)
|
|
224
248
|
- Optional GLPK: `solvers/glpk.js` / `solvers/glpk.min.js`
|
|
225
249
|
- Optional Z3: `solvers/z3.js` / `solvers/z3.min.js`, `solvers/z3-built.js`, `solvers/z3-built.wasm`
|
|
226
250
|
2. **Content Security Policy (CSP) Headers**:
|
|
227
251
|
- Allow WebAssembly compilation (`'wasm-unsafe-eval'` in `script-src`).
|
|
228
252
|
- If using the default Web Worker or cross-origin Blob worker bootstrap, allow `worker-src 'self' blob:;`.
|
|
229
|
-
- If `blob:` workers are prohibited by policy, either serve `highs-worker.js` from `'self'` or run on the main thread with `await m.solve({ useWorker: false })`.
|
|
253
|
+
- If `blob:` workers are prohibited by policy, either serve `highs-worker.js` / `solvers/pumpkin-worker.js` from `'self'` or run on the main thread with `await m.solve({ useWorker: false })`.
|
|
230
254
|
3. **Cross-Origin Isolation (Z3 Only)**:
|
|
231
|
-
- HiGHS and GLPK run in standard browser contexts without special headers.
|
|
255
|
+
- HiGHS, Pumpkin, and GLPK run in standard browser contexts without special headers.
|
|
232
256
|
- Z3 WASM uses pthreads + `SharedArrayBuffer` and requires `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (`credentialless` works in Chromium/Firefox, whereas Safari requires `require-corp`). See the [Cross-Origin Isolation Guide](./cross-origin.md) for setup details.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# Constraint Programming (CP) Modeling
|
|
2
|
+
|
|
3
|
+
WaSHI allows you to formulate both **Mathematical Optimization (LP / MIP / Convex QP)** and **Constraint Programming (CP)** problems through the same TypeScript algebraic modeling API (`Model`, `expr`, `sum`, `dot`). When you solve with bundled **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`), global predicates (`distinct`, `disjoint`, `cumulative`, `allowed`) and piecewise/element primitives (`max`, `min`, `abs`, `at`) run on native Lazy Clause Generation (LCG) propagators instead of Big-M or time-indexed 0-1 MIP linearizations.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. MIP vs. CP Modeling Mindset
|
|
8
|
+
|
|
9
|
+
In **MIP (HiGHS / GLPK)**, combinatorial decisions are typically encoded with large matrices of 0-1 binary variables $x_{i,t} \in \{0, 1\}$ and Big-M inequalities so a simplex/branch-and-cut solver can tighten continuous LP relaxations.
|
|
10
|
+
|
|
11
|
+
In **CP (Pumpkin)**, you model **what** each entity chooses directly using finite-domain integers (`m.integer(keys, { lb, ub })`) and declarative **global constraints**:
|
|
12
|
+
|
|
13
|
+
| Modeling Dimension | MIP Pattern (`HiGHS` / `GLPK`) | CP Pattern (`Pumpkin`) | SMT (`Z3`) |
|
|
14
|
+
| :--- | :--- | :--- | :--- |
|
|
15
|
+
| **Start times / Slots** | Time-indexed binaries $x_{i,t}$ or pairwise Big-M precedence binaries | Bounded integer start variables `start[i]` in `[0, H]` | Unbounded/bounded integer or real variables |
|
|
16
|
+
| **Machine / Worker capacity** | $\sum_i d_i x_{i,t} \le C$ for every discrete time slot $t$ | Single horizon-independent `cumulative(tasks, C)` | Event-point load formulas |
|
|
17
|
+
| **Unary non-overlap** | Pairwise Big-M disjunctions ($y_{ij} \in \{0,1\}$) | Native `disjoint(tasks)` edge-finding propagator | Pairwise `Or` disjunctions |
|
|
18
|
+
| **Permutation / Matching** | Doubly stochastic binary assignment matrix $x_{i,j} \in \{0, 1\}$ | Integer slot variables `machine[i]` in `[0, N-1]` + `distinct(machine)` | Native `ctx.Distinct` |
|
|
19
|
+
| **Cost / Tuple lookup** | $\sum_k c_k b_k$ with $\sum_k b_k = 1$ convex-hull binaries | Native `at(costs, indexVar)` & `allowed` / `not(allowed)` tables | Nested `If` expressions |
|
|
20
|
+
| **When to choose** | Continuous flows, blending, LP duals/shadow prices, quadratic objectives (`QuadExpr`), tight LP relaxations | Scheduling horizons, cumulative/disjunctive resources, permutations, table compatibility, zero-`COOP`/`COEP` `unsatCore` | Continuous non-integer logic (`Continuous` inside `not`/`implies`), formal proofs |
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 2. Interval & Resource Scheduling (`disjoint`, `cumulative`, `max`)
|
|
25
|
+
|
|
26
|
+
Time-indexed MIP formulations create $O(|T| \cdot H)$ binary variables and capacity rows, which quickly blows up when scheduling horizons grow (WaSHI's MIP lowering rejects horizons exceeding 5,000 time steps or 25,000 pulse variables and recommends `{ solver: "pumpkin" }`).
|
|
27
|
+
|
|
28
|
+
In CP, each task is just **one bounded integer variable** `start[task]` paired with `disjoint` (exclusive unary machines) and `cumulative` (renewable worker/power pools). Because interval propagators reason directly about earliest/latest start intervals and energetic overload, scheduling models stay compact regardless of horizon granularity.
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { Model, expr, disjoint, cumulative, max, minimize } from "@ohtaman/washi";
|
|
32
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
33
|
+
|
|
34
|
+
const m = new Model("IntervalSchedulingCP", { solver: "pumpkin" });
|
|
35
|
+
const tasks = ["prep", "mill", "drill", "coat"] as const;
|
|
36
|
+
const duration = { prep: 3, mill: 4, drill: 3, coat: 2 };
|
|
37
|
+
const workers = { prep: 1, mill: 1, drill: 1, coat: 2 };
|
|
38
|
+
const start = m.integer(tasks, { lb: 0, ub: 20, prefix: "start" });
|
|
39
|
+
|
|
40
|
+
// Precedence rules: prep -> (mill, drill) -> coat
|
|
41
|
+
m.constraint(expr`${start.prep} + 3 <= ${start.mill}`, "mill_after_prep");
|
|
42
|
+
m.constraint(expr`${start.prep} + 3 <= ${start.drill}`, "drill_after_prep");
|
|
43
|
+
m.constraint(expr`${start.mill} + 4 <= ${start.coat}`, "coat_after_mill");
|
|
44
|
+
m.constraint(expr`${start.drill} + 3 <= ${start.coat}`, "coat_after_drill");
|
|
45
|
+
|
|
46
|
+
// Single CNC spindle shared between mill and drill
|
|
47
|
+
m.constraint(
|
|
48
|
+
disjoint([
|
|
49
|
+
{ start: start.mill, duration: duration.mill },
|
|
50
|
+
{ start: start.drill, duration: duration.drill },
|
|
51
|
+
]),
|
|
52
|
+
"single_cnc"
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
// At most 2 operators working simultaneously across all tasks
|
|
56
|
+
m.constraint(
|
|
57
|
+
cumulative(
|
|
58
|
+
tasks.map((t) => ({ start: start[t], duration: duration[t], demand: workers[t] })),
|
|
59
|
+
2
|
|
60
|
+
),
|
|
61
|
+
"operator_pool"
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
m.objective(minimize(max(tasks.map((t) => expr`${start[t]} + ${duration[t]}`))));
|
|
65
|
+
await m.solve();
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
See the full runnable project scheduling walkthrough in [Resource-Constrained Project Scheduling (RCPSP)](../examples/project-scheduling.md).
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 3. Combinatorial Assignment, Table Rules & Element Lookup (`distinct`, `allowed`, `at`)
|
|
73
|
+
|
|
74
|
+
Instead of an $N \times M$ binary matrix $x_{j,m} \in \{0, 1\}$, assign each job a single bounded integer variable `machine[job]` with domain $\{0, \dots, M-1\}$:
|
|
75
|
+
|
|
76
|
+
- **`distinct(machine)`**: Forces every job onto a separate machine using Pumpkin's `all_different` propagator.
|
|
77
|
+
- **`allowed(vars, tuples)` / `not(allowed(vars, tuples))`**: Encodes arbitrary compatibility or incompatibility rules between discrete decisions without manual Big-M algebra.
|
|
78
|
+
- **`at(costs, indexVar)`**: Looks up a numeric cost from `costs[indexVar]` using Pumpkin's native `element` propagator—avoiding $M$ selector binary variables per job.
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { Model, expr, distinct, allowed, not, at, minimize } from "@ohtaman/washi";
|
|
82
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
83
|
+
|
|
84
|
+
const m = new Model("MachineAssignmentCP", { solver: "pumpkin" });
|
|
85
|
+
const jobs = ["jobA", "jobB", "jobC"] as const;
|
|
86
|
+
const machine = m.integer(jobs, { lb: 0, ub: 2, prefix: "machine" });
|
|
87
|
+
|
|
88
|
+
const costA = [5, 10, 40];
|
|
89
|
+
const costB = [20, 15, 30];
|
|
90
|
+
const costC = [45, 30, 25];
|
|
91
|
+
|
|
92
|
+
// Each job runs on a distinct machine (0, 1, or 2)
|
|
93
|
+
m.constraint(distinct(machine), "one_job_per_machine");
|
|
94
|
+
|
|
95
|
+
// Safety interlock: Job A on Machine 0 cannot pair with Job B on Machine 1
|
|
96
|
+
m.constraint(not(allowed([machine.jobA, machine.jobB], [[0, 1]])), "interlock_pair");
|
|
97
|
+
|
|
98
|
+
// Variable-indexed cost lookup via 0-based Element primitive at(table, indexVar)
|
|
99
|
+
m.objective(
|
|
100
|
+
minimize(
|
|
101
|
+
expr`at(${costA}, ${machine.jobA}) + at(${costB}, ${machine.jobB}) + at(${costC}, ${machine.jobC})`
|
|
102
|
+
)
|
|
103
|
+
);
|
|
104
|
+
await m.solve();
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## 4. Domain Tightening, Symmetry Breaking & Conflict Diagnosis
|
|
110
|
+
|
|
111
|
+
### Keep Integer Domains Finite and Tight
|
|
112
|
+
Pumpkin uses signed 32-bit integer propagators and rejects `Continuous`, fractional, or unbounded variables (`lb: -Infinity` or `ub: Infinity`). Every `m.integer()` variable on Pumpkin must have finite integer `[lb, ub]` within $[-(2^{30} - 1),\, 2^{30} - 1]$ (see [Pumpkin Domain Preconditions](../solvers/pumpkin.md#domain-api-preconditions)). Tight horizons directly shrink propagator domains and accelerate conflict learning.
|
|
113
|
+
|
|
114
|
+
### Break Permutation Symmetry with Strict Ordering (`<`)
|
|
115
|
+
When selecting $k$ items into $k$ interchangeable slots (`slot[0]`, ..., `slot[k-1]`), all $k!$ permutations have identical cost, forcing a branch-and-bound or CP search tree to explore symmetric duplicates. Adding strict inequality ordering `slot[0] < slot[1] < ...` simultaneously enforces all-different and collapses all $k!$ permutations into a single canonical sequence:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import { Model, expr, at, minimize } from "@ohtaman/washi";
|
|
119
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
120
|
+
|
|
121
|
+
const m = new Model("SymmetryBreakingCP", { solver: "pumpkin" });
|
|
122
|
+
const latencyMs = [600, 380, 420, 470, 550];
|
|
123
|
+
const slot = m.integer(3, { lb: 0, ub: 4, prefix: "slot" });
|
|
124
|
+
|
|
125
|
+
// Strict ascending order enforces all-different AND eliminates 3! = 6 permutation symmetries
|
|
126
|
+
m.constraint([
|
|
127
|
+
expr`${slot[0]} < ${slot[1]}`,
|
|
128
|
+
expr`${slot[1]} < ${slot[2]}`,
|
|
129
|
+
]);
|
|
130
|
+
|
|
131
|
+
m.objective(
|
|
132
|
+
minimize(
|
|
133
|
+
expr`at(${latencyMs}, ${slot[0]}) + at(${latencyMs}, ${slot[1]}) + at(${latencyMs}, ${slot[2]})`
|
|
134
|
+
)
|
|
135
|
+
);
|
|
136
|
+
await m.solve();
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Warm Starts & Zero-`COOP`/`COEP` Conflict Diagnosis
|
|
140
|
+
- **Warm Starts (`initialValue`)**: Provide feasible domain hints via `{ initialValue: val }` on `m.integer()` or `m.binary()` to seed Pumpkin's value selection (`WarmStart` brancher).
|
|
141
|
+
- **Conflict Diagnosis (`m.check()`)**: If a CP schedule or rule set returns `"Infeasible"`, calling `await m.check({ solver: "pumpkin" })` (without changing any constraints or adding `COOP`/`COEP` headers in browsers) extracts `unsatCore` / `conflicts` identifying which named precedence, resource, or deadline rules collide—see [Conflict Diagnosis (`unsatCore`)](./unsat-core.md).
|
|
@@ -36,6 +36,7 @@ m.constraint(expr`${x} + ${y} == 30`, "exact_quota");
|
|
|
36
36
|
- `<=`: Upper bound constraint
|
|
37
37
|
- `>=`: Lower bound constraint
|
|
38
38
|
- `==` or `=`: Exact equality constraint
|
|
39
|
+
- `<`, `>`, `!=`: Discrete strict inequality / disequality constraints (integer-valued expressions only; see [Discrete Comparisons](#discrete-comparisons))
|
|
39
40
|
|
|
40
41
|
### Batch Registration
|
|
41
42
|
Pass an array of constraints to `m.constraint([...])` to register them transactionally in a single call:
|
|
@@ -56,8 +57,8 @@ m.constraint(expr`${x} + ${y} <= 100`, "budget_cap");
|
|
|
56
57
|
|
|
57
58
|
### Why Name Constraints?
|
|
58
59
|
1. **Model Inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain these descriptive names (sanitized if needed) so you can inspect the generated formulation.
|
|
59
|
-
2. **Conflict Diagnosis (`conflicts` / `unsatCore`)**: When constraints contradict each other, `m.check()` returns the conflicting constraint names (via built-in HiGHS elastic relaxation or Z3 `unsatCore`).
|
|
60
|
-
3. **Direct Lookup (`m.
|
|
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.
|
|
61
62
|
|
|
62
63
|
---
|
|
63
64
|
|
|
@@ -82,6 +83,23 @@ m.constraint(expr`dot(${weights}, ${selected}) <= 25`, "capacity_limit");
|
|
|
82
83
|
|
|
83
84
|
---
|
|
84
85
|
|
|
86
|
+
## Dual Values, Shadow Prices & Lookups
|
|
87
|
+
|
|
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()`):
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
const woodConstraint = m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
|
|
92
|
+
|
|
93
|
+
await m.solve();
|
|
94
|
+
|
|
95
|
+
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)
|
|
98
|
+
console.log("Total constraints:", m.constraints.size);
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
85
103
|
## Conditional / Indicator Constraints (`m.indicator`)
|
|
86
104
|
|
|
87
105
|
When a linear constraint should only take effect when a binary decision variable (`m.binary()`) equals `1` (or `0`), use `m.indicator()`:
|
|
@@ -107,6 +125,9 @@ When `options.M` is omitted, WaSHI automatically derives a minimal valid Big-M v
|
|
|
107
125
|
|
|
108
126
|
If any referenced variable lacks the required finite bound, `m.indicator()` throws an error prompting for finite bounds or an explicit `options.M`.
|
|
109
127
|
|
|
128
|
+
> [!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.
|
|
130
|
+
|
|
110
131
|
### Explicit `M` Override
|
|
111
132
|
|
|
112
133
|
You can override the derived Big-M by passing `{ M: number }`:
|
|
@@ -125,7 +146,7 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
|
|
|
125
146
|
|
|
126
147
|
## Propositional Logic & SMT Constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`)
|
|
127
148
|
|
|
128
|
-
WaSHI provides first-class logical operators to combine propositional boolean variables (`m.bool()`) and linear constraints (`Constraint`). Logical formulas are solved natively by
|
|
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**:
|
|
129
150
|
|
|
130
151
|
```typescript
|
|
131
152
|
import { Model, expr, and, or, not, implies, xor } from "@ohtaman/washi";
|
|
@@ -149,35 +170,64 @@ m.constraint(
|
|
|
149
170
|
m.constraint(and(or(isAdmin, hasMfa), not(xor(isAdmin, hasMfa))), "policy");
|
|
150
171
|
```
|
|
151
172
|
|
|
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)`.
|
|
174
|
+
|
|
152
175
|
### Choosing Between `m.indicator()` and `implies()`
|
|
153
176
|
|
|
154
177
|
| Feature | `m.indicator(binVar, constraint, opts)` | `implies(a, b)` / `a.implies(b)` |
|
|
155
178
|
| :--- | :--- | :--- |
|
|
156
179
|
| **Trigger variable** | Numeric `Binary` variable (`m.binary()`) | `BoolVar` (`m.bool()`), `BoolOp`, or `Constraint` |
|
|
157
180
|
| **Consequent** | Linear `Constraint` (`<=`, `>=`, `==`) | `BoolVar`, `BoolOp`, or linear `Constraint` |
|
|
158
|
-
| **Target Solvers** | **All MIP/LP solvers** (HiGHS, GLPK
|
|
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) |
|
|
159
182
|
| **Primary Use Case** | MIP optimization models with arithmetic binary variables (`m.solve()`) | Logical rule systems and SMT feasibility (`m.check()`) |
|
|
160
183
|
|
|
161
184
|
> [!NOTE]
|
|
162
|
-
> **
|
|
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.
|
|
163
186
|
|
|
164
187
|
---
|
|
165
188
|
|
|
166
|
-
##
|
|
189
|
+
## Discrete Comparisons (`!=`, `<`, `>`)
|
|
167
190
|
|
|
168
|
-
|
|
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):
|
|
169
192
|
|
|
170
193
|
```typescript
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
194
|
+
const rankA = m.integer("rankA", { lb: 1, ub: 4 });
|
|
195
|
+
const rankB = m.integer("rankB", { lb: 1, ub: 4 });
|
|
196
|
+
const roomA = m.integer("roomA", { lb: 1, ub: 3 });
|
|
197
|
+
const roomB = m.integer("roomB", { lb: 1, ub: 3 });
|
|
174
198
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
console.log("Total linear constraints:", m.numConstrs);
|
|
199
|
+
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
|
|
178
201
|
```
|
|
179
202
|
|
|
180
|
-
|
|
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.
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## CP Global Constraints (`distinct`, `disjoint`, `cumulative`, `allowed`)
|
|
208
|
+
|
|
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).
|
|
210
|
+
|
|
211
|
+
| Predicate | Semantics | HiGHS / GLPK | Pumpkin | Z3 |
|
|
212
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
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` |
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
import { Model, expr, distinct, disjoint, cumulative, allowed, not, minimize } from "@ohtaman/washi";
|
|
220
|
+
|
|
221
|
+
const m = new Model("ScheduleAndAssign");
|
|
222
|
+
const s = m.integer(2, { lb: 0, ub: 10, prefix: "s" });
|
|
223
|
+
const room = m.integer(2, { lb: 1, ub: 2, prefix: "room" });
|
|
224
|
+
|
|
225
|
+
m.constraint(distinct(room), "unique_rooms");
|
|
226
|
+
m.constraint(disjoint([{ start: s[0], duration: 4 }, { start: s[1], duration: 3 }]), "machine_1");
|
|
227
|
+
m.constraint(not(allowed([room[0], room[1]], [[1, 2]])), "forbid_1_2");
|
|
228
|
+
m.constraint(cumulative([{ start: s[0], duration: 4, demand: 1 }, { start: s[1], duration: 3, demand: 1 }], 2), "workers");
|
|
229
|
+
m.objective(minimize(expr`${s[0]} + ${s[1]}`));
|
|
230
|
+
```
|
|
181
231
|
|
|
182
232
|
> [!TIP]
|
|
183
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).
|
|
@@ -9,65 +9,6 @@ When monolithic Mixed-Integer Programming (MIP) models have exponentially many c
|
|
|
9
9
|
|
|
10
10
|
---
|
|
11
11
|
|
|
12
|
-
## Foundational Primitives
|
|
13
|
-
|
|
14
|
-
WaSHI exposes four lower-level primitives used internally by the decomposition orchestrators and available directly for custom algorithms:
|
|
15
|
-
|
|
16
|
-
### 1. Constraint Duals (`c.dual`)
|
|
17
|
-
After solving a continuous linear program (LP), read the shadow price (marginal impact on the objective per unit change in RHS) of each constraint:
|
|
18
|
-
|
|
19
|
-
```typescript
|
|
20
|
-
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
21
|
-
|
|
22
|
-
const m = new Model();
|
|
23
|
-
const x = m.continuous("x", { lb: 0 });
|
|
24
|
-
const y = m.continuous("y", { lb: 0 });
|
|
25
|
-
|
|
26
|
-
m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
|
|
27
|
-
const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
|
|
28
|
-
await m.solve();
|
|
29
|
-
|
|
30
|
-
console.log(c.dual); // Dual value / shadow price
|
|
31
|
-
console.log(m.solution?.duals.capacity); // Lookup by constraint name
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
### 2. Continuous LP Relaxation (`m.relax()`)
|
|
35
|
-
`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:
|
|
36
|
-
|
|
37
|
-
```typescript
|
|
38
|
-
// Solves the continuous LP relaxation and populates m.solution.duals
|
|
39
|
-
const status = await m.relax();
|
|
40
|
-
console.log("LP relaxation bound:", m.objectiveValue);
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
### 3. Dynamic Column Injection (`m.addColumn()`)
|
|
44
|
-
Create a new decision variable, set its objective coefficient, and attach its non-zero coefficients to existing named constraints in a single call:
|
|
45
|
-
|
|
46
|
-
```typescript
|
|
47
|
-
const col = m.addColumn({
|
|
48
|
-
name: "pattern_1",
|
|
49
|
-
type: "Integer", // or "Continuous" / "Binary"
|
|
50
|
-
lb: 0,
|
|
51
|
-
cost: 1, // Objective coefficient
|
|
52
|
-
coefficients: {
|
|
53
|
-
capacity: 2,
|
|
54
|
-
},
|
|
55
|
-
});
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
### 4. Dynamic Constraint Term Updates (`c.addTerm()` / `c.setTerm()`)
|
|
59
|
-
Increment or overwrite the coefficient of a variable inside an existing linear constraint:
|
|
60
|
-
|
|
61
|
-
```typescript
|
|
62
|
-
const extra = m.continuous("extra", { lb: 0 });
|
|
63
|
-
const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
|
|
64
|
-
|
|
65
|
-
budget.addTerm(extra, 5); // Adds +5 * extra to the LHS
|
|
66
|
-
budget.setTerm(extra, 0); // Setting 0 removes extra from the constraint
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
---
|
|
70
|
-
|
|
71
12
|
## Column Generation (`solveColumnGeneration`)
|
|
72
13
|
|
|
73
14
|
`master.solveColumnGeneration(options)` starts from a **Restricted Master Problem (RMP)** containing an initial feasible subset of columns and executes the column generation loop:
|
|
@@ -259,6 +200,65 @@ console.log(result.objectiveValue); // 70 (y = 1, theta = 30)
|
|
|
259
200
|
|
|
260
201
|
---
|
|
261
202
|
|
|
203
|
+
## Low-Level Primitives (Custom Loops)
|
|
204
|
+
|
|
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:
|
|
206
|
+
|
|
207
|
+
### 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:
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
212
|
+
|
|
213
|
+
const m = new Model();
|
|
214
|
+
const x = m.continuous("x", { lb: 0 });
|
|
215
|
+
const y = m.continuous("y", { lb: 0 });
|
|
216
|
+
|
|
217
|
+
m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
|
|
218
|
+
const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
|
|
219
|
+
await m.solve();
|
|
220
|
+
|
|
221
|
+
console.log(c.dual); // Dual value / shadow price
|
|
222
|
+
console.log(m.solution?.duals.capacity); // Lookup by constraint name
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### 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:
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
// Solves the continuous LP relaxation and populates m.solution.duals
|
|
230
|
+
const status = await m.relax();
|
|
231
|
+
console.log("LP relaxation bound:", m.objectiveValue);
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### 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:
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
const col = m.column({
|
|
239
|
+
name: "pattern_1",
|
|
240
|
+
type: "Integer", // or "Continuous" / "Binary"
|
|
241
|
+
lb: 0,
|
|
242
|
+
cost: 1, // Objective coefficient
|
|
243
|
+
coefficients: {
|
|
244
|
+
capacity: 2,
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
### 4. Dynamic Constraint Term Updates (`c.addTerm()` / `c.setTerm()`)
|
|
250
|
+
Increment or overwrite the coefficient of a variable inside an existing linear constraint:
|
|
251
|
+
|
|
252
|
+
```typescript
|
|
253
|
+
const extra = m.continuous("extra", { lb: 0 });
|
|
254
|
+
const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
|
|
255
|
+
|
|
256
|
+
budget.addTerm(extra, 5); // Adds +5 * extra to the LHS
|
|
257
|
+
budget.setTerm(extra, 0); // Setting 0 removes extra from the constraint
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
---
|
|
261
|
+
|
|
262
262
|
## Related Examples & Formulation Tips
|
|
263
263
|
|
|
264
264
|
- **Full Decomposition Walkthroughs**:
|
|
@@ -43,6 +43,7 @@ const balanceConstraint = expr`${x} + 2 * ${y} <= 40`;
|
|
|
43
43
|
- **Unary Plus & Negation**: `-${x} + 10`, `+${x}`
|
|
44
44
|
- **Parentheses**: `2 * (${x} + ${y})`
|
|
45
45
|
- **Aggregations (`sum` & `dot`)**: `sum(${xVec}) <= 100`, `dot(${costs}, ${xVec})`, `sum(${rows}, ${(r) => grid[r][col]})`
|
|
46
|
+
- **Piecewise-Linear & Element Functions (`max`, `min`, `abs`, `at`)**: `max(${xVec}) <= 15`, `sum(abs(${w} - ${target}))`, `at(${costs}, ${idx})` (see [Piecewise-Linear & Element Expressions](#piecewise-linear-element-expressions-max-min-abs-at))
|
|
46
47
|
- **Element-Wise Container Arithmetic**: `sum((${price} - ${cost}) * ${qty})`, `sum((${xVec} - ${target})^2)`, `dot(${price} - ${cost}, ${qty})`
|
|
47
48
|
- **Nested Expressions**: `expr` interpolates variables, numbers, `Array` / `Record` containers (inside `sum` or `dot`), and nested `LinExpr` / `QuadExpr` objects.
|
|
48
49
|
|
|
@@ -132,22 +133,18 @@ const totalShippingCost = expr`dot(${costs}, ${ship})`;
|
|
|
132
133
|
|
|
133
134
|
## Composing Aggregations in `expr`
|
|
134
135
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
Write mathematical operators, `sum(...)`, `dot(..., ...)`, and comparison symbols (`<=`, `>=`, `==`) in the template string, and pass variables, scalars, and containers (`Array` / `Record`) via `${...}`:
|
|
136
|
+
Keep operators, `sum(...)`, `dot(..., ...)`, and comparisons (`<=`, `>=`, `==`) in the template string, and interpolate containers directly via `${...}` rather than pre-evaluating standalone `sum()`/`dot()` or `Object.values()`:
|
|
138
137
|
|
|
139
138
|
```typescript
|
|
140
|
-
//
|
|
139
|
+
// Verbose: nested standalone calls and Object.values()
|
|
141
140
|
const totalProfit1 = expr`${dot(profits, vars)}`;
|
|
142
141
|
const cap1 = expr`${sum(Object.values(vars))} <= 100`;
|
|
143
142
|
|
|
144
|
-
//
|
|
143
|
+
// Recommended: direct sum() and dot() inside expr
|
|
145
144
|
const totalProfit2 = expr`dot(${profits}, ${vars})`;
|
|
146
145
|
const cap2 = expr`sum(${vars}) <= 100`;
|
|
147
146
|
```
|
|
148
147
|
|
|
149
|
-
### Common `expr` Aggregation Syntax
|
|
150
|
-
|
|
151
148
|
| Operation | Mathematical Formula | WaSHI Expression |
|
|
152
149
|
| :--- | :--- | :--- |
|
|
153
150
|
| **Total sum** (1D/2D `Array` or `Record`) | $\sum_i x_i \le C$ | `` m.constraint(expr`sum(${x}) <= ${C}`) `` |
|
|
@@ -211,6 +208,38 @@ m.objective(minimize(risk));
|
|
|
211
208
|
|
|
212
209
|
---
|
|
213
210
|
|
|
211
|
+
## Piecewise-Linear & Element Expressions (`max`, `min`, `abs`, `at`)
|
|
212
|
+
|
|
213
|
+
WaSHI provides backend-agnostic scalar piecewise-linear (`max`, `min`, `abs`) and 0-based variable-indexed lookup (`at`) primitives that work directly inside `` expr`...` `` or as standalone helpers imported from `@ohtaman/washi`:
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
import { Model, expr, minimize, abs, max, min, at } from "@ohtaman/washi";
|
|
217
|
+
|
|
218
|
+
const m = new Model();
|
|
219
|
+
const w = m.continuous(3, { lb: 0, ub: 20, prefix: "w" });
|
|
220
|
+
const target = [4, 7, 10];
|
|
221
|
+
const route = m.integer("route", { lb: 0, ub: 2 });
|
|
222
|
+
const routeCost = [18, 12, 25];
|
|
223
|
+
|
|
224
|
+
// Convex LP epigraph (zero binary variables on HiGHS / GLPK):
|
|
225
|
+
m.objective(
|
|
226
|
+
minimize(expr`sum(abs(${w} - ${target})) + at(${routeCost}, ${route})`)
|
|
227
|
+
);
|
|
228
|
+
m.constraint(expr`max(${w}) <= 15`, "peak_cap");
|
|
229
|
+
|
|
230
|
+
// Nested composition and programmatic helpers also work:
|
|
231
|
+
const maxErr = max(expr`abs(${w[0]} - 4)`, abs(expr`${w[1]} - 7`));
|
|
232
|
+
m.constraint(expr`${maxErr} <= 3`);
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
- **Element-wise container support**: Inside `expr`, `abs(${arr} - ${target})` evaluates element-wise across matching 1D/2D `Array`, `Iterable`, or `Record` containers so patterns like `` expr`sum(abs(${w} - ${target}))` `` and `` expr`max(abs(${pred} - ${actual}))` `` work naturally.
|
|
236
|
+
- **Polarity-aware MIP lowering vs native CP/SMT**:
|
|
237
|
+
- In convex directions on HiGHS and GLPK (`minimize` or `<=` on `max`/`abs`, `maximize` or `>=` on `min`), WaSHI emits pure continuous LP epigraph constraints with **zero binary variables** (even on unbounded `Continuous` variables).
|
|
238
|
+
- In non-convex or equality contexts (`minimize(min(...))`, `maximize(abs(...))`, `max(...) >= rhs`, `abs(...) == rhs`), HiGHS and GLPK emit bounded MIP formulations (requiring finite variable bounds), Pumpkin lowers via native `maximum`/`minimum`/`absolute` propagators over bounded integers, and Z3 uses native `If` (`ITE`).
|
|
239
|
+
- **0-based element lookup (`at(array, index)`)**: Models the classic CP `Element` constraint (`array[index]`). Requires an integer-valued `index` expression and automatically enforces $0 \le \text{index} < \text{array.length}$ across all solvers (native `element` propagator on Pumpkin, nested `If` + bounds guards on Z3, and binary convex-hull linearization on HiGHS/GLPK).
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
214
243
|
## Evaluating Expressions After Solving (`.value`)
|
|
215
244
|
|
|
216
245
|
Both `LinExpr` and `QuadExpr` expose a `.value` getter (`number | null`). Once a model has been solved and all referenced variables have finite primal values, you can evaluate any sub-expression directly:
|
|
@@ -250,6 +279,9 @@ In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent
|
|
|
250
279
|
| `.mul(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Multiplies by a scalar `number`, or multiplies two linear terms into a `QuadExpr`. |
|
|
251
280
|
| `.div(divisor)` | `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Divides by a non-zero finite scalar `number`. |
|
|
252
281
|
| `.neg()` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Negates all terms ($-e$). |
|
|
253
|
-
| `.le(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs
|
|
254
|
-
| `.ge(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs
|
|
255
|
-
| `.eq(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs
|
|
282
|
+
| `.le(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`; linear LHS required). |
|
|
283
|
+
| `.ge(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`; linear LHS required). |
|
|
284
|
+
| `.eq(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs`; linear LHS required). |
|
|
285
|
+
| `.lt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $<$ constraint (`lhs - rhs <= -1`; integer-valued expressions only). |
|
|
286
|
+
| `.gt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $>$ constraint (`lhs - rhs >= 1`; integer-valued expressions only). |
|
|
287
|
+
| `.ne(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $\ne$ constraint (`lhs != rhs`; integer-valued expressions only). |
|