@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.
Files changed (81) hide show
  1. package/README.md +32 -34
  2. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  3. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  4. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  5. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  6. package/dist/browser/solvers/highs.js +1414 -0
  7. package/dist/browser/washi.js +1090 -1473
  8. package/dist/browser/washi.min.js +4 -4
  9. package/dist/lib/solvers/glpk.js +34 -32
  10. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  11. package/dist/lib/solvers/highs.js +410 -0
  12. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  13. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  14. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  15. package/dist/lib/solvers/pumpkin.js +247 -1146
  16. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  17. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  18. package/dist/lib/solvers/z3.js +125 -123
  19. package/dist/lib/washi.js +2426 -1340
  20. package/dist/types/index.d.ts +1 -2
  21. package/dist/types/index.d.ts.map +1 -1
  22. package/dist/types/modeler/index.d.ts +0 -1
  23. package/dist/types/modeler/index.d.ts.map +1 -1
  24. package/dist/types/modeler/model.d.ts +6 -7
  25. package/dist/types/modeler/model.d.ts.map +1 -1
  26. package/dist/types/modeler/solvers/index.d.ts +2 -1
  27. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  29. package/docs/examples/diet-sensitivity.md +33 -14
  30. package/docs/examples/ecommerce-coupons.md +17 -9
  31. package/docs/examples/index.md +34 -30
  32. package/docs/examples/knapsack.md +11 -5
  33. package/docs/examples/portfolio-qp.md +21 -8
  34. package/docs/examples/production.md +10 -5
  35. package/docs/examples/project-scheduling.md +25 -12
  36. package/docs/examples/shift-scheduling.md +27 -19
  37. package/docs/examples/smt-security.md +27 -12
  38. package/docs/examples/transportation.md +23 -13
  39. package/docs/examples/traveling-salesperson.md +34 -22
  40. package/docs/examples/unsat-core.md +27 -15
  41. package/docs/examples/vehicle-routing.md +74 -28
  42. package/docs/getting-started/ai-agents.md +129 -90
  43. package/docs/getting-started/coding-agents.md +60 -41
  44. package/docs/getting-started/cross-origin.md +27 -14
  45. package/docs/getting-started/index.md +23 -16
  46. package/docs/getting-started/runtimes.md +70 -40
  47. package/docs/guide/constraint-programming.md +74 -44
  48. package/docs/guide/constraints.md +71 -39
  49. package/docs/guide/decomposition.md +72 -42
  50. package/docs/guide/expressions.md +79 -48
  51. package/docs/guide/formulation-tips.md +46 -27
  52. package/docs/guide/objectives.md +55 -31
  53. package/docs/guide/unsat-core.md +56 -53
  54. package/docs/guide/variables.md +61 -28
  55. package/docs/solvers/custom-solver.md +155 -119
  56. package/docs/solvers/glpk.md +58 -17
  57. package/docs/solvers/highs.md +115 -43
  58. package/docs/solvers/index.md +33 -26
  59. package/docs/solvers/pumpkin.md +71 -63
  60. package/docs/solvers/z3.md +63 -25
  61. package/llms-full.txt +1623 -953
  62. package/llms.txt +125 -93
  63. package/package.json +29 -22
  64. package/skills/washi/SKILL.md +43 -22
  65. package/README.ja.md +0 -248
  66. package/README.zh-CN.md +0 -248
  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,6 +1,14 @@
1
1
  # Runtime Environments & Deployment
2
2
 
