@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
package/llms-full.txt
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# AI Coding Agent Quick-Reference Guide
|
|
2
2
|
|
|
3
3
|
> **Scope Note**: This document is the **consumer modeling quick-reference** for AI coding agents and developers building optimization or satisfiability models with `@ohtaman/washi`.
|
|
4
|
-
> - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `
|
|
4
|
+
> - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `verify()` verification, and Pumpkin / Z3 `unsatCore` conflict-diagnosis workflow skill (compatible with Claude Code, Antigravity, Cursor, Codex, and other `SKILL.md`-aware agents), use [`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md) (also shipped in the npm package at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`):
|
|
5
5
|
> ```bash
|
|
6
6
|
> # Install directly via the skills CLI (skills.sh / vercel-labs/skills)
|
|
7
7
|
> npx skills add ohtaman/washi
|
|
@@ -24,6 +24,14 @@ import {
|
|
|
24
24
|
expr,
|
|
25
25
|
sum,
|
|
26
26
|
dot,
|
|
27
|
+
abs,
|
|
28
|
+
max,
|
|
29
|
+
min,
|
|
30
|
+
at,
|
|
31
|
+
distinct,
|
|
32
|
+
disjoint,
|
|
33
|
+
cumulative,
|
|
34
|
+
allowed,
|
|
27
35
|
maximize,
|
|
28
36
|
minimize,
|
|
29
37
|
and,
|
|
@@ -34,6 +42,8 @@ import {
|
|
|
34
42
|
setHighsWasmUrl,
|
|
35
43
|
} from "@ohtaman/washi";
|
|
36
44
|
|
|
45
|
+
// Bundled CP/LCG solver plugin (zero external dependencies; registers "pumpkin"):
|
|
46
|
+
import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
|
|
37
47
|
// Optional solver plugins (require installing peer dependencies first):
|
|
38
48
|
// npm install z3-solver
|
|
39
49
|
import "@ohtaman/washi/solvers/z3";
|
|
@@ -45,10 +55,12 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
45
55
|
|
|
46
56
|
- **Browser ESM**:
|
|
47
57
|
- Core (HiGHS built-in): `import { Model, expr, maximize } from "./washi/washi.js";`
|
|
58
|
+
- Pumpkin plugin: `import "./washi/solvers/pumpkin.js";`
|
|
48
59
|
- GLPK plugin: `import "./washi/solvers/glpk.js";`
|
|
49
60
|
- Z3 plugin: `import "./washi/solvers/z3.js";`
|
|
50
61
|
- **Classic `<script>` / CodePen (IIFE)**:
|
|
51
62
|
- Core: `<script src="./washi/washi.min.js"></script>` (exposes global `Washi`)
|
|
63
|
+
- Pumpkin plugin: `<script src="./washi/solvers/pumpkin.min.js"></script>` (registers `"pumpkin"`, exposes `WashiPumpkin`)
|
|
52
64
|
- GLPK plugin: `<script src="./washi/solvers/glpk.min.js"></script>` (registers `"glpk"`, exposes `WashiGLPK`)
|
|
53
65
|
- Z3 plugin: `<script src="./washi/solvers/z3.min.js"></script>` (registers `"z3"`, exposes `WashiZ3`)
|
|
54
66
|
|
|
@@ -57,7 +69,8 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
57
69
|
1. **Bundled WASM by default (no implicit CDN fallback)**:
|
|
58
70
|
- In Node.js and modern bundlers, WebAssembly assets resolve relative to the module automatically.
|
|
59
71
|
- In browser deployments, deploy the full `dist/browser/` directory (JS, Worker, and `.wasm` files) together. If a local WASM URL is missing or returns an HTML SPA fallback, initialization fails immediately and reports the attempted URL—it **never** silently switches to a public CDN.
|
|
60
|
-
- In browser runtimes, to load `highs.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` or
|
|
72
|
+
- In browser runtimes, to load `highs.wasm` or `pumpkin.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` (or `await m.solve({ wasmUrl: "https://.../highs.wasm" })`) for HiGHS, or `setPumpkinWasmUrl("https://.../pumpkin.wasm")` (or `await m.solve({ solver: "pumpkin", wasmUrl: "https://.../pumpkin.wasm" })`) for Pumpkin (ignored in Node.js for HiGHS; for Pumpkin in Node.js, bundled local `pumpkin.wasm` is used by default unless overridden with a `file://` URL).
|
|
73
|
+
- **Pumpkin runs without `COOP`/`COEP`**: Unlike Z3, Pumpkin (`@ohtaman/washi/solvers/pumpkin`) uses single-threaded WASM inside a regular Web Worker and does **not** require `SharedArrayBuffer` or Cross-Origin Isolation headers (`COOP`/`COEP`). It requires bounded finite integer/binary variables (`lb`, `ub` in `[-(2^30 - 1), 2^30 - 1]`) and integer linear coefficients/RHS, and supports `initialValue` warm starts across `solve()` and `check()` (no `Continuous`, `QuadExpr`, or `relax: true`).
|
|
61
74
|
2. **Z3 requires a Secure Context, Cross-Origin Isolation, and CORS in browsers**:
|
|
62
75
|
- Z3 WebAssembly uses `SharedArrayBuffer` multithreading. Browser pages running Z3 must run in a secure context (`window.isSecureContext === true`, i.e., HTTPS or `localhost`) and be cross-origin isolated (`window.crossOriginIsolated === true`) by serving:
|
|
63
76
|
- `Cross-Origin-Opener-Policy: same-origin` (on the document)
|
|
@@ -66,8 +79,8 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
66
79
|
- Importing `@ohtaman/washi` never auto-injects a Service Worker. When a secure context or cross-origin isolation is absent in a browser, Z3 rejects immediately with a descriptive error.
|
|
67
80
|
3. **Web Workers & Cancellation (`AbortSignal`)**:
|
|
68
81
|
- Pre-solve cancellation (`signal.aborted` before execution starts) is supported across all solvers.
|
|
69
|
-
- In browsers where `Worker` is available on a non-opaque effective origin (`window.origin !== "null"`), HiGHS
|
|
70
|
-
- On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
|
|
82
|
+
- In browsers where `Worker` is available on a non-opaque effective origin (`window.origin !== "null"`), both **HiGHS** and **Pumpkin** run in dedicated Web Workers by default (`useWorker: true`). On opaque effective origins (`window.origin === "null"`, such as `file:` URLs or `sandbox="allow-scripts"` `<iframe>` embeds without `allow-same-origin`), both default to main-thread execution (`useWorker: false`). Passing `{ signal }` to `m.solve({ signal })` or `m.check({ signal })` preemptively terminates an in-flight Worker run (or cancels queued Worker requests).
|
|
83
|
+
- On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Main-thread / Node.js Pumpkin checks `should_abort` checkpoints across branching and termination hooks. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
|
|
71
84
|
|
|
72
85
|
---
|
|
73
86
|
|
|
@@ -85,7 +98,7 @@ const x = m.continuous("x", { lb: 0, ub: 100 });
|
|
|
85
98
|
const y = m.continuous("y", { lb: 0, ub: 100 });
|
|
86
99
|
const n = m.integer("n", { lb: 0, ub: 10 });
|
|
87
100
|
const b = m.binary("b");
|
|
88
|
-
const flag = m.bool("flag"); // Propositional boolean (
|
|
101
|
+
const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native LCG/SMT on Pumpkin/Z3)
|
|
89
102
|
|
|
90
103
|
// Indexed variable containers:
|
|
91
104
|
// - Numeric dimension -> Array
|
|
@@ -99,25 +112,27 @@ const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
|
|
|
99
112
|
- **Optional Primal Initial Values (`initialValue?: number`)**:
|
|
100
113
|
- Numeric variable constructors (`m.continuous`, `m.integer`, `m.binary`, and `new Var`) and the mutable `v.initialValue` property accept an optional finite primal hint (validated with tolerance `1e-6` against bounds `[lb, ub]` and integer/binary domains), kept distinct from the solved `v.value`.
|
|
101
114
|
- A start may be complete or partial (e.g., transferred by stable variable names when rebuilding a MIP model). Supplying `initialValue` is a hint only—it does **not** fix the variable, add a hard constraint, or guarantee solver acceptance or a runtime speedup.
|
|
102
|
-
- Supported by **HiGHS** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
|
|
115
|
+
- Supported by **HiGHS** and **Pumpkin** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
|
|
103
116
|
|
|
104
|
-
### Step 2: Build Expressions (`expr`, `sum`, `dot`)
|
|
117
|
+
### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
|
|
105
118
|
|
|
106
119
|
- **Unified `expr` template tag**:
|
|
107
120
|
- Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${n} - 10` ``, `` expr`dot(${profit}, ${byItem}) - 20 * ${b}` ``, `` expr`sum((${price} - ${cost}) * ${byItem})` ``
|
|
121
|
+
- Piecewise-linear & element primitives (`max`, `min`, `abs`, `at`, usable inside `expr` or standalone): `` expr`max(${vec}) + sum(abs(${vec} - ${target}))` ``, `` expr`max(abs(${pred} - ${actual}))` ``, `` expr`at(${costs}, ${idx})` `` (0-based integer `idx`, automatically enforcing $0 \le \text{idx} < \text{costs.length}$). On HiGHS/GLPK, convex directions (`minimize` or `<=` on `max`/`abs`, `maximize` or `>=` on `min`) lower to pure continuous LP epigraphs with zero binary variables, while non-convex/equality contexts use exact bounded MIP formulations (finite bounds required); Pumpkin lowers natively (`maximum`/`minimum`/`absolute`/`element`) and Z3 uses native `If` (ITE).
|
|
108
122
|
- Quadratic expression (`QuadExpr`): `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${vec} - ${target})^2)` `` (supported for convex QP objectives on purely continuous models using `m.continuous`; built-in HiGHS does not support MIQP models containing integer, binary, or boolean variables).
|
|
109
|
-
-
|
|
123
|
+
- Constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` (supports `<=`, `>=`, `==`, `=`, plus discrete integer-only `<`, `>`, `!=`).
|
|
110
124
|
- **Aggregations & Element-Wise Container Arithmetic**:
|
|
111
|
-
- `sum(containerOrItems, mapper?)` (usable inside `` expr`sum(...)` `` or standalone `sum(...)`) sums a 1D/2D `Array`, `Iterable`, or plain `Record` of `Var` / `LinExpr` / `number` (without needing `Object.values(record)`), or maps over items/counts via `sum(items, (item, i) => ...)`. Inside `` expr`sum(...)` ``, element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`)
|
|
125
|
+
- `sum(containerOrItems, mapper?)` (usable inside `` expr`sum(...)` `` or standalone `sum(...)`) sums a 1D/2D `Array`, `Iterable`, or plain `Record` of `Var` / `LinExpr` / `number` (without needing `Object.values(record)`), or maps over items/counts via `sum(items, (item, i) => ...)`. Inside `` expr`sum(...)` ``, element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`) and `abs(...)` mapping are also supported.
|
|
112
126
|
- `dot(a, b)` (usable inside `` expr`dot(${a}, ${b})` `` or standalone `dot(a, b)`) computes the inner product of matching 1D arrays, 2D arrays (`number[][]` / `Var[][]`, computing the Frobenius inner product $\sum_{i,j} A_{i,j} B_{i,j}$), plain records (`Record<string, ...>`), or mixed Array/Record containers in either operand order.
|
|
113
127
|
- **Fluent methods**:
|
|
114
128
|
- Arithmetic (on `LinExpr` and `QuadExpr`; `Var` supports `.add()`, `.sub()`, `.mul()`, `.neg()`): `.add(other)`, `.sub(other)`, `.mul(other)`, `.div(scalar)`, `.neg()`
|
|
115
|
-
- Comparisons (on `Var` and `
|
|
116
|
-
-
|
|
129
|
+
- Comparisons (on `Var`, `LinExpr`, and `QuadExpr`): `.le(rhs, name?)`, `.ge(rhs, name?)`, `.eq(rhs, name?)`, plus discrete integer-only `.lt(rhs, name?)`, `.gt(rhs, name?)`, `.ne(rhs, name?)` (Continuous / fractional operands throw immediately)
|
|
130
|
+
- CP global constraints (`BoolExpr` predicates composable with logical operators): `distinct(...args)` (pairwise `!=` on HiGHS/GLPK, `all_different` via pairwise `binary_not_equals` on Pumpkin `0.5.0`, `ctx.Distinct` on Z3), `disjoint(tasks)` (`{ start, duration }`, native `disjunctive_strict` Vilím edge-finding on Pumpkin), `cumulative(tasks, capacity)` (`{ start, duration, demand }`, native `cumulative` time-table on Pumpkin; MIP time-indexed formulation enforces a horizon memory guard recommending `{ solver: "pumpkin" }`), and `allowed(vars, tuples)` (`table` / `negative_table` on Pumpkin)
|
|
131
|
+
- Boolean logic (on `BoolVar`, `BoolExpr`, and `Constraint`): standalone `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, `xor(a, b)` and fluent `.and(...)`, `.or(...)`, `.not()`, `.implies(...)`, `.xor(...)`—solved natively on Z3 and Pumpkin (bounded integers) and automatically linearized to 0-1 MIP on HiGHS/GLPK (negated comparison `Constraint`s in `implies` antecedents, `not`, or `xor` use exact $\pm 1$ shifts over integer-valued `Integer`/`Binary` expressions; `Continuous` or non-integer negated `Constraint`s throw on MIP solvers—use `{ solver: "z3" }`, or write ``or(expr`... >= ... + eps`, ...)`` / `m.bool()`)
|
|
117
132
|
|
|
118
133
|
### Step 3: Register Objective & Constraints on the Model
|
|
119
134
|
|
|
120
|
-
Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)
|
|
135
|
+
Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)` (when `options.M` is omitted in `m.indicator()`, HiGHS/GLPK use tight derived Big-M and preserve `toLpString()`, while Pumpkin lowers natively via `implied_by` and Z3 via `ctx.Implies` unless the returned `Constraint` row is subsequently mutated):
|
|
121
136
|
|
|
122
137
|
```ts
|
|
123
138
|
// Set objective using maximize() or minimize()
|
|
@@ -130,16 +145,16 @@ const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
|
|
|
130
145
|
m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
|
|
131
146
|
```
|
|
132
147
|
|
|
133
|
-
### Step 4: Execute (`solve` or `check`) & Verify (`
|
|
148
|
+
### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
|
|
134
149
|
|
|
135
150
|
- **Optimization (`await m.solve(options?)`)**:
|
|
136
151
|
- Returns `SolverStatus` (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`, `"Sat"`, or `"Unsat"`). Built-in optimization solvers return the optimization statuses (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`), where a time-, iteration-, or solution-limited run (or an interrupted solve) that found a valid primal incumbent returns `"Feasible"`; `"Sat"` and `"Unsat"` are included in `SolverStatus` for satisfiability/custom solver adapters (such as `MockSolver`).
|
|
137
|
-
- Read values via `x.value`, `expr`...`.value`, `m.
|
|
138
|
-
- Call `m.
|
|
152
|
+
- Read values via `x.value`, `expr`...`.value`, `m.values`, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`, and inspect registered entities via `m.variables` (`ReadonlyMap<string, Var | BoolVar>`) and `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`).
|
|
153
|
+
- Call `m.verify()` after solving to independently verify variable finiteness, variable bounds (`lb`/`ub`), integer/binary/boolean domains, linear constraint residuals, and logical constraints (`VerificationReport`: `{ valid, complete, maxViolation, violations, ... }`). Note that `verify()` checks primal feasibility of variables and constraints; it does not recompute or compare `m.objectiveValue`.
|
|
139
154
|
- **Satisfiability & Conflict Diagnosis (`await m.check(options?)`)**:
|
|
140
155
|
- Returns `CheckResult` (`{ status: "Sat" | "Unsat" | "Unknown", values: Record<string, number | boolean>, conflicts?: readonly string[], unsatCore?: readonly string[], runTime?: number }`), where `conflicts` is populated when the model is proven `"Unsat"`.
|
|
141
|
-
- For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `implies`, `xor`), `m.check()` works with any solver (including the default HiGHS and GLPK via single-solve elastic slack relaxation, automatically linearizing logical constraints into 0-1 MIP formulation) and diagnoses conflicting constraints as `conflicts` (leaving `unsatCore: undefined` for semantic rigor).
|
|
142
|
-
- Exact
|
|
156
|
+
- For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`), `m.check()` works with any solver (including the default HiGHS and GLPK via single-solve elastic slack relaxation, automatically linearizing logical constraints into 0-1 MIP formulation) and diagnoses conflicting constraints as `conflicts` (leaving `unsatCore: undefined` for semantic rigor).
|
|
157
|
+
- Exact unsatisfiable-core extraction (`result.unsatCore` and `result.conflicts`) is provided when using `{ solver: "z3" }` or `{ solver: "pumpkin" }`. Use `"pumpkin"` (`@ohtaman/washi/solvers/pumpkin`) for bounded-integer/propositional models in environments without `COOP`/`COEP` headers, and use `"z3"` when `Continuous` variables or fractional arithmetic are involved. Because Z3 and Pumpkin assert variable bounds (`lb`/`ub`) and binary `{0, 1}` domains directly while tracking registered constraints, `unsatCore` reports a subset of registered constraint names that conflicts *together with the model's fixed variable bounds/domains* (and is not guaranteed minimal).
|
|
143
158
|
- **No concurrent mutation during async solve/check**:
|
|
144
159
|
- Mutating variables, constraints, or the objective while `await m.solve()` or `await m.check()` is pending invalidates the in-flight execution and rejects the stale promise.
|
|
145
160
|
|
|
@@ -171,8 +186,8 @@ export async function runMipExample() {
|
|
|
171
186
|
});
|
|
172
187
|
|
|
173
188
|
const status = await m.solve();
|
|
174
|
-
const report = m.
|
|
175
|
-
const values =
|
|
189
|
+
const report = m.verify();
|
|
190
|
+
const values = { desk: qty.desk.value, chair: qty.chair.value };
|
|
176
191
|
|
|
177
192
|
return {
|
|
178
193
|
status,
|
|
@@ -202,7 +217,7 @@ export async function runQpExample() {
|
|
|
202
217
|
m.constraint(expr`${x} + ${y} >= 4`, "budget");
|
|
203
218
|
|
|
204
219
|
const status = await m.solve();
|
|
205
|
-
const report = m.
|
|
220
|
+
const report = m.verify();
|
|
206
221
|
|
|
207
222
|
return {
|
|
208
223
|
status,
|
|
@@ -237,6 +252,57 @@ export async function runZ3Example() {
|
|
|
237
252
|
}
|
|
238
253
|
```
|
|
239
254
|
|
|
255
|
+
### Example D: Pumpkin CP Disjunctive Scheduling & Zero-COOP/COEP Unsat Core
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
|
|
259
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
260
|
+
|
|
261
|
+
export async function runPumpkinExample() {
|
|
262
|
+
// Part 1: Bounded-integer CP scheduling with native global propagators
|
|
263
|
+
const cpModel = new Model("WorkshopSchedule", { solver: "pumpkin" });
|
|
264
|
+
const start = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 0, ub: 20, prefix: "start" });
|
|
265
|
+
const bench = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 1, ub: 3, prefix: "bench" });
|
|
266
|
+
|
|
267
|
+
cpModel.constraint(
|
|
268
|
+
disjoint([
|
|
269
|
+
{ start: start.cut, duration: 4 },
|
|
270
|
+
{ start: start.weld, duration: 3 },
|
|
271
|
+
{ start: start.paint, duration: 2 },
|
|
272
|
+
]),
|
|
273
|
+
"single_line"
|
|
274
|
+
);
|
|
275
|
+
cpModel.constraint(expr`${start.cut} + 4 <= ${start.weld}`, "cut_before_weld");
|
|
276
|
+
cpModel.constraint(expr`${start.weld} + 3 <= ${start.paint}`, "weld_before_paint");
|
|
277
|
+
cpModel.constraint(distinct(bench), "unique_benches");
|
|
278
|
+
cpModel.objective(minimize(expr`${start.paint} + 2`));
|
|
279
|
+
|
|
280
|
+
const status = await cpModel.solve();
|
|
281
|
+
const report = cpModel.verify();
|
|
282
|
+
|
|
283
|
+
// Part 2: Zero-COOP/COEP unsatCore diagnosis on bounded integers & booleans
|
|
284
|
+
const unsatModel = new Model("DiscreteConflict", { solver: "pumpkin" });
|
|
285
|
+
const vip = unsatModel.bool("vip");
|
|
286
|
+
const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
|
|
287
|
+
|
|
288
|
+
unsatModel.constraint(vip, "customer_is_vip");
|
|
289
|
+
unsatModel.constraint(implies(vip, expr`${discount} >= 20`), "vip_min_discount");
|
|
290
|
+
unsatModel.constraint(expr`${discount} <= 10`, "campaign_cap");
|
|
291
|
+
|
|
292
|
+
const unsatResult = await unsatModel.check();
|
|
293
|
+
return {
|
|
294
|
+
status,
|
|
295
|
+
makespan: cpModel.objectiveValue,
|
|
296
|
+
starts: { cut: start.cut.value, weld: start.weld.value, paint: start.paint.value },
|
|
297
|
+
benches: { cut: bench.cut.value, weld: bench.weld.value, paint: bench.paint.value },
|
|
298
|
+
valid: report.valid,
|
|
299
|
+
unsatStatus: unsatResult.status,
|
|
300
|
+
conflicts: unsatResult.conflicts,
|
|
301
|
+
unsatCore: unsatResult.unsatCore,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
240
306
|
---
|
|
241
307
|
|
|
242
308
|
## 4. Negative Examples & Common Pitfalls
|
|
@@ -261,14 +327,17 @@ export function verifyNegativePatterns() {
|
|
|
261
327
|
// 3. DO NOT use quadratic terms inside linear constraints:
|
|
262
328
|
// WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
|
|
263
329
|
|
|
264
|
-
// 4. DO NOT use retired aliases (removed in #59 / #81):
|
|
330
|
+
// 4. DO NOT use retired aliases (removed in #59 / #81 / #236 / #273):
|
|
265
331
|
// - Use `expr` instead of retired `c` template tag
|
|
266
332
|
// - Use `m.constraint(...)` instead of `m.constrain(...)` or `m.add(...)`
|
|
267
|
-
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)`
|
|
333
|
+
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` / `m.objective()` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)` / `m.objectiveExpr`
|
|
268
334
|
// - Use `await m.solve()` instead of `await m.optimize()`
|
|
335
|
+
// - Use `m.verify()` instead of `m.validateSolution()` (and rely on automatic integrity validation in `solve()` / `check()` / `toLpString()` instead of `m.validateIntegrity()`)
|
|
336
|
+
// - Use `m.column(...)` instead of `m.addColumn(...)`
|
|
269
337
|
// - Use `.le()`, `.ge()`, `.eq()` instead of `.lessThanOrEqual()`, `.greaterThanOrEqual()`, `.equalTo()`
|
|
270
|
-
// - Use `.value`
|
|
271
|
-
// - Use `m.variables` / `m.constraints` instead of `m.vars` / `m.constrs`
|
|
338
|
+
// - Use `.value` instead of `m.getValues(...)` or `expr.getValue()`
|
|
339
|
+
// - Use `m.variables` / `m.constraints` (`ReadonlyMap` with `.get()` / `.size`) instead of `m.vars` / `m.constrs` / `m.boolVars` / `m.logicalConstraints` / `m.numVars` / `m.numConstrs` / `get*ByName()`
|
|
340
|
+
// - Use `relativeGap` / `absoluteGap` instead of `relGap` / `mipGap` / `absGap`
|
|
272
341
|
return { m, x, y, maximize };
|
|
273
342
|
}
|
|
274
343
|
```
|
|
@@ -276,43 +345,20 @@ export function verifyNegativePatterns() {
|
|
|
276
345
|
### Practical OR Modeling Guardrails
|
|
277
346
|
|
|
278
347
|
- **Prefer inequalities (`>=` / `<=`) over exact equalities (`==`)** for demand coverage and resource limits when objective costs are positive; reserve `==` for physical conservation laws (e.g., flow balance, portfolio weights summing to `1`).
|
|
279
|
-
- **Always provide finite `lb` and `ub` bounds** on variables referenced inside `m.indicator(...)` and omit `M` so WaSHI automatically derives the tightest valid Big-M
|
|
348
|
+
- **Always provide finite `lb` and `ub` bounds** on variables referenced inside `m.indicator(...)` and omit `M` so WaSHI automatically derives the tightest valid Big-M (`m.indicator()` throws if required bounds are infinite and no explicit `M` is provided).
|
|
280
349
|
- **Use soft constraints (elastic slack variables)** for non-rigid business targets (e.g., preferred staffing, safety stock, day-off requests) by adding a non-negative slack variable (`lb: 0`) with a tiered objective penalty, reserving hard constraints for physical or legal invariants.
|
|
281
350
|
|
|
282
351
|
---
|
|
283
352
|
|
|
284
353
|
# Introduction & Installation
|
|
285
354
|
|
|
286
|
-
**WaSHI** (WebAssembly-backed, Solver-independent, High-level modeling Interface) brings the algebraic modeling style of Python's **PuLP** to the TypeScript and JavaScript ecosystem. Write expressions naturally with tagged templates (`expr`) and solve mathematical optimization problems directly in **Node.js and the browser** using WebAssembly solvers (**HiGHS**, **Z3**, and **GLPK**).
|
|
287
|
-
|
|
288
|
-
```typescript
|
|
289
|
-
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
290
|
-
|
|
291
|
-
const m = new Model("production");
|
|
292
|
-
|
|
293
|
-
// 1. Define decision variables with realistic finite bounds (lb / ub)
|
|
294
|
-
const desks = m.integer("desks", { lb: 0, ub: 100 });
|
|
295
|
-
const chairs = m.integer("chairs", { lb: 0, ub: 100 });
|
|
296
|
-
|
|
297
|
-
// 2. Set the objective function and constraints
|
|
298
|
-
m.objective(maximize(expr`30 * ${desks} + 50 * ${chairs}`));
|
|
299
|
-
m.constraint(expr`${desks} + 2 * ${chairs} <= 40`, "wood_capacity");
|
|
300
|
-
m.constraint(expr`2 * ${desks} + ${chairs} <= 50`, "labor_capacity");
|
|
301
|
-
|
|
302
|
-
// 3. Solve (built-in HiGHS WebAssembly) and validate the solution
|
|
303
|
-
const status = await m.solve();
|
|
304
|
-
if (m.hasPrimalSolution) {
|
|
305
|
-
const report = m.validateSolution();
|
|
306
|
-
console.log(status, report.valid); // "Optimal", true
|
|
307
|
-
console.log(`Profit: ${m.objectiveValue} (desks=${desks.value}, chairs=${chairs.value})`); // 1100 (desks=20, chairs=10)
|
|
308
|
-
}
|
|
309
|
-
```
|
|
355
|
+
**WaSHI** (WebAssembly-backed, Solver-independent, High-level modeling Interface) brings the algebraic modeling style of Python's **PuLP** to the TypeScript and JavaScript ecosystem. Write expressions naturally with tagged templates (`expr`) and solve mathematical optimization and constraint programming problems directly in **Node.js and the browser** using WebAssembly solvers (**HiGHS**, **Pumpkin**, **Z3**, and **GLPK**).
|
|
310
356
|
|
|
311
357
|
---
|
|
312
358
|
|
|
313
359
|
## 📦 Installation
|
|
314
360
|
|
|
315
|
-
|
|
361
|
+
Both the default **HiGHS** solver (LP / MIP / Convex QP) and the **Pumpkin** CP/LCG solver (`@ohtaman/washi/solvers/pumpkin`) are bundled with zero external dependencies and work out of the box:
|
|
316
362
|
|
|
317
363
|
```bash [npm]
|
|
318
364
|
npm install @ohtaman/washi
|
|
@@ -330,40 +376,62 @@ yarn add @ohtaman/washi
|
|
|
330
376
|
bun add @ohtaman/washi
|
|
331
377
|
```
|
|
332
378
|
|
|
333
|
-
Install optional peer dependencies
|
|
379
|
+
Install optional peer dependencies when you need **Z3** (SMT logic and Unsat Core conflict diagnosis) or **GLPK**:
|
|
334
380
|
|
|
335
381
|
```bash
|
|
336
382
|
npm install z3-solver # For SMT logic and Unsat Core conflict diagnosis
|
|
337
383
|
npm install glpk.js # For GLPK solver (GPL-3.0)
|
|
338
384
|
```
|
|
339
385
|
|
|
386
|
+
Using an AI coding agent? See [Coding with AI Agents](docs/getting-started/coding-agents.md) for `npx skills add ohtaman/washi`, `llms.txt`, and ready-to-use prompt templates.
|
|
387
|
+
|
|
340
388
|
---
|
|
341
389
|
|
|
342
|
-
##
|
|
390
|
+
## 🚀 Quick Start
|
|
343
391
|
|
|
344
|
-
|
|
345
|
-
- **Lightweight embedding with standard Web APIs & UIs**: Go beyond local analysis scripts by shipping **interactive Web tools, mini-games, or Chrome extensions** that anyone can open via a URL with zero backend hosting cost. You can wire mathematical optimization directly into drag-and-drop UIs or **standard browser capabilities**—such as screen/camera capture and speech recognition (Web Speech API)—with no network round-trips or external data transfer.
|
|
346
|
-
- **End-to-end type safety from app data to model**: Prevent common indexing and dictionary-key mistakes with TypeScript's type system. Typed variable dictionaries (`Record<K, Var>`) and variable-reference interpolation (`` expr`30 * ${qty.desk} <= 40` ``) connect directly to your application schemas, preserving compile-time variable/key checks, IDE autocompletion, and symbol renaming.
|
|
347
|
-
- **Strong synergy with AI development & LLM workflows**: Keeping your application and optimization model in a **single TypeScript codebase** lets you validate everything in one test runner—without crossing a Python service boundary—and deploy easily as static assets or a single service. That tight test-and-deploy loop fits AI-assisted coding naturally, while at runtime you can pair flexible LLM extraction with exact solver feasibility and conflict diagnosis (`unsatCore`) in the same runtime.
|
|
392
|
+
Here is a complete production-planning model illustrating the three steps of a typical WaSHI workflow:
|
|
348
393
|
|
|
349
|
-
|
|
394
|
+
```typescript
|
|
395
|
+
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
350
396
|
|
|
351
|
-
|
|
397
|
+
const m = new Model("production");
|
|
352
398
|
|
|
353
|
-
|
|
399
|
+
// 1. Define decision variables with realistic finite bounds (lb / ub)
|
|
400
|
+
const desks = m.integer("desks", { lb: 0, ub: 100 });
|
|
401
|
+
const chairs = m.integer("chairs", { lb: 0, ub: 100 });
|
|
354
402
|
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
403
|
+
// 2. Set the objective function and constraints
|
|
404
|
+
m.objective(maximize(expr`30 * ${desks} + 50 * ${chairs}`));
|
|
405
|
+
m.constraint(expr`${desks} + 2 * ${chairs} <= 40`, "wood_capacity");
|
|
406
|
+
m.constraint(expr`2 * ${desks} + ${chairs} <= 50`, "labor_capacity");
|
|
407
|
+
|
|
408
|
+
// 3. Solve (built-in HiGHS WebAssembly) and verify the solution
|
|
409
|
+
const status = await m.solve();
|
|
410
|
+
if (m.hasPrimalSolution) {
|
|
411
|
+
const report = m.verify();
|
|
412
|
+
console.log(status, report.valid); // "Optimal", true
|
|
413
|
+
console.log(`Profit: ${m.objectiveValue} (desks=${desks.value}, chairs=${chairs.value})`); // 1100 (desks=20, chairs=10)
|
|
414
|
+
}
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
1. **Define decision variables (`lb`, `ub`)**: Create variables with `m.continuous()`, `m.integer()`, or `m.binary()`, providing finite `lb` and `ub` bounds when known.
|
|
418
|
+
2. **Describe the objective and constraints (`expr`)**: Formulate equations naturally with `` expr`...` ``, and pass constraint names to make infeasibility debugging straightforward.
|
|
419
|
+
3. **Solve and verify (`solve`, `verify`)**: `await m.solve()` runs the bundled HiGHS WebAssembly solver. Check `m.hasPrimalSolution` before reading `.value`, and call `m.verify()` to independently verify that bounds, integrality, and constraints hold.
|
|
358
420
|
|
|
359
421
|
---
|
|
360
422
|
|
|
361
423
|
## 🧭 Next Steps
|
|
362
424
|
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
- **[
|
|
366
|
-
- **[
|
|
425
|
+
### Choose Your Workflow
|
|
426
|
+
|
|
427
|
+
- **Build with an AI Coding Agent**: [Coding with AI Agents](docs/getting-started/coding-agents.md) — Setup with `npx skills add`, `llms.txt` / Context7, ready-to-use prompt examples across problem types and deployment targets, and conflict debugging
|
|
428
|
+
- **Write Models Directly in TypeScript**: [Modeling Guide](docs/guide/variables.md) — Array/dictionary variables, aggregations (`sum`, `dot`), logical constraints, and conflict diagnosis
|
|
429
|
+
|
|
430
|
+
### Reference & Examples
|
|
431
|
+
|
|
432
|
+
- **[Examples & API Finder](docs/examples/index.md)**: 12 runnable optimization and SMT recipes—from shift scheduling and portfolio QP to vehicle routing
|
|
433
|
+
- **[Solvers Overview](docs/solvers/index.md)**: Compare bundled HiGHS and Pumpkin with optional Z3 and GLPK adapters
|
|
434
|
+
- **[Runtime Environments](docs/getting-started/runtimes.md)**: Setup details for Node.js, Vite / Next.js bundlers, CDNs, standalone HTML, and desktop/mobile WebViews
|
|
367
435
|
|
|
368
436
|
---
|
|
369
437
|
|
|
@@ -377,7 +445,7 @@ WaSHI runs across JavaScript and TypeScript runtimes—from Node.js, Bun, and De
|
|
|
377
445
|
|
|
378
446
|
### Node.js
|
|
379
447
|
|
|
380
|
-
WaSHI supports Node.js (v18+) out of the box with standard ECMAScript Modules (ESM).
|
|
448
|
+
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:
|
|
381
449
|
|
|
382
450
|
```typescript
|
|
383
451
|
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
@@ -444,10 +512,10 @@ export async function runOptimization() {
|
|
|
444
512
|
}
|
|
445
513
|
```
|
|
446
514
|
|
|
447
|
-
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. (
|
|
515
|
+
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](docs/getting-started/cross-origin.md).)
|
|
448
516
|
|
|
449
517
|
#### Background Web Worker Execution (Default)
|
|
450
|
-
In browsers, HiGHS automatically
|
|
518
|
+
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`).
|
|
451
519
|
|
|
452
520
|
If your environment prohibits Web Workers or you explicitly want main-thread execution, pass `useWorker: false`:
|
|
453
521
|
|
|
@@ -455,18 +523,20 @@ If your environment prohibits Web Workers or you explicitly want main-thread exe
|
|
|
455
523
|
await m.solve({ useWorker: false });
|
|
456
524
|
```
|
|
457
525
|
|
|
458
|
-
#### Customizing
|
|
459
|
-
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.).
|
|
526
|
+
#### Customizing WASM Asset URLs
|
|
527
|
+
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.).
|
|
460
528
|
|
|
461
|
-
If your bundler or static server hosts `.wasm` files under a custom path, configure the URL globally or per solve:
|
|
529
|
+
If your bundler or static server hosts `.wasm` files under a custom path, configure the URL globally or per solve/check:
|
|
462
530
|
|
|
463
531
|
```typescript
|
|
464
532
|
import { setHighsWasmUrl } from "@ohtaman/washi";
|
|
533
|
+
import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
|
|
465
534
|
|
|
466
535
|
// Option A: Configure globally before solving
|
|
467
536
|
setHighsWasmUrl("/assets/wasm/highs.wasm");
|
|
537
|
+
setPumpkinWasmUrl("/assets/wasm/pumpkin.wasm");
|
|
468
538
|
|
|
469
|
-
// Option B: Configure per solve call
|
|
539
|
+
// Option B: Configure per solve / check call
|
|
470
540
|
await m.solve({ wasmUrl: "/assets/wasm/highs.wasm" });
|
|
471
541
|
```
|
|
472
542
|
|
|
@@ -502,6 +572,24 @@ export default function OptimizerComponent() {
|
|
|
502
572
|
}
|
|
503
573
|
```
|
|
504
574
|
|
|
575
|
+
### Desktop & Mobile WebView Apps (Tauri / Capacitor / PWA)
|
|
576
|
+
|
|
577
|
+
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.
|
|
578
|
+
|
|
579
|
+
In `tauri.conf.json`, allow WebAssembly compilation (`'wasm-unsafe-eval'` in `script-src`) and Web Workers (`worker-src 'self' blob:`), or pass `{ useWorker: false }`:
|
|
580
|
+
|
|
581
|
+
```json
|
|
582
|
+
{
|
|
583
|
+
"app": {
|
|
584
|
+
"security": {
|
|
585
|
+
"csp": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:"
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
Bundled **HiGHS** and **Pumpkin** are recommended over **Z3** in desktop and mobile WebViews because they do not require `SharedArrayBuffer` or `COOP`/`COEP` headers.
|
|
592
|
+
|
|
505
593
|
---
|
|
506
594
|
|
|
507
595
|
## 📦 Browser ESM (`<script type="module">`)
|
|
@@ -511,10 +599,11 @@ Without a bundler, you can import the pre-built browser ESM module directly from
|
|
|
511
599
|
```html
|
|
512
600
|
<script type="module">
|
|
513
601
|
// From an npm CDN (or "./dist/browser/washi.js" when self-hosted):
|
|
514
|
-
import { Model, expr, maximize } from "https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
515
|
-
//
|
|
516
|
-
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
517
|
-
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
602
|
+
import { Model, expr, maximize } from "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.js";
|
|
603
|
+
// Bundled / optional solver plugins:
|
|
604
|
+
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin.js";
|
|
605
|
+
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/glpk.js";
|
|
606
|
+
// import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/z3.js";
|
|
518
607
|
|
|
519
608
|
const m = new Model("BrowserESM");
|
|
520
609
|
const x = m.integer("x", { lb: 0, ub: 100 });
|
|
@@ -549,10 +638,11 @@ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a stan
|
|
|
549
638
|
<pre id="output">Solving...</pre>
|
|
550
639
|
|
|
551
640
|
<!-- Core WaSHI + HiGHS (MIT) via CDN (or "./dist/browser/washi.min.js" when self-hosted) -->
|
|
552
|
-
<script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
553
|
-
<!--
|
|
554
|
-
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
555
|
-
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi
|
|
641
|
+
<script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.min.js"></script>
|
|
642
|
+
<!-- Bundled / optional plugins (auto-register on window.Washi): -->
|
|
643
|
+
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin.min.js"></script> -->
|
|
644
|
+
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/glpk.min.js"></script> -->
|
|
645
|
+
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/z3.min.js"></script> -->
|
|
556
646
|
|
|
557
647
|
<script>
|
|
558
648
|
(async () => {
|
|
@@ -580,7 +670,8 @@ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a stan
|
|
|
580
670
|
```
|
|
581
671
|
|
|
582
672
|
> [!NOTE]
|
|
583
|
-
>
|
|
673
|
+
> - **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://..."`).
|
|
674
|
+
> - **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://`.
|
|
584
675
|
|
|
585
676
|
---
|
|
586
677
|
|
|
@@ -590,14 +681,15 @@ WaSHI never phones home or falls back to public CDNs. To self-host in an air-gap
|
|
|
590
681
|
|
|
591
682
|
1. **Copy Static Assets**: Serve the files from `node_modules/@ohtaman/washi/dist/browser/` on your own origin:
|
|
592
683
|
- `washi.js` / `washi.min.js`, `highs.wasm`, and `highs-worker.js`
|
|
684
|
+
- Bundled Pumpkin: `solvers/pumpkin.js` / `solvers/pumpkin.min.js`, `solvers/pumpkin.wasm`, `solvers/pumpkin-worker.js` (plus `solvers/pumpkin-*.js` chunks)
|
|
593
685
|
- Optional GLPK: `solvers/glpk.js` / `solvers/glpk.min.js`
|
|
594
686
|
- Optional Z3: `solvers/z3.js` / `solvers/z3.min.js`, `solvers/z3-built.js`, `solvers/z3-built.wasm`
|
|
595
687
|
2. **Content Security Policy (CSP) Headers**:
|
|
596
688
|
- Allow WebAssembly compilation (`'wasm-unsafe-eval'` in `script-src`).
|
|
597
689
|
- If using the default Web Worker or cross-origin Blob worker bootstrap, allow `worker-src 'self' blob:;`.
|
|
598
|
-
- 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 })`.
|
|
690
|
+
- 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 })`.
|
|
599
691
|
3. **Cross-Origin Isolation (Z3 Only)**:
|
|
600
|
-
- HiGHS and GLPK run in standard browser contexts without special headers.
|
|
692
|
+
- HiGHS, Pumpkin, and GLPK run in standard browser contexts without special headers.
|
|
601
693
|
- 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](docs/getting-started/cross-origin.md) for setup details.
|
|
602
694
|
|
|
603
695
|
---
|
|
@@ -607,7 +699,7 @@ WaSHI never phones home or falls back to public CDNs. To self-host in an air-gap
|
|
|
607
699
|
When running the **Z3** solver inside a web browser, Cross-Origin Isolation HTTP headers are required so the browser enables `SharedArrayBuffer`.
|
|
608
700
|
|
|
609
701
|
> [!TIP]
|
|
610
|
-
> **Not needed for HiGHS, GLPK, or Node.js**:
|
|
702
|
+
> **Not needed for HiGHS, Pumpkin, GLPK, or Node.js**: Bundled **HiGHS** and **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`), as well as the **GLPK** plugin, run in standard browser contexts without Cross-Origin Isolation or `SharedArrayBuffer` (including Pumpkin CP solving, propositional logic, and `unsatCore` conflict diagnosis). Running Z3 in **Node.js** also requires no HTTP headers. You only need this page when using `@ohtaman/washi/solvers/z3` in the browser.
|
|
611
703
|
|
|
612
704
|
---
|
|
613
705
|
|
|
@@ -703,7 +795,7 @@ app.use((req, res, next) => {
|
|
|
703
795
|
|
|
704
796
|
Platforms like GitHub Pages do not allow customizing HTTP response headers directly. You can use **`coi-serviceworker`** to inject the isolation headers via a client-side Service Worker:
|
|
705
797
|
|
|
706
|
-
1.
|
|
798
|
+
1. Obtain `coi-serviceworker.js` from [`coi-serviceworker`](https://github.com/gzuidhof/coi-serviceworker) (GitHub / npm) or WaSHI's reference [`public/coi-serviceworker.js`](https://github.com/ohtaman/washi/blob/main/public/coi-serviceworker.js), and place it at your site root.
|
|
707
799
|
2. Load it in your HTML `<head>`:
|
|
708
800
|
|
|
709
801
|
```html
|
|
@@ -777,7 +869,7 @@ m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
|
|
|
777
869
|
| **Linear arithmetic (`expr`, `sum`, `dot`, objective costs)** | ✅ Native (`` expr`30 * ${b}` ``) | ❌ Cannot be multiplied by numbers or summed directly |
|
|
778
870
|
| **Indicator constraints (`m.indicator(b, ...)` )** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
|
|
779
871
|
| **Propositional logic (`and`, `or`, `not`, `implies`, `xor`)** | Via comparison (`` expr`${b} == 1` ``) | ✅ Native first-class methods (`.implies()`, `.and()`) |
|
|
780
|
-
| **Solver execution** | Native 0-1 MIP on HiGHS/GLPK; bounded integer on Z3 | Native boolean proposition on Z3; auto-linearized to 0-1 MIP on HiGHS/GLPK |
|
|
872
|
+
| **Solver execution** | Native 0-1 MIP on HiGHS/GLPK; bounded `{0, 1}` integer on Pumpkin/Z3 | Native boolean proposition on Pumpkin/Z3; auto-linearized to 0-1 MIP on HiGHS/GLPK |
|
|
781
873
|
|
|
782
874
|
> [!TIP]
|
|
783
875
|
> Use **`m.binary()`** when a decision participates in arithmetic expressions—such as linear sums ($\sum x_i \ge 3$), objective cost terms ($c_i x_i$), or `m.indicator()`. Use **`m.bool()`** when expressing logical conditions with `implies()`, `and()`, and `or()` without numeric coefficients.
|
|
@@ -839,11 +931,17 @@ const schedule = m.binary(factories, 7, { prefix: "open_day" });
|
|
|
839
931
|
|
|
840
932
|
| Option | Type | Default | Description |
|
|
841
933
|
| :--- | :--- | :--- | :--- |
|
|
842
|
-
| `lb` | `number` | `0` | Lower bound. Defaults to `0` (non-negative). |
|
|
934
|
+
| `lb` | `number` | `0` | Lower bound. Defaults to `0` (non-negative). Pass `-Infinity` for free lower bounds. |
|
|
843
935
|
| `ub` | `number` | `Infinity` (or `1` for binary) | Upper bound. |
|
|
936
|
+
| `prefix` | `string` | `"x"` (`"p"` for `m.bool()`) | Name prefix for unnamed scalar variables and indexed arrays/matrices (e.g., `queen_0_0`). |
|
|
844
937
|
| `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Underlying variable domain category. |
|
|
845
938
|
| `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP warm start), kept distinct from solved `variable.value`. |
|
|
846
939
|
|
|
940
|
+
### Designing Bounds (`lb` & `ub`)
|
|
941
|
+
|
|
942
|
+
- **Default non-negativity**: Numeric variables default to `lb: 0, ub: Infinity`. If a variable can take negative values (such as net inventory change or deviation), explicitly pass `{ lb: -Infinity }`.
|
|
943
|
+
- **Prefer realistic finite bounds**: Specifying finite `lb` and `ub` values strengthens MIP presolve, allows `m.indicator()` to derive tight Big-M constants automatically, and is required by bounded-integer CP solvers such as **Pumpkin**.
|
|
944
|
+
|
|
847
945
|
---
|
|
848
946
|
|
|
849
947
|
## Primal Initial Values (Warm-Start Hints)
|
|
@@ -865,43 +963,50 @@ const openWarehouse2 = m2.binary("open_warehouse", {
|
|
|
865
963
|
const extraCapacity = m2.continuous("extra_capacity", { lb: 0 }); // Partial start: no initialValue needed
|
|
866
964
|
```
|
|
867
965
|
|
|
868
|
-
- **Hint vs. Hard Constraint**: `initialValue` is an optional solver hint (passed to HiGHS via `setSolution`). It does **not** fix the variable or add a constraint, and `variable.value` remains `null` until solved. *(To penalize deviations from a previous plan, see [Formulation Patterns & Tips](docs/guide/formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).)*
|
|
966
|
+
- **Hint vs. Hard Constraint**: `initialValue` is an optional solver hint (passed to HiGHS via `setSolution`, or to Pumpkin's `WarmStart` branching strategy). It does **not** fix the variable or add a constraint, and `variable.value` remains `null` until solved. *(To penalize deviations from a previous plan, see [Formulation Patterns & Tips](docs/guide/formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).)*
|
|
869
967
|
- **Validation & Tolerance (`1e-6`)**: Supplied values must be finite numbers within `[lb - 1e-6, ub + 1e-6]` (and within `1e-6` of an integer for `"Integer"` and `"Binary"` variables). Partial starts are accepted without needing to satisfy every model constraint, though supplying a complete constraint-feasible assignment gives MIP solvers an immediate incumbent bound.
|
|
870
|
-
- **Solver Support**: Supported by **HiGHS** (`capabilities.supportsWarmStart === true`). Solvers without warm-start support (**GLPK**, **Z3**, or custom adapters without `supportsWarmStart: true`) reject `solve()` and `check()` with a descriptive error rather than silently ignoring `initialValue`.
|
|
968
|
+
- **Solver Support**: Supported by **HiGHS** and **Pumpkin** (`capabilities.supportsWarmStart === true`; Pumpkin supports `initialValue` on bounded `Integer` and `Binary` variables in both `solve()` and `check()`). Solvers without warm-start support (**GLPK**, **Z3**, or custom adapters without `supportsWarmStart: true`) reject `solve()` and `check()` with a descriptive error rather than silently ignoring `initialValue`.
|
|
871
969
|
|
|
872
970
|
---
|
|
873
971
|
|
|
874
972
|
## Accessing Solution Values & Reduced Costs
|
|
875
973
|
|
|
876
|
-
After calling `await m.solve()` or `await m.check()`, assigned variable values are accessible via `variable.value` (returns `number | null` for `Var`, or `boolean | null` for `BoolVar`) or
|
|
974
|
+
After calling `await m.solve()` or `await m.check()`, assigned variable values are accessible directly via `variable.value` (returns `number | null` for `Var`, or `boolean | null` for `BoolVar`), or by variable name via `m.values`:
|
|
877
975
|
|
|
878
976
|
```typescript
|
|
879
977
|
await m.solve();
|
|
880
978
|
|
|
881
|
-
//
|
|
979
|
+
// Scalar variable primal & boolean values
|
|
882
980
|
console.log(`trucks: ${trucks.value}`);
|
|
981
|
+
console.log(`isAdmin: ${isAdmin.value}`);
|
|
883
982
|
|
|
884
|
-
//
|
|
885
|
-
|
|
983
|
+
// Indexed 1D & 2D variable containers
|
|
984
|
+
const packedItems = items.filter((it) => selected[it].value === 1);
|
|
985
|
+
console.log(`Tokyo -> StoreA: ${ship.Tokyo.StoreA.value}`);
|
|
886
986
|
|
|
887
|
-
//
|
|
888
|
-
|
|
889
|
-
// { laptop: 1, phone: 0, tablet: 1 }
|
|
987
|
+
// Name-keyed ReadonlyMap lookup (ReadonlyMap<string, number | boolean>)
|
|
988
|
+
console.log(`trucks by name: ${m.values.get("trucks")}`);
|
|
890
989
|
|
|
891
|
-
|
|
892
|
-
|
|
990
|
+
// Reduced cost (LP sensitivity analysis)
|
|
991
|
+
console.log(`fuel reduced cost: ${fuel.reducedCost}`);
|
|
893
992
|
```
|
|
894
993
|
|
|
895
994
|
---
|
|
896
995
|
|
|
897
996
|
## Looking Up Variables by Name
|
|
898
997
|
|
|
899
|
-
|
|
998
|
+
All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are exposed through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
|
|
900
999
|
|
|
901
1000
|
```typescript
|
|
902
|
-
const v = m.
|
|
903
|
-
const b = m.
|
|
904
|
-
console.log("
|
|
1001
|
+
const v = m.variables.get("trucks"); // Var | BoolVar | undefined
|
|
1002
|
+
const b = m.variables.get("isAdmin"); // Var | BoolVar | undefined
|
|
1003
|
+
console.log("Has trucks:", m.variables.has("trucks"));
|
|
1004
|
+
console.log("Total variables:", m.variables.size);
|
|
1005
|
+
|
|
1006
|
+
// Narrow by v.type ("Continuous" | "Integer" | "Binary" | "Boolean"):
|
|
1007
|
+
if (v && v.type !== "Boolean") {
|
|
1008
|
+
console.log("Bounds:", v.lb, v.ub);
|
|
1009
|
+
}
|
|
905
1010
|
```
|
|
906
1011
|
|
|
907
1012
|
---
|
|
@@ -951,6 +1056,7 @@ const balanceConstraint = expr`${x} + 2 * ${y} <= 40`;
|
|
|
951
1056
|
- **Unary Plus & Negation**: `-${x} + 10`, `+${x}`
|
|
952
1057
|
- **Parentheses**: `2 * (${x} + ${y})`
|
|
953
1058
|
- **Aggregations (`sum` & `dot`)**: `sum(${xVec}) <= 100`, `dot(${costs}, ${xVec})`, `sum(${rows}, ${(r) => grid[r][col]})`
|
|
1059
|
+
- **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))
|
|
954
1060
|
- **Element-Wise Container Arithmetic**: `sum((${price} - ${cost}) * ${qty})`, `sum((${xVec} - ${target})^2)`, `dot(${price} - ${cost}, ${qty})`
|
|
955
1061
|
- **Nested Expressions**: `expr` interpolates variables, numbers, `Array` / `Record` containers (inside `sum` or `dot`), and nested `LinExpr` / `QuadExpr` objects.
|
|
956
1062
|
|
|
@@ -1040,22 +1146,18 @@ const totalShippingCost = expr`dot(${costs}, ${ship})`;
|
|
|
1040
1146
|
|
|
1041
1147
|
## Composing Aggregations in `expr`
|
|
1042
1148
|
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
Write mathematical operators, `sum(...)`, `dot(..., ...)`, and comparison symbols (`<=`, `>=`, `==`) in the template string, and pass variables, scalars, and containers (`Array` / `Record`) via `${...}`:
|
|
1149
|
+
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()`:
|
|
1046
1150
|
|
|
1047
1151
|
```typescript
|
|
1048
|
-
//
|
|
1152
|
+
// Verbose: nested standalone calls and Object.values()
|
|
1049
1153
|
const totalProfit1 = expr`${dot(profits, vars)}`;
|
|
1050
1154
|
const cap1 = expr`${sum(Object.values(vars))} <= 100`;
|
|
1051
1155
|
|
|
1052
|
-
//
|
|
1156
|
+
// Recommended: direct sum() and dot() inside expr
|
|
1053
1157
|
const totalProfit2 = expr`dot(${profits}, ${vars})`;
|
|
1054
1158
|
const cap2 = expr`sum(${vars}) <= 100`;
|
|
1055
1159
|
```
|
|
1056
1160
|
|
|
1057
|
-
### Common `expr` Aggregation Syntax
|
|
1058
|
-
|
|
1059
1161
|
| Operation | Mathematical Formula | WaSHI Expression |
|
|
1060
1162
|
| :--- | :--- | :--- |
|
|
1061
1163
|
| **Total sum** (1D/2D `Array` or `Record`) | $\sum_i x_i \le C$ | `` m.constraint(expr`sum(${x}) <= ${C}`) `` |
|
|
@@ -1119,6 +1221,38 @@ m.objective(minimize(risk));
|
|
|
1119
1221
|
|
|
1120
1222
|
---
|
|
1121
1223
|
|
|
1224
|
+
## Piecewise-Linear & Element Expressions (`max`, `min`, `abs`, `at`)
|
|
1225
|
+
|
|
1226
|
+
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`:
|
|
1227
|
+
|
|
1228
|
+
```typescript
|
|
1229
|
+
import { Model, expr, minimize, abs, max, min, at } from "@ohtaman/washi";
|
|
1230
|
+
|
|
1231
|
+
const m = new Model();
|
|
1232
|
+
const w = m.continuous(3, { lb: 0, ub: 20, prefix: "w" });
|
|
1233
|
+
const target = [4, 7, 10];
|
|
1234
|
+
const route = m.integer("route", { lb: 0, ub: 2 });
|
|
1235
|
+
const routeCost = [18, 12, 25];
|
|
1236
|
+
|
|
1237
|
+
// Convex LP epigraph (zero binary variables on HiGHS / GLPK):
|
|
1238
|
+
m.objective(
|
|
1239
|
+
minimize(expr`sum(abs(${w} - ${target})) + at(${routeCost}, ${route})`)
|
|
1240
|
+
);
|
|
1241
|
+
m.constraint(expr`max(${w}) <= 15`, "peak_cap");
|
|
1242
|
+
|
|
1243
|
+
// Nested composition and programmatic helpers also work:
|
|
1244
|
+
const maxErr = max(expr`abs(${w[0]} - 4)`, abs(expr`${w[1]} - 7`));
|
|
1245
|
+
m.constraint(expr`${maxErr} <= 3`);
|
|
1246
|
+
```
|
|
1247
|
+
|
|
1248
|
+
- **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.
|
|
1249
|
+
- **Polarity-aware MIP lowering vs native CP/SMT**:
|
|
1250
|
+
- 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).
|
|
1251
|
+
- 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`).
|
|
1252
|
+
- **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).
|
|
1253
|
+
|
|
1254
|
+
---
|
|
1255
|
+
|
|
1122
1256
|
## Evaluating Expressions After Solving (`.value`)
|
|
1123
1257
|
|
|
1124
1258
|
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:
|
|
@@ -1158,9 +1292,12 @@ In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent
|
|
|
1158
1292
|
| `.mul(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Multiplies by a scalar `number`, or multiplies two linear terms into a `QuadExpr`. |
|
|
1159
1293
|
| `.div(divisor)` | `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Divides by a non-zero finite scalar `number`. |
|
|
1160
1294
|
| `.neg()` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Negates all terms ($-e$). |
|
|
1161
|
-
| `.le(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs
|
|
1162
|
-
| `.ge(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs
|
|
1163
|
-
| `.eq(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs
|
|
1295
|
+
| `.le(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`; linear LHS required). |
|
|
1296
|
+
| `.ge(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`; linear LHS required). |
|
|
1297
|
+
| `.eq(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs`; linear LHS required). |
|
|
1298
|
+
| `.lt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $<$ constraint (`lhs - rhs <= -1`; integer-valued expressions only). |
|
|
1299
|
+
| `.gt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $>$ constraint (`lhs - rhs >= 1`; integer-valued expressions only). |
|
|
1300
|
+
| `.ne(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $\ne$ constraint (`lhs != rhs`; integer-valued expressions only). |
|
|
1164
1301
|
|
|
1165
1302
|
---
|
|
1166
1303
|
|
|
@@ -1202,6 +1339,7 @@ m.constraint(expr`${x} + ${y} == 30`, "exact_quota");
|
|
|
1202
1339
|
- `<=`: Upper bound constraint
|
|
1203
1340
|
- `>=`: Lower bound constraint
|
|
1204
1341
|
- `==` or `=`: Exact equality constraint
|
|
1342
|
+
- `<`, `>`, `!=`: Discrete strict inequality / disequality constraints (integer-valued expressions only; see [Discrete Comparisons](#discrete-comparisons))
|
|
1205
1343
|
|
|
1206
1344
|
### Batch Registration
|
|
1207
1345
|
Pass an array of constraints to `m.constraint([...])` to register them transactionally in a single call:
|
|
@@ -1222,8 +1360,8 @@ m.constraint(expr`${x} + ${y} <= 100`, "budget_cap");
|
|
|
1222
1360
|
|
|
1223
1361
|
### Why Name Constraints?
|
|
1224
1362
|
1. **Model Inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain these descriptive names (sanitized if needed) so you can inspect the generated formulation.
|
|
1225
|
-
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`).
|
|
1226
|
-
3. **Direct Lookup (`m.
|
|
1363
|
+
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`).
|
|
1364
|
+
3. **Direct Lookup (`m.constraints.get()`)**: Retrieve any registered constraint by name after solving to inspect its `dual` or `slack` value.
|
|
1227
1365
|
|
|
1228
1366
|
---
|
|
1229
1367
|
|
|
@@ -1248,6 +1386,23 @@ m.constraint(expr`dot(${weights}, ${selected}) <= 25`, "capacity_limit");
|
|
|
1248
1386
|
|
|
1249
1387
|
---
|
|
1250
1388
|
|
|
1389
|
+
## Dual Values, Shadow Prices & Lookups
|
|
1390
|
+
|
|
1391
|
+
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()`):
|
|
1392
|
+
|
|
1393
|
+
```typescript
|
|
1394
|
+
const woodConstraint = m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
|
|
1395
|
+
|
|
1396
|
+
await m.solve();
|
|
1397
|
+
|
|
1398
|
+
console.log("Shadow price (dual):", woodConstraint.dual);
|
|
1399
|
+
console.log("Slack surplus:", woodConstraint.slack);
|
|
1400
|
+
console.log("Looked-up dual:", m.constraints.get("wood")?.dual); // number | null (null for MIP, CP, or logical constraints)
|
|
1401
|
+
console.log("Total constraints:", m.constraints.size);
|
|
1402
|
+
```
|
|
1403
|
+
|
|
1404
|
+
---
|
|
1405
|
+
|
|
1251
1406
|
## Conditional / Indicator Constraints (`m.indicator`)
|
|
1252
1407
|
|
|
1253
1408
|
When a linear constraint should only take effect when a binary decision variable (`m.binary()`) equals `1` (or `0`), use `m.indicator()`:
|
|
@@ -1273,6 +1428,9 @@ When `options.M` is omitted, WaSHI automatically derives a minimal valid Big-M v
|
|
|
1273
1428
|
|
|
1274
1429
|
If any referenced variable lacks the required finite bound, `m.indicator()` throws an error prompting for finite bounds or an explicit `options.M`.
|
|
1275
1430
|
|
|
1431
|
+
> [!NOTE]
|
|
1432
|
+
> **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.
|
|
1433
|
+
|
|
1276
1434
|
### Explicit `M` Override
|
|
1277
1435
|
|
|
1278
1436
|
You can override the derived Big-M by passing `{ M: number }`:
|
|
@@ -1291,7 +1449,7 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
|
|
|
1291
1449
|
|
|
1292
1450
|
## Propositional Logic & SMT Constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`)
|
|
1293
1451
|
|
|
1294
|
-
WaSHI provides first-class logical operators to combine propositional boolean variables (`m.bool()`) and linear constraints (`Constraint`). Logical formulas are solved natively by
|
|
1452
|
+
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**:
|
|
1295
1453
|
|
|
1296
1454
|
```typescript
|
|
1297
1455
|
import { Model, expr, and, or, not, implies, xor } from "@ohtaman/washi";
|
|
@@ -1315,35 +1473,64 @@ m.constraint(
|
|
|
1315
1473
|
m.constraint(and(or(isAdmin, hasMfa), not(xor(isAdmin, hasMfa))), "policy");
|
|
1316
1474
|
```
|
|
1317
1475
|
|
|
1476
|
+
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)`.
|
|
1477
|
+
|
|
1318
1478
|
### Choosing Between `m.indicator()` and `implies()`
|
|
1319
1479
|
|
|
1320
1480
|
| Feature | `m.indicator(binVar, constraint, opts)` | `implies(a, b)` / `a.implies(b)` |
|
|
1321
1481
|
| :--- | :--- | :--- |
|
|
1322
1482
|
| **Trigger variable** | Numeric `Binary` variable (`m.binary()`) | `BoolVar` (`m.bool()`), `BoolOp`, or `Constraint` |
|
|
1323
1483
|
| **Consequent** | Linear `Constraint` (`<=`, `>=`, `==`) | `BoolVar`, `BoolOp`, or linear `Constraint` |
|
|
1324
|
-
| **Target Solvers** | **All MIP/LP solvers** (HiGHS, GLPK
|
|
1484
|
+
| **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) |
|
|
1325
1485
|
| **Primary Use Case** | MIP optimization models with arithmetic binary variables (`m.solve()`) | Logical rule systems and SMT feasibility (`m.check()`) |
|
|
1326
1486
|
|
|
1327
1487
|
> [!NOTE]
|
|
1328
|
-
> **
|
|
1488
|
+
> **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.
|
|
1329
1489
|
|
|
1330
1490
|
---
|
|
1331
1491
|
|
|
1332
|
-
##
|
|
1492
|
+
## Discrete Comparisons (`!=`, `<`, `>`)
|
|
1333
1493
|
|
|
1334
|
-
|
|
1494
|
+
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):
|
|
1335
1495
|
|
|
1336
1496
|
```typescript
|
|
1337
|
-
const
|
|
1497
|
+
const rankA = m.integer("rankA", { lb: 1, ub: 4 });
|
|
1498
|
+
const rankB = m.integer("rankB", { lb: 1, ub: 4 });
|
|
1499
|
+
const roomA = m.integer("roomA", { lb: 1, ub: 3 });
|
|
1500
|
+
const roomB = m.integer("roomB", { lb: 1, ub: 3 });
|
|
1338
1501
|
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
console.log("Shadow price (dual):", woodConstraint.dual);
|
|
1342
|
-
console.log("Slack surplus:", woodConstraint.slack);
|
|
1343
|
-
console.log("Total linear constraints:", m.numConstrs);
|
|
1502
|
+
m.constraint(expr`${rankA} < ${rankB}`, "strict_order"); // lowered via rankA - rankB <= -1
|
|
1503
|
+
m.constraint(expr`${roomA} != ${roomB}`, "diff_room"); // native not_equals on Pumpkin, neq on Z3, single-binary MIP on HiGHS/GLPK
|
|
1344
1504
|
```
|
|
1345
1505
|
|
|
1346
|
-
|
|
1506
|
+
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.
|
|
1507
|
+
|
|
1508
|
+
---
|
|
1509
|
+
|
|
1510
|
+
## CP Global Constraints (`distinct`, `disjoint`, `cumulative`, `allowed`)
|
|
1511
|
+
|
|
1512
|
+
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](docs/guide/constraint-programming.md).
|
|
1513
|
+
|
|
1514
|
+
| Predicate | Semantics | HiGHS / GLPK | Pumpkin | Z3 |
|
|
1515
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
1516
|
+
| `distinct(...args)` | Pairwise `a != b` across integer expressions / 1D–2D containers (`AllDifferent`) | Pairwise `!=` MIP | `all_different` | `ctx.Distinct` |
|
|
1517
|
+
| `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 |
|
|
1518
|
+
| `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 |
|
|
1519
|
+
| `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` |
|
|
1520
|
+
|
|
1521
|
+
```typescript
|
|
1522
|
+
import { Model, expr, distinct, disjoint, cumulative, allowed, not, minimize } from "@ohtaman/washi";
|
|
1523
|
+
|
|
1524
|
+
const m = new Model("ScheduleAndAssign");
|
|
1525
|
+
const s = m.integer(2, { lb: 0, ub: 10, prefix: "s" });
|
|
1526
|
+
const room = m.integer(2, { lb: 1, ub: 2, prefix: "room" });
|
|
1527
|
+
|
|
1528
|
+
m.constraint(distinct(room), "unique_rooms");
|
|
1529
|
+
m.constraint(disjoint([{ start: s[0], duration: 4 }, { start: s[1], duration: 3 }]), "machine_1");
|
|
1530
|
+
m.constraint(not(allowed([room[0], room[1]], [[1, 2]])), "forbid_1_2");
|
|
1531
|
+
m.constraint(cumulative([{ start: s[0], duration: 4, demand: 1 }, { start: s[1], duration: 3, demand: 1 }], 2), "workers");
|
|
1532
|
+
m.objective(minimize(expr`${s[0]} + ${s[1]}`));
|
|
1533
|
+
```
|
|
1347
1534
|
|
|
1348
1535
|
> [!TIP]
|
|
1349
1536
|
> For modeling techniques such as **soft constraints with slack variables** and **symmetry breaking**, see [Formulation Patterns & Optimization Tips](docs/guide/formulation-tips.md#_3-constraint-design-numerical-conditioning).
|
|
@@ -1378,7 +1565,7 @@ m.constraint(expr`2 * ${x} + 3 * ${y} <= 100`, "resource_limit");
|
|
|
1378
1565
|
Calling `m.objective()` with no arguments returns the current objective expression (`LinExpr | QuadExpr`). If you omit setting an objective, the model defaults to minimizing `0`.
|
|
1379
1566
|
|
|
1380
1567
|
> [!TIP]
|
|
1381
|
-
> For objective formulation patterns—such as **Min-Max / Max-Min load balancing**, **weighted-sum vs. lexicographic multi-objective optimization**, and **MIP stopping tolerances (`
|
|
1568
|
+
> For objective formulation patterns—such as **Min-Max / Max-Min load balancing**, **weighted-sum vs. lexicographic multi-objective optimization**, and **MIP stopping tolerances (`relativeGap` / `absoluteGap`)**—see [Formulation Patterns & Optimization Tips](docs/guide/formulation-tips.md#_4-multi-objective-mip-stopping-design).
|
|
1382
1569
|
|
|
1383
1570
|
---
|
|
1384
1571
|
|
|
@@ -1389,13 +1576,13 @@ WaSHI provides two asynchronous execution entrypoints:
|
|
|
1389
1576
|
| Method | Return Value | Purpose |
|
|
1390
1577
|
| :--- | :--- | :--- |
|
|
1391
1578
|
| **`await m.solve(options?)`** | `Promise<SolverStatus>` | Optimizes the objective (`Minimize` or `Maximize`) subject to all constraints. Populates primal values, objective value, MIP bounds/gaps, and LP duals/slacks. |
|
|
1392
|
-
| **`await m.check(options?)`** | `Promise<CheckResult>` | Checks constraint satisfiability without an objective. Returns `{ status, values, conflicts?, unsatCore?, runTime? }` where `values: Record<string, number \| boolean>` contains both numeric and Boolean variable assignments. Ideal for SMT/SAT verification and Z3 `unsatCore` extraction. |
|
|
1579
|
+
| **`await m.check(options?)`** | `Promise<CheckResult>` | Checks constraint satisfiability without an objective. Returns `{ status, values, conflicts?, unsatCore?, runTime? }` where `values: Record<string, number \| boolean>` contains both numeric and Boolean variable assignments. Ideal for CP/SMT/SAT verification and Pumpkin / Z3 `unsatCore` extraction. |
|
|
1393
1580
|
|
|
1394
1581
|
```typescript
|
|
1395
1582
|
const status = await m.solve({
|
|
1396
|
-
timeLimit: 10.0,
|
|
1397
|
-
|
|
1398
|
-
outputFlag: false,
|
|
1583
|
+
timeLimit: 10.0, // Timeout in seconds
|
|
1584
|
+
relativeGap: 0.01, // Stop within 1% of global optimum
|
|
1585
|
+
outputFlag: false, // Enable/disable solver console logging (HiGHS: outputFlag, GLPK: verbose)
|
|
1399
1586
|
});
|
|
1400
1587
|
```
|
|
1401
1588
|
|
|
@@ -1403,14 +1590,14 @@ const status = await m.solve({
|
|
|
1403
1590
|
|
|
1404
1591
|
| Option | Type | Default | Description |
|
|
1405
1592
|
| :--- | :--- | :--- | :--- |
|
|
1406
|
-
| `solver` | `string` \| `Solver` | Model's solver (`"highs"`) | Registered solver name (e.g. `"highs"`, `"z3"`, `"glpk"`, or custom) or `Solver` instance for this run. |
|
|
1593
|
+
| `solver` | `string` \| `Solver` | Model's solver (`"highs"`) | Registered solver name (e.g. `"highs"`, `"pumpkin"`, `"z3"`, `"glpk"`, or custom) or `Solver` instance for this run. |
|
|
1407
1594
|
| `timeLimit` | `number` | `undefined` | Maximum solve duration in seconds. |
|
|
1408
|
-
| `
|
|
1409
|
-
| `
|
|
1595
|
+
| `relativeGap` | `number` | `undefined` | Relative MIP optimality gap tolerance (e.g. `0.01` for 1%). |
|
|
1596
|
+
| `absoluteGap` | `number` | `undefined` | Absolute MIP optimality gap tolerance (HiGHS `mip_abs_gap`). |
|
|
1410
1597
|
| `presolve` | `"on"` \| `"off"` \| `"choose"` | `"choose"` | Controls solver presolve reduction prior to optimization. |
|
|
1411
1598
|
| `outputFlag` / `verbose` | `boolean` | `false` | Emits internal solver iteration logs (`outputFlag` for HiGHS, `verbose` for GLPK). |
|
|
1412
|
-
| `useWorker` | `boolean` | `true` (browser) | Offloads HiGHS to
|
|
1413
|
-
| `wasmUrl` | `string` | Auto-resolved | Custom URL to load `highs.wasm` in browser deployments. |
|
|
1599
|
+
| `useWorker` | `boolean` | `true` (browser) | Offloads **HiGHS** and **Pumpkin** to dedicated Web Workers in browsers. Set `false` for main-thread execution. |
|
|
1600
|
+
| `wasmUrl` | `string` | Auto-resolved | Custom URL to load `highs.wasm` or `pumpkin.wasm` in browser deployments. |
|
|
1414
1601
|
| `signal` | `AbortSignal` | `undefined` | Cooperative cancellation signal (`AbortController.signal`). |
|
|
1415
1602
|
| `onProgress` | `(e: SolveProgressEvent) => void` | `undefined` | Callback receiving live solver progress snapshots. |
|
|
1416
1603
|
|
|
@@ -1418,52 +1605,6 @@ You can also pass a solver name directly as the first argument: `await m.solve("
|
|
|
1418
1605
|
|
|
1419
1606
|
---
|
|
1420
1607
|
|
|
1421
|
-
## Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
|
|
1422
|
-
|
|
1423
|
-
For long-running MIP optimizations in interactive UIs, you can stream live branch-and-bound progress (`SolveProgressEvent`) and allow users to cancel the solve cleanly with `AbortController`:
|
|
1424
|
-
|
|
1425
|
-
```typescript
|
|
1426
|
-
const controller = new AbortController();
|
|
1427
|
-
|
|
1428
|
-
// Example: cancel if the user clicks a "Stop" button or after a custom condition
|
|
1429
|
-
const status = await m.solve({
|
|
1430
|
-
signal: controller.signal,
|
|
1431
|
-
onProgress: (event) => {
|
|
1432
|
-
console.log(
|
|
1433
|
-
`[${event.elapsedTime.toFixed(1)}s] ` +
|
|
1434
|
-
`Best: ${event.objectiveValue ?? "—"}, ` +
|
|
1435
|
-
`Bound: ${event.objectiveBound ?? "—"}, ` +
|
|
1436
|
-
`Gap: ${event.mipGap !== undefined ? (event.mipGap * 100).toFixed(2) + "%" : "—"}`
|
|
1437
|
-
);
|
|
1438
|
-
|
|
1439
|
-
// Optional: stop early as soon as a good-enough incumbent is found
|
|
1440
|
-
if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
|
|
1441
|
-
controller.abort();
|
|
1442
|
-
}
|
|
1443
|
-
},
|
|
1444
|
-
});
|
|
1445
|
-
|
|
1446
|
-
console.log("Status:", m.status); // "Feasible" (if an incumbent was found before abort) or "Unknown"
|
|
1447
|
-
console.log("Termination:", m.terminationStatus); // "Interrupted"
|
|
1448
|
-
console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
|
|
1449
|
-
```
|
|
1450
|
-
|
|
1451
|
-
### `SolveProgressEvent` Fields
|
|
1452
|
-
|
|
1453
|
-
| Field | Type | Description |
|
|
1454
|
-
| :--- | :--- | :--- |
|
|
1455
|
-
| `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
|
|
1456
|
-
| `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
|
|
1457
|
-
| `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
|
|
1458
|
-
| `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
|
|
1459
|
-
| `relGap` / `mipGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
|
|
1460
|
-
| `absGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
|
|
1461
|
-
| `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
|
|
1462
|
-
| `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
|
|
1463
|
-
| `message` | `string \| undefined` | Raw progress line emitted by the solver. |
|
|
1464
|
-
|
|
1465
|
-
---
|
|
1466
|
-
|
|
1467
1608
|
## Reading Results, Bounds & Solver Status
|
|
1468
1609
|
|
|
1469
1610
|
After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
|
|
@@ -1478,14 +1619,17 @@ console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value /
|
|
|
1478
1619
|
// Objective & MIP Gap Metrics
|
|
1479
1620
|
console.log("Objective Value:", m.objectiveValue); // Best primal objective (or null)
|
|
1480
1621
|
console.log("Objective Bound:", m.objectiveBound); // Best dual bound (or undefined)
|
|
1481
|
-
console.log("Relative Gap:", m.
|
|
1482
|
-
console.log("Absolute Gap:", m.
|
|
1622
|
+
console.log("Relative Gap:", m.relativeGap); // Relative MIP gap
|
|
1623
|
+
console.log("Absolute Gap:", m.absoluteGap); // |objectiveValue - objectiveBound|
|
|
1483
1624
|
|
|
1484
|
-
//
|
|
1625
|
+
// Variable Values (via .value or name-keyed m.values ReadonlyMap)
|
|
1485
1626
|
console.log("x =", x.value, "y =", y.value);
|
|
1486
|
-
console.log(m.
|
|
1627
|
+
console.log("x by name:", m.values.get("x"));
|
|
1487
1628
|
```
|
|
1488
1629
|
|
|
1630
|
+
> [!TIP]
|
|
1631
|
+
> To independently check that the returned values satisfy all bounds, integrality requirements, and constraints within tolerance, call `m.verify()`—see [Diagnosis, Verification & Debugging](docs/guide/unsat-core.md#independent-solution-verification-m-verify).
|
|
1632
|
+
|
|
1489
1633
|
### Understanding `m.status` vs. `m.terminationStatus`
|
|
1490
1634
|
|
|
1491
1635
|
When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two distinct questions matter:
|
|
@@ -1512,38 +1656,85 @@ If an integer-feasible incumbent was found before hitting `timeLimit` or `signal
|
|
|
1512
1656
|
|
|
1513
1657
|
---
|
|
1514
1658
|
|
|
1659
|
+
## Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
|
|
1660
|
+
|
|
1661
|
+
For long-running MIP optimizations in interactive UIs, you can stream live branch-and-bound progress (`SolveProgressEvent`) and allow users to cancel the solve cleanly with `AbortController`:
|
|
1662
|
+
|
|
1663
|
+
```typescript
|
|
1664
|
+
const controller = new AbortController();
|
|
1665
|
+
|
|
1666
|
+
// Example: cancel if the user clicks a "Stop" button or after a custom condition
|
|
1667
|
+
const status = await m.solve({
|
|
1668
|
+
signal: controller.signal,
|
|
1669
|
+
onProgress: (event) => {
|
|
1670
|
+
console.log(
|
|
1671
|
+
`[${event.elapsedTime.toFixed(1)}s] ` +
|
|
1672
|
+
`Best: ${event.objectiveValue ?? "—"}, ` +
|
|
1673
|
+
`Bound: ${event.objectiveBound ?? "—"}, ` +
|
|
1674
|
+
`Gap: ${event.relativeGap !== undefined ? (event.relativeGap * 100).toFixed(2) + "%" : "—"}`
|
|
1675
|
+
);
|
|
1676
|
+
|
|
1677
|
+
// Optional: stop early as soon as a good-enough incumbent is found
|
|
1678
|
+
if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
|
|
1679
|
+
controller.abort();
|
|
1680
|
+
}
|
|
1681
|
+
},
|
|
1682
|
+
});
|
|
1683
|
+
|
|
1684
|
+
console.log("Status:", m.status); // "Feasible" (if an incumbent was found before abort) or "Unknown"
|
|
1685
|
+
console.log("Termination:", m.terminationStatus); // "Interrupted"
|
|
1686
|
+
console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
|
|
1687
|
+
```
|
|
1688
|
+
|
|
1689
|
+
### `SolveProgressEvent` Fields
|
|
1690
|
+
|
|
1691
|
+
| Field | Type | Description |
|
|
1692
|
+
| :--- | :--- | :--- |
|
|
1693
|
+
| `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
|
|
1694
|
+
| `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
|
|
1695
|
+
| `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
|
|
1696
|
+
| `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
|
|
1697
|
+
| `relativeGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
|
|
1698
|
+
| `absoluteGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
|
|
1699
|
+
| `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
|
|
1700
|
+
| `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
|
|
1701
|
+
| `message` | `string \| undefined` | Raw progress line emitted by the solver. |
|
|
1702
|
+
|
|
1703
|
+
---
|
|
1704
|
+
|
|
1515
1705
|
## Model Mutations & Execution Validity
|
|
1516
1706
|
|
|
1517
1707
|
A `Model` instance keeps its solution state synchronized across mutations made through `Model` methods and `Model` / `Var` / `Constraint` property setters:
|
|
1518
1708
|
|
|
1519
|
-
1. **Post-Solve Mutations Reset Solution State**: Adding variables or constraints, updating the objective (`m.objective(...)`, `m.
|
|
1709
|
+
1. **Post-Solve Mutations Reset Solution State**: Adding variables or constraints, updating the objective (`m.objective(...)`, `m.sense = ...`), or modifying variable bounds/types (`v.lb`, `v.ub`, `v.type`) or constraint properties (`c.lhs`, `c.sense`, `c.rhs`) immediately resets `m.status` to `"NotSolved"`, clears `m.solution` and `m.objectiveValue`, and resets variable/constraint primal and dual values to `null`.
|
|
1520
1710
|
2. **Mid-Flight Mutations Discard Stale Runs**: If the model is modified via these APIs while an asynchronous `m.solve()` or `m.check()` call is in progress, the stale solver result is discarded, the model remains in `"NotSolved"`, and the in-flight promise rejects with an explicit error.
|
|
1521
1711
|
3. **Overlapping Executions**: Starting a new `m.solve()` or `m.check()` call supersedes any earlier in-flight call on the same model so out-of-order completions can never overwrite the latest run's state.
|
|
1522
1712
|
4. **Transactional Batch Edits**: If an invalid edit is rejected (including batch array calls like `m.constraint([...])`), the model rolls back the failed edit without leaving partial entities registered or invalidating an existing valid solution.
|
|
1523
1713
|
|
|
1524
1714
|
> [!NOTE]
|
|
1525
|
-
> Renaming already-registered variables or constraints (e.g., reassigning `c.name` after registration) or mutating internal backing
|
|
1715
|
+
> Renaming already-registered variables or constraints (e.g., reassigning `c.name` after registration) or mutating internal backing maps and ASTs directly (such as `c.lhs.terms` or `BoolOp.children`) is unsupported and will be rejected by internal model integrity validation on the next solve/check/export call.
|
|
1526
1716
|
|
|
1527
1717
|
---
|
|
1528
1718
|
|
|
1529
|
-
# Conflict Diagnosis (`unsatCore`) &
|
|
1719
|
+
# Conflict Diagnosis (`unsatCore`), Validation & Debugging
|
|
1530
1720
|
|
|
1531
|
-
When building real-world optimization and
|
|
1532
|
-
1. **Why is my model infeasible?** Which specific business rules contradict each other?
|
|
1533
|
-
2. **Does the solver's solution genuinely satisfy every constraint?** How do I verify tolerances, integrality, and formulations?
|
|
1721
|
+
When building real-world optimization and rule systems, you need to diagnose infeasible models, verify returned solutions, and inspect or unit-test formulations cleanly.
|
|
1534
1722
|
|
|
1535
|
-
WaSHI provides
|
|
1723
|
+
WaSHI provides a unified verification and debugging toolkit for all three:
|
|
1724
|
+
- **Conflict diagnosis (`m.check()`)**: Pinpoint contradictory constraints via built-in HiGHS elastic relaxation, bundled Pumpkin Unsat Core, or Z3 Unsat Core.
|
|
1725
|
+
- **Solution verification & LP inspection (`m.verify()`, `m.toLpString()`)**: Independently verify variable bounds, integrality, and constraints, and export CPLEX `.lp` text to inspect generated equations.
|
|
1726
|
+
- **Fast unit testing (`MockSolver`)**: Test application model-building and post-processing logic in CI without loading WebAssembly.
|
|
1536
1727
|
|
|
1537
1728
|
---
|
|
1538
1729
|
|
|
1539
1730
|
## Conflict Diagnosis (`unsatCore` / `conflicts`)
|
|
1540
1731
|
|
|
1541
1732
|
When an optimization run (`m.solve()`) returns **`"Infeasible"`**, the status alone tells you that no solution satisfies every constraint—not *which* rules conflict with each other.
|
|
1542
|
-
By calling **`await m.check({ solver: "z3" })
|
|
1733
|
+
By calling **`await m.check({ solver: "pumpkin" })`** (for bounded integer and boolean models without `COOP`/`COEP` headers or external peer dependencies) or **`await m.check({ solver: "z3" })`** (for models including `Continuous` variables or fractional arithmetic), WaSHI computes an **Unsatisfiable Core (`unsatCore`)**—a conflicting subset of named constraints that cannot be satisfied simultaneously:
|
|
1543
1734
|
|
|
1544
1735
|
```typescript
|
|
1545
1736
|
import { Model, expr } from "@ohtaman/washi";
|
|
1546
|
-
// Register the Z3 solver plugin
|
|
1737
|
+
// Register the Z3 solver plugin (for Continuous / real-valued SMT models)
|
|
1547
1738
|
import "@ohtaman/washi/solvers/z3";
|
|
1548
1739
|
|
|
1549
1740
|
const m = new Model();
|
|
@@ -1567,14 +1758,15 @@ if (result.status === "Unsat") {
|
|
|
1567
1758
|
Notice that `routine_operating_cost` is **not** in the core, because only `minimum_regulatory_reserve` ($x \ge 100$) and `budget_ceiling` ($x \le 50$) directly contradict each other.
|
|
1568
1759
|
|
|
1569
1760
|
> [!IMPORTANT]
|
|
1570
|
-
> - **Use `m.check({ solver: "z3" })` for Unsat Core extraction**: `m.solve()` runs optimization
|
|
1761
|
+
> - **Use `m.check({ solver: "pumpkin" })` or `m.check({ solver: "z3" })` for Unsat Core extraction**: `m.solve()` runs optimization, whereas `m.check()` runs assumption-tracked satisfiability checking (Pumpkin assumption core or `Z3.Solver.assertAndTrack`) and populates `result.conflicts` / `m.conflicts` (and alias `m.unsatCore`).
|
|
1571
1762
|
> - **Name your constraints**: Variable bounds (`lb`, `ub`) act as background domain declarations. To include a bound or business rule in the reported `unsatCore` list, register it as a named constraint via `m.constraint(expr`...`, "rule_name")`.
|
|
1572
1763
|
|
|
1573
|
-
### Workflow: Infeasibility Diagnosis with HiGHS or Z3
|
|
1764
|
+
### Workflow: Infeasibility Diagnosis with HiGHS, Pumpkin, or Z3
|
|
1574
1765
|
|
|
1575
|
-
Because WaSHI models are solver-independent, you can
|
|
1576
|
-
1. **Built-in HiGHS & GLPK (default)**: `await m.check()` uses a single-solve elastic slack formulation ($\min \sum s_i$) to identify which constraints required relaxation (`diag.conflicts`), requiring no extra
|
|
1577
|
-
2. **
|
|
1766
|
+
Because WaSHI models are solver-independent, you can choose from three diagnosis strategies:
|
|
1767
|
+
1. **Built-in HiGHS & GLPK (default)**: `await m.check()` uses a single-solve elastic slack formulation ($\min \sum s_i$) to identify which constraints required relaxation (`diag.conflicts`), requiring no extra imports.
|
|
1768
|
+
2. **Bundled Pumpkin CP/LCG Solver**: `await m.check({ solver: "pumpkin" })` (after `import "@ohtaman/washi/solvers/pumpkin"`) extracts a scale-invariant `unsatCore` / `conflicts` over bounded integer and boolean models with **zero external dependencies** and **zero browser `COOP` / `COEP` headers**.
|
|
1769
|
+
3. **Z3 SMT Solver**: `await m.check({ solver: "z3" })` uses SMT tracking to extract an exact unsatisfiable core (`diag.unsatCore` / `diag.conflicts`), including models with `Continuous` variables or fractional arithmetic.
|
|
1578
1770
|
|
|
1579
1771
|
```typescript
|
|
1580
1772
|
const status = await m.solve(); // Fast MIP solve with default HiGHS
|
|
@@ -1584,27 +1776,34 @@ if (status === "Infeasible") {
|
|
|
1584
1776
|
const diag = await m.check();
|
|
1585
1777
|
console.error("Model is infeasible due to conflicting rules:", diag.conflicts);
|
|
1586
1778
|
|
|
1587
|
-
// Option 2:
|
|
1779
|
+
// Option 2: Bundled zero-COOP/COEP unsat core with Pumpkin (bounded int/bool models; requires import "@ohtaman/washi/solvers/pumpkin")
|
|
1780
|
+
// const pumpkinDiag = await m.check({ solver: "pumpkin" });
|
|
1781
|
+
// console.error("Pumpkin Unsat Core:", pumpkinDiag.unsatCore);
|
|
1782
|
+
|
|
1783
|
+
// Option 3: Exact SMT unsat core diagnosis with Z3 (supports Continuous/real vars; requires import "@ohtaman/washi/solvers/z3")
|
|
1588
1784
|
// const z3Diag = await m.check({ solver: "z3" });
|
|
1589
1785
|
// console.error("Z3 Unsat Core:", z3Diag.unsatCore);
|
|
1590
1786
|
}
|
|
1591
1787
|
```
|
|
1592
1788
|
|
|
1593
|
-
### Comparing Z3 `unsatCore
|
|
1789
|
+
### Comparing Pumpkin `unsatCore`, Z3 `unsatCore`, and HiGHS Elastic Slack `conflicts`
|
|
1594
1790
|
|
|
1595
|
-
| Property | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()`) |
|
|
1596
|
-
| :--- | :--- | :--- |
|
|
1597
|
-
| **
|
|
1598
|
-
| **
|
|
1599
|
-
| **
|
|
1600
|
-
| **
|
|
1791
|
+
| Property | Pumpkin (`m.check({ solver: "pumpkin" })`) | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()`) |
|
|
1792
|
+
| :--- | :--- | :--- | :--- |
|
|
1793
|
+
| **Setup & Dependencies** | **Bundled** (`@ohtaman/washi/solvers/pumpkin`, zero peer deps) | Optional peer dependency (`z3-solver`) | **Built-in** (HiGHS) / optional `glpk.js` |
|
|
1794
|
+
| **Browser Headers** | **None** (`COOP` / `COEP` not required) | Requires `COOP` / `COEP` (`SharedArrayBuffer`) | **None** |
|
|
1795
|
+
| **Supported Variables** | Bounded `Integer`, `Binary`, `BoolVar` | `Continuous`, `Integer`, `Binary`, `BoolVar` | `Continuous`, `Integer`, `Binary`, `BoolVar` |
|
|
1796
|
+
| **Algorithm** | LCG conflict analysis under constraint assumptions | SMT assumption tracking (`assertAndTrack`) | Single-solve $L_1$ elastic slack relaxation ($\min \sum s_i$) |
|
|
1797
|
+
| **Populated Fields** | Both `result.unsatCore` and `result.conflicts` | Both `result.unsatCore` and `result.conflicts` | `result.conflicts` (`unsatCore` is `undefined`) |
|
|
1798
|
+
| **Semantic Meaning** | A **contradictory subset** of rules that cannot all hold together | A **contradictory subset** of rules that cannot all hold together | A **minimum-violation repair set** of constraints whose relaxation restores feasibility |
|
|
1799
|
+
| **Unit-Scaling Sensitivity** | **Scale-invariant** (pure logical/integer contradiction) | **Scale-invariant** (pure logical/algebraic contradiction) | **Scale-sensitive** (minimizing unweighted $\sum s_i$ prefers relaxing a headcount constraint by `2` units over a budget constraint by `10,000` dollars) |
|
|
1601
1800
|
|
|
1602
1801
|
> [!TIP]
|
|
1603
|
-
> When diagnosing models that mix constraints of vastly different magnitudes (e.g., headcount $\le 8$ alongside budget $\le 50{,}000$), use **`m.check({ solver: "z3" })`** if you want
|
|
1802
|
+
> When diagnosing models that mix constraints of vastly different magnitudes (e.g., headcount $\le 8$ alongside budget $\le 50{,}000$), use **`m.check({ solver: "pumpkin" })`** (for bounded integer/boolean models without `COOP`/`COEP`) or **`m.check({ solver: "z3" })`** (when `Continuous` variables or fractional thresholds are present) if you want a scale-invariant set of mutually contradictory rules, or normalize constraint scales when relying on unweighted $L_1$ slack relaxation.
|
|
1604
1803
|
|
|
1605
1804
|
---
|
|
1606
1805
|
|
|
1607
|
-
## Independent Solution
|
|
1806
|
+
## Independent Solution Verification (`m.verify()`)
|
|
1608
1807
|
|
|
1609
1808
|
After solving a model (or supplying a custom candidate map via `values`), you can independently verify that all variable bounds, integer/binary domains, linear constraints, and logical SMT formulas hold against the original model definitions:
|
|
1610
1809
|
|
|
@@ -1612,7 +1811,7 @@ After solving a model (or supplying a custom candidate map via `values`), you ca
|
|
|
1612
1811
|
const status = await m.solve();
|
|
1613
1812
|
|
|
1614
1813
|
if (m.hasPrimalSolution) {
|
|
1615
|
-
const report = m.
|
|
1814
|
+
const report = m.verify({
|
|
1616
1815
|
feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
|
|
1617
1816
|
integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
|
|
1618
1817
|
evaluateLogicalConstraints: true,
|
|
@@ -1629,18 +1828,18 @@ if (m.hasPrimalSolution) {
|
|
|
1629
1828
|
}
|
|
1630
1829
|
```
|
|
1631
1830
|
|
|
1632
|
-
### `
|
|
1831
|
+
### `VerificationReport` Summary
|
|
1633
1832
|
|
|
1634
1833
|
| Property | Type | Description |
|
|
1635
1834
|
| :--- | :--- | :--- |
|
|
1636
1835
|
| `valid` | `boolean` | `true` iff `complete === true`, `uncheckedConstraints.length === 0`, and `violations.length === 0`. |
|
|
1637
1836
|
| `complete` | `boolean` | `true` when all variables, Boolean variables, linear constraints, and logical constraints were evaluated. |
|
|
1638
1837
|
| `maxViolation` | `number` | Largest numeric violation magnitude across all evaluated bounds, integrality checks, and constraints. |
|
|
1639
|
-
| `violations` | `
|
|
1640
|
-
| `violationsByName` | `Record<string,
|
|
1838
|
+
| `violations` | `VerificationViolation[]` | Flat list of violations (`"missing_value"`, `"non_finite_value"`, `"invalid_boolean_value"`, `"lower_bound"`, `"upper_bound"`, `"integrality"`, `"linear_constraint"`, `"logical_constraint"`, `"unchecked_constraint"`). |
|
|
1839
|
+
| `violationsByName` | `Record<string, VerificationViolation[]>` | Violations grouped by variable or constraint name. |
|
|
1641
1840
|
| `uncheckedConstraints` | `string[]` | Names of constraints that could not be evaluated. |
|
|
1642
1841
|
| `missingVariables` | `string[]` | Names of numeric or Boolean variables whose values were `null` or `undefined`. |
|
|
1643
|
-
| `summary` | `
|
|
1842
|
+
| `summary` | `VerificationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
|
|
1644
1843
|
|
|
1645
1844
|
---
|
|
1646
1845
|
|
|
@@ -1695,73 +1894,158 @@ console.log(x.value, y.value); // 10, 20
|
|
|
1695
1894
|
|
|
1696
1895
|
---
|
|
1697
1896
|
|
|
1698
|
-
#
|
|
1897
|
+
# Constraint Programming (CP) Modeling
|
|
1699
1898
|
|
|
1700
|
-
|
|
1899
|
+
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.
|
|
1701
1900
|
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1901
|
+
---
|
|
1902
|
+
|
|
1903
|
+
## 1. MIP vs. CP Modeling Mindset
|
|
1904
|
+
|
|
1905
|
+
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.
|
|
1906
|
+
|
|
1907
|
+
In **CP (Pumpkin)**, you model **what** each entity chooses directly using finite-domain integers (`m.integer(keys, { lb, ub })`) and declarative **global constraints**:
|
|
1908
|
+
|
|
1909
|
+
| Modeling Dimension | MIP Pattern (`HiGHS` / `GLPK`) | CP Pattern (`Pumpkin`) | SMT (`Z3`) |
|
|
1910
|
+
| :--- | :--- | :--- | :--- |
|
|
1911
|
+
| **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 |
|
|
1912
|
+
| **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 |
|
|
1913
|
+
| **Unary non-overlap** | Pairwise Big-M disjunctions ($y_{ij} \in \{0,1\}$) | Native `disjoint(tasks)` edge-finding propagator | Pairwise `Or` disjunctions |
|
|
1914
|
+
| **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` |
|
|
1915
|
+
| **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 |
|
|
1916
|
+
| **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 |
|
|
1706
1917
|
|
|
1707
1918
|
---
|
|
1708
1919
|
|
|
1709
|
-
##
|
|
1920
|
+
## 2. Interval & Resource Scheduling (`disjoint`, `cumulative`, `max`)
|
|
1710
1921
|
|
|
1711
|
-
WaSHI
|
|
1922
|
+
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" }`).
|
|
1712
1923
|
|
|
1713
|
-
|
|
1714
|
-
After solving a continuous linear program (LP), read the shadow price (marginal impact on the objective per unit change in RHS) of each constraint:
|
|
1924
|
+
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.
|
|
1715
1925
|
|
|
1716
1926
|
```typescript
|
|
1717
|
-
import { Model, expr,
|
|
1927
|
+
import { Model, expr, disjoint, cumulative, max, minimize } from "@ohtaman/washi";
|
|
1928
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
1929
|
+
|
|
1930
|
+
const m = new Model("IntervalSchedulingCP", { solver: "pumpkin" });
|
|
1931
|
+
const tasks = ["prep", "mill", "drill", "coat"] as const;
|
|
1932
|
+
const duration = { prep: 3, mill: 4, drill: 3, coat: 2 };
|
|
1933
|
+
const workers = { prep: 1, mill: 1, drill: 1, coat: 2 };
|
|
1934
|
+
const start = m.integer(tasks, { lb: 0, ub: 20, prefix: "start" });
|
|
1935
|
+
|
|
1936
|
+
// Precedence rules: prep -> (mill, drill) -> coat
|
|
1937
|
+
m.constraint(expr`${start.prep} + 3 <= ${start.mill}`, "mill_after_prep");
|
|
1938
|
+
m.constraint(expr`${start.prep} + 3 <= ${start.drill}`, "drill_after_prep");
|
|
1939
|
+
m.constraint(expr`${start.mill} + 4 <= ${start.coat}`, "coat_after_mill");
|
|
1940
|
+
m.constraint(expr`${start.drill} + 3 <= ${start.coat}`, "coat_after_drill");
|
|
1941
|
+
|
|
1942
|
+
// Single CNC spindle shared between mill and drill
|
|
1943
|
+
m.constraint(
|
|
1944
|
+
disjoint([
|
|
1945
|
+
{ start: start.mill, duration: duration.mill },
|
|
1946
|
+
{ start: start.drill, duration: duration.drill },
|
|
1947
|
+
]),
|
|
1948
|
+
"single_cnc"
|
|
1949
|
+
);
|
|
1718
1950
|
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1951
|
+
// At most 2 operators working simultaneously across all tasks
|
|
1952
|
+
m.constraint(
|
|
1953
|
+
cumulative(
|
|
1954
|
+
tasks.map((t) => ({ start: start[t], duration: duration[t], demand: workers[t] })),
|
|
1955
|
+
2
|
|
1956
|
+
),
|
|
1957
|
+
"operator_pool"
|
|
1958
|
+
);
|
|
1722
1959
|
|
|
1723
|
-
m.objective(
|
|
1724
|
-
const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
|
|
1960
|
+
m.objective(minimize(max(tasks.map((t) => expr`${start[t]} + ${duration[t]}`))));
|
|
1725
1961
|
await m.solve();
|
|
1962
|
+
```
|
|
1726
1963
|
|
|
1727
|
-
|
|
1728
|
-
|
|
1964
|
+
See the full runnable project scheduling walkthrough in [Resource-Constrained Project Scheduling (RCPSP)](docs/examples/project-scheduling.md).
|
|
1965
|
+
|
|
1966
|
+
---
|
|
1967
|
+
|
|
1968
|
+
## 3. Combinatorial Assignment, Table Rules & Element Lookup (`distinct`, `allowed`, `at`)
|
|
1969
|
+
|
|
1970
|
+
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\}$:
|
|
1971
|
+
|
|
1972
|
+
- **`distinct(machine)`**: Forces every job onto a separate machine using Pumpkin's `all_different` propagator.
|
|
1973
|
+
- **`allowed(vars, tuples)` / `not(allowed(vars, tuples))`**: Encodes arbitrary compatibility or incompatibility rules between discrete decisions without manual Big-M algebra.
|
|
1974
|
+
- **`at(costs, indexVar)`**: Looks up a numeric cost from `costs[indexVar]` using Pumpkin's native `element` propagator—avoiding $M$ selector binary variables per job.
|
|
1975
|
+
|
|
1976
|
+
```typescript
|
|
1977
|
+
import { Model, expr, distinct, allowed, not, at, minimize } from "@ohtaman/washi";
|
|
1978
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
1979
|
+
|
|
1980
|
+
const m = new Model("MachineAssignmentCP", { solver: "pumpkin" });
|
|
1981
|
+
const jobs = ["jobA", "jobB", "jobC"] as const;
|
|
1982
|
+
const machine = m.integer(jobs, { lb: 0, ub: 2, prefix: "machine" });
|
|
1983
|
+
|
|
1984
|
+
const costA = [5, 10, 40];
|
|
1985
|
+
const costB = [20, 15, 30];
|
|
1986
|
+
const costC = [45, 30, 25];
|
|
1987
|
+
|
|
1988
|
+
// Each job runs on a distinct machine (0, 1, or 2)
|
|
1989
|
+
m.constraint(distinct(machine), "one_job_per_machine");
|
|
1990
|
+
|
|
1991
|
+
// Safety interlock: Job A on Machine 0 cannot pair with Job B on Machine 1
|
|
1992
|
+
m.constraint(not(allowed([machine.jobA, machine.jobB], [[0, 1]])), "interlock_pair");
|
|
1993
|
+
|
|
1994
|
+
// Variable-indexed cost lookup via 0-based Element primitive at(table, indexVar)
|
|
1995
|
+
m.objective(
|
|
1996
|
+
minimize(
|
|
1997
|
+
expr`at(${costA}, ${machine.jobA}) + at(${costB}, ${machine.jobB}) + at(${costC}, ${machine.jobC})`
|
|
1998
|
+
)
|
|
1999
|
+
);
|
|
2000
|
+
await m.solve();
|
|
1729
2001
|
```
|
|
1730
2002
|
|
|
1731
|
-
|
|
1732
|
-
|
|
2003
|
+
---
|
|
2004
|
+
|
|
2005
|
+
## 4. Domain Tightening, Symmetry Breaking & Conflict Diagnosis
|
|
2006
|
+
|
|
2007
|
+
### Keep Integer Domains Finite and Tight
|
|
2008
|
+
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](docs/solvers/pumpkin.md#domain-api-preconditions)). Tight horizons directly shrink propagator domains and accelerate conflict learning.
|
|
2009
|
+
|
|
2010
|
+
### Break Permutation Symmetry with Strict Ordering (`<`)
|
|
2011
|
+
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:
|
|
1733
2012
|
|
|
1734
2013
|
```typescript
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
2014
|
+
import { Model, expr, at, minimize } from "@ohtaman/washi";
|
|
2015
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
2016
|
+
|
|
2017
|
+
const m = new Model("SymmetryBreakingCP", { solver: "pumpkin" });
|
|
2018
|
+
const latencyMs = [600, 380, 420, 470, 550];
|
|
2019
|
+
const slot = m.integer(3, { lb: 0, ub: 4, prefix: "slot" });
|
|
2020
|
+
|
|
2021
|
+
// Strict ascending order enforces all-different AND eliminates 3! = 6 permutation symmetries
|
|
2022
|
+
m.constraint([
|
|
2023
|
+
expr`${slot[0]} < ${slot[1]}`,
|
|
2024
|
+
expr`${slot[1]} < ${slot[2]}`,
|
|
2025
|
+
]);
|
|
2026
|
+
|
|
2027
|
+
m.objective(
|
|
2028
|
+
minimize(
|
|
2029
|
+
expr`at(${latencyMs}, ${slot[0]}) + at(${latencyMs}, ${slot[1]}) + at(${latencyMs}, ${slot[2]})`
|
|
2030
|
+
)
|
|
2031
|
+
);
|
|
2032
|
+
await m.solve();
|
|
1738
2033
|
```
|
|
1739
2034
|
|
|
1740
|
-
###
|
|
1741
|
-
|
|
2035
|
+
### Warm Starts & Zero-`COOP`/`COEP` Conflict Diagnosis
|
|
2036
|
+
- **Warm Starts (`initialValue`)**: Provide feasible domain hints via `{ initialValue: val }` on `m.integer()` or `m.binary()` to seed Pumpkin's value selection (`WarmStart` brancher).
|
|
2037
|
+
- **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`)](docs/guide/unsat-core.md).
|
|
1742
2038
|
|
|
1743
|
-
|
|
1744
|
-
const col = m.addColumn({
|
|
1745
|
-
name: "pattern_1",
|
|
1746
|
-
type: "Integer", // or "Continuous" / "Binary"
|
|
1747
|
-
lb: 0,
|
|
1748
|
-
cost: 1, // Objective coefficient
|
|
1749
|
-
coefficients: {
|
|
1750
|
-
capacity: 2,
|
|
1751
|
-
},
|
|
1752
|
-
});
|
|
1753
|
-
```
|
|
2039
|
+
---
|
|
1754
2040
|
|
|
1755
|
-
|
|
1756
|
-
Increment or overwrite the coefficient of a variable inside an existing linear constraint:
|
|
2041
|
+
# Decomposition Methods (`solveColumnGeneration` & `solveBenders`)
|
|
1757
2042
|
|
|
1758
|
-
|
|
1759
|
-
const extra = m.continuous("extra", { lb: 0 });
|
|
1760
|
-
const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
|
|
2043
|
+
When monolithic Mixed-Integer Programming (MIP) models have exponentially many candidate patterns or large multi-stage subproblems, WaSHI provides two high-level decomposition orchestrators—`master.solveColumnGeneration()` and `master.solveBenders()`—along with low-level primitives for dual inspection and dynamic model updates.
|
|
1761
2044
|
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
2045
|
+
| Decomposition Method | WaSHI Orchestrator | Typical Use Case |
|
|
2046
|
+
| :--- | :--- | :--- |
|
|
2047
|
+
| **Column Generation** *(Dantzig-Wolfe)* | [`master.solveColumnGeneration()`](#column-generation-solvecolumngeneration) | Models with exponentially many patterns, routes, or schedules (e.g., Cutting Stock, Vehicle Routing, Crew Rostering). |
|
|
2048
|
+
| **Benders Decomposition** *(and Lazy Cuts)* | [`master.solveBenders()`](#benders-decomposition-solvebenders) | Two-stage or complicating-variable problems (e.g., Facility Location + Dispatch, Stochastic Planning, TSP Subtour Elimination). |
|
|
1765
2049
|
|
|
1766
2050
|
---
|
|
1767
2051
|
|
|
@@ -1956,6 +2240,65 @@ console.log(result.objectiveValue); // 70 (y = 1, theta = 30)
|
|
|
1956
2240
|
|
|
1957
2241
|
---
|
|
1958
2242
|
|
|
2243
|
+
## Low-Level Primitives (Custom Loops)
|
|
2244
|
+
|
|
2245
|
+
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:
|
|
2246
|
+
|
|
2247
|
+
### 1. Constraint Duals (`c.dual`)
|
|
2248
|
+
After solving a continuous linear program (LP), read the shadow price (marginal impact on the objective per unit change in RHS) of each constraint:
|
|
2249
|
+
|
|
2250
|
+
```typescript
|
|
2251
|
+
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
2252
|
+
|
|
2253
|
+
const m = new Model();
|
|
2254
|
+
const x = m.continuous("x", { lb: 0 });
|
|
2255
|
+
const y = m.continuous("y", { lb: 0 });
|
|
2256
|
+
|
|
2257
|
+
m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
|
|
2258
|
+
const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
|
|
2259
|
+
await m.solve();
|
|
2260
|
+
|
|
2261
|
+
console.log(c.dual); // Dual value / shadow price
|
|
2262
|
+
console.log(m.solution?.duals.capacity); // Lookup by constraint name
|
|
2263
|
+
```
|
|
2264
|
+
|
|
2265
|
+
### 2. Continuous LP Relaxation (`m.relax()`)
|
|
2266
|
+
`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:
|
|
2267
|
+
|
|
2268
|
+
```typescript
|
|
2269
|
+
// Solves the continuous LP relaxation and populates m.solution.duals
|
|
2270
|
+
const status = await m.relax();
|
|
2271
|
+
console.log("LP relaxation bound:", m.objectiveValue);
|
|
2272
|
+
```
|
|
2273
|
+
|
|
2274
|
+
### 3. Dynamic Column Injection (`m.column()`)
|
|
2275
|
+
Create a new decision variable, set its objective coefficient, and attach its non-zero coefficients to existing named constraints in a single call:
|
|
2276
|
+
|
|
2277
|
+
```typescript
|
|
2278
|
+
const col = m.column({
|
|
2279
|
+
name: "pattern_1",
|
|
2280
|
+
type: "Integer", // or "Continuous" / "Binary"
|
|
2281
|
+
lb: 0,
|
|
2282
|
+
cost: 1, // Objective coefficient
|
|
2283
|
+
coefficients: {
|
|
2284
|
+
capacity: 2,
|
|
2285
|
+
},
|
|
2286
|
+
});
|
|
2287
|
+
```
|
|
2288
|
+
|
|
2289
|
+
### 4. Dynamic Constraint Term Updates (`c.addTerm()` / `c.setTerm()`)
|
|
2290
|
+
Increment or overwrite the coefficient of a variable inside an existing linear constraint:
|
|
2291
|
+
|
|
2292
|
+
```typescript
|
|
2293
|
+
const extra = m.continuous("extra", { lb: 0 });
|
|
2294
|
+
const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
|
|
2295
|
+
|
|
2296
|
+
budget.addTerm(extra, 5); // Adds +5 * extra to the LHS
|
|
2297
|
+
budget.setTerm(extra, 0); // Setting 0 removes extra from the constraint
|
|
2298
|
+
```
|
|
2299
|
+
|
|
2300
|
+
---
|
|
2301
|
+
|
|
1959
2302
|
## Related Examples & Formulation Tips
|
|
1960
2303
|
|
|
1961
2304
|
- **Full Decomposition Walkthroughs**:
|
|
@@ -1967,7 +2310,7 @@ console.log(result.objectiveValue); // 70 (y = 1, theta = 30)
|
|
|
1967
2310
|
|
|
1968
2311
|
# Formulation Patterns & Optimization Tips
|
|
1969
2312
|
|
|
1970
|
-
While the preceding Modeling Guide pages cover WaSHI's APIs (`Model`, `expr`, `m.constraint`, `m.solve`, etc.), this page collects standard mathematical optimization formulation patterns and solver tuning techniques frequently used in linear and mixed-integer programming (LP/MIP).
|
|
2313
|
+
While the preceding Modeling Guide pages cover WaSHI's APIs (`Model`, `expr`, `m.constraint`, `m.solve`, etc.), this page collects standard mathematical optimization formulation patterns and solver tuning techniques frequently used in linear and mixed-integer programming (LP/MIP). *(For Constraint Programming idioms such as `disjoint`, `cumulative`, `distinct`, `allowed`, and `at` with Pumpkin, see the [Constraint Programming (CP) Modeling Guide](docs/guide/constraint-programming.md).)*
|
|
1971
2314
|
|
|
1972
2315
|
---
|
|
1973
2316
|
|
|
@@ -2044,7 +2387,9 @@ m.objective(maximize(expr`10 * ${xA} + 10 * ${xB} + 5 * ${bothAB}`));
|
|
|
2044
2387
|
|
|
2045
2388
|
### Min-Max & Max-Min Objectives (Load Balancing)
|
|
2046
2389
|
|
|
2047
|
-
|
|
2390
|
+
WaSHI's built-in `max(...)` and `min(...)` primitives (see [Piecewise-Linear & Element Expressions](docs/guide/expressions.md#piecewise-linear-element-expressions-max-min-abs-at)) already automate convex LP epigraph lowering on HiGHS/GLPK and map directly to native propagators on Pumpkin.
|
|
2391
|
+
|
|
2392
|
+
When you need explicit access to the auxiliary ceiling/floor variable $z$—for example, to reuse it inside a second-stage constraint for lexicographic optimization (Section 4)—you can write the epigraph reformulation directly by constraining every individual load $\text{load}_i \le z$ and minimizing $z$ (or $\text{u}_i \ge z$ and maximizing $z$ for Max-Min):
|
|
2048
2393
|
|
|
2049
2394
|
$$\min z \quad \text{subject to} \quad \text{load}_i \le z \quad \forall i$$
|
|
2050
2395
|
|
|
@@ -2064,8 +2409,6 @@ m.constraint(expr`sum(${hours}) >= 60`, "total_required_work");
|
|
|
2064
2409
|
m.objective(minimize(maxHours));
|
|
2065
2410
|
```
|
|
2066
2411
|
|
|
2067
|
-
*(Symmetrically, to **maximize the minimum** level $\max \min_i u_i$, impose $u_i \ge z$ for all $i$ and set `m.objective(maximize(z))`.)*
|
|
2068
|
-
|
|
2069
2412
|
---
|
|
2070
2413
|
|
|
2071
2414
|
## 3. Constraint Design & Numerical Conditioning
|
|
@@ -2162,8 +2505,8 @@ await m.solve();
|
|
|
2162
2505
|
In combinatorial MIP problems, solvers often find a near-optimal feasible solution within seconds, then spend most of the remaining runtime closing the final fraction of a percent in the branch-and-bound tree (**tail-off**).
|
|
2163
2506
|
|
|
2164
2507
|
In interactive UIs and batch pipelines, combine `timeLimit` with business-meaningful tolerances in [`m.solve(options)`](docs/guide/objectives.md#solve-options-solveoptions):
|
|
2165
|
-
- **`
|
|
2166
|
-
- **`
|
|
2508
|
+
- **`relativeGap: 0.01`**: Stop immediately once the incumbent is proven within **1%** of the theoretical dual bound.
|
|
2509
|
+
- **`absoluteGap: 100`**: Stop immediately once `|objectiveValue - objectiveBound| <= 100` in the objective's native units.
|
|
2167
2510
|
|
|
2168
2511
|
---
|
|
2169
2512
|
|
|
@@ -2191,8 +2534,9 @@ WaSHI is designed around a pluggable, decoupled solver architecture. You formula
|
|
|
2191
2534
|
| Solver | Engine License | Problem Classes | Best For | Status in WaSHI |
|
|
2192
2535
|
| :--- | :--- | :--- | :--- | :--- |
|
|
2193
2536
|
| **[HiGHS](https://github.com/ERGO-Code/HiGHS)** | **MIT** | **LP, MIP, Convex QP** | Industrial-scale optimization, operations research, finance | **Built-in default** (zero configuration) |
|
|
2194
|
-
| **[
|
|
2195
|
-
| **[
|
|
2537
|
+
| **[Pumpkin](https://github.com/ConSol-Lab/Pumpkin)** | **MIT** | **CP, LCG, Logic, Bounded Integer** | Disjunctive scheduling, CP global constraints, zero-COOP/COEP `unsatCore` | **Bundled plugin** (`@ohtaman/washi/solvers/pumpkin`, zero external deps) |
|
|
2538
|
+
| **[Z3](https://github.com/Z3Prover/z3)** (via [`z3-solver`](https://www.npmjs.com/package/z3-solver)) | **MIT** | **SMT, SAT, Logic, MIP** | Propositional logic, conflict diagnosis (`unsatCore`), rule engines | Optional peer plugin (`@ohtaman/washi/solvers/z3`, requires `z3-solver`) |
|
|
2539
|
+
| **[GLPK](https://www.gnu.org/software/glpk/)** (via [`glpk.js`](https://www.npmjs.com/package/glpk.js)) | **GPL-3.0** | **LP, MIP** | Academic benchmarks, legacy GLPK compatibility | Optional peer plugin (`@ohtaman/washi/solvers/glpk`, requires `glpk.js`) |
|
|
2196
2540
|
| **Mock** | **MIT** | *Any* | Ultra-fast unit testing in CI without loading WebAssembly | Built-in |
|
|
2197
2541
|
|
|
2198
2542
|
---
|
|
@@ -2205,13 +2549,17 @@ Specify the solver by name when creating your `Model`:
|
|
|
2205
2549
|
// 1. Built-in HiGHS (default)
|
|
2206
2550
|
const m1 = new Model({ solver: "highs" });
|
|
2207
2551
|
|
|
2208
|
-
// 2.
|
|
2552
|
+
// 2. Pumpkin CP/LCG solver (bundled WASM, zero COOP/COEP)
|
|
2553
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
2554
|
+
const m2 = new Model({ solver: "pumpkin" });
|
|
2555
|
+
|
|
2556
|
+
// 3. Z3 SMT solver
|
|
2209
2557
|
import "@ohtaman/washi/solvers/z3";
|
|
2210
|
-
const
|
|
2558
|
+
const m3 = new Model({ solver: "z3" });
|
|
2211
2559
|
|
|
2212
|
-
//
|
|
2560
|
+
// 4. GLPK solver
|
|
2213
2561
|
import "@ohtaman/washi/solvers/glpk";
|
|
2214
|
-
const
|
|
2562
|
+
const m4 = new Model({ solver: "glpk" });
|
|
2215
2563
|
```
|
|
2216
2564
|
|
|
2217
2565
|
---
|
|
@@ -2219,6 +2567,7 @@ const m3 = new Model({ solver: "glpk" });
|
|
|
2219
2567
|
## Solver Guides
|
|
2220
2568
|
|
|
2221
2569
|
- [HiGHS Guide](docs/solvers/highs.md): Background Web Worker execution, MIP tolerances, and Convex QP solving.
|
|
2570
|
+
- [Pumpkin Guide](docs/solvers/pumpkin.md): Bundled LCG constraint programming, background Web Worker execution, CP global constraints, warm starts, and zero-COOP/COEP `unsatCore`.
|
|
2222
2571
|
- [Z3 Guide](docs/solvers/z3.md): SMT assertions, logic modeling, and Unsat Core analysis.
|
|
2223
2572
|
- [GLPK Guide](docs/solvers/glpk.md): GLPK adapter, GPL-3.0 licensing considerations, and browser usage.
|
|
2224
2573
|
- [Custom Solvers](docs/solvers/custom-solver.md): Step-by-step developer tutorial for integrating proprietary or cloud REST solvers.
|
|
@@ -2243,26 +2592,6 @@ In `@ohtaman/washi`, HiGHS runs entirely in WebAssembly compiled directly from o
|
|
|
2243
2592
|
|
|
2244
2593
|
---
|
|
2245
2594
|
|
|
2246
|
-
## Architecture & WebAssembly Runtime
|
|
2247
|
-
|
|
2248
|
-
WaSHI compiles official HiGHS C++ source directly to WebAssembly (`highs.wasm`) with `-fwasm-exceptions` and single-threaded universal portability (`-DHIGHS_NO_DEFAULT_THREADS=ON`). By interfacing directly with HiGHS's native C API (`highs_c_api.h`), WaSHI achieves zero-copy solution extraction via typed array views on WebAssembly linear memory, rapid upstream release tracking, and a self-contained zero-dependency distribution.
|
|
2249
|
-
|
|
2250
|
-
### Callbacks & Solver Interactivity
|
|
2251
|
-
|
|
2252
|
-
- **Progress Monitoring & Cancellation (Supported)**:
|
|
2253
|
-
Through HiGHS's internal logging and interrupt hooks, WaSHI provides real-time progress callbacks (`onProgress`) and cooperative mid-solve cancellation via standard `AbortSignal`.
|
|
2254
|
-
- **Dynamic Cuts / Lazy Constraints (Not Exposed in WASM Driver)**:
|
|
2255
|
-
WaSHI's HiGHS WebAssembly C API driver currently binds logging, progress, interrupt, and incumbent callbacks and does not expose in-tree lazy constraint or user cut callbacks across the WASM-to-JS boundary. For problems requiring dynamic subtour elimination or Benders decomposition, use [`await m.solveBenders({ subproblem })`](docs/guide/decomposition.md#benders-decomposition-solvebenders) (or a manual outer cutting-plane loop: solve $\to$ detect violation $\to$ `model.constraint(...)` $\to$ re-solve), which iteratively separates cuts and converges to the same exact optimal solution.
|
|
2256
|
-
|
|
2257
|
-
### WebAssembly Asset Lifecycle & On-Demand Builds
|
|
2258
|
-
|
|
2259
|
-
HiGHS's WebAssembly binary (`public/highs.wasm`) and runtime driver (`runtime.js`) are managed via `highs.config.json` with cryptographic SHA-256 verification:
|
|
2260
|
-
- **Zero-Friction Verification**: Build and distribution pipelines run `node scripts/ensure-highs-wasm.mjs`, verifying local assets in milliseconds before bundling.
|
|
2261
|
-
- **On-Demand Release Download**: When assets are missing or updated, `ensure-highs-wasm.mjs` automatically downloads verified binaries from WaSHI's GitHub Release assets.
|
|
2262
|
-
- **Compiling from Source**: When updating HiGHS or modifying compiler flags, run `npm run build:highs-wasm` with the Emscripten SDK (`emcc`), CMake, and Ninja installed, and upload the rebuilt assets to the `highs-<version>` GitHub Release tag (`gh release upload highs-v1.15.1 public/highs.wasm src/modeler/solvers/highs/runtime.js --clobber`) so on-demand downloads match `highs.config.json` (or run `.github/workflows/build-wasm.yml` and commit the `highs-wasm-assets` artifact including `highs.config.json`).
|
|
2263
|
-
|
|
2264
|
-
---
|
|
2265
|
-
|
|
2266
2595
|
## Supported Problem Classes
|
|
2267
2596
|
|
|
2268
2597
|
### 1. Linear Programming (LP)
|
|
@@ -2312,8 +2641,8 @@ const controller = new AbortController();
|
|
|
2312
2641
|
|
|
2313
2642
|
await model.solve({
|
|
2314
2643
|
timeLimit: 60.0, // Maximum solve time in seconds
|
|
2315
|
-
|
|
2316
|
-
|
|
2644
|
+
relativeGap: 0.001, // Terminate when within 0.1% of global optimality
|
|
2645
|
+
absoluteGap: 1.0, // Absolute MIP optimality gap tolerance
|
|
2317
2646
|
presolve: "on", // Presolve control ("on" | "off" | "choose")
|
|
2318
2647
|
outputFlag: true, // Output internal simplex / branch-and-bound logs (output_flag)
|
|
2319
2648
|
signal: controller.signal,
|
|
@@ -2326,7 +2655,7 @@ await model.solve({
|
|
|
2326
2655
|
if (model.hasPrimalSolution) {
|
|
2327
2656
|
console.log(
|
|
2328
2657
|
`Usable solution (${model.status}, termination: ${model.terminationStatus}):`,
|
|
2329
|
-
`obj = ${model.objectiveValue}, gap = ${((model.
|
|
2658
|
+
`obj = ${model.objectiveValue}, gap = ${((model.relativeGap ?? 0) * 100).toFixed(2)}%`
|
|
2330
2659
|
);
|
|
2331
2660
|
}
|
|
2332
2661
|
```
|
|
@@ -2353,6 +2682,21 @@ const syncModel = new Model({
|
|
|
2353
2682
|
|
|
2354
2683
|
---
|
|
2355
2684
|
|
|
2685
|
+
## Architecture & WebAssembly Runtime
|
|
2686
|
+
|
|
2687
|
+
WaSHI compiles official HiGHS C++ source directly to WebAssembly (`highs.wasm`) with `-fwasm-exceptions` and single-threaded universal portability (`-DHIGHS_NO_DEFAULT_THREADS=ON`). By interfacing directly with HiGHS's native C API (`highs_c_api.h`), WaSHI achieves zero-copy solution extraction via typed array views on WebAssembly linear memory, rapid upstream release tracking, and a self-contained zero-dependency distribution.
|
|
2688
|
+
|
|
2689
|
+
Bundled `highs.wasm` and `runtime.js` artifacts are tracked and verified via SHA-256 checksums in `highs.config.json`. Maintainers rebuilding HiGHS from source can follow the instructions in [`CONTRIBUTING.md`](https://github.com/ohtaman/washi/blob/main/CONTRIBUTING.md#4-rebuilding-webassembly-assets--release-workflow).
|
|
2690
|
+
|
|
2691
|
+
### Callbacks & Solver Interactivity
|
|
2692
|
+
|
|
2693
|
+
- **Progress Monitoring & Cancellation (Supported)**:
|
|
2694
|
+
Through HiGHS's internal logging and interrupt hooks, WaSHI provides real-time progress callbacks (`onProgress`) and cooperative mid-solve cancellation via standard `AbortSignal`.
|
|
2695
|
+
- **Dynamic Cuts / Lazy Constraints (Not Exposed in WASM Driver)**:
|
|
2696
|
+
WaSHI's HiGHS WebAssembly C API driver currently binds logging, progress, interrupt, and incumbent callbacks and does not expose in-tree lazy constraint or user cut callbacks across the WASM-to-JS boundary. For problems requiring dynamic subtour elimination or Benders decomposition, use [`await m.solveBenders({ subproblem })`](docs/guide/decomposition.md#benders-decomposition-solvebenders) (or a manual outer cutting-plane loop: solve $\to$ detect violation $\to$ `model.constraint(...)` $\to$ re-solve), which iteratively separates cuts and converges to the same exact optimal solution.
|
|
2697
|
+
|
|
2698
|
+
---
|
|
2699
|
+
|
|
2356
2700
|
## References & Upstream Links
|
|
2357
2701
|
|
|
2358
2702
|
- **Official Website**: [https://highs.dev/](https://highs.dev/)
|
|
@@ -2363,6 +2707,172 @@ const syncModel = new Model({
|
|
|
2363
2707
|
|
|
2364
2708
|
---
|
|
2365
2709
|
|
|
2710
|
+
# Pumpkin Constraint Programming Solver
|
|
2711
|
+
|
|
2712
|
+
**Pumpkin** is a Lazy Clause Generation (LCG) constraint programming solver developed in pure Rust by ConSol Lab at TU Delft ([ConSol-Lab/Pumpkin](https://github.com/ConSol-Lab/Pumpkin) · [docs.rs/pumpkin-core](https://docs.rs/pumpkin-core)). WaSHI compiles Pumpkin (`v0.5.0`) directly to WebAssembly and bundles it in `@ohtaman/washi/solvers/pumpkin` with zero external runtime dependencies.
|
|
2713
|
+
|
|
2714
|
+
Unlike multi-threaded WASM engines, Pumpkin runs as a single-threaded WebAssembly instance inside a Web Worker (or directly in Node.js) and **does not require Cross-Origin Isolation (`COOP` / `COEP`) headers** in browsers.
|
|
2715
|
+
|
|
2716
|
+
---
|
|
2717
|
+
|
|
2718
|
+
## Key Features in WaSHI
|
|
2719
|
+
|
|
2720
|
+
- **Bundled & Zero External Dependencies**: `pumpkin.wasm` (`~1.4 MB`) is shipped directly with `@ohtaman/washi` and tree-shaken into `@ohtaman/washi/solvers/pumpkin`—no separate `npm install` peer dependency or Rust toolchain required.
|
|
2721
|
+
- **Permissive MIT License**: 100% commercially friendly, including all transitive Rust WASM dependencies (`MIT`, `Apache-2.0`, `Unicode-3.0`).
|
|
2722
|
+
- **Background Web Worker & Zero `COOP` / `COEP`**: Runs in a dedicated Web Worker on HTTP(S) origins without `SharedArrayBuffer` or Cross-Origin Isolation headers, keeping UI rendering responsive while working in standard static hosts and third-party iframes.
|
|
2723
|
+
- **Native CP Global Constraints & Propagators**: Lowers `distinct()` (`all_different` via pairwise `binary_not_equals` in Pumpkin `v0.5.0`), `disjoint()` (`disjunctive_strict` Vilím edge-finding), `cumulative()` (time-table filtering), `allowed()` / `not(allowed())` (`table` / `negative_table`), `at()` (`element`), `max()` / `min()` / `abs()` (`maximum` / `minimum` / `absolute`), discrete `!=` (`not_equals`), and `m.indicator()` (with `M` omitted, via `implied_by`) directly to Pumpkin constraints.
|
|
2724
|
+
- **Zero-`COOP` / `COEP` Unsat Core Diagnosis**: `await model.check({ solver: "pumpkin" })` extracts conflicting named rules (`unsatCore` / `conflicts`) over bounded integer and boolean constraints in standard browser contexts.
|
|
2725
|
+
- **Warm-Start Support (`initialValue`)**: Supports non-binding primal initial value hints (`initialValue`, `supportsWarmStart: true`) on bounded `Integer` and `Binary` variables in both `solve()` and `check()` via Pumpkin's `WarmStart` brancher (kept distinct from solved `Var.value`).
|
|
2726
|
+
|
|
2727
|
+
---
|
|
2728
|
+
|
|
2729
|
+
## Supported Problem Classes
|
|
2730
|
+
|
|
2731
|
+
> [!TIP]
|
|
2732
|
+
> **HiGHS vs. Pumpkin vs. Z3**:
|
|
2733
|
+
> - Use **HiGHS** (`{ solver: "highs" }`) for Continuous LPs, Convex QPs, or large linear-relaxation-dominated MILPs.
|
|
2734
|
+
> - Use **Pumpkin** (`{ solver: "pumpkin" }`) for disjunctive scheduling, CP global constraints, bounded integer + propositional logic models, and zero-`COOP`/`COEP` `unsatCore` extraction.
|
|
2735
|
+
> - Use **Z3** (`{ solver: "z3" }`) when you need continuous variables inside `implies(...)` / `not(...)` or arbitrary real-valued SMT arithmetic.
|
|
2736
|
+
|
|
2737
|
+
### 1. Disjunctive Scheduling & Global CP Constraints (`model.solve()`)
|
|
2738
|
+
|
|
2739
|
+
Model unary/cumulative resource scheduling, precedence logic (`implies`, `not`), and global predicates (`disjoint`, `distinct`, `cumulative`, `allowed`, `at`, `max`, `min`, `abs`) directly over bounded integers:
|
|
2740
|
+
|
|
2741
|
+
```typescript
|
|
2742
|
+
import { Model, disjoint, expr, implies, minimize, not } from "@ohtaman/washi";
|
|
2743
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
2744
|
+
|
|
2745
|
+
const model = new Model("SchedulingStep", { solver: "pumpkin" });
|
|
2746
|
+
|
|
2747
|
+
const s1 = model.integer("start_job1", { lb: 0, ub: 20 });
|
|
2748
|
+
const s2 = model.integer("start_job2", { lb: 0, ub: 20 });
|
|
2749
|
+
const job1First = model.bool("job1_first");
|
|
2750
|
+
|
|
2751
|
+
model.constraint(
|
|
2752
|
+
disjoint([
|
|
2753
|
+
{ start: s1, duration: 6 },
|
|
2754
|
+
{ start: s2, duration: 4 },
|
|
2755
|
+
]),
|
|
2756
|
+
"single_machine"
|
|
2757
|
+
);
|
|
2758
|
+
model.constraint(implies(job1First, expr`${s1} + 6 <= ${s2}`), "job1_before_job2");
|
|
2759
|
+
model.constraint(implies(not(job1First), expr`${s2} + 4 <= ${s1}`), "job2_before_job1");
|
|
2760
|
+
|
|
2761
|
+
model.objective(minimize(expr`${s1} + ${s2}`));
|
|
2762
|
+
await model.solve();
|
|
2763
|
+
|
|
2764
|
+
console.log(`Status: ${model.status}, s1=${s1.value}, s2=${s2.value}`);
|
|
2765
|
+
```
|
|
2766
|
+
|
|
2767
|
+
### 2. Satisfiability & Unsat Core Diagnosis (`model.check()`)
|
|
2768
|
+
|
|
2769
|
+
Call `await model.check()` to verify satisfiability over integer linear constraints, CP global constraints, and nested propositional logic (`and`, `or`, `not`, `implies`, `xor`), and isolate conflicting named rules (`conflicts` / `unsatCore`) when unsatisfiable:
|
|
2770
|
+
|
|
2771
|
+
```typescript
|
|
2772
|
+
import { Model, expr, implies } from "@ohtaman/washi";
|
|
2773
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
2774
|
+
|
|
2775
|
+
const model = new Model("PolicyConflict", { solver: "pumpkin" });
|
|
2776
|
+
const vip = model.bool("vip");
|
|
2777
|
+
const seats = model.integer("seats", { lb: 0, ub: 20 });
|
|
2778
|
+
|
|
2779
|
+
model.constraint(vip, "vip_active");
|
|
2780
|
+
model.constraint(implies(vip, expr`${seats} >= 8`), "vip_seats");
|
|
2781
|
+
model.constraint(expr`${seats} <= 5`, "room_cap");
|
|
2782
|
+
|
|
2783
|
+
const result = await model.check();
|
|
2784
|
+
if (result.status === "Unsat") {
|
|
2785
|
+
console.log("Conflicting rules:", result.conflicts); // also on result.unsatCore / model.unsatCore
|
|
2786
|
+
}
|
|
2787
|
+
```
|
|
2788
|
+
|
|
2789
|
+
---
|
|
2790
|
+
|
|
2791
|
+
## Solver Options
|
|
2792
|
+
|
|
2793
|
+
Pass solver options into `model.solve()` or `model.check()`:
|
|
2794
|
+
|
|
2795
|
+
```typescript
|
|
2796
|
+
const controller = new AbortController();
|
|
2797
|
+
|
|
2798
|
+
await model.solve({
|
|
2799
|
+
timeLimit: 30.0, // Maximum solve time in seconds
|
|
2800
|
+
signal: controller.signal,
|
|
2801
|
+
onProgress: (ev) => {
|
|
2802
|
+
console.log(`Elapsed: ${ev.elapsedTime.toFixed(1)}s, Best: ${ev.objectiveValue}`);
|
|
2803
|
+
},
|
|
2804
|
+
});
|
|
2805
|
+
|
|
2806
|
+
// Always check hasPrimalSolution when timeLimit or AbortSignal is used:
|
|
2807
|
+
if (model.hasPrimalSolution) {
|
|
2808
|
+
console.log(
|
|
2809
|
+
`Usable solution (${model.status}, termination: ${model.terminationStatus}):`,
|
|
2810
|
+
`obj = ${model.objectiveValue}`
|
|
2811
|
+
);
|
|
2812
|
+
}
|
|
2813
|
+
```
|
|
2814
|
+
|
|
2815
|
+
---
|
|
2816
|
+
|
|
2817
|
+
## Domain & API Preconditions
|
|
2818
|
+
|
|
2819
|
+
Pumpkin is strictly a **bounded integer & boolean CP/LCG solver**. Unsupported constructs are rejected with explicit errors rather than silent rounding or fallbacks:
|
|
2820
|
+
|
|
2821
|
+
- **Bounded integer / binary / boolean variables only**: All `Var` instances must be finite integers (`Integer` or `Binary`) with `lb` and `ub` within `[-(2^30 - 1), 2^30 - 1]`. Unbounded integers (`-Infinity` / `Infinity`) and `Continuous` variables throw an explicit error.
|
|
2822
|
+
- **Integer linear arithmetic**: Constraint coefficients, adjusted RHS values (`rhs - lhs.constant`), and scaled variable bounds must be exact integers within safe signed 32-bit range (`|rhs| + sum_i max(|c_i * lb_i|, |c_i * ub_i|) <= 2^31 - 2`). Objective constants (`f64`) may be fractional.
|
|
2823
|
+
- **Unsupported features**: `QuadExpr` objectives/constraints, `Continuous` variables, unbounded variables, and `relax: true` throw explicit errors.
|
|
2824
|
+
|
|
2825
|
+
---
|
|
2826
|
+
|
|
2827
|
+
## Worker & WASM Configuration in Browsers
|
|
2828
|
+
|
|
2829
|
+
By default in browsers, `@ohtaman/washi/solvers/pumpkin` resolves the bundled `pumpkin.wasm` and spawns `pumpkin-worker.js` in a dedicated Web Worker on HTTP(S) origins (falling back to main-thread execution on `file:` URLs or opaque-origin sandboxed iframes).
|
|
2830
|
+
|
|
2831
|
+
To execute synchronously on the main thread (or in environments where Web Workers are prohibited), pass `useWorker: false` to `model.solve()` / `model.check()` or instantiate `PumpkinSolver`:
|
|
2832
|
+
|
|
2833
|
+
```typescript
|
|
2834
|
+
import { Model } from "@ohtaman/washi";
|
|
2835
|
+
import { PumpkinSolver, setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
|
|
2836
|
+
|
|
2837
|
+
// Option 1: Per solve / check call
|
|
2838
|
+
await model.solve({ useWorker: false });
|
|
2839
|
+
|
|
2840
|
+
// Option 2: When instantiating the solver
|
|
2841
|
+
const syncModel = new Model({
|
|
2842
|
+
solver: new PumpkinSolver({ useWorker: false }),
|
|
2843
|
+
});
|
|
2844
|
+
|
|
2845
|
+
// Host pumpkin.wasm at a custom path or CDN (globally or per call via { wasmUrl }):
|
|
2846
|
+
setPumpkinWasmUrl("/assets/wasm/pumpkin.wasm");
|
|
2847
|
+
```
|
|
2848
|
+
|
|
2849
|
+
If `pumpkin.wasm` cannot be loaded or returns an HTML SPA fallback instead of a WebAssembly binary, Pumpkin rejects explicitly with the attempted URL and performs **no silent CDN fallback**.
|
|
2850
|
+
|
|
2851
|
+
---
|
|
2852
|
+
|
|
2853
|
+
## Architecture & WebAssembly Runtime
|
|
2854
|
+
|
|
2855
|
+
WaSHI compiles its Rust WebAssembly wrapper (`wasm/pumpkin`, linking `pumpkin-core`, `pumpkin-constraints`, `pumpkin-propagators`, and `pumpkin-conflict-resolvers` `v0.5.0` to `wasm32-unknown-unknown`) directly to `pumpkin.wasm` with `wasm-bindgen` bindings.
|
|
2856
|
+
|
|
2857
|
+
Bundled `pumpkin.wasm` and `runtime.js` / `runtime.d.ts` artifacts are tracked and verified via SHA-256 checksums in `pumpkin.config.json`. Maintainers rebuilding Pumpkin from source can follow the instructions in [`CONTRIBUTING.md`](https://github.com/ohtaman/washi/blob/main/CONTRIBUTING.md#4-rebuilding-webassembly-assets--release-workflow).
|
|
2858
|
+
|
|
2859
|
+
### Callbacks & Solver Interactivity
|
|
2860
|
+
|
|
2861
|
+
- **Progress Monitoring & Cancellation (Supported)**:
|
|
2862
|
+
During `solve()`, Pumpkin emits real-time incumbent progress callbacks (`onProgress`, providing `elapsedTime` and `objectiveValue`) and honors `AbortSignal`: browser Web Worker execution supports preemptive mid-solve Worker termination and queue cancellation, while main-thread and Node.js runs poll cooperative `should_abort` checkpoints across branching and termination hooks.
|
|
2863
|
+
- **Exact Discrete Optimality**:
|
|
2864
|
+
As an exact LCG solver over finite integer domains, Pumpkin proves optimality via nogood clause learning and objective-bound strengthening (`LinearSatUnsat`) rather than LP relaxation tolerances (`relativeGap`, `absoluteGap`, or `presolve`).
|
|
2865
|
+
|
|
2866
|
+
---
|
|
2867
|
+
|
|
2868
|
+
## References & Upstream Links
|
|
2869
|
+
|
|
2870
|
+
- **Modeling Guide & Walkthrough**: [Constraint Programming (CP) Modeling](docs/guide/constraint-programming.md) · [Resource-Constrained Project Scheduling (RCPSP)](docs/examples/project-scheduling.md)
|
|
2871
|
+
- **Source Repository**: [ConSol-Lab/Pumpkin](https://github.com/ConSol-Lab/Pumpkin) (MIT License — ConSol Lab, TU Delft)
|
|
2872
|
+
- **Rust Crate & API Docs**: [docs.rs/pumpkin-core](https://docs.rs/pumpkin-core) · [crates.io/crates/pumpkin-core](https://crates.io/crates/pumpkin-core)
|
|
2873
|
+
|
|
2874
|
+
---
|
|
2875
|
+
|
|
2366
2876
|
# Z3 SMT Solver Engine
|
|
2367
2877
|
|
|
2368
2878
|
**Z3** is a theorem prover and Satisfiability Modulo Theories (SMT) solver developed by Microsoft Research. In WaSHI, Z3 provides advanced propositional logic reasoning and conflict diagnosis.
|
|
@@ -2389,7 +2899,7 @@ npm install z3-solver
|
|
|
2389
2899
|
Z3 can perform exact rational arithmetic without floating-point inaccuracies.
|
|
2390
2900
|
|
|
2391
2901
|
> [!TIP]
|
|
2392
|
-
> **Z3
|
|
2902
|
+
> **Z3 vs. Pumpkin vs. HiGHS**: Z3 excels at satisfiability checking (`m.check()`), formal policy verification, implications with continuous or fractional antecedents (`` implies(expr`${temp} <= 50.5`, alarm) ``), and scale-invariant `unsatCore` extraction over mixed continuous/integer theories. For bounded-integer and boolean models where `COOP`/`COEP` headers or `z3-solver` are undesirable, bundled **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`) provides native propositional logic and `unsatCore` extraction without `SharedArrayBuffer`. For numerical LP, MIP, or Convex QP optimization with objective functions over tens or hundreds of variables, use the built-in **HiGHS** solver (`m.solve()`), whose simplex relaxations and branch-and-bound cutting planes are orders of magnitude faster than `Z3.Optimize`. Or combine them in a hybrid pipeline: verify/diagnose rules with Z3 or Pumpkin `m.check()`, then optimize costs with HiGHS `m.solve()`.
|
|
2393
2903
|
|
|
2394
2904
|
---
|
|
2395
2905
|
|
|
@@ -2436,7 +2946,7 @@ if (result.status === "Unsat") {
|
|
|
2436
2946
|
|
|
2437
2947
|
## Browser Security Note
|
|
2438
2948
|
|
|
2439
|
-
In browser environments, the Z3 WASM engine relies on pthreads and `SharedArrayBuffer`, which require cross-origin isolation headers (`COOP` / `COEP`). See the [Cross-Origin Isolation Guide](docs/getting-started/cross-origin.md) for detailed setup.
|
|
2949
|
+
In browser environments, the Z3 WASM engine relies on pthreads and `SharedArrayBuffer`, which require cross-origin isolation headers (`COOP` / `COEP`). See the [Cross-Origin Isolation Guide](docs/getting-started/cross-origin.md) for detailed setup. If your model uses only bounded integers and booleans and you cannot configure `COOP` / `COEP` headers (or want zero external dependencies), use the bundled [Pumpkin solver](docs/solvers/pumpkin.md) (`@ohtaman/washi/solvers/pumpkin`) instead.
|
|
2440
2950
|
|
|
2441
2951
|
## Runtime Failures and Thread Cleanup
|
|
2442
2952
|
|
|
@@ -2518,7 +3028,7 @@ GLPK return codes are mapped strictly to WaSHI `SolverStatus`:
|
|
|
2518
3028
|
|
|
2519
3029
|
This guide describes how to build, test, and distribute custom solver plugins for **WaSHI** (`@ohtaman/washi`).
|
|
2520
3030
|
|
|
2521
|
-
WaSHI features a pluggable, decoupled solver architecture. Core `@ohtaman/washi` bundles
|
|
3031
|
+
WaSHI features a pluggable, decoupled solver architecture. Core `@ohtaman/washi` bundles the zero-config HiGHS WASM engine and a Mock solver, while `@ohtaman/washi/solvers/pumpkin` provides a bundled CP/LCG WASM plugin. Any third-party solver—whether implemented in WebAssembly, native C++, a Web Worker, or an external cloud REST/RPC backend—can be registered and used through the unified `Model` API.
|
|
2522
3032
|
|
|
2523
3033
|
---
|
|
2524
3034
|
|
|
@@ -2529,6 +3039,7 @@ graph TD
|
|
|
2529
3039
|
A[WaSHI Model] --> B[Solver Registry Map Symbol.for]
|
|
2530
3040
|
B --> C[HiGHS WASM Engine Core]
|
|
2531
3041
|
B --> D[Mock Solver Core]
|
|
3042
|
+
B --> H[Pumpkin WASM Plugin @ohtaman/washi/solvers/pumpkin]
|
|
2532
3043
|
B --> E[GLPK Plugin @ohtaman/washi/solvers/glpk]
|
|
2533
3044
|
B --> F[Z3 SMT Plugin @ohtaman/washi/solvers/z3]
|
|
2534
3045
|
B --> G[Your Custom Solver Plugin]
|
|
@@ -2585,7 +3096,7 @@ export interface Solver {
|
|
|
2585
3096
|
* Main solve method for LP, MIP, QP, and SMT optimization models.
|
|
2586
3097
|
*
|
|
2587
3098
|
* @param modelData Typed in-memory model structure (variables, constraints, objective, sense, boolVars, logicalConstraints)
|
|
2588
|
-
* @param options Runtime execution options (timeLimit,
|
|
3099
|
+
* @param options Runtime execution options (timeLimit, relativeGap, absoluteGap, verbose, signal, onProgress, etc.)
|
|
2589
3100
|
*/
|
|
2590
3101
|
solve(
|
|
2591
3102
|
modelData: SolveModelData,
|
|
@@ -2635,7 +3146,7 @@ export interface SolveModelData extends CheckModelData {
|
|
|
2635
3146
|
|
|
2636
3147
|
Custom solvers declare their supported features using `capabilities`. Before dispatching `solve()` or `check()`, `Model` validates:
|
|
2637
3148
|
- `supportsQP === false` when the objective contains quadratic terms (`QuadExpr`),
|
|
2638
|
-
- when the model contains logical constraints (`m.logicalConstraints`) and the solver
|
|
3149
|
+
- when the model contains logical constraints (added via `m.constraint(...)`, appearing in `m.constraints` with `kind: "logical"` and passed to solvers in `modelData.logicalConstraints`) and the solver supports neither native logical constraints (`supportsLogicalConstraints !== true`) nor SMT (`supportsSMT !== true`), `Model` automatically linearizes them into equivalent 0-1 MIP binary variables and linear constraints via `linearizeModelForMip`, and
|
|
2639
3150
|
- `supportsWarmStart !== true` when any variable has a primal `initialValue` set.
|
|
2640
3151
|
|
|
2641
3152
|
```typescript
|
|
@@ -2652,6 +3163,9 @@ export interface SolverCapabilities {
|
|
|
2652
3163
|
/** Supports satisfiability modulo theories / boolean logic constraints */
|
|
2653
3164
|
supportsSMT?: boolean;
|
|
2654
3165
|
|
|
3166
|
+
/** Supports native boolean/propositional logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`) without SMT continuous theories */
|
|
3167
|
+
supportsLogicalConstraints?: boolean;
|
|
3168
|
+
|
|
2655
3169
|
/** Supports extracting an unsatisfiable core (conflicting constraint subset) */
|
|
2656
3170
|
supportsUnsatCore?: boolean;
|
|
2657
3171
|
|
|
@@ -2669,8 +3183,11 @@ export interface SolverOptions {
|
|
|
2669
3183
|
/** Time limit in seconds */
|
|
2670
3184
|
timeLimit?: number;
|
|
2671
3185
|
|
|
2672
|
-
/** Relative MIP optimality gap tolerance */
|
|
2673
|
-
|
|
3186
|
+
/** Relative MIP optimality gap tolerance (e.g. 0.01 for 1%) */
|
|
3187
|
+
relativeGap?: number;
|
|
3188
|
+
|
|
3189
|
+
/** Absolute MIP optimality gap tolerance */
|
|
3190
|
+
absoluteGap?: number;
|
|
2674
3191
|
|
|
2675
3192
|
/** Enable solver console logging */
|
|
2676
3193
|
verbose?: boolean;
|
|
@@ -2688,7 +3205,7 @@ export interface SolverOptions {
|
|
|
2688
3205
|
|
|
2689
3206
|
### Optional LP Serialization & Symbol-Mapping Helpers
|
|
2690
3207
|
|
|
2691
|
-
Solvers that consume structured JS/WASM data (such as `GLPKSolver
|
|
3208
|
+
Solvers that consume structured JS/WASM data (such as `PumpkinSolver`, `GLPKSolver`, and `Z3Solver`) work directly with `SolveModelData` / `CheckModelData`.
|
|
2692
3209
|
If your adapter targets a backend that requires CPLEX/HiGHS LP text or restricted identifier syntax, WaSHI exports opt-in helpers:
|
|
2693
3210
|
|
|
2694
3211
|
- `generateLpString(modelData): LpExportResult` — serializes `modelData` into a CPLEX LP format string (`lpString`) along with collision-safe symbol lookup maps (`nameToVar`, `nameToConstraint`).
|
|
@@ -2731,13 +3248,10 @@ export interface SolverResult {
|
|
|
2731
3248
|
objectiveBound?: number;
|
|
2732
3249
|
|
|
2733
3250
|
/** Relative MIP optimality gap when provided by the solver */
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
/** Alias for relGap: relative MIP optimality gap when provided by the solver */
|
|
2737
|
-
mipGap?: number;
|
|
3251
|
+
relativeGap?: number;
|
|
2738
3252
|
|
|
2739
3253
|
/** Absolute MIP optimality gap |objectiveValue - objectiveBound| (computed automatically when both are finite) */
|
|
2740
|
-
|
|
3254
|
+
absoluteGap?: number;
|
|
2741
3255
|
|
|
2742
3256
|
/** Variable primal values keyed by canonical variable name (non-finite values are ignored) */
|
|
2743
3257
|
values: Record<string, number>;
|
|
@@ -2833,7 +3347,8 @@ export class CloudSolver implements Solver {
|
|
|
2833
3347
|
body: JSON.stringify({
|
|
2834
3348
|
lp: lpString,
|
|
2835
3349
|
timeLimit: options.timeLimit,
|
|
2836
|
-
|
|
3350
|
+
relativeGap: options.relativeGap,
|
|
3351
|
+
absoluteGap: options.absoluteGap,
|
|
2837
3352
|
}),
|
|
2838
3353
|
signal: options.signal,
|
|
2839
3354
|
});
|
|
@@ -3031,7 +3546,7 @@ describe("Custom Solver Integration", () => {
|
|
|
3031
3546
|
const status = await model.solve();
|
|
3032
3547
|
expect(status).toBe("Optimal");
|
|
3033
3548
|
expect(x.value).toBe(2);
|
|
3034
|
-
const c1 = model.
|
|
3549
|
+
const c1 = model.constraints.get("budget");
|
|
3035
3550
|
expect(c1?.dual).toBe(2);
|
|
3036
3551
|
} finally {
|
|
3037
3552
|
fetchSpy.mockRestore();
|
|
@@ -3048,7 +3563,7 @@ Explore runnable optimization and logic formulations built with WaSHI. Every exa
|
|
|
3048
3563
|
|
|
3049
3564
|
## Examples
|
|
3050
3565
|
|
|
3051
|
-
| Example | Problem Class | Solver | Key WaSHI APIs | Description |
|
|
3566
|
+
| Example | Problem Class | Solver | Key WaSHI APIs | Description | Playground / Guide |
|
|
3052
3567
|
| :--- | :--- | :--- | :--- | :--- | :--- |
|
|
3053
3568
|
| **[Production Planning](docs/examples/production.md)** | LP / MIP | HiGHS | `m.integer()`, `m.constraint()`, `expr` | Basic variables, tagged template literal equations, and maximizing profit under resource limits. | [Playground](https://washi.ohtaman.dev/demo/?preset=production) |
|
|
3054
3569
|
| **[0-1 Knapsack](docs/examples/knapsack.md)** | Binary MIP | HiGHS | `m.binary(keys)`, `expr` (`dot`), `m.constraint()` | 1D dictionary of `Binary` variables and linear aggregation over item arrays. | [Playground](https://washi.ohtaman.dev/demo/?preset=knapsack) |
|
|
@@ -3057,6 +3572,7 @@ Explore runnable optimization and logic formulations built with WaSHI. Every exa
|
|
|
3057
3572
|
| **[Staff Shift Scheduling](docs/examples/shift-scheduling.md)** | Binary MIP + Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `check()`, `unsatCore` | 5×7 weekly roster planner (coverage, senior duty, max shifts, day-off requests) and diagnosing conflicting vacation requests with Z3 `unsatCore`. | [Playground](https://washi.ohtaman.dev/demo/?preset=shift_scheduling) |
|
|
3058
3573
|
| **[E-Commerce Coupon Optimizer](docs/examples/ecommerce-coupons.md)** | Indicator MIP | HiGHS | `m.indicator()`, `expr` (`sum`, `dot`), `m.constraint()` | Checkout optimizer using `m.indicator()` for minimum spend thresholds, exclusive vs. stackable rules, and smart filler add-on suggestions. | [Playground](https://washi.ohtaman.dev/demo/?preset=cart_coupon) |
|
|
3059
3574
|
| **[Portfolio Optimization](docs/examples/portfolio-qp.md)** | Convex QP | HiGHS | `m.continuous()`, `m.constraint()`, `dot()`, `QuadExpr` | Markowitz mean-variance risk minimization ($w^T \Sigma w$) using `QuadExpr` subject to return targets. | [Playground](https://washi.ohtaman.dev/demo/?preset=portfolio_qp) |
|
|
3575
|
+
| **[Project Scheduling (RCPSP)](docs/examples/project-scheduling.md)** | CP / LCG + Unsat Core | Pumpkin | `m.integer()`, `disjoint()`, `cumulative()`, `max()`, `m.check()` | 6-task resource-constrained schedule (unary rig + 3-engineer crew limit) and zero-`COOP`/`COEP` `unsatCore` deadline conflict check. | [Playground](https://washi.ohtaman.dev/demo/?preset=project_scheduling) |
|
|
3060
3576
|
| **[SMT Security Policies](docs/examples/smt-security.md)** | SMT Logic | Z3 | `m.bool()`, `m.constraint()`, `m.check()` | Propositional variables (`BoolVar`) and logical connectives (`implies`, `and`, `not`, `xor`) mixed with integer bounds. | [Playground](https://washi.ohtaman.dev/demo/?preset=smt_security) |
|
|
3061
3577
|
| **[Conflict Diagnosis (`unsatCore`)](docs/examples/unsat-core.md)** | Unsat Core | Z3 | `m.constraint()`, `m.check()`, `m.unsatCore` | Extracting a conflicting constraint subset (`unsatCore`) when staffing and budget rules contradict each other. | [Playground](https://washi.ohtaman.dev/demo/?preset=conflict_diagnosis_unsat) |
|
|
3062
3578
|
| **[Vehicle Routing (CVRP)](docs/examples/vehicle-routing.md)** | Combinatorial OR / Dantzig-Wolfe | HiGHS | `m.solveColumnGeneration()`, `pricing` | Dynamic route column generation from customer dual shadow prices to minimize total fleet vehicles. | [Decomposition Guide](docs/guide/decomposition.md) |
|
|
@@ -3080,6 +3596,9 @@ Looking for a specific modeling method or solver capability? Jump straight to th
|
|
|
3080
3596
|
| `m.check()` & `m.unsatCore` | Feasibility check & conflict diagnosis | [Conflict Diagnosis](docs/examples/unsat-core.md), [Shift Scheduling](docs/examples/shift-scheduling.md) | [`05-unsat-core-diagnosis.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts) |
|
|
3081
3597
|
| `m.solveColumnGeneration()` | Dantzig-Wolfe Column Generation | [Vehicle Routing](docs/examples/vehicle-routing.md) | [`13-vehicle-routing-column-generation.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts) |
|
|
3082
3598
|
| `m.solveBenders()` | Benders Decomposition & cut separation | [Traveling Salesperson](docs/examples/traveling-salesperson.md) | [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts) |
|
|
3599
|
+
| `distinct()` / `disjoint()` / `cumulative()` / `allowed()` | Backend-agnostic CP global constraints | [Project Scheduling](docs/examples/project-scheduling.md), [CP Modeling Guide](docs/guide/constraint-programming.md) | [`15-project-scheduling-cp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts) |
|
|
3600
|
+
| `max()` / `min()` / `abs()` / `at()` | Piecewise-linear & element lookup primitives | [Project Scheduling](docs/examples/project-scheduling.md), [Expressions Guide](docs/guide/expressions.md) | [`15-project-scheduling-cp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts) |
|
|
3601
|
+
| `solver: "pumpkin"` | Bundled CP/LCG scheduling & zero-`COOP`/`COEP` `unsatCore` | [Project Scheduling](docs/examples/project-scheduling.md), [Pumpkin Solver Guide](docs/solvers/pumpkin.md) | [`15-project-scheduling-cp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts) |
|
|
3083
3602
|
| `solver: "glpk"` | Solving LP/MIP with GLPK plugin | [GLPK Solver Guide](docs/solvers/glpk.md) | [`08-glpk-solver-plugin.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/08-glpk-solver-plugin.ts) |
|
|
3084
3603
|
|
|
3085
3604
|
## Running Examples Locally in Node.js
|
|
@@ -3100,6 +3619,7 @@ npx tsx examples/node/11-shift-scheduling.ts
|
|
|
3100
3619
|
npx tsx examples/node/12-ecommerce-coupon-optimizer.ts
|
|
3101
3620
|
npx tsx examples/node/13-vehicle-routing-column-generation.ts
|
|
3102
3621
|
npx tsx examples/node/14-traveling-salesperson-benders.ts
|
|
3622
|
+
npx tsx examples/node/15-project-scheduling-cp.ts
|
|
3103
3623
|
```
|
|
3104
3624
|
|
|
3105
3625
|
---
|
|
@@ -3602,6 +4122,9 @@ m.objective(minimize(expr`dot(${costMatrix}, ${shift}) + 500 * sum(${requestedSh
|
|
|
3602
4122
|
|
|
3603
4123
|
With this soft formulation on Scenario B, HiGHS automatically finds a valid roster that honors 3 of the 4 requests (`Alice (Sat)`, `Charlie (Sat)`, and `Diana (Wed)`) and overrides only `Bob (Sat)`—choosing Bob over Alice because Bob's daily wage (`$210`) is `$10` lower than Alice's (`$220`).
|
|
3604
4124
|
|
|
4125
|
+
> [!TIP]
|
|
4126
|
+
> **Diagnosing `unsatCore` Without `COOP` / `COEP` Headers**: Because every variable in this roster model is a 0-1 binary (`m.binary(...)`) with integer coefficients, you can also run `await model.check({ solver: "pumpkin" })` (after `import "@ohtaman/washi/solvers/pumpkin"`) to extract `unsatCore` in standard browser environments without `COOP` / `COEP` headers or external peer dependencies.
|
|
4127
|
+
|
|
3605
4128
|
---
|
|
3606
4129
|
|
|
3607
4130
|
# E-Commerce Cart & Coupon Optimizer (Indicator MIP)
|
|
@@ -3787,6 +4310,111 @@ solvePortfolio();
|
|
|
3787
4310
|
|
|
3788
4311
|
---
|
|
3789
4312
|
|
|
4313
|
+
# Resource-Constrained Project Scheduling (CP / Pumpkin)
|
|
4314
|
+
|
|
4315
|
+
| Problem Class | Solver | Key APIs | Links |
|
|
4316
|
+
| :--- | :--- | :--- | :--- |
|
|
4317
|
+
| CP / LCG (RCPSP & Unsat Core) | Pumpkin (`@ohtaman/washi/solvers/pumpkin`) | `m.integer()`, `disjoint()`, `cumulative()`, `max()`, `and()`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=project_scheduling">Playground (Schedule)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=project_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts">Source Code</a></li><li><a href="/guide/constraint-programming">CP Modeling Guide</a></li></ul> |
|
|
4318
|
+
|
|
4319
|
+
The **Resource-Constrained Project Scheduling Problem (RCPSP)** models project tasks governed simultaneously by **precedence dependencies**, **unary shared equipment** (disjunctive resource), and **limited renewable team headcount** (cumulative resource).
|
|
4320
|
+
|
|
4321
|
+
Using WaSHI's bundled **Pumpkin** solver (`@ohtaman/washi/solvers/pumpkin`):
|
|
4322
|
+
1. Every task needs only **one finite-domain start variable** (`start[task]`), avoiding $O(|T| \cdot H)$ time-indexed binary variables.
|
|
4323
|
+
2. When adding tighter maintenance windows or rush shipping deadlines causes infeasibility, `m.check()` extracts the conflicting rule subset (`unsatCore`) client-side with **zero `COOP` / `COEP` headers**.
|
|
4324
|
+
|
|
4325
|
+
## Problem Inputs
|
|
4326
|
+
|
|
4327
|
+
We schedule **6 hardware prototype tasks** over a 24-hour window (`crewCapacity = 3` engineers, 1 shared Hardware-in-the-Loop (HIL) calibration rig):
|
|
4328
|
+
|
|
4329
|
+
| Task | Duration | Crew | Dependencies | Shared Rig (`disjoint`) |
|
|
4330
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
4331
|
+
| `chassis` | 4h | 2 | — | No |
|
|
4332
|
+
| `board` | 3h | 2 | — | No |
|
|
4333
|
+
| `firmware` | 4h | 1 | — | **Yes** |
|
|
4334
|
+
| `assembly` | 3h | 2 | `chassis`, `board` | No |
|
|
4335
|
+
| `calib` | 3h | 1 | `board` | **Yes** |
|
|
4336
|
+
| `test` | 2h | 2 | `assembly`, `firmware`, `calib` | **Yes** |
|
|
4337
|
+
|
|
4338
|
+
Notice that ignoring crew capacity gives a naive critical path of `9h` (`chassis 4h -> assembly 3h -> test 2h`), whereas respecting the `crewCapacity = 3` constraint prevents `{chassis, board, assembly}` (2 engineers each) from overlapping, making the true minimum makespan **`12h`**.
|
|
4339
|
+
|
|
4340
|
+
## Implementation in WaSHI
|
|
4341
|
+
|
|
4342
|
+
```typescript
|
|
4343
|
+
import { Model, expr, disjoint, cumulative, max, and, minimize } from "@ohtaman/washi";
|
|
4344
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
4345
|
+
|
|
4346
|
+
async function runProjectScheduling() {
|
|
4347
|
+
const horizon = 24;
|
|
4348
|
+
const crewCapacity = 3;
|
|
4349
|
+
const tasks = [
|
|
4350
|
+
{ id: "chassis", duration: 4, crew: 2, usesRig: false },
|
|
4351
|
+
{ id: "board", duration: 3, crew: 2, usesRig: false },
|
|
4352
|
+
{ id: "firmware", duration: 4, crew: 1, usesRig: true },
|
|
4353
|
+
{ id: "assembly", duration: 3, crew: 2, usesRig: false },
|
|
4354
|
+
{ id: "calib", duration: 3, crew: 1, usesRig: true },
|
|
4355
|
+
{ id: "test", duration: 2, crew: 2, usesRig: true },
|
|
4356
|
+
] as const;
|
|
4357
|
+
|
|
4358
|
+
const m = new Model("PrototypeRCPSP", { solver: "pumpkin" });
|
|
4359
|
+
const start = m.integer(tasks.map((t) => t.id), { lb: 0, ub: horizon, prefix: "start" });
|
|
4360
|
+
|
|
4361
|
+
// 1. Precedence network
|
|
4362
|
+
m.constraint(expr`${start.chassis} + 4 <= ${start.assembly}`, "assembly_after_chassis");
|
|
4363
|
+
m.constraint(expr`${start.board} + 3 <= ${start.assembly}`, "assembly_after_board");
|
|
4364
|
+
m.constraint(expr`${start.board} + 3 <= ${start.calib}`, "calib_after_board");
|
|
4365
|
+
m.constraint(expr`${start.assembly} + 3 <= ${start.test}`, "test_after_assembly");
|
|
4366
|
+
m.constraint(expr`${start.firmware} + 4 <= ${start.test}`, "test_after_firmware");
|
|
4367
|
+
m.constraint(expr`${start.calib} + 3 <= ${start.test}`, "test_after_calib");
|
|
4368
|
+
|
|
4369
|
+
// 2. Exclusive HIL / calibration rig & 3-engineer cumulative limit
|
|
4370
|
+
m.constraint(
|
|
4371
|
+
disjoint(tasks.filter((t) => t.usesRig).map((t) => ({ start: start[t.id], duration: t.duration }))),
|
|
4372
|
+
"single_rig"
|
|
4373
|
+
);
|
|
4374
|
+
m.constraint(
|
|
4375
|
+
cumulative(
|
|
4376
|
+
tasks.map((t) => ({ start: start[t.id], duration: t.duration, demand: t.crew })),
|
|
4377
|
+
crewCapacity
|
|
4378
|
+
),
|
|
4379
|
+
"crew_limit"
|
|
4380
|
+
);
|
|
4381
|
+
|
|
4382
|
+
// 3. Minimize project makespan: max_t (start[t] + duration[t])
|
|
4383
|
+
const makespan = max(tasks.map((t) => expr`${start[t.id]} + ${t.duration}`));
|
|
4384
|
+
m.objective(minimize(makespan));
|
|
4385
|
+
|
|
4386
|
+
const status = await m.solve();
|
|
4387
|
+
const optMakespan = m.objectiveValue;
|
|
4388
|
+
const report = m.verify();
|
|
4389
|
+
console.log(`Status: ${status} (valid: ${report.valid}), Minimum Makespan: ${optMakespan}h`);
|
|
4390
|
+
for (const t of tasks) {
|
|
4391
|
+
const s = start[t.id].value ?? 0;
|
|
4392
|
+
console.log(` ${t.id}: [${s}h, ${s + t.duration}h) crew=${t.crew}${t.usesRig ? " [Rig]" : ""}`);
|
|
4393
|
+
}
|
|
4394
|
+
|
|
4395
|
+
// 4. Diagnose an impossible rush deadline when the rig is offline for maintenance [0, 6)
|
|
4396
|
+
m.constraint(
|
|
4397
|
+
and(expr`${start.firmware} >= 6`, expr`${start.calib} >= 6`),
|
|
4398
|
+
"rig_maintenance_window"
|
|
4399
|
+
);
|
|
4400
|
+
m.constraint(expr`${makespan} <= 13`, "rush_ship_deadline");
|
|
4401
|
+
|
|
4402
|
+
const diag = await m.check();
|
|
4403
|
+
console.log(`Deadline Check: ${diag.status}`);
|
|
4404
|
+
console.log(`Unsat Core: ${(diag.unsatCore ?? []).join(", ")}`);
|
|
4405
|
+
}
|
|
4406
|
+
|
|
4407
|
+
runProjectScheduling();
|
|
4408
|
+
```
|
|
4409
|
+
|
|
4410
|
+
## Practical Notes
|
|
4411
|
+
|
|
4412
|
+
- **Why Pumpkin shines here**: Combining `disjoint` (edge-finding) and `cumulative` (time-table propagation) directly on bounded integers lets Pumpkin learn why a schedule bottlenecks (`crew_limit` or `single_rig`) cleanly through Lazy Clause Generation, with zero time-indexed binary variables.
|
|
4413
|
+
- **Snapshot `m.objectiveValue` before `m.check()`**: Calling `await m.check()` on the same `Model` clears prior `solve()` fields (`m.objectiveValue` becomes `null`), so capture optimization outputs before running feasibility/conflict checks.
|
|
4414
|
+
- **Client-side `unsatCore` without `COOP` / `COEP`**: Notice that `diag.unsatCore` excludes unrelated `crew_limit` while isolating the rig maintenance (`firmware >= 6`, `calib >= 6`), `assembly -> test` chain (`test >= 7`), unary `single_rig` total of 9h ($\implies \text{completion} \ge 15 > 13$), and `rush_ship_deadline`.
|
|
4415
|
+
|
|
4416
|
+
---
|
|
4417
|
+
|
|
3790
4418
|
# SMT Security Policies
|
|
3791
4419
|
|
|
3792
4420
|
| Problem Class | Solver | Key APIs | Links |
|
|
@@ -3869,6 +4497,7 @@ verifySecurityRules();
|
|
|
3869
4497
|
|
|
3870
4498
|
- **Proof by Refutation (Counterexample Search)**: A single `Sat` check shows that *a* valid assignment exists. To formally prove that a safety property $P$ (such as `sirenActive`) **must** hold in *every* valid state, assert its negation `not(P)` and verify that `m.check()` returns `"Unsat"`. If it returns `"Sat"`, the solver's variable values give you a concrete counterexample (security loophole).
|
|
3871
4499
|
- **One-Way Implication (`implies`) vs. Equivalence**: In classical logic, `` implies(expr`${luxLevel} <= 50`, isNight) `` only constrains `isNight` when `luxLevel <= 50`. During daytime (`luxLevel > 50`), `isNight` is unconstrained ("open-world" assumption) and could be assigned either `true` or `false` unless you also add the converse rule `` implies(expr`${luxLevel} >= 51`, not(isNight)) ``.
|
|
4500
|
+
- **Running Without `COOP` / `COEP` Headers (`solver: "pumpkin"`)**: Because all variables in this model are propositional `BoolVar`s and bounded integers (`luxLevel` in `[0, 1000]`), the exact same deduction and counterexample `unsatCore` proof works out of the box with bundled `@ohtaman/washi/solvers/pumpkin` (`m.check({ solver: "pumpkin" })`) without `COOP` / `COEP` headers or `z3-solver`.
|
|
3872
4501
|
|
|
3873
4502
|
---
|
|
3874
4503
|
|
|
@@ -3939,8 +4568,9 @@ diagnoseConflicts();
|
|
|
3939
4568
|
|
|
3940
4569
|
## Practical Notes
|
|
3941
4570
|
|
|
3942
|
-
- **Z3
|
|
3943
|
-
- **
|
|
4571
|
+
- **Choosing Between Pumpkin, Z3, and HiGHS for Conflict Diagnosis**:
|
|
4572
|
+
- **Pumpkin (`m.check({ solver: "pumpkin" })`)** is bundled with `@ohtaman/washi/solvers/pumpkin` (zero external dependencies, no `COOP` / `COEP` headers) and extracts scale-invariant `unsatCore` subsets for discrete models where all variables are bounded `Integer`, `Binary`, or `BoolVar` (for example, when `budget` above is modeled with `m.integer("budget", ...)`).
|
|
4573
|
+
- **Z3 (`m.check({ solver: "z3" })`)** supports `Continuous` variables (like `budget` above) and fractional arithmetic, returning all four rules that jointly form the contradiction (`budget_limit`, `rush_required`, `rush_staffing_rule`, `strict_board_budget_cap`), while excluding the innocent `minimum_one_employee` rule.
|
|
3944
4574
|
- **HiGHS (`m.check({ solver: "highs" })`)** solves a single $L_1$ elastic slack minimization problem ($\min \sum s_i$). Because relaxing `rush_staffing_rule` (or `rush_required`) requires a slack of only `1`–`2` units whereas relaxing `strict_board_budget_cap` requires a slack of `14,000` dollars, unweighted $L_1$ minimization naturally highlights the smallest-magnitude repair (`rush_required`) needed to restore feasibility.
|
|
3945
4575
|
|
|
3946
4576
|
---
|
|
@@ -4166,7 +4796,7 @@ $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S
|
|
|
4166
4796
|
|
|
4167
4797
|
Because there are $2^n - 2$ subsets, enumerating all subtour constraints upfront is impractical as $n$ grows. With **Benders Decomposition (Lazy Constraint Separation)**, constraints are added only when violated:
|
|
4168
4798
|
1. **Master Problem**: Solves the degree-assignment relaxation (each city has 1 incoming and 1 outgoing edge).
|
|
4169
|
-
2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds
|
|
4799
|
+
2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds **Benders Feasibility Cuts** eliminating all detected subtours simultaneously (multi-cut separation) and resolves until a single connected tour is obtained.
|
|
4170
4800
|
|
|
4171
4801
|
## Problem Inputs
|
|
4172
4802
|
|