3
- WaSHI runs across JavaScript and TypeScript runtimes—from Node.js, Bun, and Deno to modern bundlers, static hosting, and vanilla browser `<script>` tags—without native C/C++ compilation.
3
+ WaSHI runs across JavaScript and TypeScript runtimes and deployment targets without native solver compilation. Supported targets include Node.js, Bun, Deno, modern bundlers, static hosting, classic `<script>` tags, and offline WebView apps.
4
+
5
+ | Target Environment | Entry Point | Worker & Header Notes |
6
+ | --- | --- | --- |
7
+ | **Node.js (v18+), Bun, Deno** | `@ohtaman/washi` (`npm:@ohtaman/washi` in Deno) | Loads bundled `.wasm` from disk; no HTTP headers required. |
8
+ | **Vite, Next.js, Webpack, Rollup** | `@ohtaman/washi` | Runs HiGHS and Pumpkin in Web Workers by default. |
9
+ | **Tauri, Capacitor, PWA** | `@ohtaman/washi` (standard Vite build) | Runs offline; allow `'wasm-unsafe-eval'` in `script-src` and `worker-src 'self' blob:` (or pass `{ useWorker: false }`) in your Content Security Policy (`CSP`). |
10
+ | **Browser ESM (`<script type="module">`)** | `dist/browser/washi.js` | Keep all `dist/browser/` files together when self-hosting. |
11
+ | **Standalone HTML / CDN (`<script>`)** | `dist/browser/washi.min.js` | Exposes `window.Washi`; CDN builds also run directly on `file://`. |
4
12
 
5
13
  ---
6
14
 
@@ -8,7 +16,7 @@ WaSHI runs across JavaScript and TypeScript runtimes—from Node.js, Bun, and De
8
16
 
9
17
  ### Node.js
10
18
 
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:
19
+ WaSHI supports Node.js 18+ with standard ECMAScript Modules (`ESM`). Both bundled WebAssembly engines—HiGHS (default) and Pumpkin (`{ solver: "pumpkin" }`)—load directly from `solvers/` inside the installed package with zero extra imports:
12
20
 
13
21
  ```typescript
14
22
  import { Model, expr, maximize } from "@ohtaman/washi";
@@ -27,7 +35,7 @@ if (m.hasPrimalSolution) {
27
35
  }
28
36
  ```
29
37
 
30
- Run directly with `tsx` or `node`:
38
+ Run TypeScript files directly with `tsx` (or compiled `.js` with `node`):
31
39
 
32
40
  ```bash
33
41
  npx tsx app.ts
@@ -61,10 +69,10 @@ if (m.hasPrimalSolution) {
61
69
 
62
70
  ### Modern Bundlers & Static Deployment
63
71
 
64
- When importing `@ohtaman/washi` in a browser bundler, the `browser` export condition resolves automatically:
72
+ The package root export (`@ohtaman/washi`) resolves `import` and `default` to `./dist/lib/washi.js` (and `types` to `./dist/types/index.d.ts`). That unified ESM bundle detects Node.js versus browser runtimes automatically at execution time:
65
73
 
66
74
  ```typescript
67
- import { Model, expr, maximize } from "@ohtaman/washi";
75
+ import { Model, maximize } from "@ohtaman/washi";
68
76
 
69
77
  export async function runOptimization() {
70
78
  const m = new Model({ solver: "highs" });
@@ -75,37 +83,42 @@ export async function runOptimization() {
75
83
  }
76
84
  ```
77
85
 
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).)
86
+ Because the modeler (JS/TS) and bundled solvers (WebAssembly) execute entirely on the client, static builds from `vite build` deploy directly to **GitHub Pages, Cloudflare Pages, Vercel, or Netlify** without a backend server. HiGHS, Pumpkin, and GLPK need no special HTTP headers; for Z3's browser headers, see **Offline, Intranet & Strict CSP Environments** below.
79
87
 
80
88
  #### Background Web Worker Execution (Default)
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
89
 
83
- If your environment prohibits Web Workers or you explicitly want main-thread execution, pass `useWorker: false`:
90
+ In browsers, **HiGHS** and **Pumpkin** run inside dedicated Web Workers by default. This keeps the main UI thread responsive during `LP`, `MIP`, `QP`, and `CP` solves while enabling `onProgress` callbacks and `AbortSignal` cancellation.
91
+
92
+ Pass `useWorker: false` if your environment prohibits Web Workers or you prefer main-thread execution:
84
93
 
85
94
  ```typescript
86
95
  await m.solve({ useWorker: false });
87
96
  ```
88
97
 
89
98
  #### 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
99
 
92
- If your bundler or static server hosts `.wasm` files under a custom path, configure the URL globally or per solve/check:
100
+ By default, WaSHI resolves `solvers/highs.wasm` and `solvers/pumpkin.wasm` relative to the bundle via `import.meta.url`. It **never** falls back to external CDNs (`jsDelivr`, `unpkg`, etc.).
101
+
102
+ If your browser host serves `.wasm` files from a custom path, override the URL globally or per call. For HiGHS, `setHighsWasmUrl()` (from `@ohtaman/washi/solvers/highs`) and `{ wasmUrl }` are browser-only (ignored in Node.js); Pumpkin (`setPumpkinWasmUrl()` from `@ohtaman/washi/solvers/pumpkin`) also accepts `file://` URLs in Node.js, and Z3 uses `setZ3Assets()` or `{ z3JsUrl, z3WasmUrl }`:
93
103
 
94
104
  ```typescript
95
- import { setHighsWasmUrl } from "@ohtaman/washi";
105
+ import { setHighsWasmUrl } from "@ohtaman/washi/solvers/highs";
96
106
  import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
107
+ import { setZ3Assets } from "@ohtaman/washi/solvers/z3"; // Optional Z3 plugin
97
108
 
98
109
  // Option A: Configure globally before solving
99
110
  setHighsWasmUrl("/assets/wasm/highs.wasm");
100
111
  setPumpkinWasmUrl("/assets/wasm/pumpkin.wasm");
112
+ setZ3Assets({ jsUrl: "/assets/z3/z3-built.js", wasmUrl: "/assets/z3/z3-built.wasm" });
101
113
 
102
114
  // Option B: Configure per solve / check call
103
115
  await m.solve({ wasmUrl: "/assets/wasm/highs.wasm" });
116
+ // For Z3: await m.check({ solver: "z3", z3JsUrl: "...", z3WasmUrl: "..." });
104
117
  ```
105
118
 
106
119
  ### Next.js & Server-Side Rendering (SSR)
107
120
 
108
- In Next.js App Router or Pages Router, optimization models can run either in Server Actions / API Routes (Node.js runtime) or on the client inside `"use client"` components:
121
+ In Next.js App Router or Pages Router, models run either on the server (Server Actions / API Routes) or in the browser inside `"use client"` components. Below is a client component example:
109
122
 
110
123
  ```tsx
111
124
  "use client";
@@ -137,9 +150,9 @@ export default function OptimizerComponent() {
137
150
 
138
151
  ### Desktop & Mobile WebView Apps (Tauri / Capacitor / PWA)
139
152
 
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.
153
+ Standard Vite frontends bundle **HiGHS** and **Pumpkin** as static assets for offline execution. They run in Tauri (`tauri://localhost` or `http://tauri.localhost`), Capacitor mobile WebViews, and offline PWAs with no native solver build step.
141
154
 
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 }`:
155
+ In `tauri.conf.json`, include `'wasm-unsafe-eval'` and `worker-src 'self' blob:` in your `CSP` string. If you run on the main thread with `{ useWorker: false }`, you can omit `worker-src` (see the full CSP table below):
143
156
 
144
157
  ```json
145
158
  {
@@ -151,20 +164,19 @@ In `tauri.conf.json`, allow WebAssembly compilation (`'wasm-unsafe-eval'` in `sc
151
164
  }
152
165
  ```
153
166
 
154
- Bundled **HiGHS** and **Pumpkin** are recommended over **Z3** in desktop and mobile WebViews because they do not require `SharedArrayBuffer` or `COOP`/`COEP` headers.
167
+ Prefer bundled HiGHS and Pumpkin in WebViews to avoid Z3's [Cross-Origin Isolation](./cross-origin.md) requirements.
155
168
 
156
169
  ---
157
170
 
158
171
  ## 📦 Browser ESM (`<script type="module">`)
159
172
 
160
- Without a bundler, you can import the pre-built browser ESM module directly from your own static server or an npm CDN:
173
+ Without a bundler, import the pre-built browser ESM module from your own static server or an npm CDN:
161
174
 
162
175
  ```html
163
176
  <script type="module">
164
- // From an npm CDN (or "./dist/browser/washi.js" when self-hosted):
177
+ // From an npm CDN (or "./dist/browser/washi.js" when self-hosted; includes HiGHS and Pumpkin):
165
178
  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";
179
+ // Optional solver plugins:
168
180
  // import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/glpk.js";
169
181
  // import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/z3.js";
170
182
 
@@ -187,7 +199,7 @@ Without a bundler, you can import the pre-built browser ESM module directly from
187
199
 
188
200
  ## 🟨 Classic `<script>` Tags (IIFE / Standalone HTML / CDN)
189
201
 
190
- For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a standard `<script>` tag. All exports are attached to the global `window.Washi` object:
202
+ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a classic `<script>` tag. This immediately invoked function expression (`IIFE`) bundle exposes the core API on the global `window.Washi` object:
191
203
 
192
204
  ```html
193
205
  <!DOCTYPE html>
@@ -200,10 +212,9 @@ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a stan
200
212
  <h1>WaSHI Browser Optimization</h1>
201
213
  <pre id="output">Solving...</pre>
202
214
 
203
- <!-- Core WaSHI + HiGHS (MIT) via CDN (or "./dist/browser/washi.min.js" when self-hosted) -->
215
+ <!-- Core WaSHI + bundled HiGHS & Pumpkin (MIT) via CDN (or "./dist/browser/washi.min.js" when self-hosted) -->
204
216
  <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> -->
217
+ <!-- Optional plugins (load after washi.min.js; auto-register when window.Washi is present): -->
207
218
  <!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/glpk.min.js"></script> -->
208
219
  <!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/z3.min.js"></script> -->
209
220
 
@@ -232,25 +243,44 @@ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a stan
232
243
  </html>
233
244
  ```
234
245
 
235
- > [!NOTE]
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://`.
246
+ ### Cross-Origin CDN Workers
247
+
248
+ On standard `http://` and `https://` origins, browsers block direct `new Worker("https://cdn...")` calls. WaSHI automatically bridges cross-origin CDN workers with a small ES module `Blob` bootstrap.
249
+
250
+ ### Opening Local `.html` Files Directly (`file://`)
251
+
252
+ | Scenario | Behavior & Requirement |
253
+ | --- | --- |
254
+ | **CDN scripts** | Loading `washi.min.js` from an HTTPS CDN includes both HiGHS and Pumpkin and works by double-clicking a local `.html` file (`file://`) with no local server. |
255
+ | **Opaque origins (`window.origin === "null"`)** | On `file://` pages or sandboxed `<iframe>` embeds without `allow-same-origin`, WaSHI runs HiGHS and Pumpkin on the main thread when `useWorker` is omitted. |
256
+ | **Self-hosted `.wasm` & Z3** | Local `.wasm` files require `http://` or `https://` because browsers block `fetch()` on `file://`. Z3 also requires Cross-Origin Isolation (see below). |
238
257
 
239
258
  ---
240
259
 
241
260
  ## 🔒 Offline, Intranet & Strict CSP Environments
242
261
 
243
- WaSHI never phones home or falls back to public CDNs. To self-host in an air-gapped intranet or under a strict Content Security Policy (CSP):
244
-
245
- 1. **Copy Static Assets**: Serve the files from `node_modules/@ohtaman/washi/dist/browser/` on your own origin:
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)
248
- - Optional GLPK: `solvers/glpk.js` / `solvers/glpk.min.js`
249
- - Optional Z3: `solvers/z3.js` / `solvers/z3.min.js`, `solvers/z3-built.js`, `solvers/z3-built.wasm`
250
- 2. **Content Security Policy (CSP) Headers**:
251
- - Allow WebAssembly compilation (`'wasm-unsafe-eval'` in `script-src`).
252
- - If using the default Web Worker or cross-origin Blob worker bootstrap, allow `worker-src 'self' blob:;`.
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 })`.
254
- 3. **Cross-Origin Isolation (Z3 Only)**:
255
- - HiGHS, Pumpkin, and GLPK run in standard browser contexts without special headers.
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.
262
+ WaSHI never phones home or falls back to public CDNs. To self-host in an air-gapped intranet or under a strict `CSP`, configure three areas:
263
+
264
+ ### 1. Deploy `dist/browser/` Intact
265
+
266
+ Copy `node_modules/@ohtaman/washi/dist/browser/` to your static origin as a complete directory. Even the classic IIFE bundle (`washi.min.js`) spawns `solvers/highs-worker.js` and `solvers/pumpkin-worker.js` as Web Workers by default unless `{ useWorker: false }` is passed. Both the ESM entry points and these worker scripts import hashed `*.js` chunks under `dist/browser/` via relative paths.
267
+
268
+ | Bundle | Required Files under `dist/browser/` |
269
+ | --- | --- |
270
+ | **Core** | `washi.js` / `washi.min.js` |
271
+ | **Bundled HiGHS** | `solvers/highs.js`, `solvers/highs.wasm`, `solvers/highs-worker.js`, and `solvers/highs-*.js` chunks |
272
+ | **Bundled Pumpkin** | `solvers/pumpkin.js`, `solvers/pumpkin.wasm`, `solvers/pumpkin-worker.js`, and `solvers/pumpkin-*.js` chunks |
273
+ | **Optional GLPK** | `solvers/glpk.js` / `solvers/glpk.min.js` |
274
+ | **Optional Z3** | `solvers/z3.js` / `solvers/z3.min.js`, `solvers/z3-built.js`, `solvers/z3-built.wasm` |
275
+
276
+ ### 2. Configure CSP Directives
277
+
278
+ | Directive | Required Value | Purpose |
279
+ | --- | --- | --- |
280
+ | `script-src` | `'wasm-unsafe-eval'` | Allows WebAssembly module compilation. |
281
+ | `worker-src` | `'self' blob:` | Allows default Web Workers and CDN `Blob` worker bootstraps. |
282
+ | `worker-src` (if `blob:` is disallowed) | `'self'` only | Serve `solvers/highs-worker.js` / `solvers/pumpkin-worker.js` from `'self'`, or pass `{ useWorker: false }`. |
283
+
284
+ ### 3. Enable Cross-Origin Isolation (Z3 Only)
285
+
286
+ HiGHS, Pumpkin, and GLPK run in standard browser contexts without isolation headers. Z3 uses `SharedArrayBuffer` multithreading, so browsers require a **Secure Context** (`https://` or `http://localhost`). You must also serve `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` headers (`COOP`/`COEP`); see the [Cross-Origin Isolation Guide](./cross-origin.md).
@@ -1,35 +1,56 @@
1
1
  # Constraint Programming (CP) Modeling
2
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.
3
+ WaSHI lets you write both Mathematical Optimization (LP / MIP / QP) and Constraint Programming (CP) models with the same TypeScript API.
4
+ Using the bundled **Pumpkin** solver (`{ solver: "pumpkin" }`, zero extra imports), you can model scheduling, resource limits, all-different rules, and table lookups directly without expanding them into large 0-1 matrices.
4
5
 
5
6
  ---
6
7
 
7
- ## 1. MIP vs. CP Modeling Mindset
8
+ ## 1. When to Use CP (Pumpkin) vs. MIP (HiGHS / GLPK)
8
9
 
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
+ The two paradigms differ in how they represent decisions and prune the search space.
10
11
 
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
+ ### Mixed-Integer Programming (`HiGHS` / `GLPK`)
12
13
 
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 |
14
+ MIP represents decisions with continuous and integer (including 0-1) variables, expresses rules as linear inequalities, and solves them with LP relaxation and branch-and-bound.
15
+ This excels at continuous flows, linear budgets, quadratic objectives, and LP dual analysis.
16
+ However, discretizing fine-grained timelines or expanding combinatorial structures into 0-1 variables can make the model grow huge.
17
+
18
+ ### Constraint Programming (`Pumpkin`)
19
+
20
+ CP assigns each decision a finite integer domain and connects variables with **global constraints**—high-level predicates that express structured combinatorial rules across groups of variables.
21
+ During search, **domain propagation** automatically prunes impossible values from each variable's domain whenever variable domains or constraints tighten, keeping models compact.
22
+
23
+ The table below shows how common modeling patterns map between MIP and CP:
24
+
25
+ | Task / Pattern | MIP (`HiGHS` / `GLPK`) | CP (`Pumpkin`) |
26
+ | :--- | :--- | :--- |
27
+ | **Start times** | One 0-1 variable per task and time slot | One integer variable `start[i]` per task |
28
+ | **Non-overlapping tasks** | Pairwise ordering binaries + Big-M inequalities | `disjoint(tasks)` |
29
+ | **Shared worker / machine capacity** | One linear sum constraint per time step | `cumulative(tasks, capacity)` |
30
+ | **One-to-one assignment** | 2D 0-1 assignment matrix | `machine[i]` + `distinct(machine)` |
31
+ | **Value / cost lookup by choice** | Weighted sum over 0-1 selector variables | `at(costs, indexVar)` |
32
+ | **Best suited for** | Continuous flows, blending, quadratic objectives, dual analysis | Scheduling, resource limits, permutations, compatibility tables |
33
+
34
+ > [!TIP]
35
+ > Use `HiGHS` when your model requires `Continuous` variables, decimal coefficients, or quadratic objectives, or `Z3` for continuous logical rules.
36
+ > Try `Pumpkin` when your model uses bounded integers and Booleans for scheduling, routing, or combinatorial assignment.
21
37
 
22
38
  ---
23
39
 
24
- ## 2. Interval & Resource Scheduling (`disjoint`, `cumulative`, `max`)
40
+ ## 2. Scheduling Tasks & Shared Resources (`disjoint`, `cumulative`, `max`)
25
41
 
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" }`).
42
+ Discretizing a long timeline into 0-1 time-slot variables creates tens of thousands of MIP variables.
43
+ WaSHI's MIP converter rejects `cumulative` horizons above 5,000 steps or 25,000 slot variables and recommends `{ solver: "pumpkin" }`.
27
44
 
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.
45
+ With Pumpkin, each task needs only **one integer variable** (`start[task]`), regardless of horizon granularity.
46
+ Three primitives cover most interval-scheduling models:
47
+
48
+ - **`disjoint(tasks)`**: Takes task objects `{ start, duration }` and forbids any two intervals `[start, start + duration)` from overlapping on a shared single machine.
49
+ - **`cumulative(tasks, capacity)`**: Takes task objects `{ start, duration, demand }` and enforces that total active resource demand never exceeds `capacity` at any moment.
50
+ - **`max(...)`**: Computes the **makespan**—the latest completion time across all tasks, $\max_i (\text{start}_i + \text{duration}_i)$—so you can minimize total schedule length.
29
51
 
30
52
  ```typescript
31
53
  import { Model, expr, disjoint, cumulative, max, minimize } from "@ohtaman/washi";
32
- import "@ohtaman/washi/solvers/pumpkin";
33
54
 
34
55
  const m = new Model("IntervalSchedulingCP", { solver: "pumpkin" });
35
56
  const tasks = ["prep", "mill", "drill", "coat"] as const;
@@ -38,12 +59,12 @@ const workers = { prep: 1, mill: 1, drill: 1, coat: 2 };
38
59
  const start = m.integer(tasks, { lb: 0, ub: 20, prefix: "start" });
39
60
 
40
61
  // 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");
62
+ m.constraint(expr`${start.prep} + ${duration.prep} <= ${start.mill}`, "mill_after_prep");
63
+ m.constraint(expr`${start.prep} + ${duration.prep} <= ${start.drill}`, "drill_after_prep");
64
+ m.constraint(expr`${start.mill} + ${duration.mill} <= ${start.coat}`, "coat_after_mill");
65
+ m.constraint(expr`${start.drill} + ${duration.drill} <= ${start.coat}`, "coat_after_drill");
45
66
 
46
- // Single CNC spindle shared between mill and drill
67
+ // Single CNC machine shared between mill and drill
47
68
  m.constraint(
48
69
  disjoint([
49
70
  { start: start.mill, duration: duration.mill },
@@ -52,7 +73,7 @@ m.constraint(
52
73
  "single_cnc"
53
74
  );
54
75
 
55
- // At most 2 operators working simultaneously across all tasks
76
+ // At most 2 operators working at the same time
56
77
  m.constraint(
57
78
  cumulative(
58
79
  tasks.map((t) => ({ start: start[t], duration: duration[t], demand: workers[t] })),
@@ -63,23 +84,23 @@ m.constraint(
63
84
 
64
85
  m.objective(minimize(max(tasks.map((t) => expr`${start[t]} + ${duration[t]}`))));
65
86
  await m.solve();
87
+ console.log("Makespan:", m.objectiveValue);
66
88
  ```
67
89
 
68
- See the full runnable project scheduling walkthrough in [Resource-Constrained Project Scheduling (RCPSP)](../examples/project-scheduling.md).
90
+ See the full walkthrough in [Resource-Constrained Project Scheduling (RCPSP)](../examples/project-scheduling.md).
69
91
 
70
92
  ---
71
93
 
72
- ## 3. Combinatorial Assignment, Table Rules & Element Lookup (`distinct`, `allowed`, `at`)
94
+ ## 3. Assignment, Compatibility Tables & Cost Lookup (`distinct`, `allowed`, `at`)
73
95
 
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\}$:
96
+ Instead of an $N \times M$ matrix of 0-1 assignment variables, give each job a single bounded integer variable `machine[job]` ranging from `0` to `M - 1`:
75
97
 
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.
98
+ - **`distinct(machine)`**: Global all-different constraint forcing every job onto a distinct machine.
99
+ - **`allowed(vars, tuples)` / `not(allowed(vars, tuples))`**: Global table constraint permitting or forbidding explicit value tuples without Big-M inequalities.
100
+ - **`at(costs, indexVar)`**: Variable-indexed lookup returning `costs[indexVar]` directly inside an `expr` or objective.
79
101
 
80
102
  ```typescript
81
- import { Model, expr, distinct, allowed, not, at, minimize } from "@ohtaman/washi";
82
- import "@ohtaman/washi/solvers/pumpkin";
103
+ import { Model, expr, distinct, allowed, not, minimize } from "@ohtaman/washi";
83
104
 
84
105
  const m = new Model("MachineAssignmentCP", { solver: "pumpkin" });
85
106
  const jobs = ["jobA", "jobB", "jobC"] as const;
@@ -89,40 +110,47 @@ const costA = [5, 10, 40];
89
110
  const costB = [20, 15, 30];
90
111
  const costC = [45, 30, 25];
91
112
 
92
- // Each job runs on a distinct machine (0, 1, or 2)
113
+ // Each job runs on a separate machine (0, 1, or 2)
93
114
  m.constraint(distinct(machine), "one_job_per_machine");
94
115
 
95
- // Safety interlock: Job A on Machine 0 cannot pair with Job B on Machine 1
116
+ // Forbid placing Job A on Machine 0 while Job B is on Machine 1
96
117
  m.constraint(not(allowed([machine.jobA, machine.jobB], [[0, 1]])), "interlock_pair");
97
118
 
98
- // Variable-indexed cost lookup via 0-based Element primitive at(table, indexVar)
119
+ // Look up each job's cost by its assigned machine index
99
120
  m.objective(
100
121
  minimize(
101
122
  expr`at(${costA}, ${machine.jobA}) + at(${costB}, ${machine.jobB}) + at(${costC}, ${machine.jobC})`
102
123
  )
103
124
  );
104
125
  await m.solve();
126
+ console.log("Total cost:", m.objectiveValue);
105
127
  ```
106
128
 
107
129
  ---
108
130
 
109
- ## 4. Domain Tightening, Symmetry Breaking & Conflict Diagnosis
131
+ ## 4. Practical Tips for Pumpkin Models
132
+
133
+ ### Keep Integer Bounds Finite and Tight
110
134
 
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.
135
+ Pumpkin supports only finite integers within $[-(2^{30} - 1),\, 2^{30} - 1]$.
136
+ It rejects `Continuous` variables, non-integer coefficients or constants, and infinite bounds (`-Infinity` / `Infinity`).
137
+ Tighter `[lb, ub]` intervals shrink domains upfront and make domain propagation more effective.
138
+ See [Pumpkin Domain Preconditions](../solvers/pumpkin.md#domain-api-preconditions).
113
139
 
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:
140
+ ### Break Symmetry with Strict Ordering (`<`)
141
+
142
+ When picking $k$ distinct items into $k$ interchangeable slots (`slot[0]`, ..., `slot[k-1]`), every permutation of the same items has the same objective value.
143
+ Without symmetry breaking, the solver wastes time checking $k!$ equivalent orderings.
144
+ Adding `slot[0] < slot[1] < ...` enforces both uniqueness and a single canonical order:
116
145
 
117
146
  ```typescript
118
- import { Model, expr, at, minimize } from "@ohtaman/washi";
119
- import "@ohtaman/washi/solvers/pumpkin";
147
+ import { Model, expr, minimize } from "@ohtaman/washi";
120
148
 
121
149
  const m = new Model("SymmetryBreakingCP", { solver: "pumpkin" });
122
150
  const latencyMs = [600, 380, 420, 470, 550];
123
151
  const slot = m.integer(3, { lb: 0, ub: 4, prefix: "slot" });
124
152
 
125
- // Strict ascending order enforces all-different AND eliminates 3! = 6 permutation symmetries
153
+ // Strict ascending order enforces uniqueness and removes 3! = 6 duplicate orderings
126
154
  m.constraint([
127
155
  expr`${slot[0]} < ${slot[1]}`,
128
156
  expr`${slot[1]} < ${slot[2]}`,
@@ -134,8 +162,10 @@ m.objective(
134
162
  )
135
163
  );
136
164
  await m.solve();
165
+ console.log("Best 3 latencies total:", m.objectiveValue);
137
166
  ```
138
167
 
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).
168
+ ### Warm Starts & Conflict Diagnosis
169
+
170
+ - **Warm starts (`initialValue`)**: Pass `{ initialValue: val }` to `m.integer()` or `m.binary()` to guide Pumpkin's initial value selection.
171
+ - **Conflict diagnosis (`m.check()`)**: If a CP model returns `"Infeasible"`, call `await m.check({ solver: "pumpkin" })` to pinpoint conflicting named constraints. See [Conflict Diagnosis (`unsatCore`)](./unsat-core.md).