@ohtaman/washi 0.6.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.
Files changed (147) hide show
  1. package/README.ja.md +139 -418
  2. package/README.md +139 -418
  3. package/README.zh-CN.md +139 -418
  4. package/THIRD_PARTY_LICENSES.md +39 -4
  5. package/dist/browser/__vite-browser-external-rTVKos2U.js +7 -0
  6. package/dist/browser/browser-runtime-AG5QFtKf.js +2021 -0
  7. package/dist/browser/highs-worker.js +26 -11
  8. package/dist/browser/highs.wasm +0 -0
  9. package/dist/browser/{loader-DewlSho8.js → loader-i3FnqMes.js} +183 -149
  10. package/dist/browser/solvers/glpk.js +289 -238
  11. package/dist/browser/solvers/glpk.min.js +1 -1
  12. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  13. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  14. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  15. package/dist/browser/solvers/pumpkin.js +1777 -0
  16. package/dist/browser/solvers/pumpkin.min.js +1 -0
  17. package/dist/browser/solvers/pumpkin.wasm +0 -0
  18. package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
  19. package/dist/browser/solvers/z3.js +1600 -1335
  20. package/dist/browser/solvers/z3.min.js +2 -2
  21. package/dist/browser/washi.js +3828 -1315
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/highs-browser-runtime.js +1846 -1618
  25. package/dist/lib/highs-runtime.js +16 -2
  26. package/dist/lib/highs-worker.js +26 -11
  27. package/dist/lib/highs.wasm +0 -0
  28. package/dist/lib/{loader-BZUQNvh4.js → loader-CDpPXN_F.js} +138 -116
  29. package/dist/lib/registry-dx7x4e5c.js +1694 -0
  30. package/dist/lib/rolldown-runtime-DtPi1Y-2.js +13 -0
  31. package/dist/lib/solvers/glpk.js +161 -121
  32. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  33. package/dist/lib/solvers/pumpkin-loader-Ow74Fa1B.js +311 -0
  34. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  35. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  36. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  37. package/dist/lib/solvers/pumpkin.js +1767 -0
  38. package/dist/lib/solvers/pumpkin.wasm +0 -0
  39. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  40. package/dist/lib/solvers/z3.js +486 -306
  41. package/dist/lib/washi.js +3054 -1202
  42. package/dist/types/decomposition/benders.d.ts.map +1 -1
  43. package/dist/types/index.d.ts +3 -3
  44. package/dist/types/index.d.ts.map +1 -1
  45. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  46. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  47. package/dist/types/modeler/constraint.d.ts +40 -4
  48. package/dist/types/modeler/constraint.d.ts.map +1 -1
  49. package/dist/types/modeler/expression.d.ts +176 -28
  50. package/dist/types/modeler/expression.d.ts.map +1 -1
  51. package/dist/types/modeler/index.d.ts +5 -6
  52. package/dist/types/modeler/index.d.ts.map +1 -1
  53. package/dist/types/modeler/linearizer.d.ts +11 -2
  54. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  55. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  56. package/dist/types/modeler/model.d.ts +97 -130
  57. package/dist/types/modeler/model.d.ts.map +1 -1
  58. package/dist/types/modeler/parser.d.ts +25 -5
  59. package/dist/types/modeler/parser.d.ts.map +1 -1
  60. package/dist/types/modeler/quad-expr.d.ts +8 -2
  61. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  62. package/dist/types/modeler/solution-validator.d.ts +12 -12
  63. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  64. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  65. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  66. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  67. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  68. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  69. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  70. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  72. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  73. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  74. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  75. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  76. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  77. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  78. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  79. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  80. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  81. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  82. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  83. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  84. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  85. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  86. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  87. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  88. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  89. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  90. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  91. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  92. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  93. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  94. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  95. package/dist/types/modeler/solvers/types.d.ts +9 -9
  96. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  97. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  98. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  99. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  100. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  101. package/dist/types/modeler/types.d.ts +12 -15
  102. package/dist/types/modeler/types.d.ts.map +1 -1
  103. package/dist/types/modeler/validation.d.ts +26 -2
  104. package/dist/types/modeler/validation.d.ts.map +1 -1
  105. package/dist/types/modeler/variable.d.ts +9 -5
  106. package/dist/types/modeler/variable.d.ts.map +1 -1
  107. package/docs/examples/diet-sensitivity.md +15 -14
  108. package/docs/examples/ecommerce-coupons.md +15 -22
  109. package/docs/examples/index.md +20 -13
  110. package/docs/examples/knapsack.md +8 -7
  111. package/docs/examples/portfolio-qp.md +11 -4
  112. package/docs/examples/production.md +4 -4
  113. package/docs/examples/project-scheduling.md +106 -0
  114. package/docs/examples/shift-scheduling.md +23 -7
  115. package/docs/examples/smt-security.md +17 -4
  116. package/docs/examples/transportation.md +46 -19
  117. package/docs/examples/traveling-salesperson.md +29 -45
  118. package/docs/examples/unsat-core.md +16 -5
  119. package/docs/examples/vehicle-routing.md +10 -8
  120. package/docs/getting-started/ai-agents.md +114 -34
  121. package/docs/getting-started/coding-agents.md +158 -0
  122. package/docs/getting-started/cross-origin.md +56 -28
  123. package/docs/getting-started/index.md +36 -66
  124. package/docs/getting-started/runtimes.md +98 -69
  125. package/docs/guide/constraint-programming.md +141 -0
  126. package/docs/guide/constraints.md +100 -44
  127. package/docs/guide/decomposition.md +141 -273
  128. package/docs/guide/expressions.md +125 -42
  129. package/docs/guide/formulation-tips.md +212 -0
  130. package/docs/guide/objectives.md +70 -64
  131. package/docs/guide/unsat-core.md +44 -23
  132. package/docs/guide/variables.md +56 -48
  133. package/docs/solvers/custom-solver.md +18 -13
  134. package/docs/solvers/highs.md +41 -25
  135. package/docs/solvers/index.md +13 -7
  136. package/docs/solvers/pumpkin.md +163 -0
  137. package/docs/solvers/z3.md +4 -1
  138. package/llms-full.txt +1732 -860
  139. package/llms.txt +59 -36
  140. package/package.json +40 -13
  141. package/skills/washi/SKILL.md +91 -35
  142. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  143. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  144. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  145. package/dist/lib/registry-C20sxTwm.js +0 -964
  146. package/docs/ja/getting-started/ai-agents.md +0 -270
  147. package/docs/zh/getting-started/ai-agents.md +0 -270
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, `validateSolution()` verification, and 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`):
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 pass `await m.solve({ wasmUrl: "https://.../highs.wasm" })` (ignored in Node.js, which always loads the local Node `highs` package runtime).
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, HiGHS runs in a dedicated Web Worker by default (`useWorker: true`). Passing `{ signal }` to `m.solve({ signal })` preemptively terminates an in-flight Worker solve (or cancels queued Worker requests).
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
 
@@ -82,9 +95,10 @@ const m = new Model("ExampleModel");
82
95
 
83
96
  // Scalar variables
84
97
  const x = m.continuous("x", { lb: 0, ub: 100 });
98
+ const y = m.continuous("y", { lb: 0, ub: 100 });
85
99
  const n = m.integer("n", { lb: 0, ub: 10 });
86
100
  const b = m.binary("b");
87
- const flag = m.bool("flag"); // Propositional boolean (for Z3 / logical constraints)
101
+ const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native LCG/SMT on Pumpkin/Z3)
88
102
 
89
103
  // Indexed variable containers:
90
104
  // - Numeric dimension -> Array
@@ -98,47 +112,49 @@ const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
98
112
  - **Optional Primal Initial Values (`initialValue?: number`)**:
99
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`.
100
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.
101
- - 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`.
102
116
 
103
- ### Step 2: Build Expressions (`expr`, `sum`, `dot`)
117
+ ### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
104
118
 
105
119
  - **Unified `expr` template tag**:
106
- - Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${n} - 10` ``
107
- - Quadratic expression (`QuadExpr`): `` expr`${x}^2 + 2 * ${x} * ${n} + ${n}^2` `` (variable-by-variable products and squares are supported for convex QP objectives).
108
- - Linear constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` `` (supports `<=`, `>=`, `==`, and `=`).
109
- - **Aggregations**:
110
- - `sum(iterable, mapper?)` sums an `Iterable` of `Var` / `LinExpr` / `number` (e.g., `Var[]`, `grid.flat()`, or `Object.values(record)`).
111
- - `dot(a, b)` computes the inner product of matching 1D arrays, 2D arrays (`number[][]` / `Var[][]`), plain records (`Record<string, ...>`), or mixed Array/Record containers in either operand order.
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).
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).
123
+ - Constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` (supports `<=`, `>=`, `==`, `=`, plus discrete integer-only `<`, `>`, `!=`).
124
+ - **Aggregations & Element-Wise Container Arithmetic**:
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.
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.
112
127
  - **Fluent methods**:
113
128
  - Arithmetic (on `LinExpr` and `QuadExpr`; `Var` supports `.add()`, `.sub()`, `.mul()`, `.neg()`): `.add(other)`, `.sub(other)`, `.mul(other)`, `.div(scalar)`, `.neg()`
114
- - Comparisons (on `Var` and `LinExpr`): `.le(rhs, name?)`, `.ge(rhs, name?)`, `.eq(rhs, name?)`
115
- - Boolean logic (on `BoolVar`, `BoolExpr`, and `Constraint` for Z3): standalone `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, `xor(a, b)` and fluent `.and(...)`, `.or(...)`, `.not()`, `.implies(...)`, `.xor(...)`
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()`)
116
132
 
117
133
  ### Step 3: Register Objective & Constraints on the Model
118
134
 
119
- 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):
120
136
 
121
137
  ```ts
122
138
  // Set objective using maximize() or minimize()
123
139
  m.objective(maximize(expr`30 * ${x} + 50 * ${n}`));
124
140
 
125
- // Register constraints on the model
126
- m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
141
+ // Register constraints on the model (returns the registered Constraint / BoolExpr or array)
142
+ const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
127
143
 
128
144
  // Indicator constraint (MIP Big-M reformulation: b === 1 => x <= 50)
129
145
  m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
130
146
  ```
131
147
 
132
- ### Step 4: Execute (`solve` or `check`) & Verify (`validateSolution`)
148
+ ### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
133
149
 
134
150
  - **Optimization (`await m.solve(options?)`)**:
135
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`).
136
- - Read values via `x.value`, `expr`...`.value`, `m.getValues(x)`, `m.getValues(container)`, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`.
137
- - Call `m.validateSolution()` after solving to independently verify variable finiteness, variable bounds (`lb`/`ub`), integer/binary/boolean domains, linear constraint residuals, and logical constraints (`SolutionValidationReport`: `{ valid, complete, maxViolation, violations, ... }`). Note that `validateSolution()` checks primal feasibility of variables and constraints; it does not recompute or compare `m.objectiveValue`.
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`.
138
154
  - **Satisfiability & Conflict Diagnosis (`await m.check(options?)`)**:
139
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"`.
140
- - 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).
141
- - Exact SMT unsatisfiable-core extraction (`result.unsatCore` and `result.conflicts`) is provided when using an SMT-capable solver (`{ solver: "z3" }`). Because Z3 asserts 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).
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).
142
158
  - **No concurrent mutation during async solve/check**:
143
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.
144
160
 
@@ -161,14 +177,17 @@ export async function runMipExample() {
161
177
  const qty = m.integer(products, { lb: 0, ub: 100 });
162
178
  const setup = m.binary("setup");
163
179
 
164
- m.objective(maximize(expr`${dot(profit, qty)} - 20 * ${setup}`));
165
- m.constraint(expr`${dot(woodPerUnit, qty)} <= 40`, "wood_cap");
166
- m.constraint(expr`${dot(laborPerUnit, qty)} <= 50`, "labor_cap");
167
- m.constraint(expr`${sum(Object.values(qty))} <= 30 * ${setup}`, "require_setup");
180
+ m.objective(maximize(expr`dot(${profit}, ${qty}) - 20 * ${setup}`));
181
+ m.constraint(expr`dot(${woodPerUnit}, ${qty}) <= 40`, "wood_cap");
182
+ m.constraint(expr`dot(${laborPerUnit}, ${qty}) <= 50`, "labor_cap");
183
+ m.indicator(setup, expr`sum(${qty}) <= 0`, {
184
+ activeValue: 0,
185
+ name: "require_setup",
186
+ });
168
187
 
169
188
  const status = await m.solve();
170
- const report = m.validateSolution();
171
- const values = m.getValues(qty);
189
+ const report = m.verify();
190
+ const values = { desk: qty.desk.value, chair: qty.chair.value };
172
191
 
173
192
  return {
174
193
  status,
@@ -198,7 +217,7 @@ export async function runQpExample() {
198
217
  m.constraint(expr`${x} + ${y} >= 4`, "budget");
199
218
 
200
219
  const status = await m.solve();
201
- const report = m.validateSolution();
220
+ const report = m.verify();
202
221
 
203
222
  return {
204
223
  status,
@@ -233,6 +252,57 @@ export async function runZ3Example() {
233
252
  }
234
253
  ```
235
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
+
236
306
  ---
237
307
 
238
308
  ## 4. Negative Examples & Common Pitfalls
@@ -257,36 +327,38 @@ export function verifyNegativePatterns() {
257
327
  // 3. DO NOT use quadratic terms inside linear constraints:
258
328
  // WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
259
329
 
260
- // 4. DO NOT use retired aliases (removed in #59 / #81):
330
+ // 4. DO NOT use retired aliases (removed in #59 / #81 / #236 / #273):
261
331
  // - Use `expr` instead of retired `c` template tag
262
332
  // - Use `m.constraint(...)` instead of `m.constrain(...)` or `m.add(...)`
263
- // - 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`
264
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(...)`
265
337
  // - Use `.le()`, `.ge()`, `.eq()` instead of `.lessThanOrEqual()`, `.greaterThanOrEqual()`, `.equalTo()`
266
- // - Use `.value` or `m.getValues(...)` instead of `expr.getValue()`
267
- // - 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`
268
341
  return { m, x, y, maximize };
269
342
  }
270
343
  ```
271
344
 
272
- ---
273
-
274
- # Introduction & Installation
345
+ ### Practical OR Modeling Guardrails
275
346
 
276
- Welcome to **WaSHI** (WebAssembly-backed, Solver-independent, High-level modeling Interface).
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`).
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).
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.
277
350
 
278
- WaSHI brings the algebraic modeling style of Python's **PuLP** and Julia's **JuMP** to the TypeScript and JavaScript ecosystem. You can formulate mathematical optimization problems using algebraic expressions and solve them locally using WebAssembly solvers (**HiGHS**, **Z3**, and **GLPK**)—without a separate Python service or native C/C++ build steps.
351
+ ---
279
352
 
280
- ### Why TypeScript & WebAssembly?
353
+ # Introduction & Installation
281
354
 
282
- - **Removing the deployment bottleneck**: In traditional optimization workflows (e.g., Python with PuLP or Pyomo), turning a model into an interactive application requires provisioning a backend service and managing native C/C++ solver binaries. As AI-assisted development accelerates UI and application prototyping, backend infrastructure often becomes the primary bottleneck to shipping. Running both the modeler and WebAssembly solvers on standard Web technologies allows an optimization tool to be deployed as static assets (e.g., on GitHub Pages or Cloudflare Pages, serving the generated JS, Worker, and WASM files; with COOP/COEP headers when using Z3)—and makes it straightforward to pair mathematical optimization with in-browser LLMs (e.g., WebGPU / WebLLM) entirely on the client.
283
- - **Algebraic syntax without operator overloading (`expr`)**: Because JavaScript lacks operator overloading, libraries usually trade off between verbose method chaining (`x.mul(30).add(y.mul(50))`) and untyped strings (`"30 * x + 50 * y"`). WaSHI uses tagged template literals (`` expr`30 * ${x} + 50 * ${y} <= 40` ``) similar to parameterized SQL queries—parsing infix operators while binding `${x}` directly as typed TypeScript object references for static type checking, IDE symbol renaming, and multi-dimensional indexing (`${flow[i][j]}`).
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**).
284
356
 
285
357
  ---
286
358
 
287
359
  ## 📦 Installation
288
360
 
289
- Install WaSHI using your preferred package manager:
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:
290
362
 
291
363
  ```bash [npm]
292
364
  npm install @ohtaman/washi
@@ -304,96 +376,76 @@ yarn add @ohtaman/washi
304
376
  bun add @ohtaman/washi
305
377
  ```
306
378
 
307
- ### Optional Solver Dependencies
308
-
309
- WaSHI ships with **HiGHS** built-in with zero configuration. If you need SMT logic / Unsat Core diagnosis via **Z3**, or compatibility with **GLPK**, install their respective peer dependencies:
379
+ Install optional peer dependencies when you need **Z3** (SMT logic and Unsat Core conflict diagnosis) or **GLPK**:
310
380
 
311
381
  ```bash
312
- # For SMT logic and Unsat Core conflict diagnosis
313
- npm install z3-solver
314
-
315
- # For GLPK solver (GPL-3.0)
316
- npm install glpk.js
382
+ npm install z3-solver # For SMT logic and Unsat Core conflict diagnosis
383
+ npm install glpk.js # For GLPK solver (GPL-3.0)
317
384
  ```
318
385
 
319
- ---
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.
320
387
 
321
- ## 🚀 Quickstart Walkthrough
388
+ ---
322
389
 
323
- Here is a step-by-step example of solving a production allocation problem.
390
+ ## 🚀 Quick Start
324
391
 
325
- ### 1. Import the Core Classes
392
+ Here is a complete production-planning model illustrating the three steps of a typical WaSHI workflow:
326
393
 
327
394
  ```typescript
328
395
  import { Model, expr, maximize } from "@ohtaman/washi";
329
- ```
330
-
331
- ### 2. Instantiate a Model
332
-
333
- ```typescript
334
- const model = new Model("WoodworkingProfit");
335
- ```
336
396
 
337
- ### 3. Add Decision Variables
397
+ const m = new Model("production");
338
398
 
339
- Variables represent the unknowns you want to determine. Factory methods (`m.continuous`, `m.integer`, `m.binary`) clearly define their domain:
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 });
340
402
 
341
- ```typescript
342
- const x = model.integer("x", { lb: 0 });
343
- const y = model.integer("y", { lb: 0 });
344
- ```
345
-
346
- ### 4. Set the Objective Function
347
-
348
- Use the `expr` tagged template literal along with `maximize(...)` or `minimize(...)` to define the goal:
349
-
350
- ```typescript
351
- // Maximize 30*x + 50*y
352
- model.objective(maximize(expr`30 * ${x} + 50 * ${y}`));
353
- ```
354
-
355
- ### 5. Add Constraints
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");
356
407
 
357
- Use `model.constraint()` with the `expr` tagged template to formulate equality and inequality constraints:
358
-
359
- ```typescript
360
- model.constraint(expr`${x} + 2 * ${y} <= 40`, "wood_capacity");
361
- model.constraint(expr`2 * ${x} + ${y} <= 50`, "labor_capacity");
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
+ }
362
415
  ```
363
416
 
364
- ### 6. Solve and Extract Results
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.
365
420
 
366
- Solve the model asynchronously via WebAssembly (HiGHS by default):
421
+ ---
367
422
 
368
- ```typescript
369
- const status = await model.solve();
423
+ ## 🧭 Next Steps
370
424
 
371
- console.log("Status:", status); // "Optimal"
372
- console.log("Optimal Objective Value:", model.objectiveValue); // 1100
373
- console.log(`Solution: x = ${x.value}, y = ${y.value}`); // x = 20, y = 10
374
- ```
425
+ ### Choose Your Workflow
375
426
 
376
- ---
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
377
429
 
378
- ## 🧭 Next Steps
430
+ ### Reference & Examples
379
431
 
380
- - Give AI coding agents a concise API & deployment reference with the [AI Coding Agent Quick-Reference Guide](docs/getting-started/ai-agents.md).
381
- - Learn how to run WaSHI across different environments in [Runtime Environments](docs/getting-started/runtimes.md).
382
- - Understand how to formulate complex expressions in the [Modeling Guide](docs/guide/expressions.md).
383
- - Explore built-in and pluggable solvers in the [Solvers Matrix](docs/solvers/index.md).
384
- - Browse 9 runnable optimization and SMT recipes in [Examples & API Finder](docs/examples/index.md).
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
385
435
 
386
436
  ---
387
437
 
388
438
  # Runtime Environments & Deployment
389
439
 
390
- WaSHI runs across JavaScript and TypeScript runtimes—from Node.js, Bun, and Deno to modern bundlers, vanilla browser `<script>` tags, and air-gapped intranets—without native C/C++ compilation.
440
+ WaSHI runs across JavaScript and TypeScript runtimes—from Node.js, Bun, and Deno to modern bundlers, static hosting, and vanilla browser `<script>` tags—without native C/C++ compilation.
391
441
 
392
442
  ---
393
443
 
394
- ## 🟢 Node.js
444
+ ## 🟢 Node.js, Bun & Deno
395
445
 
396
- WaSHI supports Node.js (v18+) out of the box with standard ECMAScript Modules (ESM). The built-in HiGHS WebAssembly binary is loaded directly from the installed package.
446
+ ### Node.js
447
+
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:
397
449
 
398
450
  ```typescript
399
451
  import { Model, expr, maximize } from "@ohtaman/washi";
@@ -406,8 +458,10 @@ m.objective(maximize(expr`2 * ${x} + 3 * ${y}`));
406
458
  m.constraint(expr`${x} + ${y} <= 15`, "capacity");
407
459
 
408
460
  await m.solve();
409
- console.log(`Status: ${m.status}, Objective: ${m.objectiveValue}`);
410
- console.log(`x = ${x.value}, y = ${y.value}`);
461
+ if (m.hasPrimalSolution) {
462
+ console.log(`Status: ${m.status}, Objective: ${m.objectiveValue}`);
463
+ console.log(`x = ${x.value}, y = ${y.value}`);
464
+ }
411
465
  ```
412
466
 
413
467
  Run directly with `tsx` or `node`:
@@ -416,11 +470,33 @@ Run directly with `tsx` or `node`:
416
470
  npx tsx app.ts
417
471
  ```
418
472
 
473
+ ### Bun & Deno
474
+
475
+ ```bash
476
+ # Bun
477
+ bun add @ohtaman/washi
478
+ bun run app.ts
479
+ ```
480
+
481
+ In Deno (v1.30+ with `npm:` specifiers):
482
+
483
+ ```typescript
484
+ import { Model, maximize } from "npm:@ohtaman/washi";
485
+
486
+ const m = new Model();
487
+ const x = m.continuous("x", { lb: 0, ub: 10 });
488
+ m.objective(maximize(x));
489
+ await m.solve();
490
+ if (m.hasPrimalSolution) {
491
+ console.log("x =", x.value);
492
+ }
493
+ ```
494
+
419
495
  ---
420
496
 
421
- ## 🌐 Bundlers (Vite, Webpack, Rollup, Next.js)
497
+ ## 🌐 Bundlers & Static Hosting (Vite, Next.js, Webpack, Rollup)
422
498
 
423
- ### Modern Bundlers (Vite / Rollup / Webpack)
499
+ ### Modern Bundlers & Static Deployment
424
500
 
425
501
  When importing `@ohtaman/washi` in a browser bundler, the `browser` export condition resolves automatically:
426
502
 
@@ -432,31 +508,35 @@ export async function runOptimization() {
432
508
  const x = m.continuous("x", { lb: 0, ub: 100 });
433
509
  m.objective(maximize(x));
434
510
  await m.solve();
435
- return x.value;
511
+ return m.hasPrimalSolution ? x.value : null;
436
512
  }
437
513
  ```
438
514
 
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).)
516
+
439
517
  #### Background Web Worker Execution (Default)
440
- In browsers, HiGHS automatically runs inside a dedicated **Web Worker** so long-running LP/MIP/QP solves never freeze the main UI thread, animations, or user input, while enabling real-time progress events (`onProgress`) and cancellation (`AbortSignal`).
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`).
441
519
 
442
- If your environment prohibits Web Workers or you explicitly want synchronous main-thread execution, pass `useWorker: false`:
520
+ If your environment prohibits Web Workers or you explicitly want main-thread execution, pass `useWorker: false`:
443
521
 
444
522
  ```typescript
445
523
  await m.solve({ useWorker: false });
446
524
  ```
447
525
 
448
- #### Customizing the HiGHS WASM Asset URL
449
- 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.).
450
528
 
451
- 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:
452
530
 
453
531
  ```typescript
454
532
  import { setHighsWasmUrl } from "@ohtaman/washi";
533
+ import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
455
534
 
456
535
  // Option A: Configure globally before solving
457
536
  setHighsWasmUrl("/assets/wasm/highs.wasm");
537
+ setPumpkinWasmUrl("/assets/wasm/pumpkin.wasm");
458
538
 
459
- // Option B: Configure per solve call
539
+ // Option B: Configure per solve / check call
460
540
  await m.solve({ wasmUrl: "/assets/wasm/highs.wasm" });
461
541
  ```
462
542
 
@@ -478,7 +558,9 @@ export default function OptimizerComponent() {
478
558
  const x = m.continuous("x", { lb: 0, ub: 50 });
479
559
  m.objective(maximize(x));
480
560
  await m.solve();
481
- setVal(x.value);
561
+ if (m.hasPrimalSolution) {
562
+ setVal(x.value);
563
+ }
482
564
  };
483
565
 
484
566
  return (
@@ -490,40 +572,59 @@ export default function OptimizerComponent() {
490
572
  }
491
573
  ```
492
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
+
493
593
  ---
494
594
 
495
595
  ## 📦 Browser ESM (`<script type="module">`)
496
596
 
497
- You can import the pre-bundled browser ESM modules directly from a local static server (or from an npm CDN once a compatible release is published) without a build step:
597
+ Without a bundler, you can import the pre-built browser ESM module directly from your own static server or an npm CDN:
498
598
 
499
599
  ```html
500
600
  <script type="module">
501
- // Serve from your local static server / dist:
502
- import { Model, expr, maximize } from "./dist/browser/washi.js";
503
- // Or from an npm CDN once a compatible release is published:
504
- // import { Model, expr, maximize } from "https://cdn.jsdelivr.net/npm/@ohtaman/washi@<version>/dist/browser/washi.js";
505
- // Optional solver plugins:
506
- // import "./dist/browser/solvers/glpk.js";
507
- // import "./dist/browser/solvers/z3.js";
601
+ // From an npm CDN (or "./dist/browser/washi.js" when self-hosted):
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";
508
607
 
509
608
  const m = new Model("BrowserESM");
510
- const x = m.integer("x", { lb: 0 });
511
- const y = m.integer("y", { lb: 0 });
609
+ const x = m.integer("x", { lb: 0, ub: 100 });
610
+ const y = m.integer("y", { lb: 0, ub: 100 });
512
611
 
513
612
  m.objective(maximize(expr`30 * ${x} + 50 * ${y}`));
514
613
  m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
515
614
  m.constraint(expr`2 * ${x} + ${y} <= 50`, "labor");
516
615
 
517
616
  await m.solve();
518
- console.log("Optimal Objective:", m.objectiveValue);
617
+ if (m.hasPrimalSolution) {
618
+ console.log("Optimal Objective:", m.objectiveValue);
619
+ }
519
620
  </script>
520
621
  ```
521
622
 
522
623
  ---
523
624
 
524
- ## 🟨 Classic `<script>` Tags (IIFE / Standalone Build / CDN)
625
+ ## 🟨 Classic `<script>` Tags (IIFE / Standalone HTML / CDN)
525
626
 
526
- For static HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a standard `<script>` tag. All exports are attached to the global `window.Washi` object:
627
+ For single-file HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a standard `<script>` tag. All exports are attached to the global `window.Washi` object:
527
628
 
528
629
  ```html
529
630
  <!DOCTYPE html>
@@ -536,13 +637,12 @@ For static HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a standard
536
637
  <h1>WaSHI Browser Optimization</h1>
537
638
  <pre id="output">Solving...</pre>
538
639
 
539
- <!-- Core WaSHI + HiGHS (MIT) from local static build / assets -->
540
- <script src="./dist/browser/washi.min.js"></script>
541
- <!-- Or via CDN once a compatible release is published: -->
542
- <!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi@<version>/dist/browser/washi.min.js"></script> -->
543
- <!-- Optional plugins (auto-register on window.Washi): -->
544
- <!-- <script src="./dist/browser/solvers/glpk.min.js"></script> -->
545
- <!-- <script src="./dist/browser/solvers/z3.min.js"></script> -->
640
+ <!-- Core WaSHI + HiGHS (MIT) via CDN (or "./dist/browser/washi.min.js" when self-hosted) -->
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> -->
546
646
 
547
647
  <script>
548
648
  (async () => {
@@ -557,10 +657,12 @@ For static HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a standard
557
657
 
558
658
  await m.solve();
559
659
 
560
- document.getElementById("output").textContent =
561
- `Status: ${m.status}\n` +
562
- `Objective: ${m.objectiveValue}\n` +
563
- `x = ${x.value}, y = ${y.value}`;
660
+ if (m.hasPrimalSolution) {
661
+ document.getElementById("output").textContent =
662
+ `Status: ${m.status}\n` +
663
+ `Objective: ${m.objectiveValue}\n` +
664
+ `x = ${x.value}, y = ${y.value}`;
665
+ }
564
666
  })();
565
667
  </script>
566
668
  </body>
@@ -568,7 +670,8 @@ For static HTML pages, CodePen, or JSFiddle, load `washi.min.js` via a standard
568
670
  ```
569
671
 
570
672
  > [!NOTE]
571
- > When loading `washi.min.js` from a cross-origin CDN (such as jsDelivr or unpkg), browsers block direct `new Worker("https://cdn...")` construction due to the same-origin policy. WaSHI automatically bridges cross-origin workers via a lightweight `Blob` wrapper using `importScripts()`, so Web Worker execution works out of the box from CDNs.
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://`.
572
675
 
573
676
  ---
574
677
 
@@ -578,87 +681,86 @@ WaSHI never phones home or falls back to public CDNs. To self-host in an air-gap
578
681
 
579
682
  1. **Copy Static Assets**: Serve the files from `node_modules/@ohtaman/washi/dist/browser/` on your own origin:
580
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)
581
685
  - Optional GLPK: `solvers/glpk.js` / `solvers/glpk.min.js`
582
686
  - Optional Z3: `solvers/z3.js` / `solvers/z3.min.js`, `solvers/z3-built.js`, `solvers/z3-built.wasm`
583
687
  2. **Content Security Policy (CSP) Headers**:
584
688
  - Allow WebAssembly compilation (`'wasm-unsafe-eval'` in `script-src`).
585
- - If using the default Web Worker or cross-origin Blob worker fallback, allow `worker-src 'self' blob:;`.
586
- - 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 })`.
689
+ - If using the default Web Worker or cross-origin Blob worker bootstrap, allow `worker-src 'self' blob:;`.
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 })`.
587
691
  3. **Cross-Origin Isolation (Z3 Only)**:
588
- - HiGHS and GLPK run in standard browser contexts without special headers.
589
- - Z3 WASM uses pthreads + `SharedArrayBuffer` and requires `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (or `credentialless`). See the [Cross-Origin Isolation Guide](docs/getting-started/cross-origin.md) for setup details.
590
-
591
- ---
592
-
593
- ## ⚡ Bun & Deno
594
-
595
- ### Bun
596
-
597
- ```bash
598
- bun add @ohtaman/washi
599
- bun run app.ts
600
- ```
601
-
602
- ### Deno
603
-
604
- In Deno (v1.30+ with `npm:` specifiers):
605
-
606
- ```typescript
607
- import { Model, maximize } from "npm:@ohtaman/washi";
608
-
609
- const m = new Model();
610
- const x = m.continuous("x", { lb: 0, ub: 10 });
611
- m.objective(maximize(x));
612
- await m.solve();
613
- console.log("x =", x.value);
614
- ```
692
+ - HiGHS, Pumpkin, and GLPK run in standard browser contexts without special headers.
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.
615
694
 
616
695
  ---
617
696
 
618
697
  # Cross-Origin Isolation (Z3 & Browsers)
619
698
 
620
- When running the **Z3** solver engine inside a web browser, special HTTP headers are required due to browser security models.
699
+ When running the **Z3** solver inside a web browser, Cross-Origin Isolation HTTP headers are required so the browser enables `SharedArrayBuffer`.
700
+
701
+ > [!TIP]
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.
621
703
 
622
704
  ---
623
705
 
624
706
  ## Why is Cross-Origin Isolation Required?
625
707
 
626
- The Z3 WebAssembly engine utilizes multithreading backed by `SharedArrayBuffer` and Web Workers.
627
-
628
- In modern browsers (Chrome, Firefox, Safari, Edge), `SharedArrayBuffer` is disabled by default to mitigate Spectre-style timing side-channel attacks. To re-enable it, the hosting page must be **Cross-Origin Isolated**.
708
+ Z3's WebAssembly build uses multithreading (pthreads) backed by `SharedArrayBuffer` and Web Workers. Modern browsers (Chrome, Firefox, Safari, Edge) disable `SharedArrayBuffer` by default to mitigate Spectre-style side-channel attacks unless the top-level document opts into **Cross-Origin Isolation** (`window.crossOriginIsolated === true`).
629
709
 
630
710
  ---
631
711
 
632
712
  ## Required HTTP Response Headers
633
713
 
634
- To establish cross-origin isolation, your web server must serve the top-level HTML document with the following HTTP headers:
714
+ Serve the top-level HTML document with:
635
715
 
636
716
  ```http
637
717
  Cross-Origin-Opener-Policy: same-origin
638
718
  Cross-Origin-Embedder-Policy: require-corp
639
719
  ```
640
720
 
641
- In addition, any cross-origin assets (e.g. scripts or WASM files loaded from external domains) must send:
721
+ If your page loads cross-origin subresources (such as scripts, images, or WASM files from another domain), those responses must also include `Cross-Origin-Resource-Policy: cross-origin` (or CORS headers).
642
722
 
643
- ```http
644
- Cross-Origin-Resource-Policy: cross-origin
645
- ```
723
+ > [!NOTE]
724
+ > Chromium and Firefox also support `Cross-Origin-Embedder-Policy: credentialless`, which relaxes subresource CORP requirements, **but Safari (WebKit) does not support `credentialless`**. Use `require-corp` if you support Safari / iOS.
646
725
 
647
726
  ---
648
727
 
649
- ## Solutions by Hosting Environment
728
+ ## Setup by Environment
650
729
 
651
- ### 1. Custom Node.js / Express Server
730
+ ### 1. Vite (`vite.config.ts`)
652
731
 
653
- ```javascript
654
- app.use((req, res, next) => {
655
- res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
656
- res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
657
- next();
732
+ Configure both the local dev server (`vite`) and production preview server (`vite preview`):
733
+
734
+ ```typescript
735
+ import { defineConfig } from "vite";
736
+
737
+ export default defineConfig({
738
+ server: {
739
+ headers: {
740
+ "Cross-Origin-Opener-Policy": "same-origin",
741
+ "Cross-Origin-Embedder-Policy": "require-corp",
742
+ },
743
+ },
744
+ preview: {
745
+ headers: {
746
+ "Cross-Origin-Opener-Policy": "same-origin",
747
+ "Cross-Origin-Embedder-Policy": "require-corp",
748
+ },
749
+ },
658
750
  });
659
751
  ```
660
752
 
661
- ### 2. Next.js (`next.config.js`)
753
+ ### 2. Cloudflare Pages / Netlify (`public/_headers`)
754
+
755
+ Place a `_headers` file in `public/` so it is copied to the root of your build output:
756
+
757
+ ```text
758
+ /*
759
+ Cross-Origin-Opener-Policy: same-origin
760
+ Cross-Origin-Embedder-Policy: require-corp
761
+ ```
762
+
763
+ ### 3. Next.js (`next.config.js`)
662
764
 
663
765
  ```javascript
664
766
  /** @type {import('next').NextConfig} */
@@ -679,35 +781,40 @@ const nextConfig = {
679
781
  module.exports = nextConfig;
680
782
  ```
681
783
 
682
- ### 3. Static Hosting without Header Control (e.g., GitHub Pages)
784
+ ### 4. Custom Node.js / Express Server
785
+
786
+ ```javascript
787
+ app.use((req, res, next) => {
788
+ res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
789
+ res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
790
+ next();
791
+ });
792
+ ```
683
793
 
684
- Platforms like GitHub Pages or preview environments do not allow customizing response headers directly.
794
+ ### 5. Static Hosting without Header Control (e.g., GitHub Pages)
685
795
 
686
- For these environments, you can use **`coi-serviceworker`** (a lightweight Service Worker that injects isolation headers on the client side):
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:
687
797
 
688
- 1. Place `coi-serviceworker.js` in your website root.
689
- 2. In your HTML `<head>`, include:
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.
799
+ 2. Load it in your HTML `<head>`:
690
800
 
691
801
  ```html
692
802
  <script src="/coi-serviceworker.js"></script>
693
803
  ```
694
804
 
695
- When a user visits for the first time, the service worker registers and reloads the page once to establish `window.crossOriginIsolated === true`.
805
+ On the first visit, the Service Worker registers and reloads the page once to establish `window.crossOriginIsolated === true`.
696
806
 
697
807
  ---
698
808
 
699
- ## Graceful Degradation in WaSHI
809
+ ## Runtime Check in WaSHI
700
810
 
701
- WaSHI's Z3 solver adapter automatically inspects the environment at runtime. If Z3 is invoked in a browser lacking cross-origin isolation, it immediately rejects with a clear, informative error message explaining that COOP/COEP headers or a service worker are required, rather than hanging silently.
702
-
703
- > [!TIP]
704
- > The default **HiGHS** solver engine does not require cross-origin isolation or `SharedArrayBuffer`. It works out of the box in standard browser contexts.
811
+ WaSHI's Z3 adapter checks `crossOriginIsolated` before initializing Z3 in the browser. If Cross-Origin Isolation is missing, `solve()` / `check()` immediately rejects with an actionable error explaining that COOP/COEP headers or a Service Worker are required, rather than hanging silently.
705
812
 
706
813
  ---
707
814
 
708
815
  # Variables & Domains
709
816
 
710
- Variables represent the mathematical decision variables in your optimization model.
817
+ Variables represent the mathematical decision variables in your optimization or logical model.
711
818
  WaSHI provides domain-specific factory methods on the `Model` instance: `m.continuous()`, `m.integer()`, `m.binary()`, and `m.bool()`.
712
819
 
713
820
  ---
@@ -715,7 +822,7 @@ WaSHI provides domain-specific factory methods on the `Model` instance: `m.conti
715
822
  ## Decision Variable Types
716
823
 
717
824
  ### 1. Continuous Variables (`m.continuous`)
718
- Can take any real number value within `[lb, ub]`. Ideal for physical measurements, flow rates, budgets, and weights:
825
+ Can take any real number value within `[lb, ub]`. Used for continuous quantities such as flow rates, weights, budgets, and portfolio allocations:
719
826
 
720
827
  ```typescript
721
828
  import { Model } from "@ohtaman/washi";
@@ -727,7 +834,7 @@ const fuel = m.continuous("fuel", { lb: 0, ub: 1000 });
727
834
  ```
728
835
 
729
836
  ### 2. Integer Variables (`m.integer`)
730
- Restricted to integers. Ideal for countable assets (machines, trucks, staff count):
837
+ Restricted to integer values within `[lb, ub]`. Used for discrete counts such as machines, vehicles, or headcount:
731
838
 
732
839
  ```typescript
733
840
  // Single integer variable bounded in [0, 15]
@@ -735,48 +842,43 @@ const trucks = m.integer("trucks", { lb: 0, ub: 15 });
735
842
  ```
736
843
 
737
844
  ### 3. Binary Variables (`m.binary`)
738
- Restricted to $\{0, 1\}$ as mathematical 0-1 values. Ideal for MIP selection, yes/no decisions, and facility selections:
845
+ Restricted to $\{0, 1\}$ as numeric values (`lb = 0`, `ub = 1`). Used for 0-1 MIP selection and yes/no decisions that appear in linear sums or objective costs:
739
846
 
740
847
  ```typescript
741
- // Single binary variable
848
+ // Single binary variable (lb = 0, ub = 1 automatically)
742
849
  const openWarehouse = m.binary("open_warehouse");
743
- // lb is automatically 0, ub is automatically 1
744
850
  ```
745
851
 
746
852
  ### 4. Propositional Boolean Variables (`m.bool`)
747
- Pure boolean logic propositions for SMT / SAT modeling with Z3:
853
+ Pure boolean propositions (`true` / `false`) for logical and SMT constraints:
748
854
 
749
855
  ```typescript
750
- // Single propositional boolean variable
751
- const isNight = m.bool("isNight");
752
- const alarmTriggered = m.bool("alarmTriggered");
856
+ // Single propositional boolean variables
857
+ const isAdmin = m.bool("isAdmin");
858
+ const hasMfa = m.bool("hasMfa");
753
859
 
754
860
  // First-class boolean operators: and, or, not, implies, xor
755
- m.constraint(alarmTriggered.implies(isNight), "alarm_policy");
861
+ m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
756
862
  ```
757
863
 
758
- ### 💡 Modeling Semi-Continuous Decisions
759
- Semi-continuous variables take values in $\{0\} \cup [L, U]$ (either zero or between a positive lower and upper bound, useful for minimum production batches or operational thresholds).
760
-
761
- While not a primitive `VarType` in `Model`, semi-continuous behavior is cleanly modeled by combining a continuous variable with a binary indicator variable and linking constraints ($L \cdot b \le x \le U \cdot b$):
864
+ ### Choosing Between `m.binary()` and `m.bool()`
762
865
 
763
- ```typescript
764
- import { Model, expr } from "@ohtaman/washi";
765
-
766
- const m = new Model();
767
- const batch = m.continuous("batch", { lb: 0, ub: 100 });
768
- const isActive = m.binary("is_active");
866
+ | Feature | `m.binary()` (`Var`) | `m.bool()` (`BoolVar`) |
867
+ | :--- | :--- | :--- |
868
+ | **Solved `.value` type** | `number \| null` (`0` or `1`) | `boolean \| null` (`true` or `false`) |
869
+ | **Linear arithmetic (`expr`, `sum`, `dot`, objective costs)** | ✅ Native (`` expr`30 * ${b}` ``) | ❌ Cannot be multiplied by numbers or summed directly |
870
+ | **Indicator constraints (`m.indicator(b, ...)` )** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
871
+ | **Propositional logic (`and`, `or`, `not`, `implies`, `xor`)** | Via comparison (`` expr`${b} == 1` ``) | ✅ Native first-class methods (`.implies()`, `.and()`) |
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 |
769
873
 
770
- // If isActive === 0, batch is forced to 0; if 1, batch is within [10, 100]
771
- m.constraint(expr`${batch} >= 10 * ${isActive}`, "min_batch_run");
772
- m.constraint(expr`${batch} <= 100 * ${isActive}`, "max_batch_run");
773
- ```
874
+ > [!TIP]
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.
774
876
 
775
877
  ---
776
878
 
777
879
  ## Multi-Dimensional & Array Creation
778
880
 
779
- The domain factory methods (`continuous`, `integer`, `binary`, `bool`) support count, arrays of keys, and row/column keys to create 1D arrays, typed dictionaries, and 2D matrices in a single call.
881
+ The domain factory methods (`continuous`, `integer`, `binary`, `bool`) accept a numeric count or an array of string keys to create 1D arrays, typed dictionaries, and 2D matrices in a single call.
780
882
 
781
883
  ### By Count
782
884
  Pass a number to create an array of variables:
@@ -787,15 +889,15 @@ const flags = m.bool(3); // BoolVar[] (p_0, p_1, p_2)
787
889
  ```
788
890
 
789
891
  ### 1D Variable Dictionaries
790
- Pass an array of keys to get a typed dictionary `Record<string, Var>` or `Record<string, BoolVar>`:
892
+ Pass an array of keys to get a typed dictionary `Record<K, Var>` or `Record<K, BoolVar>`:
791
893
 
792
894
  ```typescript
793
- const items = ["laptop", "phone", "tablet"];
895
+ const items = ["laptop", "phone", "tablet"] as const;
794
896
 
795
897
  // Record<"laptop" | "phone" | "tablet", Var>
796
898
  const selected = m.binary(items);
797
899
 
798
- const perms = m.bool(["read", "write", "execute"]);
900
+ const perms = m.bool(["read", "write", "execute"] as const);
799
901
  // perms.read, perms.write, perms.execute
800
902
  ```
801
903
 
@@ -829,16 +931,22 @@ const schedule = m.binary(factories, 7, { prefix: "open_day" });
829
931
 
830
932
  | Option | Type | Default | Description |
831
933
  | :--- | :--- | :--- | :--- |
832
- | `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. |
833
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`). |
834
937
  | `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Underlying variable domain category. |
835
- | `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP start), kept distinct from solved `variable.value`. |
938
+ | `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP warm start), kept distinct from solved `variable.value`. |
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**.
836
944
 
837
945
  ---
838
946
 
839
947
  ## Primal Initial Values (Warm-Start Hints)
840
948
 
841
- When rebuilding a model across iterations with stable variable names, you can supply optional primal initial values (`initialValue`) on a subset or all numeric variables (`m.continuous`, `m.integer`, `m.binary`, or `v.initialValue = ...`):
949
+ When rebuilding a model across iterations, you can supply optional primal initial values (`initialValue`) on a subset or all numeric variables (`m.continuous`, `m.integer`, `m.binary`, or `v.initialValue = ...`):
842
950
 
843
951
  ```typescript
844
952
  const prevValues: Record<string, number | null> = { trucks: 8, open_warehouse: 1 };
@@ -855,43 +963,50 @@ const openWarehouse2 = m2.binary("open_warehouse", {
855
963
  const extraCapacity = m2.continuous("extra_capacity", { lb: 0 }); // Partial start: no initialValue needed
856
964
  ```
857
965
 
858
- - **Hint vs. Hard Constraint**: `initialValue` is strictly an optional solver hint (passed to HiGHS via `setSolution`). It does **not** fix the variable, add a constraint, or guarantee either solver acceptance or a runtime speedup. It remains separate from `variable.value` (which is `null` until solved and populated with the solver's primal solution).
859
- - **Validation & Tolerance (`1e-6`)**: Supplied values must be finite numbers within `[lb - 1e-6, ub + 1e-6]` (and within `1e-6` of an integer inside bounds for `"Integer"` and `"Binary"` variables). Partial starts are not required to satisfy every model constraint.
860
- - **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`.
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).)*
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.
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`.
861
969
 
862
970
  ---
863
971
 
864
972
  ## Accessing Solution Values & Reduced Costs
865
973
 
866
- After calling `await m.solve()` or `await m.check()`, assigned variable values (optimal or incumbent primal values from `solve()`, or a satisfying assignment from `check()`) are accessible via `variable.value` (returns `number | null` for `Var`, or `boolean | null` for `BoolVar`) or the bulk accessor `m.getValues()`:
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`:
867
975
 
868
976
  ```typescript
869
977
  await m.solve();
870
978
 
871
- // Single variable primal value
979
+ // Scalar variable primal & boolean values
872
980
  console.log(`trucks: ${trucks.value}`);
981
+ console.log(`isAdmin: ${isAdmin.value}`);
873
982
 
874
- // Reduced cost (LP sensitivity analysis — how much an objective coefficient must improve before a variable at its bound enters the basis)
875
- console.log(`fuel reduced cost: ${fuel.reducedCost}`);
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}`);
876
986
 
877
- // Bulk extraction for 1D or 2D collections (works for both Var and BoolVar collections)
878
- const selectedValues = m.getValues(selected);
879
- // { 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")}`);
880
989
 
881
- const flowValues = m.getValues(ship);
882
- // { Tokyo: { StoreA: 50, ... }, Osaka: { ... } }
990
+ // Reduced cost (LP sensitivity analysis)
991
+ console.log(`fuel reduced cost: ${fuel.reducedCost}`);
883
992
  ```
884
993
 
885
994
  ---
886
995
 
887
996
  ## Looking Up Variables by Name
888
997
 
889
- You can retrieve registered decision variables by name or inspect the total variable count on the model:
998
+ All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are exposed through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
890
999
 
891
1000
  ```typescript
892
- const v = m.getVarByName("trucks"); // Var | undefined
893
- const b = m.getBoolVarByName("isNight"); // BoolVar | undefined
894
- console.log("Total numeric variables:", m.numVars);
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
+ }
895
1010
  ```
896
1011
 
897
1012
  ---
@@ -900,7 +1015,7 @@ console.log("Total numeric variables:", m.numVars);
900
1015
 
901
1016
  Mathematical expressions are linear or quadratic combinations of decision variables and numeric coefficients.
902
1017
 
903
- In JavaScript and TypeScript—which do not support operator overloading—WaSHI provides the **unified tagged template literal (`expr`)**, **`sum()`**, and matrix/vector **`dot()`** to construct algebraic expressions without losing static type safety.
1018
+ In JavaScript and TypeScript—which do not support operator overloading—WaSHI provides the **unified tagged template literal (`expr`)**, **`sum()`**, and matrix/vector **`dot()`** to construct algebraic expressions with full static type safety.
904
1019
 
905
1020
  | Approach | Example | Infix readability | Type safety & IDE rename | Indexed variables (`flow[i][j]`) |
906
1021
  | :--- | :--- | :--- | :--- | :--- |
@@ -910,9 +1025,9 @@ In JavaScript and TypeScript—which do not support operator overloading—WaSHI
910
1025
 
911
1026
  ---
912
1027
 
913
- ## ✍️ Tagged Template Literal (`expr`)
1028
+ ## Tagged Template Literal (`expr`)
914
1029
 
915
- Similar to parameterized `sql` tagged templates, `expr` receives the static operator text (`+`, `-`, `*`, `^2`, `<=`, `>=`, `==`) separately from the interpolated `${...}` values (`Var`, `LinExpr`, `QuadExpr`, or finite `number`). Variables are bound by object reference rather than resolved by string name, avoiding naming collisions and preserving TypeScript type checking and IDE refactoring.
1030
+ Similar to parameterized `sql` tagged templates, `expr` receives static operator text (`+`, `-`, `*`, `^2`, `<=`, `>=`, `==`) separately from interpolated `${...}` values (`Var`, `LinExpr`, `QuadExpr`, or finite `number`). Variables are bound by object reference rather than resolved by string name, avoiding naming collisions and preserving TypeScript type checking and IDE refactoring.
916
1031
 
917
1032
  Use `expr` for both arithmetic expressions (`LinExpr | QuadExpr`) and relational constraints (`Constraint`):
918
1033
 
@@ -935,44 +1050,56 @@ const balanceConstraint = expr`${x} + 2 * ${y} <= 40`;
935
1050
 
936
1051
  ### Supported Syntax in `expr`
937
1052
  - **Addition & Subtraction**: `${x} + ${y} - 5`
938
- - **Scalar Multiplication**: `4 * ${x}`, `${x} * 4`
1053
+ - **Scalar Multiplication & Division**: `4 * ${x}`, `${x} / 2`
939
1054
  - **Variable Multiplication (Quadratic terms)**: `${x} * ${y}`, `2 * ${x} * ${x}`
940
1055
  - **Powers & Exponentiation**: `${x}^2`, `${x}**2`
941
- - **Unary Negation**: `-${x} + 10`
1056
+ - **Unary Plus & Negation**: `-${x} + 10`, `+${x}`
942
1057
  - **Parentheses**: `2 * (${x} + ${y})`
943
- - **Nested Expressions**: `expr` seamlessly interpolates variables, numbers, `sum()` results, and nested expressions.
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))
1060
+ - **Element-Wise Container Arithmetic**: `sum((${price} - ${cost}) * ${qty})`, `sum((${xVec} - ${target})^2)`, `dot(${price} - ${cost}, ${qty})`
1061
+ - **Nested Expressions**: `expr` interpolates variables, numbers, `Array` / `Record` containers (inside `sum` or `dot`), and nested `LinExpr` / `QuadExpr` objects.
944
1062
 
945
1063
  > [!NOTE]
946
1064
  > For relational comparisons (`<=`, `>=`, `==`), `expr` (e.g., ``expr`${x} + 2 * ${y} <= 40` ``) returns a first-class `Constraint`.
947
- > For arithmetic expressions without comparison operators, `expr` uniformly handles linear and quadratic expressions (up to degree 2): if quadratic terms are present, `expr` returns a `QuadExpr`; otherwise, it returns a `LinExpr`. Polynomial terms of degree $> 2$ (e.g. ``${x} * ${y} * ${z}``, ``${x}^3``) and non-linear constraints (e.g. ``${x} * ${y} <= 10``) are rejected because standard MILP/LP/QP formulations only support linear constraints and quadratic objectives.
1065
+ > For arithmetic expressions without comparison operators, `expr` uniformly handles linear and quadratic expressions (up to degree 2): if quadratic terms are present, `expr` returns a `QuadExpr`; otherwise, it returns a `LinExpr`. Interpolated `Array` or `Record` containers must be reduced to a scalar via `sum(...)` or `dot(..., ...)`. Polynomial terms of degree $> 2$ (e.g., ``${x} * ${y} * ${z}``, ``${x}^3``) and non-linear constraints (e.g., ``${x} * ${y} <= 10``) throw an error because LP/MIP/QP formulations require linear constraints and at most quadratic objectives.
948
1066
 
949
1067
  ---
950
1068
 
951
- ## ⚡ High-Performance Summation (`sum`)
1069
+ ## High-Performance Summation (`sum`)
952
1070
 
953
- For iterating over large collections of variables or indices:
1071
+ Sum 1D or 2D `Array`, `Iterable`, or `Record` containers directly inside `` expr`sum(...)` `` or via the standalone `sum()` helper:
954
1072
 
955
1073
  ```typescript
956
- import { sum } from "@ohtaman/washi";
1074
+ import { expr, sum } from "@ohtaman/washi";
957
1075
 
958
- const items = ["A", "B", "C"];
1076
+ const items = ["A", "B", "C"] as const;
959
1077
  const weights = { A: 10, B: 20, C: 30 };
960
1078
  const x = m.binary(items);
961
1079
 
962
- // 1. Transform elements with a mapping callback:
1080
+ // 1. Direct Record or Array summation inside expr (no Object.values() needed):
1081
+ m.constraint(expr`sum(${x}) <= 2`, "max_selected");
1082
+
1083
+ // 2. Element-wise arithmetic inside expr`sum(...)`:
1084
+ const weightedExpr = expr`sum(${weights} * ${x})`;
1085
+
1086
+ // 3. Transform elements with a mapping callback (standalone or inside expr):
963
1087
  const totalWeight = sum(items, (item) => x[item].mul(weights[item]));
964
1088
 
965
- // 2. Direct array summation:
966
- const count = sum(Object.values(x));
1089
+ // 4. Standalone 1D/2D Record or Array summation:
1090
+ const count = sum(x);
967
1091
  ```
968
1092
 
969
- `sum()` runs in $O(N)$ linear time without AST overhead.
1093
+ `sum()` runs in $O(N)$ linear time without AST parsing overhead.
1094
+
1095
+ > [!TIP]
1096
+ > **Avoid $O(N^2)$ `expr` Re-Assignment Inside Loops**: Because `LinExpr` and `expr` results are immutable, accumulating terms one by one via ``total = expr`${total} + ${x[i]}` `` inside a loop copies all previously accumulated terms on every iteration ($O(N^2)$ time and memory). Pass arrays or records to `sum(x)` or `dot(coeffs, x)` for $O(N)$ construction.
970
1097
 
971
1098
  ---
972
1099
 
973
- ## 🎯 Dot Product (`dot`)
1100
+ ## Dot Product (`dot`)
974
1101
 
975
- The `dot(a, b)` helper computes linear combinations of numeric coefficients (`number`) and variables or linear expressions (`Var | LinExpr`) in either operand order (`dot(coeffs, vars)` or `dot(vars, coeffs)`).
1102
+ The `dot(a, b)` helper (usable both inside `` expr`dot(${a}, ${b})` `` and as a standalone function `dot(a, b)`) computes linear combinations of numeric coefficients (`number`) and variables or linear expressions (`Var | LinExpr`) in either operand order (`dot(coeffs, vars)` or `dot(vars, coeffs)`).
976
1103
 
977
1104
  Supported 1D and 2D container shapes:
978
1105
  - **1D Arrays**: `number[]` $\times$ `(Var | LinExpr)[]`
@@ -985,41 +1112,70 @@ Mismatched array lengths, missing dictionary keys, or non-finite/non-linear leav
985
1112
 
986
1113
  ### 1D Vector Dot Product
987
1114
  ```typescript
988
- import { dot } from "@ohtaman/washi";
1115
+ import { expr, dot } from "@ohtaman/washi";
989
1116
 
990
1117
  const profits = { desk: 30, chair: 50 };
991
- const vars = m.integer(["desk", "chair"]);
1118
+ const vars = m.integer(["desk", "chair"] as const);
992
1119
 
993
- // Computes 30 * vars.desk + 50 * vars.chair
994
- const totalProfit = dot(profits, vars);
1120
+ // Computes 30 * vars.desk + 50 * vars.chair inside expr (or via standalone dot(profits, vars))
1121
+ const totalProfit = expr`dot(${profits}, ${vars})`;
995
1122
  ```
996
1123
 
997
- ### 2D Matrix Dot Product
1124
+ ### 2D Matrix Inner Product (Frobenius Inner Product)
998
1125
  Works directly with 2D arrays (`m.continuous(rows, cols)`), nested dictionaries (`m.continuous(rowKeys, colKeys)`), or mixed 2D containers:
999
1126
 
1000
1127
  ```typescript
1001
- const factories = ["Tokyo", "Osaka"];
1002
- const stores = ["StoreA", "StoreB"];
1128
+ const factories = ["Tokyo", "Osaka"] as const;
1129
+ const stores = ["StoreA", "StoreB"] as const;
1003
1130
 
1004
1131
  const costs = {
1005
1132
  Tokyo: { StoreA: 4, StoreB: 7 },
1006
1133
  Osaka: { StoreA: 8, StoreB: 3 },
1007
1134
  };
1008
1135
 
1009
- const ship = m.continuous(factories, stores);
1136
+ const ship = m.continuous(factories, stores, { lb: 0 });
1137
+
1138
+ // Total shipping cost across all routes (equivalent to expr`sum(${costs} * ${ship})`):
1139
+ const totalShippingCost = expr`dot(${costs}, ${ship})`;
1140
+ ```
1141
+
1142
+ > [!NOTE]
1143
+ > **2D `dot(A, B)` is the Frobenius Inner Product**: For 2D matrices or nested records, `dot(A, B)` computes the scalar **Frobenius inner product** $\langle A, B \rangle_F = \sum_{i,j} A_{i,j} B_{i,j}$ (the sum of element-wise products across all rows and columns, equivalent to `` expr`sum(${A} * ${B})` ``), **not** the matrix-matrix product $(AB)_{i,k} = \sum_j A_{i,j} B_{j,k}$.
1144
+
1145
+ ---
1146
+
1147
+ ## Composing Aggregations in `expr`
1148
+
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()`:
1150
+
1151
+ ```typescript
1152
+ // Verbose: nested standalone calls and Object.values()
1153
+ const totalProfit1 = expr`${dot(profits, vars)}`;
1154
+ const cap1 = expr`${sum(Object.values(vars))} <= 100`;
1010
1155
 
1011
- // Total shipping cost in one line:
1012
- m.objective(minimize(dot(costs, ship)));
1156
+ // Recommended: direct sum() and dot() inside expr
1157
+ const totalProfit2 = expr`dot(${profits}, ${vars})`;
1158
+ const cap2 = expr`sum(${vars}) <= 100`;
1013
1159
  ```
1014
1160
 
1161
+ | Operation | Mathematical Formula | WaSHI Expression |
1162
+ | :--- | :--- | :--- |
1163
+ | **Total sum** (1D/2D `Array` or `Record`) | $\sum_i x_i \le C$ | `` m.constraint(expr`sum(${x}) <= ${C}`) `` |
1164
+ | **Inner product** (1D vector or 2D Frobenius) | $\sum_i c_i x_i \le B$ | `` m.constraint(expr`dot(${c}, ${x}) <= ${B}`) `` |
1165
+ | **Element-wise difference & product** | $\sum_i (p_i - c_i) \cdot x_i$ | `` expr`sum((${price} - ${cost}) * ${x})` `` |
1166
+ | **Sum of squared deviations (QP)** | $\sum_i (x_i - t_i)^2$ | `` expr`sum((${x} - ${target})^2)` `` |
1167
+ | **Element-wise constraints** ($\forall i \in I$) | $a_i x_i \le b_i \quad (\forall i)$ | `` m.constraint(items.map((i) => expr`${a[i]} * ${x[i]} <= ${b[i]}`)) `` |
1168
+ | **2D row sums** (for each row $f$) | $\sum_s X_{f,s} \le S_f \quad (\forall f)$ | `` m.constraint(factories.map((f) => expr`sum(${ship[f]}) <= ${supply[f]}`)) `` |
1169
+ | **2D column sums** (for each column $s$) | $\sum_f X_{f,s} \ge D_s \quad (\forall s)$ | `` m.constraint(stores.map((s) => expr`sum(${factories}, ${(f) => ship[f][s]}) >= ${demand[s]}`)) `` |
1170
+
1015
1171
  ---
1016
1172
 
1017
- ## 🧮 Quadratic Expressions (`QuadExpr` & `expr`)
1173
+ ## Quadratic Expressions (`QuadExpr` & `expr`)
1018
1174
 
1019
- WaSHI natively supports Convex Quadratic Programming (QP) with the HiGHS solver. Quadratic objectives can be written uniformly using the `expr` template literal, or algebraically using `QuadExpr` and `.mul()`:
1175
+ WaSHI supports Convex Quadratic Programming (QP) objectives via the HiGHS solver. Quadratic expressions can be written using the `expr` template literal or constructed programmatically with `QuadExpr` and `.mul()`.
1020
1176
 
1021
1177
  ### 1. Using `expr` (Recommended)
1022
- You can write quadratic formulas naturally with `*`, `^2`, or `**2`:
1178
+ Write quadratic terms with `*`, `^2`, or `**2`:
1023
1179
 
1024
1180
  ```typescript
1025
1181
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -1036,7 +1192,7 @@ m.constraint(expr`${x} + ${y} >= 4`);
1036
1192
  ```
1037
1193
 
1038
1194
  ### 2. Method Chaining with `.mul()` or `QuadExpr`
1039
- Alternatively, you can construct quadratic expressions programmatically:
1195
+ You can also construct quadratic expressions programmatically:
1040
1196
 
1041
1197
  ```typescript
1042
1198
  import { Model, QuadExpr, minimize } from "@ohtaman/washi";
@@ -1045,12 +1201,11 @@ const m = new Model();
1045
1201
  const x = m.continuous("x", { lb: 0 });
1046
1202
  const y = m.continuous("y", { lb: 0 });
1047
1203
 
1048
- // 1. Construct quadratic terms with .mul()
1049
- // Represents x * y + 2 * x^2
1204
+ // 1. Construct quadratic terms with .mul() (x * y + 2 * x^2)
1050
1205
  const quad = x.mul(y).add(x.mul(x).mul(2));
1051
1206
 
1052
- // 2. Build portfolio risk objective: w^T * Sigma * w
1053
- const assets = ["Tech", "Bonds"];
1207
+ // 2. Build portfolio variance objective: w^T * Sigma * w
1208
+ const assets = ["Tech", "Bonds"] as const;
1054
1209
  const w = m.continuous(assets, { lb: 0, ub: 1 });
1055
1210
 
1056
1211
  let risk = new QuadExpr();
@@ -1061,13 +1216,54 @@ risk = risk.add(w.Bonds.mul(w.Bonds).mul(0.01));
1061
1216
  m.objective(minimize(risk));
1062
1217
  ```
1063
1218
 
1219
+ > [!NOTE]
1220
+ > **Convexity Requirement ($\mathbf{Q} \succeq 0$)**: QP solvers (including HiGHS) require the quadratic objective matrix $\mathbf{Q}$ to be **positive semi-definite (PSD)** when minimizing (or negative semi-definite when maximizing). Sum-of-squares terms ($\sum_i (x_i - t_i)^2$) and covariance matrices ($\mathbf{w}^\top \boldsymbol{\Sigma} \mathbf{w}$) are guaranteed PSD, whereas indefinite products over continuous variables (such as minimizing $x \cdot y$) are non-convex and rejected by the solver. *(To linearize the product of two binary variables $x_A \cdot x_B$ in MILP, see [Formulation Patterns & Tips](docs/guide/formulation-tips.md#product-of-two-binary-variables).)*
1221
+
1222
+ ---
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
+
1064
1254
  ---
1065
1255
 
1066
- ## 📊 Evaluating Expressions After Solving (`.value`)
1256
+ ## Evaluating Expressions After Solving (`.value`)
1067
1257
 
1068
- 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—such as total department cost, portfolio return, or resource utilization—directly without manual arithmetic:
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:
1069
1259
 
1070
1260
  ```typescript
1261
+ import { Model, expr, maximize } from "@ohtaman/washi";
1262
+
1263
+ const m = new Model();
1264
+ const x = m.integer("x", { lb: 0 });
1265
+ const y = m.integer("y", { lb: 0 });
1266
+
1071
1267
  const revenue = expr`30 * ${x} + 50 * ${y}`;
1072
1268
  const laborUsed = expr`2 * ${x} + ${y}`;
1073
1269
 
@@ -1085,7 +1281,7 @@ If the model has not been solved (or any variable in the expression has `value =
1085
1281
 
1086
1282
  ---
1087
1283
 
1088
- ## 🔗 Fluent Arithmetic & Relational Methods
1284
+ ## Fluent Arithmetic & Relational Methods
1089
1285
 
1090
1286
  In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent methods for programmatic expression building:
1091
1287
 
@@ -1096,26 +1292,29 @@ In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent
1096
1292
  | `.mul(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Multiplies by a scalar `number`, or multiplies two linear terms into a `QuadExpr`. |
1097
1293
  | `.div(divisor)` | `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Divides by a non-zero finite scalar `number`. |
1098
1294
  | `.neg()` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Negates all terms ($-e$). |
1099
- | `.le(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`). |
1100
- | `.ge(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`). |
1101
- | `.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). |
1102
1301
 
1103
1302
  ---
1104
1303
 
1105
1304
  # Constraints (`m.constraint` & `m.indicator`)
1106
1305
 
1107
1306
  Constraints restrict the feasible solution space of your mathematical or logical model.
1108
- In WaSHI, both linear arithmetic constraints and propositional SMT formulas are registered using **`m.constraint()`**:
1307
+ In WaSHI, both linear arithmetic constraints and propositional logic formulas are registered using **`m.constraint()`**:
1109
1308
 
1110
1309
  ```typescript
1111
- m.constraint(expr`${desks} + 2 * ${chairs} <= 40`, "wood_limit");
1310
+ m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood_limit");
1112
1311
  ```
1113
1312
 
1114
1313
  ---
1115
1314
 
1116
- ## ✍️ Algebraic Linear Constraints (`expr`)
1315
+ ## Algebraic Linear Constraints (`expr`)
1117
1316
 
1118
- The `expr` tagged template literal syntax allows writing equations and inequalities with natural mathematical notation:
1317
+ The `expr` tagged template literal allows writing equations and inequalities with standard mathematical notation:
1119
1318
 
1120
1319
  ```typescript
1121
1320
  import { Model, expr } from "@ohtaman/washi";
@@ -1134,13 +1333,16 @@ m.constraint(expr`3 * ${x} + ${y} >= 20`, "min_demand");
1134
1333
  m.constraint(expr`${x} + ${y} == 30`, "exact_quota");
1135
1334
  ```
1136
1335
 
1336
+ `m.constraint()` returns the registered `Constraint` (or `BoolExpr` for logical formulas), or an array when passed a batch array.
1337
+
1137
1338
  ### Supported Comparison Operators
1138
1339
  - `<=`: Upper bound constraint
1139
1340
  - `>=`: Lower bound constraint
1140
1341
  - `==` or `=`: Exact equality constraint
1342
+ - `<`, `>`, `!=`: Discrete strict inequality / disequality constraints (integer-valued expressions only; see [Discrete Comparisons](#discrete-comparisons))
1141
1343
 
1142
1344
  ### Batch Registration
1143
- You can pass an array of constraints to `m.constraint([...])` to register them transactionally in a single call:
1345
+ Pass an array of constraints to `m.constraint([...])` to register them transactionally in a single call:
1144
1346
 
1145
1347
  ```typescript
1146
1348
  m.constraint([expr`${x} <= 10`, expr`${y} <= 20`]);
@@ -1148,50 +1350,68 @@ m.constraint([expr`${x} <= 10`, expr`${y} <= 20`]);
1148
1350
 
1149
1351
  ---
1150
1352
 
1151
- ## 🏷️ Naming Constraints
1353
+ ## Naming Constraints
1152
1354
 
1153
- Every constraint can be given a unique, descriptive name as the second argument of `m.constraint(c, name)`:
1355
+ Pass a unique, descriptive name as the second argument of `m.constraint(c, name)`:
1154
1356
 
1155
1357
  ```typescript
1156
1358
  m.constraint(expr`${x} + ${y} <= 100`, "budget_cap");
1157
1359
  ```
1158
1360
 
1159
1361
  ### Why Name Constraints?
1160
- 1. **Model Inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain these descriptive names (sanitized if needed) so you can inspect the exact generated formulation.
1161
- 2. **Conflict Diagnosis (`conflicts` / `unsatCore`)**: When constraints contradict each other, Z3 `m.check()` returns the exact constraint names forming the conflicting subset.
1162
- 3. **Direct Lookup (`m.getConstraintByName()`)**: Retrieve a constraint by name after solving to inspect its `dual` or `slack` value.
1362
+ 1. **Model Inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain these descriptive names (sanitized if needed) so you can inspect the generated formulation.
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.
1163
1365
 
1164
1366
  ---
1165
1367
 
1166
- ## 🔁 Adding Constraints over Iterables & Sums
1368
+ ## Aggregated Constraints (`sum` & `dot`)
1167
1369
 
1168
- Use `sum()` or `dot()` inside `expr` to express linear aggregations cleanly:
1370
+ Use `sum(...)` and `dot(..., ...)` directly inside `expr` to express linear aggregations over arrays and dictionaries cleanly:
1169
1371
 
1170
1372
  ```typescript
1171
- import { Model, sum, expr } from "@ohtaman/washi";
1373
+ import { Model, expr } from "@ohtaman/washi";
1172
1374
 
1173
- const items = ["A", "B", "C"];
1375
+ const m = new Model();
1376
+ const items = ["A", "B", "C"] as const;
1174
1377
  const weights = { A: 5, B: 10, C: 15 };
1175
1378
  const selected = m.binary(items);
1176
1379
 
1380
+ // Select at most 2 items
1381
+ m.constraint(expr`sum(${selected}) <= 2`, "max_items");
1382
+
1177
1383
  // Total weight cannot exceed capacity 25
1178
- m.constraint(
1179
- expr`${sum(items, (i) => selected[i].mul(weights[i]))} <= 25`,
1180
- "capacity_limit"
1181
- );
1384
+ m.constraint(expr`dot(${weights}, ${selected}) <= 25`, "capacity_limit");
1385
+ ```
1386
+
1387
+ ---
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);
1182
1402
  ```
1183
1403
 
1184
1404
  ---
1185
1405
 
1186
- ## 🎯 Conditional / Indicator Constraints (`m.indicator`)
1406
+ ## Conditional / Indicator Constraints (`m.indicator`)
1187
1407
 
1188
- When a linear constraint should only take effect when a binary decision variable is active (`1` or `0`), use `m.indicator()`:
1408
+ When a linear constraint should only take effect when a binary decision variable (`m.binary()`) equals `1` (or `0`), use `m.indicator()`:
1189
1409
 
1190
1410
  ```typescript
1191
1411
  const useDiscount = m.binary("use_discount");
1192
1412
  const cartTotal = m.continuous("cart_total", { lb: 0, ub: 10_000 });
1193
1413
 
1194
- // If useDiscount == 1, then cartTotal >= 100
1414
+ // If useDiscount == 1, enforce cartTotal >= 100
1195
1415
  // WaSHI automatically derives a safe, tight Big-M from the variable bounds
1196
1416
  m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
1197
1417
  activeValue: 1,
@@ -1201,16 +1421,19 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
1201
1421
 
1202
1422
  ### Safe Automatic Big-M Derivation & Bounds
1203
1423
 
1204
- When `options.M` is omitted, WaSHI automatically derives a safe, minimal Big-M value from the finite variable bounds:
1424
+ When `options.M` is omitted, WaSHI automatically derives a minimal valid Big-M value from finite variable bounds (`lb` and `ub`):
1205
1425
  - For `<=` constraints, variables with positive coefficients require finite upper bounds (`ub`), and negative coefficients require finite lower bounds (`lb`).
1206
1426
  - For `>=` constraints, variables with positive coefficients require finite lower bounds (`lb`), and negative coefficients require finite upper bounds (`ub`).
1207
- - For `==` constraints, safe bounds are derived separately for both the `<=` and `>=` directions (generating `name_le` and `name_ge`).
1427
+ - For `==` constraints, bounds are derived separately for both the `<=` and `>=` directions (generating `name_le` and `name_ge`).
1428
+
1429
+ If any referenced variable lacks the required finite bound, `m.indicator()` throws an error prompting for finite bounds or an explicit `options.M`.
1208
1430
 
1209
- If any referenced variable lacks the required finite bounds, `m.indicator()` throws an actionable error prompting for finite bounds or an explicit `options.M`.
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.
1210
1433
 
1211
- ### Explicit Override & Numerical Stability
1434
+ ### Explicit `M` Override
1212
1435
 
1213
- You can override the derived Big-M by providing `{ M: number }`:
1436
+ You can override the derived Big-M by passing `{ M: number }`:
1214
1437
 
1215
1438
  ```typescript
1216
1439
  m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
@@ -1220,15 +1443,13 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
1220
1443
  ```
1221
1444
 
1222
1445
  > [!TIP]
1223
- > **Numerical Stability vs. Correctness**:
1224
- > An $M$ value that is too small can inadvertently cut off valid solutions. Conversely, an excessively large $M$ (e.g., $10^9$) causes poor matrix conditioning and numerical instability in MIP solvers.
1225
- > By setting explicit, realistic variable bounds (`lb` and `ub`), WaSHI derives the tightest possible safe Big-M automatically.
1446
+ > **Prefer Finite Variable Bounds Over Arbitrary Large `M`**: An $M$ value that is too small can cut off valid feasible solutions, whereas an excessively large $M$ (e.g., $10^9$) degrades numerical conditioning in MIP solvers. Setting realistic `lb` and `ub` bounds on variables lets WaSHI compute the tightest safe Big-M automatically.
1226
1447
 
1227
1448
  ---
1228
1449
 
1229
- ## 🧠 Propositional Logic & SMT Constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`)
1450
+ ## Propositional Logic & SMT Constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`)
1230
1451
 
1231
- When solving with the **Z3** SMT engine (`@ohtaman/washi/solvers/z3`), you can combine propositional boolean variables (`m.bool()`) and linear constraints (`Constraint`) using first-class logical operators:
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**:
1232
1453
 
1233
1454
  ```typescript
1234
1455
  import { Model, expr, and, or, not, implies, xor } from "@ohtaman/washi";
@@ -1237,14 +1458,14 @@ import "@ohtaman/washi/solvers/z3";
1237
1458
  const m = new Model({ solver: "z3" });
1238
1459
  const isAdmin = m.bool("isAdmin");
1239
1460
  const hasMfa = m.bool("hasMfa");
1240
- const Clearance = m.integer("clearance", { lb: 0, ub: 5 });
1461
+ const clearance = m.integer("clearance", { lb: 0, ub: 5 });
1241
1462
 
1242
1463
  // Method syntax on BoolVar / BoolOp:
1243
1464
  m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
1244
1465
 
1245
1466
  // Mixing boolean propositions with linear arithmetic comparisons:
1246
1467
  m.constraint(
1247
- implies(isAdmin, expr`${Clearance} >= 4`),
1468
+ implies(isAdmin, expr`${clearance} >= 4`),
1248
1469
  "admin_clearance_level"
1249
1470
  );
1250
1471
 
@@ -1252,33 +1473,67 @@ m.constraint(
1252
1473
  m.constraint(and(or(isAdmin, hasMfa), not(xor(isAdmin, hasMfa))), "policy");
1253
1474
  ```
1254
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
+
1255
1478
  ### Choosing Between `m.indicator()` and `implies()`
1256
1479
 
1257
1480
  | Feature | `m.indicator(binVar, constraint, opts)` | `implies(a, b)` / `a.implies(b)` |
1258
1481
  | :--- | :--- | :--- |
1259
1482
  | **Trigger variable** | Numeric `Binary` variable (`m.binary()`) | `BoolVar` (`m.bool()`), `BoolOp`, or `Constraint` |
1260
1483
  | **Consequent** | Linear `Constraint` (`<=`, `>=`, `==`) | `BoolVar`, `BoolOp`, or linear `Constraint` |
1261
- | **Target Solvers** | **All MIP/LP solvers** (HiGHS, GLPK, Z3) via Big-M linearization | **All solvers** (HiGHS and GLPK via automatic 0-1 MIP linearization, Z3 natively) |
1262
- | **Best For** | Operations research & MIP optimization with an objective (`m.solve()`) | Rule engines, policy verification, and SMT feasibility (`m.check()`) |
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) |
1485
+ | **Primary Use Case** | MIP optimization models with arithmetic binary variables (`m.solve()`) | Logical rule systems and SMT feasibility (`m.check()`) |
1486
+
1487
+ > [!NOTE]
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.
1263
1489
 
1264
1490
  ---
1265
1491
 
1266
- ## 📐 Dual Values, Shadow Prices & Lookups
1492
+ ## Discrete Comparisons (`!=`, `<`, `>`)
1267
1493
 
1268
- For continuous Linear Programming (LP) problems, query the economic shadow price (`dual`) and surplus (`slack`) on each constraint:
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):
1269
1495
 
1270
1496
  ```typescript
1271
- m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
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 });
1272
1501
 
1273
- await m.solve();
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
1504
+ ```
1274
1505
 
1275
- const woodConstraint = m.getConstraintByName("wood");
1276
- console.log("Shadow price (dual):", woodConstraint?.dual);
1277
- console.log("Slack surplus:", woodConstraint?.slack);
1278
- console.log("Total linear constraints:", m.numConstrs);
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]}`));
1279
1533
  ```
1280
1534
 
1281
- For logical constraints registered with a name, use `m.getLogicalConstraintByName(name)` to look up the registered `LogicalConstraintItem`.
1535
+ > [!TIP]
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).
1282
1537
 
1283
1538
  ---
1284
1539
 
@@ -1309,22 +1564,25 @@ m.constraint(expr`2 * ${x} + 3 * ${y} <= 100`, "resource_limit");
1309
1564
 
1310
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`.
1311
1566
 
1567
+ > [!TIP]
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).
1569
+
1312
1570
  ---
1313
1571
 
1314
- ## 🚀 Solving the Model (`m.solve()` vs. `m.check()`)
1572
+ ## Solving the Model (`m.solve()` vs. `m.check()`)
1315
1573
 
1316
1574
  WaSHI provides two asynchronous execution entrypoints:
1317
1575
 
1318
1576
  | Method | Return Value | Purpose |
1319
1577
  | :--- | :--- | :--- |
1320
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. |
1321
- | **`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. |
1322
1580
 
1323
1581
  ```typescript
1324
1582
  const status = await m.solve({
1325
- timeLimit: 10.0, // Timeout in seconds
1326
- mipGap: 0.01, // Stop within 1% of global optimum
1327
- outputFlag: false, // Enable/disable solver console logging (HiGHS: outputFlag, GLPK: verbose)
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)
1328
1586
  });
1329
1587
  ```
1330
1588
 
@@ -1332,14 +1590,14 @@ const status = await m.solve({
1332
1590
 
1333
1591
  | Option | Type | Default | Description |
1334
1592
  | :--- | :--- | :--- | :--- |
1335
- | `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. |
1336
1594
  | `timeLimit` | `number` | `undefined` | Maximum solve duration in seconds. |
1337
- | `mipGap` / `relGap` | `number` | `undefined` | Relative MIP optimality gap tolerance (e.g. `0.01` for 1%). |
1338
- | `absGap` | `number` | `undefined` | Absolute MIP optimality gap tolerance (HiGHS `mip_abs_gap`). |
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`). |
1339
1597
  | `presolve` | `"on"` \| `"off"` \| `"choose"` | `"choose"` | Controls solver presolve reduction prior to optimization. |
1340
1598
  | `outputFlag` / `verbose` | `boolean` | `false` | Emits internal solver iteration logs (`outputFlag` for HiGHS, `verbose` for GLPK). |
1341
- | `useWorker` | `boolean` | `true` (browser) | Offloads HiGHS to a dedicated Web Worker in browsers. Set `false` for main-thread execution. |
1342
- | `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. |
1343
1601
  | `signal` | `AbortSignal` | `undefined` | Cooperative cancellation signal (`AbortController.signal`). |
1344
1602
  | `onProgress` | `(e: SolveProgressEvent) => void` | `undefined` | Callback receiving live solver progress snapshots. |
1345
1603
 
@@ -1347,74 +1605,31 @@ You can also pass a solver name directly as the first argument: `await m.solve("
1347
1605
 
1348
1606
  ---
1349
1607
 
1350
- ## ⏱️ Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
1608
+ ## Reading Results, Bounds & Solver Status
1351
1609
 
1352
- 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`:
1610
+ After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
1353
1611
 
1354
1612
  ```typescript
1355
- const controller = new AbortController();
1613
+ const status = await m.solve();
1356
1614
 
1357
- // Example: cancel if the user clicks a "Stop" button or after a custom condition
1358
- const status = await m.solve({
1359
- signal: controller.signal,
1360
- onProgress: (event) => {
1361
- console.log(
1362
- `[${event.elapsedTime.toFixed(1)}s] ` +
1363
- `Best: ${event.objectiveValue ?? "—"}, ` +
1364
- `Bound: ${event.objectiveBound ?? "—"}, ` +
1365
- `Gap: ${event.mipGap !== undefined ? (event.mipGap * 100).toFixed(2) + "%" : "—"}`
1366
- );
1367
-
1368
- // Optional: stop early as soon as a good-enough incumbent is found
1369
- if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
1370
- controller.abort();
1371
- }
1372
- },
1373
- });
1374
-
1375
- console.log("Status:", m.status); // "Feasible" (if an incumbent was found before abort) or "Unknown"
1376
- console.log("Termination:", m.terminationStatus); // "Interrupted"
1377
- console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
1378
- ```
1379
-
1380
- ### `SolveProgressEvent` Fields
1381
-
1382
- | Field | Type | Description |
1383
- | :--- | :--- | :--- |
1384
- | `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
1385
- | `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
1386
- | `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
1387
- | `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
1388
- | `relGap` / `mipGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
1389
- | `absGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
1390
- | `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
1391
- | `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
1392
- | `message` | `string \| undefined` | Raw progress line emitted by the solver. |
1393
-
1394
- ---
1395
-
1396
- ## 📊 Reading Results, Bounds & Solver Status
1397
-
1398
- After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
1399
-
1400
- ```typescript
1401
- const status = await m.solve();
1402
-
1403
- console.log("Status:", m.status); // e.g. "Optimal" or "Feasible"
1404
- console.log("Termination Reason:", m.terminationStatus); // e.g. "Optimal", "TimeLimit", "Interrupted"
1405
- console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value / m.objectiveValue are populated
1615
+ console.log("Status:", m.status); // e.g. "Optimal" or "Feasible"
1616
+ console.log("Termination Reason:", m.terminationStatus); // e.g. "Optimal", "TimeLimit", "Interrupted"
1617
+ console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value / m.objectiveValue are populated
1406
1618
 
1407
1619
  // Objective & MIP Gap Metrics
1408
1620
  console.log("Objective Value:", m.objectiveValue); // Best primal objective (or null)
1409
1621
  console.log("Objective Bound:", m.objectiveBound); // Best dual bound (or undefined)
1410
- console.log("Relative Gap:", m.relGap); // Relative MIP gap (alias: m.mipGap)
1411
- console.log("Absolute Gap:", m.absGap); // |objectiveValue - objectiveBound|
1622
+ console.log("Relative Gap:", m.relativeGap); // Relative MIP gap
1623
+ console.log("Absolute Gap:", m.absoluteGap); // |objectiveValue - objectiveBound|
1412
1624
 
1413
- // Individual & Bulk Variable Values
1625
+ // Variable Values (via .value or name-keyed m.values ReadonlyMap)
1414
1626
  console.log("x =", x.value, "y =", y.value);
1415
- console.log(m.getValues({ x, y })); // { x: ..., y: ... }
1627
+ console.log("x by name:", m.values.get("x"));
1416
1628
  ```
1417
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
+
1418
1633
  ### Understanding `m.status` vs. `m.terminationStatus`
1419
1634
 
1420
1635
  When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two distinct questions matter:
@@ -1441,38 +1656,85 @@ If an integer-feasible incumbent was found before hitting `timeLimit` or `signal
1441
1656
 
1442
1657
  ---
1443
1658
 
1444
- ## 🔄 Model Mutations & Execution Validity
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
+
1705
+ ## Model Mutations & Execution Validity
1445
1706
 
1446
1707
  A `Model` instance keeps its solution state synchronized across mutations made through `Model` methods and `Model` / `Var` / `Constraint` property setters:
1447
1708
 
1448
- 1. **Post-Solve Mutations Reset Solution State**: Adding variables or constraints, updating the objective (`m.objective(...)`, `m.objectiveExpr = ...`, `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`.
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`.
1449
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.
1450
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.
1451
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.
1452
1713
 
1453
1714
  > [!NOTE]
1454
- > Renaming already-registered variables or constraints (e.g., reassigning `c.name` after registration) or mutating internal backing collections and ASTs directly (such as `c.lhs.terms`, `m.constraints.splice(...)`, or `BoolOp.children`) is unsupported and will be rejected by model integrity validation on the next solve/check/export call.
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.
1455
1716
 
1456
1717
  ---
1457
1718
 
1458
- # Conflict Diagnosis (`unsatCore`) & Solution Validation
1719
+ # Conflict Diagnosis (`unsatCore`), Validation & Debugging
1459
1720
 
1460
- When building real-world optimization and configuration systems, two verification questions arise constantly:
1461
- 1. **Why is my model infeasible?** Which specific business rules contradict each other?
1462
- 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.
1463
1722
 
1464
- WaSHI provides built-in tools for both: **Unsat Core conflict diagnosis** via Z3 (`m.check()`), **independent solution validation** (`m.validateSolution()`), **LP formulation export** (`m.toLpString()`), and **fast unit testing** (`MockSolver`).
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.
1465
1727
 
1466
1728
  ---
1467
1729
 
1468
- ## 🔍 Conflict Diagnosis (`unsatCore` / `conflicts`)
1730
+ ## Conflict Diagnosis (`unsatCore` / `conflicts`)
1469
1731
 
1470
- When a model is **Infeasible**, traditional MIP solvers simply report that no solution exists without indicating *which* constraints are contradictory.
1471
- By calling **`await m.check({ solver: "z3" })`**, WaSHI uses Z3's `assertAndTrack` mechanism to compute an **Unsatisfiable Core (`unsatCore`)**—a conflicting subset of named constraints that cannot be satisfied simultaneously:
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.
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:
1472
1734
 
1473
1735
  ```typescript
1474
1736
  import { Model, expr } from "@ohtaman/washi";
1475
- // Register the Z3 solver plugin
1737
+ // Register the Z3 solver plugin (for Continuous / real-valued SMT models)
1476
1738
  import "@ohtaman/washi/solvers/z3";
1477
1739
 
1478
1740
  const m = new Model();
@@ -1496,14 +1758,15 @@ if (result.status === "Unsat") {
1496
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.
1497
1759
 
1498
1760
  > [!IMPORTANT]
1499
- > - **Use `m.check({ solver: "z3" })` for Unsat Core extraction**: `m.solve()` runs optimization (`Z3.Optimize`), whereas `m.check()` runs tracked satisfiability checking (`Z3.Solver.assertAndTrack`) and populates `result.conflicts` / `m.conflicts` (and alias `m.unsatCore`).
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`).
1500
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")`.
1501
1763
 
1502
- ### Workflow: Infeasibility Diagnosis with HiGHS or Z3
1764
+ ### Workflow: Infeasibility Diagnosis with HiGHS, Pumpkin, or Z3
1503
1765
 
1504
- Because WaSHI models are solver-independent, you can diagnose infeasibilities using either solver:
1505
- 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 dependencies.
1506
- 2. **Z3 SMT Solver**: `await m.check({ solver: "z3" })` uses SMT tracking to extract an exact unsatisfiable core (`diag.unsatCore` / `diag.conflicts`).
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.
1507
1770
 
1508
1771
  ```typescript
1509
1772
  const status = await m.solve(); // Fast MIP solve with default HiGHS
@@ -1513,15 +1776,34 @@ if (status === "Infeasible") {
1513
1776
  const diag = await m.check();
1514
1777
  console.error("Model is infeasible due to conflicting rules:", diag.conflicts);
1515
1778
 
1516
- // Option 2: Exact SMT unsat core diagnosis with Z3 (requires import "@ohtaman/washi/solvers/z3")
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")
1517
1784
  // const z3Diag = await m.check({ solver: "z3" });
1518
1785
  // console.error("Z3 Unsat Core:", z3Diag.unsatCore);
1519
1786
  }
1520
1787
  ```
1521
1788
 
1789
+ ### Comparing Pumpkin `unsatCore`, Z3 `unsatCore`, and HiGHS Elastic Slack `conflicts`
1790
+
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) |
1800
+
1801
+ > [!TIP]
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.
1803
+
1522
1804
  ---
1523
1805
 
1524
- ## ✅ Independent Solution Validation (`m.validateSolution()`)
1806
+ ## Independent Solution Verification (`m.verify()`)
1525
1807
 
1526
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:
1527
1809
 
@@ -1529,7 +1811,7 @@ After solving a model (or supplying a custom candidate map via `values`), you ca
1529
1811
  const status = await m.solve();
1530
1812
 
1531
1813
  if (m.hasPrimalSolution) {
1532
- const report = m.validateSolution({
1814
+ const report = m.verify({
1533
1815
  feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
1534
1816
  integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
1535
1817
  evaluateLogicalConstraints: true,
@@ -1546,22 +1828,22 @@ if (m.hasPrimalSolution) {
1546
1828
  }
1547
1829
  ```
1548
1830
 
1549
- ### `SolutionValidationReport` Summary
1831
+ ### `VerificationReport` Summary
1550
1832
 
1551
1833
  | Property | Type | Description |
1552
1834
  | :--- | :--- | :--- |
1553
1835
  | `valid` | `boolean` | `true` iff `complete === true`, `uncheckedConstraints.length === 0`, and `violations.length === 0`. |
1554
1836
  | `complete` | `boolean` | `true` when all variables, Boolean variables, linear constraints, and logical constraints were evaluated. |
1555
1837
  | `maxViolation` | `number` | Largest numeric violation magnitude across all evaluated bounds, integrality checks, and constraints. |
1556
- | `violations` | `SolutionViolation[]` | Flat list of violations (`"missing_value"`, `"non_finite_value"`, `"invalid_boolean_value"`, `"lower_bound"`, `"upper_bound"`, `"integrality"`, `"linear_constraint"`, `"logical_constraint"`, `"unchecked_constraint"`). |
1557
- | `violationsByName` | `Record<string, SolutionViolation[]>` | Violations grouped by variable or constraint name. |
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. |
1558
1840
  | `uncheckedConstraints` | `string[]` | Names of constraints that could not be evaluated. |
1559
1841
  | `missingVariables` | `string[]` | Names of numeric or Boolean variables whose values were `null` or `undefined`. |
1560
- | `summary` | `SolutionValidationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
1842
+ | `summary` | `VerificationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
1561
1843
 
1562
1844
  ---
1563
1845
 
1564
- ## 📄 Inspecting the LP Formulation (`m.toLpString()`)
1846
+ ## Inspecting the LP Formulation (`m.toLpString()`)
1565
1847
 
1566
1848
  When debugging coefficients, signs, or Big-M indicator expansions, call `m.toLpString()` to export the model in standard CPLEX/HiGHS `.lp` format:
1567
1849
 
@@ -1587,7 +1869,7 @@ End
1587
1869
 
1588
1870
  ---
1589
1871
 
1590
- ## 🧪 Unit Testing Application Logic with `MockSolver`
1872
+ ## Unit Testing Application Logic with `MockSolver`
1591
1873
 
1592
1874
  When running unit tests for application code that builds or consumes a WaSHI `Model`, you can use the built-in `MockSolver` (`solver: "mock"`) to return deterministic results instantaneously without loading WebAssembly:
1593
1875
 
@@ -1612,165 +1894,251 @@ console.log(x.value, y.value); // 10, 20
1612
1894
 
1613
1895
  ---
1614
1896
 
1615
- # Advanced Decomposition Methods & Best Practices
1897
+ # Constraint Programming (CP) Modeling
1616
1898
 
1617
- Mixed-Integer Programming (MIP) formulations can become slow when symmetry or coupling constraints cause branch-and-bound trees to grow large.
1618
- WaSHI provides decomposition orchestrators (`master.solveColumnGeneration` and `master.solveBenders`) along with lower-level modeling primitives for dual inspection and dynamic model modification.
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.
1619
1900
 
1620
1901
  ---
1621
1902
 
1622
- ## Why Decomposition? (When Monolithic MIP Stalls)
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.
1623
1906
 
1624
- There are two common problem structures where monolithic MIP formulations struggle:
1907
+ In **CP (Pumpkin)**, you model **what** each entity chooses directly using finite-domain integers (`m.integer(keys, { lb, ub })`) and declarative **global constraints**:
1625
1908
 
1626
- | Problem Structure | Monolithic MIP Bottleneck | Technique | WaSHI API |
1909
+ | Modeling Dimension | MIP Pattern (`HiGHS` / `GLPK`) | CP Pattern (`Pumpkin`) | SMT (`Z3`) |
1627
1910
  | :--- | :--- | :--- | :--- |
1628
- | **Symmetry & Loose Continuous Bounds**<br>*(Cutting Stock, Vehicle Routing/VRP, Crew Rostering)* | Symmetric permutations and a weak continuous relaxation enlarge the branch-and-bound tree. | **Column Generation**<br>*(Dantzig-Wolfe Decomposition)* | [`master.solveColumnGeneration()`](#column-generation-solvecolumngeneration) |
1629
- | **Complicating Decisions & Multi-Stage Structure**<br>*(Traveling Salesperson/TSP, Facility Location with Routing, Two-Stage Stochastic Planning)* | Coupling master decisions with large scenario or operational subproblems increases the matrix size. | **Benders Decomposition** | [`master.solveBenders()`](#benders-decomposition-solvebenders) |
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 |
1630
1917
 
1631
1918
  ---
1632
1919
 
1633
- ## Foundational Primitives
1920
+ ## 2. Interval & Resource Scheduling (`disjoint`, `cumulative`, `max`)
1634
1921
 
1635
- WaSHI provides fine-grained modeling primitives to inspect dual information and dynamically modify models:
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" }`).
1636
1923
 
1637
- ### 1. Constraint Duals (`dual`)
1638
- Access the dual values (marginal impact on the objective per unit change in RHS) after an LP solve:
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.
1639
1925
 
1640
1926
  ```typescript
1641
- m.constraint(expr`${x} + ${y} <= 10`, "capacity");
1642
- await m.solve();
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
+ );
1643
1950
 
1644
- const c = m.getConstraintByName("capacity")!;
1645
- console.log(c.dual); // Dual value / shadow price
1646
- console.log(m.solution?.duals.capacity);
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
+ );
1959
+
1960
+ m.objective(minimize(max(tasks.map((t) => expr`${start[t]} + ${duration[t]}`))));
1961
+ await m.solve();
1647
1962
  ```
1648
1963
 
1649
- ### 2. Continuous LP Relaxation (`model.relax()`)
1650
- Decomposition algorithms require solving the continuous LP relaxation to extract dual values. `model.relax()` temporarily relaxes all `Integer` and `Binary` variables to continuous variables within their bounds:
1964
+ See the full runnable project scheduling walkthrough in [Resource-Constrained Project Scheduling (RCPSP)](docs/examples/project-scheduling.md).
1651
1965
 
1652
- ```typescript
1653
- // Solves LP relaxation and populates shadow prices in m.solution.duals
1654
- const status = await m.relax();
1655
- console.log("Theoretical dual bound:", m.objectiveValue);
1656
- ```
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\}$:
1657
1971
 
1658
- ### 3. Dynamic Column Injection (`model.addColumn()`)
1659
- Inject a new decision variable along with its objective coefficient and constraint contributions in a single call:
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.
1660
1975
 
1661
1976
  ```typescript
1662
- const col = m.addColumn({
1663
- name: "pattern_1",
1664
- type: "Integer", // or "Continuous"
1665
- lb: 0,
1666
- cost: 1, // objective coefficient
1667
- coefficients: {
1668
- demand_itemA: 2,
1669
- demand_itemB: 1,
1670
- },
1671
- });
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();
1672
2001
  ```
1673
2002
 
1674
- ### 4. Dynamic Constraint Modification (`addTerm` / `setTerm`)
1675
- Update the coefficients of individual variables in an existing constraint:
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:
1676
2012
 
1677
2013
  ```typescript
1678
- const c = m.getConstraintByName("budget")!;
1679
- c.addTerm(newVar, 5); // Increments newVar's coefficient by 5
1680
- c.setTerm(newVar, 0); // Setting to 0 cleanly removes the term
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();
1681
2033
  ```
1682
2034
 
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).
2038
+
1683
2039
  ---
1684
2040
 
1685
- ## Column Generation (`solveColumnGeneration`)
2041
+ # Decomposition Methods (`solveColumnGeneration` & `solveBenders`)
2042
+
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.
2044
+
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). |
2049
+
2050
+ ---
1686
2051
 
1687
- Column Generation starts with a **Restricted Master Problem (RMP)** with a small subset of columns. In each iteration:
1688
- 1. It solves the RMP's LP relaxation via `master.relax()`.
1689
- 2. Evaluates a pricing subproblem using constraint shadow prices.
1690
- 3. Finds candidate columns with negative reduced costs ($\bar{c} = \text{cost} - \sum \pi_i a_i < 0$) and dynamically injects them into the master problem.
1691
- 4. Repeats until no improving columns exist.
1692
- 5. Finally solves the full master model as a Mixed-Integer Program (`finalizeAsMIP`, default: `true`) to obtain optimal integer solutions.
2052
+ ## Column Generation (`solveColumnGeneration`)
1693
2053
 
1694
- ### Column Generation with the `pricing` Callback
2054
+ `master.solveColumnGeneration(options)` starts from a **Restricted Master Problem (RMP)** containing an initial feasible subset of columns and executes the column generation loop:
2055
+ 1. Solves the continuous LP relaxation of the master problem via `master.relax()`.
2056
+ 2. Invokes your `pricing` callback with the current dual shadow prices (`duals`, `getDual`).
2057
+ 3. Evaluates candidate columns (`ColumnProposal` or `ColumnProposal[]`), dynamically injecting those with improving reduced costs ($\bar{c} = \text{cost} - \sum_i \pi_i a_i < 0$ when minimizing).
2058
+ 4. Repeats until `pricing` returns `null` / `[]` or no column improves the objective beyond `reducedCostTolerance`.
2059
+ 5. Optionally solves the final master model as a MIP (`finalizeAsMIP: true`, the default) to obtain an integer solution over all generated columns.
1695
2060
 
1696
- Provide a `pricing` callback that receives constraint shadow prices (duals), solves the subproblem (using a WaSHI model or any custom algorithm), and returns new column proposals. WaSHI automatically evaluates reduced costs and injects improving columns:
2061
+ ### Pricing with a WaSHI Subproblem Model
1697
2062
 
1698
2063
  ```typescript
1699
2064
  import { Model, expr, minimize, maximize } from "@ohtaman/washi";
1700
2065
 
1701
2066
  const rollWidth = 100;
1702
- const items = [
1703
- { id: "A", width: 45, demand: 10 },
1704
- { id: "B", width: 36, demand: 14 },
1705
- { id: "C", width: 16, demand: 20 },
1706
- ];
1707
2067
 
1708
- // 1. Define Restricted Master Problem (RMP) with naive initial single-cut patterns
2068
+ // 1. Restricted Master Problem (RMP) with simple single-item initial patterns
1709
2069
  const master = new Model("CuttingStockMaster");
1710
-
1711
- const pA = master.integer("init_A", { lb: 0 }); // 2 of A per roll (45*2 = 90 <= 100)
1712
- const pB = master.integer("init_B", { lb: 0 }); // 2 of B per roll (36*2 = 72 <= 100)
1713
- const pC = master.integer("init_C", { lb: 0 }); // 6 of C per roll (16*6 = 96 <= 100)
2070
+ const pA = master.integer("init_A", { lb: 0 }); // 2 of A (width 45) per roll
2071
+ const pB = master.integer("init_B", { lb: 0 }); // 2 of B (width 36) per roll
2072
+ const pC = master.integer("init_C", { lb: 0 }); // 6 of C (width 16) per roll
1714
2073
 
1715
2074
  master.objective(minimize(expr`${pA} + ${pB} + ${pC}`));
1716
- master.constraint(expr`2 * ${pA} >= 10`, "demand_A");
1717
- master.constraint(expr`2 * ${pB} >= 14`, "demand_B");
1718
- master.constraint(expr`6 * ${pC} >= 20`, "demand_C");
1719
- const [demandA, demandB, demandC] = master.constraints;
2075
+ const demandA = master.constraint(expr`2 * ${pA} >= 10`, "demand_A");
2076
+ const demandB = master.constraint(expr`2 * ${pB} >= 14`, "demand_B");
2077
+ const demandC = master.constraint(expr`6 * ${pC} >= 20`, "demand_C");
1720
2078
 
1721
- // 2. Solve with master.solveColumnGeneration()
2079
+ // 2. Run Column Generation
1722
2080
  const result = await master.solveColumnGeneration({
1723
2081
  finalizeAsMIP: true,
1724
2082
  pricing: async () => {
1725
- // Pricing subproblem: Bounded Knapsack
2083
+ // Knapsack pricing subproblem: find a pattern maximizing total dual value
1726
2084
  const sub = new Model("KnapsackPricing");
1727
- const a_A = sub.integer("a_A", { lb: 0, ub: 2 });
1728
- const a_B = sub.integer("a_B", { lb: 0, ub: 2 });
1729
- const a_C = sub.integer("a_C", { lb: 0, ub: 6 });
2085
+ const aA = sub.integer("a_A", { lb: 0, ub: 2 });
2086
+ const aB = sub.integer("a_B", { lb: 0, ub: 2 });
2087
+ const aC = sub.integer("a_C", { lb: 0, ub: 6 });
1730
2088
 
1731
- // Maximize shadow price collection
1732
2089
  const dualA = demandA.dual ?? 0;
1733
2090
  const dualB = demandB.dual ?? 0;
1734
2091
  const dualC = demandC.dual ?? 0;
1735
- sub.objective(maximize(expr`${dualA} * ${a_A} + ${dualB} * ${a_B} + ${dualC} * ${a_C}`));
1736
- sub.constraint(expr`45 * ${a_A} + 36 * ${a_B} + 16 * ${a_C} <= ${rollWidth}`);
2092
+ sub.objective(maximize(expr`${dualA} * ${aA} + ${dualB} * ${aB} + ${dualC} * ${aC}`));
2093
+ sub.constraint(expr`45 * ${aA} + 36 * ${aB} + 16 * ${aC} <= ${rollWidth}`);
1737
2094
 
1738
2095
  await sub.solve();
1739
2096
 
1740
- // Return the generated cutting pattern
1741
2097
  return {
1742
2098
  cost: 1,
1743
2099
  type: "Integer",
1744
2100
  coefficients: {
1745
- demand_A: Math.round(a_A.value ?? 0),
1746
- demand_B: Math.round(a_B.value ?? 0),
1747
- demand_C: Math.round(a_C.value ?? 0),
2101
+ demand_A: Math.round(aA.value ?? 0),
2102
+ demand_B: Math.round(aB.value ?? 0),
2103
+ demand_C: Math.round(aC.value ?? 0),
1748
2104
  },
1749
2105
  };
1750
2106
  },
1751
2107
  });
1752
2108
 
1753
- console.log("Optimal rolls needed:", result.objectiveValue); // 14
1754
- console.log("Iterations executed:", result.iterations);
1755
- console.log("Dynamic columns added:", result.columnsAdded);
2109
+ console.log("Optimal rolls:", result.objectiveValue); // 14
2110
+ console.log("Iterations:", result.iterations);
2111
+ console.log("Columns added:", result.columnsAdded);
1756
2112
  ```
1757
2113
 
1758
- ### Custom Pricing Algorithms (Graph / Dynamic Programming)
2114
+ ### Pricing with a Custom Algorithm (`getDual`)
1759
2115
 
1760
- Because `pricing` is a standard callback returning column definitions, you can solve the subproblem using any algorithm (e.g. Dijkstra, Bellman-Ford, or custom heuristics):
2116
+ Because `pricing` is a standard callback receiving `PricingContext`, you can also solve the pricing problem directly in TypeScript (e.g., via combinatorial search, dynamic programming, or shortest-path routines) instead of constructing a subproblem `Model`:
1761
2117
 
1762
2118
  ```typescript
1763
- const result = await master.solveColumnGeneration({
1764
- pricing: async ({ getDual }) => {
1765
- // Solve subproblem with specialized custom graph algorithm
1766
- const route = solveSpecializedShortestPath(getDual);
1767
- if (!route) return null;
1768
-
1769
- return {
1770
- cost: route.distance,
1771
- type: "Integer",
1772
- coefficients: route.visitedCustomers,
1773
- };
2119
+ const customResult = await master.solveColumnGeneration({
2120
+ maxIterations: 100,
2121
+ reducedCostTolerance: 1e-6,
2122
+ pricing: ({ getDual }) => {
2123
+ const dA = getDual("demand_A");
2124
+ const dB = getDual("demand_B");
2125
+ const dC = getDual("demand_C");
2126
+
2127
+ // Search feasible patterns (45*aA + 36*aB + 16*aC <= rollWidth) for negative reduced cost (1 - dualSum < -1e-6)
2128
+ let bestDualSum = 1 + 1e-6;
2129
+ let best: { demand_A: number; demand_B: number; demand_C: number } | null = null;
2130
+ for (let aA = 0; 45 * aA <= rollWidth; aA++) {
2131
+ for (let aB = 0; 45 * aA + 36 * aB <= rollWidth; aB++) {
2132
+ for (let aC = 0; 45 * aA + 36 * aB + 16 * aC <= rollWidth; aC++) {
2133
+ const dualSum = dA * aA + dB * aB + dC * aC;
2134
+ if (dualSum > bestDualSum) {
2135
+ bestDualSum = dualSum;
2136
+ best = { demand_A: aA, demand_B: aB, demand_C: aC };
2137
+ }
2138
+ }
2139
+ }
2140
+ }
2141
+ return best ? { cost: 1, type: "Integer", coefficients: best } : null;
1774
2142
  },
1775
2143
  });
1776
2144
  ```
@@ -1779,33 +2147,29 @@ const result = await master.solveColumnGeneration({
1779
2147
 
1780
2148
  ## Benders Decomposition (`solveBenders`)
1781
2149
 
1782
- Benders Decomposition partitions the problem into:
1783
- - **Master Problem**: Contains complicating variables (e.g., 0-1 facility opening decisions $y$) and an auxiliary variable $\theta \ge 0$ representing estimated subproblem costs.
1784
- - **Subproblem**: Solves operational decisions given fixed master values $y^*$, feeding back **Optimality Cuts** to the master.
2150
+ `master.solveBenders(options)` partitions a problem into a **Master Problem** (holding first-stage or complicating variables) and a **Subproblem** evaluated at each master candidate solution to generate **Optimality Cuts** or **Feasibility Cuts**.
1785
2151
 
1786
- ### Recommended: Automated Cut Generation with `sub.link()`
2152
+ ### Automatic Cut Generation (`sub.link()`)
1787
2153
 
1788
- Return the subproblem `Model` from your callback and register linking constraints with `sub.link(...)`. WaSHI automatically manages $\theta$, evaluates master candidate values, extracts duals, and injects Benders optimality cuts:
2154
+ Return a continuous LP subproblem `Model` from `subproblem` and declare cross-model constraints via `sub.link(...)`. WaSHI automatically manages the auxiliary cost estimator variable $\theta$, substitutes master candidate values, extracts subproblem duals, and adds Benders cuts until convergence:
1789
2155
 
1790
2156
  ```typescript
1791
2157
  import { Model, expr, minimize } from "@ohtaman/washi";
1792
2158
 
1793
- // 1. Master problem: Facility location decisions
2159
+ // 1. Master problem: binary facility opening decisions
1794
2160
  const master = new Model("FacilityMaster");
1795
2161
  const y1 = master.binary("open_F1");
1796
2162
  const y2 = master.binary("open_F2");
1797
2163
 
1798
- // Objective: Fixed facility costs (theta is managed automatically)
2164
+ // Fixed opening costs (theta for operational subproblem cost is managed automatically)
1799
2165
  master.objective(minimize(expr`100 * ${y1} + 120 * ${y2}`));
1800
- // Minimal aggregate capacity requirement
1801
- master.constraint(expr`50 * ${y1} + 60 * ${y2} >= 75`, "capacity_check");
2166
+ master.constraint(expr`50 * ${y1} + 60 * ${y2} >= 75`, "total_capacity_floor");
1802
2167
 
1803
- // 2. Solve automatically with master.solveBenders()
2168
+ // 2. Solve with automatic Benders cut generation
1804
2169
  const result = await master.solveBenders({
1805
2170
  gapTolerance: 1e-4,
1806
2171
  subproblem: () => {
1807
- // Operational dispatch subproblem
1808
- const sub = new Model("TransportSubproblem");
2172
+ const sub = new Model("DispatchSubproblem");
1809
2173
  const x11 = sub.continuous("x_11", { lb: 0 });
1810
2174
  const x12 = sub.continuous("x_12", { lb: 0 });
1811
2175
  const x13 = sub.continuous("x_13", { lb: 0 });
@@ -1819,198 +2183,343 @@ const result = await master.solveBenders({
1819
2183
  )
1820
2184
  );
1821
2185
 
1822
- // Customer demand constraints
1823
2186
  sub.constraint(expr`${x11} + ${x21} >= 20`, "demand_C1");
1824
2187
  sub.constraint(expr`${x12} + ${x22} >= 25`, "demand_C2");
1825
2188
  sub.constraint(expr`${x13} + ${x23} >= 30`, "demand_C3");
1826
2189
 
1827
- // Link subproblem flows with master decisions y1, y2 via linking constraints
2190
+ // Link subproblem dispatch flows to master binary variables y1, y2
1828
2191
  sub.link(expr`${x11} + ${x12} + ${x13} <= 50 * ${y1}`);
1829
2192
  sub.link(expr`${x21} + ${x22} + ${x23} <= 60 * ${y2}`);
1830
2193
 
1831
- return sub; // Returning the model automatically generates cuts and manages theta
2194
+ return sub;
1832
2195
  },
1833
2196
  });
1834
2197
 
1835
2198
  console.log("Optimal total cost:", result.objectiveValue); // 390
1836
- console.log("Iterations:", result.iterations);
1837
2199
  console.log("Cuts added:", result.cutsAdded);
1838
- console.log("Facility decisions:", {
1839
- F1: result.values.open_F1,
1840
- F2: result.values.open_F2,
1841
- });
2200
+ console.log("Open facilities:", result.values);
1842
2201
  ```
1843
2202
 
1844
- ### Low-Level Control: Custom `BendersCut` Callback
2203
+ > [!NOTE]
2204
+ > **`theta` Lower Bound for Negative Subproblem Objectives**: When `sub.link(...)` is used without an explicit `theta` variable, WaSHI injects `__benders_theta` with default `lb: 0` (assuming non-negative subproblem costs). If your subproblem objective can take negative values (e.g., rebate or profit terms), declare `const theta = master.continuous("theta", { lb: -1e6 })`, include `+ ${theta}` in `master.objective(...)`, and pass `{ theta }` in `solveBenders(options)`.
2205
+
2206
+ ### Manual Cut Generation (`BendersCut` / Lazy Constraints)
1845
2207
 
1846
- You can also construct Benders cuts manually by returning `BendersCut` objects:
2208
+ For combinatorial separation (such as lazy subtour elimination) or custom analytical cuts, return one `BendersCut` object, an array `BendersCut[]`, or `null` when converged:
1847
2209
 
1848
2210
  ```typescript
2211
+ import { Model, expr, minimize } from "@ohtaman/washi";
2212
+
2213
+ const master = new Model("ManualBenders");
2214
+ const y = master.binary("y");
2215
+ const theta = master.continuous("theta", { lb: 0 });
2216
+ master.objective(minimize(expr`40 * ${y} + ${theta}`));
2217
+
1849
2218
  const result = await master.solveBenders({
2219
+ theta,
1850
2220
  gapTolerance: 1e-4,
1851
- subproblem: async () => {
1852
- const open1 = y1.value ?? 0;
1853
- const open2 = y2.value ?? 0;
1854
- const estTheta = theta.value ?? 0;
1855
-
1856
- const sub = new Model("TransportSubproblem");
1857
- // ...
1858
- await sub.solve();
2221
+ subproblem: ({ getMasterValue }) => {
2222
+ const yVal = getMasterValue(y);
2223
+ const estTheta = getMasterValue(theta);
1859
2224
 
1860
- const actualCost = sub.objectiveValue!;
1861
- if (estTheta < actualCost - 1e-4) {
2225
+ // Operational cost is 100 when y = 0, or 30 when y = 1
2226
+ const actualSubCost = 100 - 70 * yVal;
2227
+ if (estTheta < actualSubCost - 1e-4) {
1862
2228
  return {
1863
- kind: "optimality",
1864
- constraint: expr`${theta} - 50 * ${sub.solution!.duals.cap1} * ${y1} - 60 * ${sub.solution!.duals.cap2} * ${y2} >= ${rhs}`,
1865
- subproblemObjective: 100 * open1 + 120 * open2 + actualCost,
2229
+ kind: "optimality", // or "feasibility" for lazy combinatorial cuts
2230
+ constraint: expr`${theta} >= 100 - 70 * ${y}`,
2231
+ subproblemObjective: 40 * yVal + actualSubCost,
1866
2232
  };
1867
2233
  }
1868
2234
  return null; // Converged
1869
2235
  },
1870
2236
  });
2237
+
2238
+ console.log(result.objectiveValue); // 70 (y = 1, theta = 30)
1871
2239
  ```
1872
2240
 
1873
2241
  ---
1874
2242
 
1875
- ## Application Examples
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";
1876
2252
 
1877
- Two common applications of decomposition methods:
2253
+ const m = new Model();
2254
+ const x = m.continuous("x", { lb: 0 });
2255
+ const y = m.continuous("y", { lb: 0 });
1878
2256
 
1879
- ### 1. Vehicle Routing Problem (CVRP) $\times$ Column Generation
1880
- *(Full executable source: [`examples/node/13-vehicle-routing-column-generation.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts))*
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
+ ```
1881
2264
 
1882
- * **Problem Structure**: Enumerating every feasible customer tour upfront produces a large number of variables.
1883
- * **Column Generation Formulation**:
1884
- * **Master Problem**: Set covering model that selects the minimum number of vehicle routes such that each customer is served.
1885
- * **Pricing Subproblem**: Knapsack model that dynamically generates a capacity-feasible route (column) with negative reduced cost based on customer dual shadow prices.
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:
1886
2267
 
1887
2268
  ```typescript
1888
- import { Model, expr, minimize, LinExpr, type Var } from "@ohtaman/washi";
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
+ ```
1889
2273
 
1890
- const vehicleCapacity = 8;
1891
- const customers = [
1892
- { id: "C1", demand: 4 },
1893
- { id: "C2", demand: 3 },
1894
- { id: "C3", demand: 5 },
1895
- { id: "C4", demand: 2 },
1896
- { id: "C5", demand: 4 },
1897
- ];
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:
1898
2276
 
1899
- // 1. Master Problem: Customer coverage
1900
- const master = new Model("CVRP_Master");
1901
- const initialRoutes: Var[] = [];
1902
- for (const cust of customers) {
1903
- initialRoutes.push(master.integer(`init_${cust.id}`, { lb: 0, ub: 1 }));
1904
- }
1905
- master.objective(minimize(initialRoutes.reduce((acc, r) => acc.add(r), new LinExpr())));
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
+
2302
+ ## Related Examples & Formulation Tips
2303
+
2304
+ - **Full Decomposition Walkthroughs**:
2305
+ - [Vehicle Routing Problem (`solveColumnGeneration`)](docs/examples/vehicle-routing.md)
2306
+ - [Traveling Salesperson Problem (`solveBenders` lazy subtour elimination)](docs/examples/traveling-salesperson.md)
2307
+ - **Formulation Tips**: See [Formulation Patterns & Optimization Tips](docs/guide/formulation-tips.md#_5-decomposition-formulation-tips) for Set Covering (`>= 1`) vs. Set Partitioning (`== 1`), Price-and-Branch (`finalizeAsMIP`), and multi-cut separation.
2308
+
2309
+ ---
2310
+
2311
+ # Formulation Patterns & Optimization Tips
2312
+
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).)*
2314
+
2315
+ ---
2316
+
2317
+ ## 1. Variables & Domain Modeling
2318
+
2319
+ ### Semi-Continuous Decisions ($\{0\} \cup [L, U]$)
2320
+
2321
+ A semi-continuous quantity must be either `0` (inactive) or within a positive interval `[L, U]` (e.g., a production batch with a minimum run size $L = 10$ and capacity $U = 100$).
2322
+
2323
+ Combine a continuous variable `x` with a binary activation variable `isActive` and linking constraints $L \cdot b \le x \le U \cdot b$:
2324
+
2325
+ ```typescript
2326
+ import { Model, expr } from "@ohtaman/washi";
2327
+
2328
+ const m = new Model("SemiContinuousBatch");
2329
+ const batch = m.continuous("batch", { lb: 0, ub: 100 });
2330
+ const isActive = m.binary("is_active");
2331
+
2332
+ // If isActive === 0, batch is forced to 0; if isActive === 1, batch lies in [10, 100]
2333
+ m.constraint(expr`${batch} >= 10 * ${isActive}`, "min_batch_run");
2334
+ m.constraint(expr`${batch} <= 100 * ${isActive}`, "max_batch_run");
2335
+ ```
2336
+
2337
+ ### Minimal-Perturbation Rescheduling vs. Warm Starting
2338
+
2339
+ When re-optimizing an existing schedule after a disruption, passing yesterday's assignment via [`initialValue`](docs/guide/variables.md#primal-initial-values-warm-start-hints) only gives the MIP solver a starting search point—it does **not** prevent the solver from changing every assignment for a tiny objective gain.
2340
+
2341
+ To keep a revised binary plan $x_i \in \{0, 1\}$ close to a baseline assignment $x_i^{\text{prev}} \in \{0, 1\}$, penalize the **Hamming distance** (number of flipped decisions) in the objective:
2342
+
2343
+ $$\text{Changes} = \sum_{i:\, x_i^{\text{prev}} = 0} x_i + \sum_{i:\, x_i^{\text{prev}} = 1} (1 - x_i)$$
2344
+
2345
+ ```typescript
2346
+ import { Model, expr, minimize } from "@ohtaman/washi";
2347
+
2348
+ const m = new Model("StableReschedule");
2349
+ const prevPlan = [1, 0, 1, 0];
2350
+ const x = prevPlan.map((prev, i) =>
2351
+ m.binary(`slot_${i}`, { initialValue: prev })
2352
+ );
2353
+
2354
+ // Linear terms counting how many 0/1 decisions differ from prevPlan
2355
+ const flipTerms = x.map((v, i) => (prevPlan[i] === 1 ? expr`1 - ${v}` : v));
2356
+
2357
+ // Require at least 3 active slots while penalizing changes from prevPlan
2358
+ m.constraint(expr`sum(${x}) >= 3`, "min_active_slots");
2359
+ m.objective(minimize(expr`5 * sum(${flipTerms})`));
2360
+ ```
1906
2361
 
1907
- for (let i = 0; i < customers.length; i++) {
1908
- master.constraint(expr`${initialRoutes[i]} >= 1`, `visit_${customers[i].id}`);
2362
+ ---
2363
+
2364
+ ## 2. Linearizing Non-Linear Expressions
2365
+
2366
+ ### Product of Two Binary Variables ($x_A \cdot x_B$)
2367
+
2368
+ In integer programming, if an interaction cost or synergy bonus applies only when two binary decisions $x_A, x_B \in \{0, 1\}$ are **both** equal to `1`, avoid introducing a quadratic term. Instead, introduce an auxiliary variable $z_{AB} \in [0, 1]$ and add the three standard McCormick / Fortet linear inequalities so the model remains a pure MILP:
2369
+
2370
+ $$z_{AB} \le x_A, \quad z_{AB} \le x_B, \quad z_{AB} \ge x_A + x_B - 1$$
2371
+
2372
+ ```typescript
2373
+ import { Model, expr, maximize } from "@ohtaman/washi";
2374
+
2375
+ const m = new Model("BinaryProductLinearization");
2376
+ const xA = m.binary("xA");
2377
+ const xB = m.binary("xB");
2378
+ // When xA and xB are binary, continuous [0, 1] bounds suffice to force bothAB into {0, 1}
2379
+ const bothAB = m.continuous("both_AB", { lb: 0, ub: 1 });
2380
+
2381
+ m.constraint(expr`${bothAB} <= ${xA}`, "and_upper_A");
2382
+ m.constraint(expr`${bothAB} <= ${xB}`, "and_upper_B");
2383
+ m.constraint(expr`${bothAB} >= ${xA} + ${xB} - 1`, "and_lower_AB");
2384
+
2385
+ m.objective(maximize(expr`10 * ${xA} + 10 * ${xB} + 5 * ${bothAB}`));
2386
+ ```
2387
+
2388
+ ### Min-Max & Max-Min Objectives (Load Balancing)
2389
+
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):
2393
+
2394
+ $$\min z \quad \text{subject to} \quad \text{load}_i \le z \quad \forall i$$
2395
+
2396
+ ```typescript
2397
+ import { Model, expr, minimize } from "@ohtaman/washi";
2398
+
2399
+ const m = new Model("MinMaxLoadBalancing");
2400
+ const workers = ["Alice", "Bob", "Carol"] as const;
2401
+ const hours = m.continuous(workers, { lb: 0, ub: 40 });
2402
+ const maxHours = m.continuous("max_hours", { lb: 0, ub: 40 });
2403
+
2404
+ // Bound every worker's hours by the shared ceiling maxHours
2405
+ m.constraint(workers.map((w) => expr`${hours[w]} <= ${maxHours}`));
2406
+ m.constraint(expr`sum(${hours}) >= 60`, "total_required_work");
2407
+
2408
+ // Minimizing maxHours distributes the 60 hours evenly (20 hours each)
2409
+ m.objective(minimize(maxHours));
2410
+ ```
2411
+
2412
+ ---
2413
+
2414
+ ## 3. Constraint Design & Numerical Conditioning
2415
+
2416
+ ### Hard vs. Soft Constraints (Elastic Slack Variables)
2417
+
2418
+ Treating every business target as a strict **hard constraint** makes a model `"Infeasible"` as soon as demand exceeds capacity. Keep physical and legal invariants as hard constraints, and model non-rigid targets as **soft constraints** by adding non-negative slack variables ($s \ge 0$) with penalty weights $W$ in the objective:
2419
+
2420
+ | Target Type | Hard Constraint | Soft Constraint ($s \ge 0$) | Objective Penalty Term (Minimize) |
2421
+ | :--- | :--- | :--- | :--- |
2422
+ | **Lower bound** | $\text{lhs} \ge b$ | $\text{lhs} + s_{\text{short}} \ge b$ | $+ W \cdot s_{\text{short}}$ |
2423
+ | **Upper bound** | $\text{lhs} \le b$ | $\text{lhs} - s_{\text{excess}} \le b$ | $+ W \cdot s_{\text{excess}}$ |
2424
+ | **Target equality** | $\text{lhs} = b$ | $\text{lhs} + s_{\text{short}} - s_{\text{excess}} = b$ | $+ W_1 \cdot s_{\text{short}} + W_2 \cdot s_{\text{excess}}$ |
2425
+
2426
+ ```typescript
2427
+ import { Model, expr, minimize } from "@ohtaman/washi";
2428
+
2429
+ const m = new Model("SoftConstraintCoverage");
2430
+ const assignedStaff = m.integer("assigned_staff", { lb: 0, ub: 4 }); // Max 4 staff available
2431
+ const shortage = m.continuous("shortage", { lb: 0 }); // Non-negative slack (s >= 0)
2432
+
2433
+ // Soft target: aim for 5 staff, allowing shortage > 0 if unavailable
2434
+ m.constraint(expr`${assignedStaff} + ${shortage} >= 5`, "target_5_staff");
2435
+
2436
+ // Penalize unmet shortage ($1,000) above regular wage ($100)
2437
+ m.objective(minimize(expr`100 * ${assignedStaff} + 1000 * ${shortage}`));
2438
+
2439
+ await m.solve();
2440
+ // assignedStaff.value === 4, shortage.value === 1 (returns best compromise instead of Infeasible)
2441
+ ```
2442
+
2443
+ > [!TIP]
2444
+ > **Scaling Penalty Weights ($W$)**: Choose $W$ larger than normal operational marginal costs (typically $10\times$ to $1{,}000\times$ unit cost), and avoid extreme constants such as $10^{12}$. Keeping the ratio between the largest and smallest coefficients within $10^5\text{–}10^6$ preserves floating-point numerical stability in LP/MIP solvers.
2445
+
2446
+ ### Symmetry Breaking for Identical Resources
2447
+
2448
+ When a model contains $K$ interchangeable resources—such as identical trucks, bins, or parallel machines—any feasible assignment has up to $K!$ equivalent permutations with the exact same objective value. Without symmetry breaking, a MIP solver explores redundant mirror-image subtrees before proving optimality.
2449
+
2450
+ Impose a canonical ordering ($u_0 \ge u_1 \ge \dots \ge u_{K-1}$) so identical resources are activated in index order:
2451
+
2452
+ ```typescript
2453
+ import { Model, expr } from "@ohtaman/washi";
2454
+
2455
+ const m = new Model("SymmetryBreaking");
2456
+ const numTrucks = 4;
2457
+ const truckUsed = m.binary(numTrucks, { prefix: "truck_used" });
2458
+
2459
+ // Only allow activating truck k+1 when truck k is also active
2460
+ for (let k = 0; k < numTrucks - 1; k++) {
2461
+ m.constraint(
2462
+ expr`${truckUsed[k]} >= ${truckUsed[k + 1]}`,
2463
+ `order_truck_${k}`
2464
+ );
1909
2465
  }
1910
- const visitConstrs = master.constraints;
2466
+ ```
1911
2467
 
1912
- // 2. Solve via Column Generation
1913
- const result = await master.solveColumnGeneration({
1914
- finalizeAsMIP: true,
1915
- pricing: async () => {
1916
- const sub = new Model("RoutePricing");
1917
- const a: Record<string, Var> = {};
1918
- const obj = new LinExpr();
1919
-
1920
- for (let i = 0; i < customers.length; i++) {
1921
- const cust = customers[i];
1922
- a[cust.id] = sub.binary(`v_${cust.id}`);
1923
- obj.addTerm(a[cust.id], visitConstrs[i].dual ?? 0);
1924
- }
2468
+ ---
1925
2469
 
1926
- sub.objective(maximize(obj));
2470
+ ## 4. Multi-Objective & MIP Stopping Design
1927
2471
 
1928
- // Capacity limit: sum(demand_i * a_i) <= vehicleCapacity
1929
- const load = customers.reduce((acc, c) => acc.add(a[c.id].mul(c.demand)), new LinExpr());
1930
- sub.constraint(expr`${load} <= ${vehicleCapacity}`);
2472
+ ### Weighted Sum vs. Lexicographic Two-Stage Optimization
1931
2473
 
1932
- await sub.solve();
2474
+ When balancing competing goals—such as minimizing total cost ($f_1$) while also minimizing peak workload ($f_2$)—two approaches are standard:
1933
2475
 
1934
- const coefficients: Record<string, number> = {};
1935
- for (const cust of customers) {
1936
- coefficients[`visit_${cust.id}`] = Math.round(a[cust.id].value ?? 0);
1937
- }
2476
+ - **Weighted Sum (Single Solve)**: Combine normalized terms into one objective, e.g., ``minimize(expr`${totalCost} + 50 * ${maxHours}`)``.
2477
+ - **Lexicographic (Hierarchical) Two-Stage Solve**: When the primary objective has strict priority, solve for $f_1$ first, add a constraint locking $f_1$ within an acceptable tolerance of its optimum $f_1^*$, and re-solve for $f_2$:
1938
2478
 
1939
- return {
1940
- cost: 1,
1941
- type: "Integer",
1942
- coefficients,
1943
- };
1944
- },
1945
- });
2479
+ ```typescript
2480
+ import { Model, expr, minimize } from "@ohtaman/washi";
2481
+
2482
+ const m = new Model("LexicographicTwoStage");
2483
+ const workers = ["Alice", "Bob"] as const;
2484
+ const wage = { Alice: 20, Bob: 20 };
2485
+ const hours = m.continuous(workers, { lb: 0, ub: 40 });
2486
+ const maxHours = m.continuous("max_hours", { lb: 0, ub: 40 });
2487
+
2488
+ const totalCost = expr`dot(${wage}, ${hours})`;
2489
+ m.constraint(expr`sum(${hours}) >= 40`, "required_hours");
2490
+ m.constraint(workers.map((w) => expr`${hours[w]} <= ${maxHours}`));
1946
2491
 
1947
- console.log("Optimal fleet size:", result.objectiveValue); // 3 vehicles
2492
+ // Stage 1: Minimize primary objective (total wage cost)
2493
+ m.objective(minimize(totalCost));
2494
+ await m.solve();
2495
+ const minCost = m.objectiveValue!;
2496
+
2497
+ // Stage 2: Keep cost within 1% of minCost and balance workload (minimize maxHours)
2498
+ m.constraint(expr`${totalCost} <= ${minCost * 1.01}`, "near_optimal_cost");
2499
+ m.objective(minimize(maxHours));
2500
+ await m.solve();
1948
2501
  ```
1949
2502
 
1950
- ### 2. Traveling Salesperson Problem (TSP) $\times$ Benders Decomposition (Lazy Subtour Elimination)
1951
- *(Full executable source: [`examples/node/14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts))*
2503
+ ### MIP Tail-Off & Optimality Gap Tolerances
1952
2504
 
1953
- * **Problem Structure**: Preventing isolated sub-loops (subtours) requires Subtour Elimination Constraints (SECs), which grow as $O(2^n)$ constraints for $n$ cities.
1954
- * **Benders Decomposition Formulation**:
1955
- * **Master Problem**: Solves the relaxed assignment problem (each city has 1 incoming and 1 outgoing edge).
1956
- * **Subproblem**: Evaluates the candidate tour graph for disconnected components. If isolated subtours exist, it lazily injects a Benders feasibility cut ($\sum_{i,j \in S} x_{ij} \le |S| - 1$) cutting off that cycle.
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**).
1957
2506
 
1958
- ```typescript
1959
- import { Model, expr, minimize, LinExpr, type Var } from "@ohtaman/washi";
2507
+ In interactive UIs and batch pipelines, combine `timeLimit` with business-meaningful tolerances in [`m.solve(options)`](docs/guide/objectives.md#solve-options-solveoptions):
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.
1960
2510
 
1961
- const n = cities.length;
1962
- const master = new Model("TSP_Master");
1963
- const x: Record<string, Var> = {};
1964
- const objExpr = new LinExpr();
2511
+ ---
1965
2512
 
1966
- for (let i = 0; i < n; i++) {
1967
- for (let j = 0; j < n; j++) {
1968
- if (i !== j) {
1969
- const v = master.binary(`x_${i}_${j}`);
1970
- x[`${i}_${j}`] = v;
1971
- objExpr.addTerm(v, dist(i, j));
1972
- }
1973
- }
1974
- }
1975
- master.objective(minimize(objExpr));
1976
-
1977
- // Degree constraints
1978
- for (let i = 0; i < n; i++) {
1979
- const outE = new LinExpr();
1980
- const inE = new LinExpr();
1981
- for (let j = 0; j < n; j++) {
1982
- if (i !== j) {
1983
- outE.addTerm(x[`${i}_${j}`], 1);
1984
- inE.addTerm(x[`${j}_${i}`], 1);
1985
- }
1986
- }
1987
- master.constraint(expr`${outE} == 1`, `out_${i}`);
1988
- master.constraint(expr`${inE} == 1`, `in_${i}`);
1989
- }
2513
+ ## 5. Decomposition Formulation Tips
1990
2514
 
1991
- // Solve with Benders lazy subtour elimination
1992
- const result = await master.solveBenders({
1993
- subproblem: () => {
1994
- const cycles = findCycles(n, (i, j) => (x[`${i}_${j}`].value ?? 0) > 0.5);
1995
- if (cycles.length === 1 && cycles[0].length === n) {
1996
- return null; // Single tour covers all cities
1997
- }
2515
+ When using [`solveColumnGeneration` or `solveBenders`](docs/guide/decomposition.md):
1998
2516
 
1999
- // Subtour detected: inject Benders feasibility cut for smallest cycle
2000
- const S = cycles.reduce((min, c) => (c.length < min.length ? c : min), cycles[0]);
2001
- const secExpr = new LinExpr();
2002
- for (const i of S) {
2003
- for (const j of S) {
2004
- if (i !== j) secExpr.addTerm(x[`${i}_${j}`], 1);
2005
- }
2006
- }
2007
- return {
2008
- kind: "feasibility",
2009
- constraint: expr`${secExpr} <= ${S.length - 1}`,
2010
- };
2011
- },
2012
- });
2013
- ```
2517
+ 1. **Set Covering (`>= 1`) vs. Set Partitioning (`== 1`) in Column Generation**:
2518
+ Formulating coverage constraints as inequalities (`>= 1`) rather than equalities (`== 1`) restricts dual shadow prices to $\pi_i \ge 0$, reducing dual oscillations and accelerating convergence whenever over-coverage can be pruned at no extra cost (e.g., Euclidean routing under the triangle inequality).
2519
+ 2. **Price-and-Branch (`finalizeAsMIP: true`) vs. Exact Branch-and-Price**:
2520
+ Solving the final Restricted Master Problem as a MIP over columns generated at the root LP relaxation (`finalizeAsMIP: true`) implements the **Price-and-Branch** heuristic—avoiding complex branching inside the pricing subproblem while producing high-quality integer solutions in practice.
2521
+ 3. **Multi-Cut Separation in Benders / Lazy Constraints**:
2522
+ When a separation callback detects multiple disconnected subtours or violated components in a candidate solution, returning cuts for **all** violated components in one batch reduces the number of master MIP re-solves (see [Traveling Salesperson (`examples/traveling-salesperson`)](docs/examples/traveling-salesperson.md)).
2014
2523
 
2015
2524
  ---
2016
2525
 
@@ -2025,8 +2534,9 @@ WaSHI is designed around a pluggable, decoupled solver architecture. You formula
2025
2534
  | Solver | Engine License | Problem Classes | Best For | Status in WaSHI |
2026
2535
  | :--- | :--- | :--- | :--- | :--- |
2027
2536
  | **[HiGHS](https://github.com/ERGO-Code/HiGHS)** | **MIT** | **LP, MIP, Convex QP** | Industrial-scale optimization, operations research, finance | **Built-in default** (zero configuration) |
2028
- | **[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 plugin (`@ohtaman/washi/solvers/z3`) |
2029
- | **[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 plugin (`@ohtaman/washi/solvers/glpk`) |
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`) |
2030
2540
  | **Mock** | **MIT** | *Any* | Ultra-fast unit testing in CI without loading WebAssembly | Built-in |
2031
2541
 
2032
2542
  ---
@@ -2039,20 +2549,25 @@ Specify the solver by name when creating your `Model`:
2039
2549
  // 1. Built-in HiGHS (default)
2040
2550
  const m1 = new Model({ solver: "highs" });
2041
2551
 
2042
- // 2. Z3 SMT solver
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
2043
2557
  import "@ohtaman/washi/solvers/z3";
2044
- const m2 = new Model({ solver: "z3" });
2558
+ const m3 = new Model({ solver: "z3" });
2045
2559
 
2046
- // 3. GLPK solver
2560
+ // 4. GLPK solver
2047
2561
  import "@ohtaman/washi/solvers/glpk";
2048
- const m3 = new Model({ solver: "glpk" });
2562
+ const m4 = new Model({ solver: "glpk" });
2049
2563
  ```
2050
2564
 
2051
2565
  ---
2052
2566
 
2053
2567
  ## Solver Guides
2054
2568
 
2055
- - [HiGHS Guide](docs/solvers/highs.md): Web Worker multithreading, MIP tolerances, and QP solving.
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`.
2056
2571
  - [Z3 Guide](docs/solvers/z3.md): SMT assertions, logic modeling, and Unsat Core analysis.
2057
2572
  - [GLPK Guide](docs/solvers/glpk.md): GLPK adapter, GPL-3.0 licensing considerations, and browser usage.
2058
2573
  - [Custom Solvers](docs/solvers/custom-solver.md): Step-by-step developer tutorial for integrating proprietary or cloud REST solvers.
@@ -2061,7 +2576,7 @@ const m3 = new Model({ solver: "glpk" });
2061
2576
 
2062
2577
  # HiGHS Solver Engine
2063
2578
 
2064
- **HiGHS** is high-performance mathematical optimization software developed at the University of Edinburgh ([ERGO-Code/HiGHS](https://github.com/ERGO-Code/HiGHS)). It is widely recognized as the state-of-the-art open-source solver for Linear Programming (LP), Mixed-Integer Programming (MIP), and Convex Quadratic Programming (QP).
2579
+ **HiGHS** is high-performance mathematical optimization software initiated at the University of Edinburgh ([highs.dev](https://highs.dev/) · [ERGO-Code/HiGHS](https://github.com/ERGO-Code/HiGHS)). It is widely recognized as the state-of-the-art open-source solver for Linear Programming (LP), Mixed-Integer Programming (MIP), and Convex Quadratic Programming (QP).
2065
2580
 
2066
2581
  In `@ohtaman/washi`, HiGHS runs entirely in WebAssembly compiled directly from official upstream source ([ERGO-Code/HiGHS](https://github.com/ERGO-Code/HiGHS)) using its native C API (`highs_c_api.h`), providing zero-config execution across Node.js, Web Workers, and browsers without third-party wrapper dependencies.
2067
2582
 
@@ -2071,32 +2586,12 @@ In `@ohtaman/washi`, HiGHS runs entirely in WebAssembly compiled directly from o
2071
2586
 
2072
2587
  - **Built-in & Zero-Config**: Bundled directly with `@ohtaman/washi` with zero external runtime dependencies. No separate peer dependency or C++ compiler required.
2073
2588
  - **Permissive MIT License**: 100% commercially friendly.
2074
- - **Web Worker Multithreading**: Automatically offloads intensive solving to background Web Workers in browser environments to avoid freezing the UI thread.
2589
+ - **Background Web Worker Execution**: Automatically offloads solving to a dedicated Web Worker in browser environments to avoid freezing the UI thread.
2075
2590
  - **Warm-Start Support (`initialValue`)**: Supports passing variable primal initial value hints (`initialValue`) to HiGHS `setSolution` for warm starting.
2076
2591
  - **Fast WASM Execution**: Runs the directly compiled 32-bit WebAssembly binary at near-native speed.
2077
2592
 
2078
2593
  ---
2079
2594
 
2080
- ## Architecture & WebAssembly Runtime
2081
-
2082
- 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.
2083
-
2084
- ### Callbacks & Solver Interactivity
2085
-
2086
- - **Progress Monitoring & Cancellation (Supported)**:
2087
- Through HiGHS's internal logging and interrupt hooks, WaSHI provides real-time progress callbacks (`onProgress`) and cooperative mid-solve cancellation via standard `AbortSignal`.
2088
- - **Dynamic Cuts / Lazy Constraints (Not Supported in WASM Wrapper)**:
2089
- The upstream WebAssembly wrapper intentionally excludes low-level native callback type 8 (`MIP lazy constraints`) due to WASM-to-JS boundary and synchronous memory safety constraints. For problems requiring subtour elimination or Benders decomposition, use an **iterative cutting-plane loop** (solve $\to$ detect violation $\to$ `model.constraint(...)` $\to$ re-solve).
2090
-
2091
- ### WebAssembly Asset Lifecycle & On-Demand Builds
2092
-
2093
- HiGHS's WebAssembly binary (`public/highs.wasm`) and runtime driver (`runtime.js`) are managed via `highs.config.json` with cryptographic SHA-256 verification:
2094
- - **Zero-Friction Verification**: Build and distribution pipelines run `node scripts/ensure-highs-wasm.mjs`, verifying local assets in milliseconds before bundling.
2095
- - **On-Demand Release Download**: When assets are missing or updated, `ensure-highs-wasm.mjs` automatically downloads verified binaries from official GitHub Release assets.
2096
- - **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`).
2097
-
2098
- ---
2099
-
2100
2595
  ## Supported Problem Classes
2101
2596
 
2102
2597
  ### 1. Linear Programming (LP)
@@ -2121,7 +2616,7 @@ const count = model.integer("count", { lb: 0, ub: 50 });
2121
2616
  ```
2122
2617
 
2123
2618
  ### 3. Convex Quadratic Programming (QP)
2124
- Solves quadratic objective functions subject to linear constraints:
2619
+ Solves continuous models with convex quadratic objective functions subject to linear constraints:
2125
2620
 
2126
2621
  ```typescript
2127
2622
  // Minimize risk/variance uniformly using expr:
@@ -2132,6 +2627,9 @@ model.objective(minimize(expr`0.5 * ${x}^2 + 0.5 * ${y}^2`));
2132
2627
  // model.objective(minimize(quadObj));
2133
2628
  ```
2134
2629
 
2630
+ > [!NOTE]
2631
+ > **Continuous Convex QP Only**: HiGHS solves Convex QP models where **all** model variables are continuous (`m.continuous`), with a positive semi-definite quadratic matrix $\mathbf{Q}$ when minimizing (or negative semi-definite when maximizing). Mixed-Integer Quadratic Programming (**MIQP**—any model combining a quadratic objective with `Integer`, `Binary`, or `BoolVar` variables) and quadratic constraints (**QCP**) are not supported; to model products of binary decisions in MILP, see [Formulation Patterns & Tips](docs/guide/formulation-tips.md).
2632
+
2135
2633
  ---
2136
2634
 
2137
2635
  ## Solver Options
@@ -2143,8 +2641,8 @@ const controller = new AbortController();
2143
2641
 
2144
2642
  await model.solve({
2145
2643
  timeLimit: 60.0, // Maximum solve time in seconds
2146
- mipGap: 0.001, // Terminate when within 0.1% of global optimality (alias: relGap)
2147
- absGap: 1.0, // Absolute MIP optimality gap tolerance
2644
+ relativeGap: 0.001, // Terminate when within 0.1% of global optimality
2645
+ absoluteGap: 1.0, // Absolute MIP optimality gap tolerance
2148
2646
  presolve: "on", // Presolve control ("on" | "off" | "choose")
2149
2647
  outputFlag: true, // Output internal simplex / branch-and-bound logs (output_flag)
2150
2648
  signal: controller.signal,
@@ -2152,6 +2650,14 @@ await model.solve({
2152
2650
  console.log(`Elapsed: ${ev.elapsedTime.toFixed(1)}s, Best: ${ev.objectiveValue}`);
2153
2651
  },
2154
2652
  });
2653
+
2654
+ // Always check hasPrimalSolution when timeLimit or AbortSignal is used:
2655
+ if (model.hasPrimalSolution) {
2656
+ console.log(
2657
+ `Usable solution (${model.status}, termination: ${model.terminationStatus}):`,
2658
+ `obj = ${model.objectiveValue}, gap = ${((model.relativeGap ?? 0) * 100).toFixed(2)}%`
2659
+ );
2660
+ }
2155
2661
  ```
2156
2662
 
2157
2663
  ---
@@ -2176,6 +2682,197 @@ const syncModel = new Model({
2176
2682
 
2177
2683
  ---
2178
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
+
2700
+ ## References & Upstream Links
2701
+
2702
+ - **Official Website**: [https://highs.dev/](https://highs.dev/)
2703
+ - **Official Documentation**: [https://ergo-code.github.io/HiGHS/](https://ergo-code.github.io/HiGHS/)
2704
+ - **Source Repository**: [ERGO-Code/HiGHS](https://github.com/ERGO-Code/HiGHS) (MIT License)
2705
+ - **Academic Citation**: If you cite HiGHS in academic or technical publications, please reference the foundational paper requested by the HiGHS authors:
2706
+ > Q. Huangfu and J. A. J. Hall, *"Parallelizing the dual revised simplex method"*, Mathematical Programming Computation, 10 (1), 119–142, 2018. DOI: [10.1007/s12532-017-0130-5](https://doi.org/10.1007/s12532-017-0130-5)
2707
+
2708
+ ---
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
+
2179
2876
  # Z3 SMT Solver Engine
2180
2877
 
2181
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.
@@ -2201,6 +2898,9 @@ npm install z3-solver
2201
2898
  3. **Exact Mathematical Guarantees**:
2202
2899
  Z3 can perform exact rational arithmetic without floating-point inaccuracies.
2203
2900
 
2901
+ > [!TIP]
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()`.
2903
+
2204
2904
  ---
2205
2905
 
2206
2906
  ## Basic Usage
@@ -2246,7 +2946,7 @@ if (result.status === "Unsat") {
2246
2946
 
2247
2947
  ## Browser Security Note
2248
2948
 
2249
- 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.
2250
2950
 
2251
2951
  ## Runtime Failures and Thread Cleanup
2252
2952
 
@@ -2328,7 +3028,7 @@ GLPK return codes are mapped strictly to WaSHI `SolverStatus`:
2328
3028
 
2329
3029
  This guide describes how to build, test, and distribute custom solver plugins for **WaSHI** (`@ohtaman/washi`).
2330
3030
 
2331
- WaSHI features a pluggable, decoupled solver architecture. Core `@ohtaman/washi` bundles only the zero-config HiGHS WASM engine and a Mock solver. 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.
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.
2332
3032
 
2333
3033
  ---
2334
3034
 
@@ -2339,6 +3039,7 @@ graph TD
2339
3039
  A[WaSHI Model] --> B[Solver Registry Map Symbol.for]
2340
3040
  B --> C[HiGHS WASM Engine Core]
2341
3041
  B --> D[Mock Solver Core]
3042
+ B --> H[Pumpkin WASM Plugin @ohtaman/washi/solvers/pumpkin]
2342
3043
  B --> E[GLPK Plugin @ohtaman/washi/solvers/glpk]
2343
3044
  B --> F[Z3 SMT Plugin @ohtaman/washi/solvers/z3]
2344
3045
  B --> G[Your Custom Solver Plugin]
@@ -2395,7 +3096,7 @@ export interface Solver {
2395
3096
  * Main solve method for LP, MIP, QP, and SMT optimization models.
2396
3097
  *
2397
3098
  * @param modelData Typed in-memory model structure (variables, constraints, objective, sense, boolVars, logicalConstraints)
2398
- * @param options Runtime execution options (timeLimit, mipGap, verbose, signal, onProgress, etc.)
3099
+ * @param options Runtime execution options (timeLimit, relativeGap, absoluteGap, verbose, signal, onProgress, etc.)
2399
3100
  */
2400
3101
  solve(
2401
3102
  modelData: SolveModelData,
@@ -2445,7 +3146,7 @@ export interface SolveModelData extends CheckModelData {
2445
3146
 
2446
3147
  Custom solvers declare their supported features using `capabilities`. Before dispatching `solve()` or `check()`, `Model` validates:
2447
3148
  - `supportsQP === false` when the objective contains quadratic terms (`QuadExpr`),
2448
- - when the model contains logical constraints (`m.logicalConstraints`) and the solver does not support SMT (`supportsSMT !== true`), `Model` automatically linearizes them into equivalent 0-1 MIP binary variables and linear constraints via `linearizeModelForMip`, and
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
2449
3150
  - `supportsWarmStart !== true` when any variable has a primal `initialValue` set.
2450
3151
 
2451
3152
  ```typescript
@@ -2462,6 +3163,9 @@ export interface SolverCapabilities {
2462
3163
  /** Supports satisfiability modulo theories / boolean logic constraints */
2463
3164
  supportsSMT?: boolean;
2464
3165
 
3166
+ /** Supports native boolean/propositional logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`) without SMT continuous theories */
3167
+ supportsLogicalConstraints?: boolean;
3168
+
2465
3169
  /** Supports extracting an unsatisfiable core (conflicting constraint subset) */
2466
3170
  supportsUnsatCore?: boolean;
2467
3171
 
@@ -2479,8 +3183,11 @@ export interface SolverOptions {
2479
3183
  /** Time limit in seconds */
2480
3184
  timeLimit?: number;
2481
3185
 
2482
- /** Relative MIP optimality gap tolerance */
2483
- mipGap?: number;
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;
2484
3191
 
2485
3192
  /** Enable solver console logging */
2486
3193
  verbose?: boolean;
@@ -2498,7 +3205,7 @@ export interface SolverOptions {
2498
3205
 
2499
3206
  ### Optional LP Serialization & Symbol-Mapping Helpers
2500
3207
 
2501
- Solvers that consume structured JS/WASM data (such as `GLPKSolver` and `Z3Solver`) work directly with `SolveModelData` / `CheckModelData`.
3208
+ Solvers that consume structured JS/WASM data (such as `PumpkinSolver`, `GLPKSolver`, and `Z3Solver`) work directly with `SolveModelData` / `CheckModelData`.
2502
3209
  If your adapter targets a backend that requires CPLEX/HiGHS LP text or restricted identifier syntax, WaSHI exports opt-in helpers:
2503
3210
 
2504
3211
  - `generateLpString(modelData): LpExportResult` — serializes `modelData` into a CPLEX LP format string (`lpString`) along with collision-safe symbol lookup maps (`nameToVar`, `nameToConstraint`).
@@ -2541,13 +3248,10 @@ export interface SolverResult {
2541
3248
  objectiveBound?: number;
2542
3249
 
2543
3250
  /** Relative MIP optimality gap when provided by the solver */
2544
- relGap?: number;
2545
-
2546
- /** Alias for relGap: relative MIP optimality gap when provided by the solver */
2547
- mipGap?: number;
3251
+ relativeGap?: number;
2548
3252
 
2549
3253
  /** Absolute MIP optimality gap |objectiveValue - objectiveBound| (computed automatically when both are finite) */
2550
- absGap?: number;
3254
+ absoluteGap?: number;
2551
3255
 
2552
3256
  /** Variable primal values keyed by canonical variable name (non-finite values are ignored) */
2553
3257
  values: Record<string, number>;
@@ -2643,7 +3347,8 @@ export class CloudSolver implements Solver {
2643
3347
  body: JSON.stringify({
2644
3348
  lp: lpString,
2645
3349
  timeLimit: options.timeLimit,
2646
- mipGap: options.mipGap,
3350
+ relativeGap: options.relativeGap,
3351
+ absoluteGap: options.absoluteGap,
2647
3352
  }),
2648
3353
  signal: options.signal,
2649
3354
  });
@@ -2841,7 +3546,7 @@ describe("Custom Solver Integration", () => {
2841
3546
  const status = await model.solve();
2842
3547
  expect(status).toBe("Optimal");
2843
3548
  expect(x.value).toBe(2);
2844
- const c1 = model.getConstraintByName("budget");
3549
+ const c1 = model.constraints.get("budget");
2845
3550
  expect(c1?.dual).toBe(2);
2846
3551
  } finally {
2847
3552
  fetchSpy.mockRestore();
@@ -2854,21 +3559,22 @@ describe("Custom Solver Integration", () => {
2854
3559
 
2855
3560
  # Examples & API Finder
2856
3561
 
2857
- Explore runnable optimization and logic formulations built with WaSHI. Every example can be executed directly inside its documentation page, or edited in the [Playground](https://ohtaman.github.io/washi/demo/).
3562
+ Explore runnable optimization and logic formulations built with WaSHI. Every example can be executed directly inside its documentation page, or edited in the [Playground](https://washi.ohtaman.dev/demo/).
2858
3563
 
2859
3564
  ## Examples
2860
3565
 
2861
- | Example | Problem Class | Solver | Key WaSHI APIs | Description | Code Editor |
3566
+ | Example | Problem Class | Solver | Key WaSHI APIs | Description | Playground / Guide |
2862
3567
  | :--- | :--- | :--- | :--- | :--- | :--- |
2863
- | **[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://ohtaman.github.io/washi/demo/?preset=production) |
2864
- | **[0-1 Knapsack](docs/examples/knapsack.md)** | Binary MIP | HiGHS | `m.binary(keys)`, `sum()`, `m.constraint()` | 1D dictionary of `Binary` variables and linear aggregation over item arrays. | [Playground](https://ohtaman.github.io/washi/demo/?preset=knapsack) |
2865
- | **[Transportation Network](docs/examples/transportation.md)** | LP | HiGHS | `m.continuous(rows, cols)`, `dot()`, `m.constraint()` | 2D matrix indexing (`ship[factory][store]`) and row/column flow balance constraints. | [Playground](https://ohtaman.github.io/washi/demo/?preset=transportation) |
2866
- | **[Diet & Sensitivity Analysis](docs/examples/diet-sensitivity.md)** | LP | HiGHS | `constr.dual`, `constr.slack`, `var.reducedCost` | Reading shadow prices (bottlenecks), constraint surpluses, and reduced costs after solving. | [Playground](https://ohtaman.github.io/washi/demo/?preset=diet_sensitivity) |
2867
- | **[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://ohtaman.github.io/washi/demo/?preset=shift_scheduling) |
2868
- | **[E-Commerce Coupon Optimizer](docs/examples/ecommerce-coupons.md)** | Indicator MIP | HiGHS | `m.indicator()`, `sum()`, `m.constraint()` | Checkout optimizer using `m.indicator()` for minimum spend thresholds, exclusive vs. stackable rules, and smart filler add-on suggestions. | [Playground](https://ohtaman.github.io/washi/demo/?preset=cart_coupon) |
2869
- | **[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://ohtaman.github.io/washi/demo/?preset=portfolio_qp) |
2870
- | **[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://ohtaman.github.io/washi/demo/?preset=smt_sat_scheduling) |
2871
- | **[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://ohtaman.github.io/washi/demo/?preset=conflict_diagnosis_unsat) |
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) |
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) |
3570
+ | **[Transportation Network](docs/examples/transportation.md)** | LP | HiGHS | `m.continuous(rows, cols)`, `expr` (`sum`, `dot`), `m.constraint()` | 2D matrix indexing (`ship[factory][store]`) and row/column flow balance constraints. | [Playground](https://washi.ohtaman.dev/demo/?preset=transportation) |
3571
+ | **[Diet & Sensitivity Analysis](docs/examples/diet-sensitivity.md)** | LP | HiGHS | `constr.dual`, `constr.slack`, `var.reducedCost` | Reading shadow prices (bottlenecks), constraint surpluses, and reduced costs after solving. | [Playground](https://washi.ohtaman.dev/demo/?preset=diet_sensitivity) |
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) |
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) |
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) |
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) |
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) |
2872
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) |
2873
3579
  | **[Traveling Salesperson (TSP)](docs/examples/traveling-salesperson.md)** | Combinatorial OR / Benders | HiGHS | `m.solveBenders()`, `subproblem` | Subtour elimination on degree-assignment relaxation using dynamic Benders feasibility cuts. | [Decomposition Guide](docs/guide/decomposition.md) |
2874
3580
 
@@ -2881,15 +3587,18 @@ Looking for a specific modeling method or solver capability? Jump straight to th
2881
3587
  | ``m.constraint(expr`...`)`` | Tagged template literal constraints | [Production Planning](docs/examples/production.md) | [`01-production-planning.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/01-production-planning.ts) |
2882
3588
  | `m.binary(keys)` / `m.continuous(keys)` | 1D dictionary of indexed variables | [0-1 Knapsack](docs/examples/knapsack.md) | [`02-knapsack-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/02-knapsack-problem.ts) |
2883
3589
  | `m.continuous(rows, cols)` / `m.binary(rows, cols)` | 2D matrix of indexed variables | [Transportation Network](docs/examples/transportation.md), [Shift Scheduling](docs/examples/shift-scheduling.md) | [`09-transportation-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts) |
2884
- | `dot(matrix, vars2d)` / `dot(vector, vars)` | Fast vector/matrix dot product | [Transportation Network](docs/examples/transportation.md), [Portfolio Optimization](docs/examples/portfolio-qp.md) | [`09-transportation-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts) |
3590
+ | ``expr`dot(${A}, ${X})` `` / `dot(A, X)` | Fast vector/matrix dot product | [Transportation Network](docs/examples/transportation.md), [Portfolio Optimization](docs/examples/portfolio-qp.md) | [`09-transportation-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts) |
2885
3591
  | `constr.dual` & `constr.slack` | Shadow prices & constraint surpluses | [Diet & Sensitivity Analysis](docs/examples/diet-sensitivity.md) | [`10-diet-sensitivity.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/10-diet-sensitivity.ts) |
2886
3592
  | `var.reducedCost` | Variable reduced costs in LP | [Diet & Sensitivity Analysis](docs/examples/diet-sensitivity.md) | [`10-diet-sensitivity.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/10-diet-sensitivity.ts) |
2887
3593
  | `m.indicator()` | Big-M conditional constraints (`binVar => constr`) | [E-Commerce Coupon Optimizer](docs/examples/ecommerce-coupons.md) | [`12-ecommerce-coupon-optimizer.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/12-ecommerce-coupon-optimizer.ts) |
2888
3594
  | `new QuadExpr()` | Convex quadratic objectives ($x^T Q x$) | [Portfolio Optimization](docs/examples/portfolio-qp.md) | [`03-portfolio-qp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/03-portfolio-qp.ts) |
2889
- | `m.bool()` & `.implies()` | Propositional logic & SMT rules | [SMT Security Policies](docs/examples/smt-security.md) | [`04-smt-security-rules.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts) |
3595
+ | `m.bool()` & `implies()` | Propositional logic & SMT rules | [SMT Security Policies](docs/examples/smt-security.md) | [`04-smt-security-rules.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts) |
2890
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) |
2891
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) |
2892
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) |
2893
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) |
2894
3603
 
2895
3604
  ## Running Examples Locally in Node.js
@@ -2908,6 +3617,9 @@ npx tsx examples/node/09-transportation-problem.ts
2908
3617
  npx tsx examples/node/10-diet-sensitivity.ts
2909
3618
  npx tsx examples/node/11-shift-scheduling.ts
2910
3619
  npx tsx examples/node/12-ecommerce-coupon-optimizer.ts
3620
+ npx tsx examples/node/13-vehicle-routing-column-generation.ts
3621
+ npx tsx examples/node/14-traveling-salesperson-benders.ts
3622
+ npx tsx examples/node/15-project-scheduling-cp.ts
2911
3623
  ```
2912
3624
 
2913
3625
  ---
@@ -2916,7 +3628,7 @@ npx tsx examples/node/12-ecommerce-coupon-optimizer.ts
2916
3628
 
2917
3629
  | Problem Class | Solver | Key APIs | Links |
2918
3630
  | :--- | :--- | :--- | :--- |
2919
- | Linear / Integer Programming (LP / MIP) | HiGHS (default) | `m.integer()`, `m.constraint()`, `expr` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=production">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/01-production-planning.ts">Source Code</a></li></ul> |
3631
+ | Linear / Integer Programming (LP / MIP) | HiGHS (default) | `m.integer()`, `m.constraint()`, `expr` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=production">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/01-production-planning.ts">Source Code</a></li></ul> |
2920
3632
 
2921
3633
  Production planning is a classic Linear Programming problem: determine the optimal quantity of each product to manufacture in order to maximize total profit while respecting resource constraints (raw materials, machine time, labor hours).
2922
3634
 
@@ -2946,9 +3658,9 @@ async function runProductionOptimization() {
2946
3658
  // Objective: Maximize total profit ($45 per chair, $80 per table)
2947
3659
  m.objective(maximize(expr`45 * ${chairs} + 80 * ${tables}`));
2948
3660
 
2949
- // Resource constraints: declarative formulas via expr and fluent constraint()
2950
- m.constraint(expr`5 * ${chairs} + 20 * ${tables} <= 400`, "mahogany_limit")
2951
- .constraint(expr`10 * ${chairs} + 15 * ${tables} <= 450`, "labor_limit");
3661
+ // Resource constraints: declarative formulas via expr and constraint()
3662
+ m.constraint(expr`5 * ${chairs} + 20 * ${tables} <= 400`, "mahogany_limit");
3663
+ m.constraint(expr`10 * ${chairs} + 15 * ${tables} <= 450`, "labor_limit");
2952
3664
 
2953
3665
  const status = await m.solve();
2954
3666
 
@@ -2966,7 +3678,7 @@ runProductionOptimization();
2966
3678
 
2967
3679
  | Problem Class | Solver | Key APIs | Links |
2968
3680
  | :--- | :--- | :--- | :--- |
2969
- | 0-1 Binary MIP | HiGHS (default) | `m.binary()`, `m.constraint()`, `expr`, `maximize`, `dot` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=knapsack">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/02-knapsack-problem.ts">Source Code</a></li></ul> |
3681
+ | 0-1 Binary MIP | HiGHS (default) | `m.binary()`, `m.constraint()`, `expr` (`dot`), `maximize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=knapsack">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/02-knapsack-problem.ts">Source Code</a></li></ul> |
2970
3682
 
2971
3683
  The 0-1 Knapsack problem is an essential combinatorial optimization problem: given a set of items, each with a weight and a value, determine which items to include in a collection so that the total weight does not exceed a given limit and the total value is maximized.
2972
3684
 
@@ -2983,7 +3695,7 @@ $$\begin{aligned}
2983
3695
  ## Implementation in WaSHI
2984
3696
 
2985
3697
  ```typescript
2986
- import { Model, maximize, dot, expr } from "@ohtaman/washi";
3698
+ import { Model, maximize, expr } from "@ohtaman/washi";
2987
3699
 
2988
3700
  async function solveKnapsack() {
2989
3701
  const m = new Model("Knapsack");
@@ -3003,17 +3715,18 @@ async function solveKnapsack() {
3003
3715
  const values = Object.fromEntries(items.map((it) => [it.name, it.value]));
3004
3716
  const weights = Object.fromEntries(items.map((it) => [it.name, it.weight]));
3005
3717
 
3006
- // Maximize total value via dot product
3007
- m.objective(maximize(dot(values, x)));
3718
+ // Maximize total value via dot() inside expr
3719
+ m.objective(maximize(expr`dot(${values}, ${x})`));
3008
3720
 
3009
- // Weight capacity constraint using natural expr and constraint() syntax
3010
- m.constraint(expr`${dot(weights, x)} <= ${maxCapacity}`, "capacity_limit");
3721
+ // Weight capacity constraint using expr and constraint()
3722
+ m.constraint(expr`dot(${weights}, ${x}) <= ${maxCapacity}`, "capacity_limit");
3011
3723
 
3012
3724
  const status = await m.solve();
3013
3725
 
3014
3726
  console.log(`Status: ${status}`);
3015
3727
  console.log(`Max Total Value: $${m.objectiveValue}`);
3016
- console.log("Selected Items:", m.getValues(x));
3728
+ const packed = items.filter((it) => x[it.name].value === 1).map((it) => it.name);
3729
+ console.log("Packed Items:", packed.join(", "));
3017
3730
  }
3018
3731
 
3019
3732
  solveKnapsack();
@@ -3025,7 +3738,7 @@ solveKnapsack();
3025
3738
 
3026
3739
  | Problem Class | Solver | Key APIs | Links |
3027
3740
  | :--- | :--- | :--- | :--- |
3028
- | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=transportation">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts">Source Code</a></li></ul> |
3741
+ | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=transportation">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts">Source Code</a></li></ul> |
3029
3742
 
3030
3743
  The transportation problem is one of the most fundamental network optimization models: determine how many units to ship from each supply origin (factory) to each destination (store) to minimize total shipping cost while respecting factory supply limits and meeting store demands.
3031
3744
 
@@ -3056,7 +3769,7 @@ $$\begin{aligned}
3056
3769
  ## Implementation in WaSHI
3057
3770
 
3058
3771
  ```typescript
3059
- import { Model, sum, dot, minimize, expr } from "@ohtaman/washi";
3772
+ import { Model, minimize, expr } from "@ohtaman/washi";
3060
3773
 
3061
3774
  const factories = ["Tokyo", "Nagoya", "Osaka"] as const;
3062
3775
  const stores = ["North", "East", "West", "South"] as const;
@@ -3070,51 +3783,78 @@ const shippingCost = {
3070
3783
  const supplies = { Tokyo: 120, Nagoya: 100, Osaka: 80 };
3071
3784
  const demands = { North: 70, East: 90, West: 60, South: 60 };
3072
3785
 
3073
- async function runTransportation() {
3786
+ async function solveScenario(label: string, cap: typeof supplies) {
3074
3787
  const m = new Model("TransportationNetwork");
3075
3788
 
3076
3789
  // 1. Create 2D continuous variables: ship[factory][store] >= 0
3077
3790
  const ship = m.continuous([...factories], [...stores], { lb: 0 });
3078
3791
 
3079
3792
  // 2. Objective: Minimize total shipping cost across all routes via 2D dot product
3080
- m.objective(minimize(dot(shippingCost, ship)));
3793
+ m.objective(minimize(expr`dot(${shippingCost}, ${ship})`));
3081
3794
 
3082
- // 3. Supply constraints (row sums): outgoing from f <= supplies[f]
3083
- for (const f of factories) {
3084
- m.constraint(
3085
- expr`${sum(stores, (s) => ship[f][s])} <= ${supplies[f]}`,
3086
- `supply_${f}`
3087
- );
3088
- }
3795
+ // 3. Supply constraints (row sums): outgoing from f <= cap[f]
3796
+ const supplyConstrs = Object.fromEntries(
3797
+ factories.map((f) => [
3798
+ f,
3799
+ m.constraint(expr`sum(${ship[f]}) <= ${cap[f]}`, `supply_${f}`),
3800
+ ])
3801
+ );
3089
3802
 
3090
3803
  // 4. Demand constraints (column sums): incoming to s >= demands[s]
3091
- for (const s of stores) {
3092
- m.constraint(
3093
- expr`${sum(factories, (f) => ship[f][s])} >= ${demands[s]}`,
3094
- `demand_${s}`
3095
- );
3096
- }
3804
+ const demandConstrs = Object.fromEntries(
3805
+ stores.map((s) => [
3806
+ s,
3807
+ m.constraint(
3808
+ expr`sum(${factories}, ${(f) => ship[f][s]}) >= ${demands[s]}`,
3809
+ `demand_${s}`
3810
+ ),
3811
+ ])
3812
+ );
3097
3813
 
3098
3814
  const status = await m.solve();
3099
- console.log(`Status: ${status}, Total Shipping Cost: $${m.objectiveValue}`);
3815
+ console.log(`[${label}] Status: ${status}, Total Shipping Cost: $${m.objectiveValue}`);
3100
3816
  for (const f of factories) {
3817
+ const dual = supplyConstrs[f].dual ?? 0;
3101
3818
  const routes = stores
3102
3819
  .map((s) => `${s}:${Math.round(ship[f][s].value ?? 0)}`)
3103
3820
  .join(", ");
3104
- console.log(` ${f.padEnd(7)} -> ${routes}`);
3821
+ console.log(` ${f.padEnd(7)} -> ${routes} (supply dual: $${dual}/u)`);
3105
3822
  }
3823
+ const demandDuals = stores
3824
+ .map((s) => `${s}:$${demandConstrs[s].dual ?? 0}`)
3825
+ .join(", ");
3826
+ console.log(` Marginal Delivered Cost (demand duals) -> ${demandDuals}`);
3827
+ }
3828
+
3829
+ async function runTransportation() {
3830
+ // Scenario A: Baseline capacities ($920)
3831
+ await solveScenario("Scenario A: Baseline", supplies);
3832
+
3833
+ // Scenario B: Tokyo capacity reduced (120 -> 80) due to maintenance ($1,000)
3834
+ await solveScenario("Scenario B: Tokyo Maintenance", {
3835
+ Tokyo: 80,
3836
+ Nagoya: 120,
3837
+ Osaka: 100,
3838
+ });
3106
3839
  }
3107
3840
 
3108
3841
  runTransportation();
3109
3842
  ```
3110
3843
 
3844
+ ## Practical Notes
3845
+
3846
+ - **Interpreting Supply & Demand Shadow Prices (`.dual`)**:
3847
+ - **`demand_s.dual` ($\ge 0$)**: The marginal delivered cost of supplying 1 additional unit to store $s$.
3848
+ - **`supply_f.dual` ($\le 0$)**: How much total network shipping cost would decrease if factory $f$'s capacity were expanded by 1 unit. In Scenario B, when Tokyo is constrained at 80 units, `supply_Tokyo.dual` becomes negative (`-$2/u`), indicating that each extra unit of capacity in Tokyo saves \$2 by avoiding rerouting through Nagoya.
3849
+ - **Total Supply vs. Total Demand ($\sum \text{Supply}_f \ge \sum \text{Demand}_s$)**: If store demands exceed aggregate factory capacity, the hard demand constraints become `"Infeasible"`. In production logistics systems, add an elastic "spot-carrier / backorder" variable $u_s \ge 0$ to each store's demand constraint ($\sum_f x_{f,s} + u_s \ge \text{Demand}_s$) with a high penalty cost so the solver allocates scarce inventory optimally rather than failing.
3850
+
3111
3851
  ---
3112
3852
 
3113
3853
  # Diet Problem & Sensitivity Analysis (LP Duals & Slacks)
3114
3854
 
3115
3855
  | Problem Class | Solver | Key APIs | Links |
3116
3856
  | :--- | :--- | :--- | :--- |
3117
- | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=diet_sensitivity">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/10-diet-sensitivity.ts">Source Code</a></li></ul> |
3857
+ | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr` (`dot`), `minimize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=diet_sensitivity">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/10-diet-sensitivity.ts">Source Code</a></li></ul> |
3118
3858
 
3119
3859
  When solving a Linear Programming model, the optimal variable values (`var.value`) are only half the story. In practice, decision-makers need to know:
3120
3860
 
@@ -3138,7 +3878,7 @@ We choose daily servings ($0 \le x_i \le 4$) among 6 food items to meet 4 daily
3138
3878
  ## Implementation in WaSHI
3139
3879
 
3140
3880
  ```typescript
3141
- import { Model, minimize, dot, expr } from "@ohtaman/washi";
3881
+ import { Model, minimize, expr } from "@ohtaman/washi";
3142
3882
 
3143
3883
  const foods = [
3144
3884
  { name: "Oats", cost: 0.60, calories: 150, protein: 5, calcium: 20, iron: 1.8 },
@@ -3161,14 +3901,16 @@ async function runDietSensitivity() {
3161
3901
  const calcs = Object.fromEntries(foods.map((f) => [f.name, f.calcium]));
3162
3902
  const irons = Object.fromEntries(foods.map((f) => [f.name, f.iron]));
3163
3903
 
3164
- // Objective: Minimize total daily cost via dot product
3165
- m.objective(minimize(dot(costs, srv)));
3904
+ // Objective: Minimize total daily cost via dot() inside expr
3905
+ m.objective(minimize(expr`dot(${costs}, ${srv})`));
3166
3906
 
3167
3907
  // Nutritional constraints defined declaratively with expr and constraint()
3168
- m.constraint(expr`${dot(cals, srv)} >= 2000`, "min_calories")
3169
- .constraint(expr`${dot(prots, srv)} >= 105`, "min_protein")
3170
- .constraint(expr`${dot(calcs, srv)} >= 1000`, "min_calcium")
3171
- .constraint(expr`${dot(irons, srv)} >= 18`, "min_iron");
3908
+ const nutConstraints = [
3909
+ m.constraint(expr`dot(${cals}, ${srv}) >= 2000`, "min_calories"),
3910
+ m.constraint(expr`dot(${prots}, ${srv}) >= 105`, "min_protein"),
3911
+ m.constraint(expr`dot(${calcs}, ${srv}) >= 1000`, "min_calcium"),
3912
+ m.constraint(expr`dot(${irons}, ${srv}) >= 18`, "min_iron"),
3913
+ ];
3172
3914
 
3173
3915
  const status = await m.solve();
3174
3916
 
@@ -3179,11 +3921,8 @@ async function runDietSensitivity() {
3179
3921
  console.log(` ${f.name.padEnd(8)}: value=${v.value?.toFixed(2)}, reducedCost=${v.reducedCost?.toFixed(4)}`);
3180
3922
  }
3181
3923
  console.log("--- Nutritional Constraints (Dual & Slack) ---");
3182
- for (const name of ["min_calories", "min_protein", "min_calcium", "min_iron"]) {
3183
- const c = m.getConstraintByName(name);
3184
- if (c) {
3185
- console.log(` ${c.name.padEnd(13)}: dual=$${c.dual?.toFixed(4)}, slack=${Math.abs(c.slack ?? 0).toFixed(2)}`);
3186
- }
3924
+ for (const c of nutConstraints) {
3925
+ console.log(` ${c.name.padEnd(13)}: dual=$${c.dual?.toFixed(4)}, slack=${Math.abs(c.slack ?? 0).toFixed(2)}`);
3187
3926
  }
3188
3927
  }
3189
3928
 
@@ -3194,7 +3933,9 @@ runDietSensitivity();
3194
3933
 
3195
3934
  - **Bottleneck constraints (`slack == 0`, `dual > 0`):** Calories (`2000 kcal`) and Iron (`18 mg`) are tight at their lower bounds. Increasing the daily Iron requirement by 1 mg increases the minimum daily diet cost by **$0.3241**.
3196
3935
  - **Constraints with surplus (`slack > 0`, `dual == 0`):** Protein (`+46.46 g` surplus) and Calcium (`+483.02 mg` surplus) are already exceeded with room to spare, so their shadow prices are `$0`.
3197
- - **Reduced cost (`Salmon`):** Unselected `Salmon` (`0.00` servings) has a reduced cost of `+1.5125`, meaning its price per serving would need to drop by at least **$1.51** before it enters the optimal daily menu.
3936
+ - **Reduced cost at lower bound (`Salmon`):** Unselected `Salmon` (`0.00` servings) has a reduced cost of `+1.5125`, meaning its price per serving would need to drop by at least **$1.51** before it enters the optimal daily menu.
3937
+ - **Negative reduced cost at upper bound (`Oats`, `Eggs`):** Both `Oats` (`reducedCost = -0.2581`) and `Eggs` (`reducedCost = -0.0887`) are pinned against their upper serving cap (`ub = 4.0`). In a minimization LP, a negative reduced cost on an upper-bounded variable tells you how much the total objective would **decrease** per unit increase in `ub`—raising the daily cap on `Oats` from 4 to 5 servings would save **$0.26/day**.
3938
+ - **Basis stability range:** Shadow prices (`dual`) and reduced costs (`reducedCost`) represent local marginal rates of change within the current optimal simplex basis. If a right-hand side or bound changes enough to trigger a basis change (for example, once another variable hits its bound), the marginal rate shifts to a new piece of the piecewise-linear optimal cost curve.
3198
3939
 
3199
3940
  ---
3200
3941
 
@@ -3202,7 +3943,7 @@ runDietSensitivity();
3202
3943
 
3203
3944
  | Problem Class | Solver | Key APIs | Links |
3204
3945
  | :--- | :--- | :--- | :--- |
3205
- | Binary MIP & SMT Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `m.constraint()`, `expr`, `minimize`, `dot`, `m.check()` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://ohtaman.github.io/washi/demo/?preset=shift_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/11-shift-scheduling.ts">Source Code</a></li></ul> |
3946
+ | Binary MIP & SMT Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/11-shift-scheduling.ts">Source Code</a></li></ul> |
3206
3947
 
3207
3948
  Staff shift scheduling is a classic real-world application of Mixed-Integer Programming in SaaS and workforce management tools. However, in real applications, **staff vacation requests frequently collide with minimum coverage or leadership rules**, causing the solver to return `Infeasible`.
3208
3949
 
@@ -3231,7 +3972,7 @@ We evaluate two distinct, named scenarios with different vacation inputs to illu
3231
3972
  ## Implementation in WaSHI
3232
3973
 
3233
3974
  ```typescript
3234
- import { Model, sum, dot, minimize, expr } from "@ohtaman/washi";
3975
+ import { Model, minimize, expr } from "@ohtaman/washi";
3235
3976
  import "@ohtaman/washi/solvers/z3";
3236
3977
 
3237
3978
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
@@ -3264,12 +4005,12 @@ function buildShiftModel(name: string, dayOffRequests: Array<{ staff: string; da
3264
4005
  ),
3265
4006
  ])
3266
4007
  );
3267
- m.objective(minimize(dot(costMatrix, shift)));
4008
+ m.objective(minimize(expr`dot(${costMatrix}, ${shift})`));
3268
4009
 
3269
4010
  // Rule 1: Daily headcount coverage
3270
4011
  for (const d of days) {
3271
4012
  m.constraint(
3272
- expr`${sum(staffList, (s) => shift[s.name][d])} >= ${requiredCoverage[d]}`,
4013
+ expr`sum(${staffList}, ${(s) => shift[s.name][d]}) >= ${requiredCoverage[d]}`,
3273
4014
  `coverage_${d}`
3274
4015
  );
3275
4016
  }
@@ -3278,7 +4019,7 @@ function buildShiftModel(name: string, dayOffRequests: Array<{ staff: string; da
3278
4019
  const seniors = staffList.filter((s) => s.isSenior);
3279
4020
  for (const d of days) {
3280
4021
  m.constraint(
3281
- expr`${sum(seniors, (s) => shift[s.name][d])} >= 1`,
4022
+ expr`sum(${seniors}, ${(s) => shift[s.name][d]}) >= 1`,
3282
4023
  `senior_duty_${d}`
3283
4024
  );
3284
4025
  }
@@ -3286,7 +4027,7 @@ function buildShiftModel(name: string, dayOffRequests: Array<{ staff: string; da
3286
4027
  // Rule 3: Max working days per staff member
3287
4028
  for (const s of staffList) {
3288
4029
  m.constraint(
3289
- expr`${sum(days, (d) => shift[s.name][d])} <= ${s.maxShifts}`,
4030
+ expr`sum(${shift[s.name]}) <= ${s.maxShifts}`,
3290
4031
  `max_shifts_${s.name}`
3291
4032
  );
3292
4033
  }
@@ -3322,7 +4063,7 @@ async function runScenario(
3322
4063
  if (status === "Optimal") {
3323
4064
  console.log(`Optimal Weekly Payroll: $${model.objectiveValue}`);
3324
4065
  for (const s of staffList) {
3325
- const schedule = days.map((d) => (Math.round(shift[s.name][d].value ?? 0) === 1 ? "ON" : " ·"));
4066
+ const schedule = days.map((d) => (shift[s.name][d].value === 1 ? "ON" : " ·"));
3326
4067
  console.log(` ${s.name.padEnd(8)}: ${schedule.join(" ")}`);
3327
4068
  }
3328
4069
  console.log("Schedule resolved successfully (no UNSAT diagnosis needed).\n");
@@ -3368,13 +4109,29 @@ async function main() {
3368
4109
  main();
3369
4110
  ```
3370
4111
 
4112
+ ## Auto-Repairing Conflicts with Soft Constraints (Elastic Requests)
4113
+
4114
+ Once Z3 `unsatCore` diagnoses that `senior_duty_Sat` conflicts with `day_off_Alice_Sat` and `day_off_Bob_Sat`, you can offer managers an automatic repair option by relaxing day-off requests from hard constraints (`shift[staff][day] == 0`) into **soft preferences** penalized in the objective (e.g., `+$500` per overridden day off):
4115
+
4116
+ ```typescript
4117
+ // Soft constraint pattern: penalize working on a requested day off by $500
4118
+ // instead of enforcing hard shift[req.staff][req.day] == 0
4119
+ const requestedShiftVars = dayOffRequests.map((req) => shift[req.staff][req.day]);
4120
+ m.objective(minimize(expr`dot(${costMatrix}, ${shift}) + 500 * sum(${requestedShiftVars})`));
4121
+ ```
4122
+
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`).
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
+
3371
4128
  ---
3372
4129
 
3373
4130
  # E-Commerce Cart & Coupon Optimizer (Indicator MIP)
3374
4131
 
3375
4132
  | Problem Class | Solver | Key APIs | Links |
3376
4133
  | :--- | :--- | :--- | :--- |
3377
- | Mixed-Integer Programming (MIP) | HiGHS (default) | `m.binary()`, `m.constraint()`, `m.indicator()`, `expr`, `minimize` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=cart_coupon">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/12-ecommerce-coupon-optimizer.ts">Source Code</a></li></ul> |
4134
+ | Mixed-Integer Programming (MIP) | HiGHS (default) | `m.binary()`, `m.constraint()`, `m.indicator()`, `expr`, `minimize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=cart_coupon">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/12-ecommerce-coupon-optimizer.ts">Source Code</a></li></ul> |
3378
4135
 
3379
4136
  Modern e-commerce checkouts often feature complex promotional rules: minimum spend thresholds, category-specific discounts, stackable vs. mutually exclusive coupons, and maximum coupon limits per order. Running an optimizer directly in the browser (or an edge worker) lets the checkout UI automatically apply the best coupon combination—and even recommend a small "filler" item when crossing a spend threshold lowers the customer's net bill.
3380
4137
 
@@ -3399,7 +4156,7 @@ By adding the `$10` cable (`$252` gross), the customer unlocks `MEGA45_250` (`-$
3399
4156
  ## Implementation in WaSHI
3400
4157
 
3401
4158
  ```typescript
3402
- import { Model, sum, minimize, expr } from "@ohtaman/washi";
4159
+ import { Model, minimize, expr } from "@ohtaman/washi";
3403
4160
 
3404
4161
  async function optimizeCheckoutCart() {
3405
4162
  const m = new Model("CartCouponOptimizer");
@@ -3420,50 +4177,43 @@ async function optimizeCheckoutCart() {
3420
4177
 
3421
4178
  // Binary decision variables for each coupon
3422
4179
  const useCoupon = m.binary(coupons.map((c) => c.id));
4180
+ const discounts = Object.fromEntries(coupons.map((c) => [c.id, c.discount]));
3423
4181
 
3424
- const merchSpend = addUsbCable.mul(usbCablePrice).add(baseCartSubtotal);
3425
- const techSpend = addUsbCable.mul(usbCablePrice).add(baseTechSubtotal);
4182
+ const merchSpend = expr`${baseCartSubtotal} + ${usbCablePrice} * ${addUsbCable}`;
4183
+ const techSpend = expr`${baseTechSubtotal} + ${usbCablePrice} * ${addUsbCable}`;
3426
4184
 
3427
- // 1. Indicator constraints: If useCoupon[id] == 1, minimum spend threshold must hold
4185
+ // 1. Indicator constraints: If useCoupon[id] == 1, minimum spend threshold must hold.
4186
+ // Omitting `M` lets WaSHI automatically derive the tightest Big-M from variable bounds!
3428
4187
  for (const cpn of coupons) {
3429
4188
  if (cpn.minCart > 0) {
3430
- m.indicator(useCoupon[cpn.id], merchSpend.ge(cpn.minCart), {
4189
+ m.indicator(useCoupon[cpn.id], expr`${merchSpend} >= ${cpn.minCart}`, {
3431
4190
  activeValue: 1,
3432
- M: 500,
3433
4191
  name: `min_spend_${cpn.id}`,
3434
4192
  });
3435
4193
  }
3436
4194
  if (cpn.minTech > 0) {
3437
- m.indicator(useCoupon[cpn.id], techSpend.ge(cpn.minTech), {
4195
+ m.indicator(useCoupon[cpn.id], expr`${techSpend} >= ${cpn.minTech}`, {
3438
4196
  activeValue: 1,
3439
- M: 500,
3440
4197
  name: `min_tech_${cpn.id}`,
3441
4198
  });
3442
4199
  }
3443
4200
  }
3444
4201
 
3445
4202
  // 2. Mutual exclusion among non-stackable ("Exclusive") coupons
3446
- const exclusiveCoupons = coupons.filter((c) => !c.stackable);
3447
- m.constraint(
3448
- expr`${sum(exclusiveCoupons, (c) => useCoupon[c.id])} <= 1`,
3449
- "at_most_one_exclusive"
3450
- );
4203
+ const exclusiveVars = coupons.filter((c) => !c.stackable).map((c) => useCoupon[c.id]);
4204
+ m.constraint(expr`sum(${exclusiveVars}) <= 1`, "at_most_one_exclusive");
3451
4205
 
3452
4206
  // 3. Max 2 coupons per order
3453
- m.constraint(
3454
- expr`${sum(coupons, (c) => useCoupon[c.id])} <= 2`,
3455
- "max_two_coupons"
3456
- );
4207
+ m.constraint(expr`sum(${useCoupon}) <= 2`, "max_two_coupons");
3457
4208
 
3458
4209
  // Objective: Minimize final net payable amount (merchSpend - totalDiscounts)
3459
- const totalDiscount = sum(coupons, (c) => useCoupon[c.id].mul(c.discount));
3460
- m.objective(minimize(merchSpend.sub(totalDiscount)));
4210
+ m.objective(minimize(expr`${merchSpend} - dot(${discounts}, ${useCoupon})`));
3461
4211
 
3462
4212
  const status = await m.solve();
3463
4213
  console.log(`Status: ${status}, Optimal Net Payable: $${m.objectiveValue}`);
3464
- console.log(`Recommended Add-on (+$10 USB-C Cable): ${(addUsbCable.value ?? 0) > 0.5 ? "YES" : "NO"}`);
4214
+ console.log(`Recommended Add-on (+$10 USB-C Cable): ${addUsbCable.value === 1 ? "YES" : "NO"}`);
3465
4215
  for (const cpn of coupons) {
3466
- const applied = (useCoupon[cpn.id].value ?? 0) > 0.5;
4216
+ const applied = useCoupon[cpn.id].value === 1;
3467
4217
  console.log(` ${applied ? "✅ [APPLIED]" : " [skipped]"} ${cpn.id.padEnd(11)} (-$${cpn.discount})`);
3468
4218
  }
3469
4219
  }
@@ -3477,7 +4227,7 @@ optimizeCheckoutCart();
3477
4227
 
3478
4228
  | Problem Class | Solver | Key APIs | Links |
3479
4229
  | :--- | :--- | :--- | :--- |
3480
- | Convex Quadratic Programming (QP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot`, `QuadExpr` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=portfolio_qp">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/03-portfolio-qp.ts">Source Code</a></li></ul> |
4230
+ | Convex Quadratic Programming (QP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot`, `QuadExpr` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=portfolio_qp">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/03-portfolio-qp.ts">Source Code</a></li></ul> |
3481
4231
 
3482
4232
  The Markowitz mean-variance portfolio optimization problem is the foundation of modern quantitative finance: allocate capital across risky assets to minimize overall portfolio variance (risk) subject to achieving a minimum required expected return.
3483
4233
 
@@ -3497,7 +4247,7 @@ where $\boldsymbol{\Sigma}$ is the positive semi-definite asset return covarianc
3497
4247
  ## Implementation in WaSHI
3498
4248
 
3499
4249
  ```typescript
3500
- import { Model, QuadExpr, sum, dot, minimize, expr } from "@ohtaman/washi";
4250
+ import { Model, QuadExpr, dot, minimize, expr } from "@ohtaman/washi";
3501
4251
 
3502
4252
  async function solvePortfolio() {
3503
4253
  const m = new Model("PortfolioQP");
@@ -3519,11 +4269,12 @@ async function solvePortfolio() {
3519
4269
  const w = m.continuous(assets, { lb: 0, ub: 1 });
3520
4270
 
3521
4271
  // 1. Budget constraint: sum(w_i) == 1.0 (100%)
3522
- m.constraint(expr`${sum(assets, (a) => w[a])} == 1.0`, "budget_limit");
4272
+ m.constraint(expr`sum(${w}) == 1.0`, "budget_limit");
3523
4273
 
3524
4274
  // 2. Expected return constraint: sum(r_i * w_i) >= 8.5%
3525
4275
  const retMap = Object.fromEntries(assets.map((a, i) => [a, expectedReturns[i]]));
3526
- m.constraint(expr`${dot(retMap, w)} >= ${targetReturn}`, "target_return");
4276
+ const portfolioReturn = dot(retMap, w);
4277
+ m.constraint(expr`${portfolioReturn} >= ${targetReturn}`, "target_return");
3527
4278
 
3528
4279
  // 3. Quadratic Objective: minimize risk w^T * Sigma * w
3529
4280
  let risk = new QuadExpr();
@@ -3542,6 +4293,7 @@ async function solvePortfolio() {
3542
4293
  console.log(`Status: ${status}`);
3543
4294
  console.log(`Variance: ${m.objectiveValue?.toFixed(6)}`);
3544
4295
  console.log(`Volatility (Std Dev): ${((Math.sqrt(m.objectiveValue || 0)) * 100).toFixed(2)}%`);
4296
+ console.log(`Expected Return: ${((portfolioReturn.value ?? 0) * 100).toFixed(2)}% (target >= ${(targetReturn * 100).toFixed(2)}%)`);
3545
4297
 
3546
4298
  assets.forEach((name) => {
3547
4299
  console.log(` ${name.padEnd(10)}: ${((w[name].value ?? 0) * 100).toFixed(2)}%`);
@@ -3551,13 +4303,123 @@ async function solvePortfolio() {
3551
4303
  solvePortfolio();
3552
4304
  ```
3553
4305
 
4306
+ ## Practical Notes
4307
+
4308
+ - **Tracing the Efficient Frontier (`targetReturn` & `portfolioReturn.value`)**: Because the achieved return (`8.50%`) matches `targetReturn` exactly, the return constraint is tightly binding on the Markowitz efficient frontier. Varying `targetReturn` across `[0.05, 0.12]` traces out the full risk-return frontier.
4309
+ - **Risk-Aversion Scalarization vs. Target Return Constraint**: If `targetReturn` is set above the highest single-asset return ($12\%$ for `Tech` under long-only weights), the hard constraint $\mathbf{r}^T \mathbf{w} \ge R_{\text{target}}$ becomes `"Infeasible"`. An alternative formulation that is always feasible for any risk appetite $\lambda > 0$ is to minimize the risk-adjusted objective $\min (\lambda \, \mathbf{w}^T \boldsymbol{\Sigma} \mathbf{w} - \mathbf{r}^T \mathbf{w})$.
4310
+
4311
+ ---
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
+
3554
4416
  ---
3555
4417
 
3556
4418
  # SMT Security Policies
3557
4419
 
3558
4420
  | Problem Class | Solver | Key APIs | Links |
3559
4421
  | :--- | :--- | :--- | :--- |
3560
- | Propositional Logic & SMT | Z3 (`@ohtaman/washi/solvers/z3`) | `m.bool()`, `m.integer()`, `m.constraint()`, `expr`, `m.check()` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=smt_sat_scheduling">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts">Source Code</a></li></ul> |
4422
+ | Propositional Logic & SMT | Z3 (`@ohtaman/washi/solvers/z3`) | `m.bool()`, `m.integer()`, `implies()`, `m.constraint()`, `expr`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=smt_security">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts">Source Code</a></li></ul> |
3561
4423
 
3562
4424
  Satisfiability Modulo Theories (SMT) combines propositional logic (Boolean SAT) with first-order theories (linear integer arithmetic, real inequalities).
3563
4425
 
@@ -3574,7 +4436,7 @@ We model a security rule system with sensor readings and logic rules:
3574
4436
  ## Implementation in WaSHI
3575
4437
 
3576
4438
  ```typescript
3577
- import { Model, not, expr } from "@ohtaman/washi";
4439
+ import { Model, implies, not, expr } from "@ohtaman/washi";
3578
4440
  import "@ohtaman/washi/solvers/z3";
3579
4441
 
3580
4442
  async function verifySecurityRules() {
@@ -3592,7 +4454,7 @@ async function verifySecurityRules() {
3592
4454
  const luxLevel = m.integer("luxLevel", { lb: 0, ub: 1000 });
3593
4455
 
3594
4456
  // Rule 1: luxLevel <= 50 implies isNight
3595
- m.constraint(luxLevel.le(50).implies(isNight), "dark_implies_night");
4457
+ m.constraint(implies(expr`${luxLevel} <= 50`, isNight), "dark_implies_night");
3596
4458
 
3597
4459
  // Rule 2: (motionDetected AND isNight AND alarmArmed) => sirenActive
3598
4460
  m.constraint(
@@ -3619,20 +4481,33 @@ async function verifySecurityRules() {
3619
4481
  console.log(`Lights On : ${lightsOn.value}`);
3620
4482
  console.log(`Door Locked : ${frontDoorUnlocked.value ? "No" : "Yes"}`);
3621
4483
  console.log(`Is Night : ${isNight.value}`);
4484
+
4485
+ // 4. Formal Safety Verification (Counterexample Search):
4486
+ // Prove that the siren CANNOT remain off under these sensor readings
4487
+ m.constraint(not(sirenActive), "counterexample_siren_off");
4488
+ const proof = await m.check({ solver: "z3" });
4489
+ console.log(`Can siren stay off? ${proof.status} (Proven safe when Unsat)`);
4490
+ console.log(`Active proof core : ${(proof.conflicts ?? []).join(", ")}`);
3622
4491
  }
3623
4492
 
3624
4493
  verifySecurityRules();
3625
4494
  ```
3626
4495
 
4496
+ ## Practical Notes
4497
+
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).
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`.
4501
+
3627
4502
  ---
3628
4503
 
3629
4504
  # Conflict Diagnosis (Unsat Core)
3630
4505
 
3631
4506
  | Problem Class | Solver | Key APIs | Links |
3632
4507
  | :--- | :--- | :--- | :--- |
3633
- | Infeasibility Diagnosis / Unsat Core | Z3 (`@ohtaman/washi/solvers/z3`) | `m.integer()`, `m.continuous()`, `m.constraint()`, `expr`, `m.check()`, `m.conflicts` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=conflict_diagnosis_unsat">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts">Source Code</a></li></ul> |
4508
+ | Infeasibility Diagnosis / Unsat Core | Z3 (`@ohtaman/washi/solvers/z3`) | `m.integer()`, `m.continuous()`, `implies()`, `m.constraint()`, `expr`, `m.check()`, `m.conflicts` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=conflict_diagnosis_unsat">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts">Source Code</a></li></ul> |
3634
4509
 
3635
- When business rules, budgets, and operational policies grow complex, constraints inevitably conflict. Traditional solvers simply report "Infeasible", leaving engineers to guess which of hundreds of rules caused the contradiction.
4510
+ When business rules, budgets, and operational policies grow complex, constraints can easily conflict. Because a standard optimization call (`m.solve()`) only reports `"Infeasible"`, WaSHI provides `m.check()` to pinpoint conflicting rules without manual trial-and-error.
3636
4511
 
3637
4512
  This example shows how to isolate the conflicting constraint subset using Z3 Unsat Core extraction.
3638
4513
 
@@ -3652,7 +4527,7 @@ $$8 \text{ engineers} \times \$8,000 = \$64,000 > \$50,000 \text{ budget!}$$
3652
4527
  ## Implementation in WaSHI
3653
4528
 
3654
4529
  ```typescript
3655
- import { Model, expr } from "@ohtaman/washi";
4530
+ import { Model, implies, expr } from "@ohtaman/washi";
3656
4531
  import "@ohtaman/washi/solvers/z3";
3657
4532
 
3658
4533
  async function diagnoseConflicts() {
@@ -3669,7 +4544,7 @@ async function diagnoseConflicts() {
3669
4544
  m.constraint(rushDelivery, "rush_required");
3670
4545
 
3671
4546
  // Rule 3: Rush delivery requires at least 8 engineers
3672
- m.constraint(rushDelivery.implies(engineers.ge(8)), "rush_staffing_rule");
4547
+ m.constraint(implies(rushDelivery, expr`${engineers} >= 8`), "rush_staffing_rule");
3673
4548
 
3674
4549
  // Rule 4: Board budget cap of $50,000 (Conflict!)
3675
4550
  m.constraint(expr`${budget} <= 50000`, "strict_board_budget_cap");
@@ -3681,19 +4556,30 @@ async function diagnoseConflicts() {
3681
4556
  const res = await m.check({ solver: "z3" });
3682
4557
 
3683
4558
  console.log(`Status: ${res.status}`);
3684
- console.log("Conflicting Constraints (conflicts):", m.conflicts);
4559
+ console.log("Z3 Unsat Core (scale-invariant):", m.conflicts);
4560
+
4561
+ // Built-in HiGHS can also diagnose conflicts via single-solve L1 elastic slack relaxation:
4562
+ const highsDiag = await m.check({ solver: "highs" });
4563
+ console.log("HiGHS Elastic Repair Set:", highsDiag.conflicts);
3685
4564
  }
3686
4565
 
3687
4566
  diagnoseConflicts();
3688
4567
  ```
3689
4568
 
4569
+ ## Practical Notes
4570
+
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.
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.
4575
+
3690
4576
  ---
3691
4577
 
3692
4578
  # Capacitated Vehicle Routing Problem (CVRP, 50 Customers via Column Generation)
3693
4579
 
3694
4580
  | Problem Class | Solver | Key APIs | Links |
3695
4581
  | :--- | :--- | :--- | :--- |
3696
- | Combinatorial OR / Dantzig-Wolfe | HiGHS (default) | `m.solveColumnGeneration()`, `pricing`, `sum()`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts">Source Code</a></li><li><a href="../guide/decomposition.md">Decomposition Guide</a></li></ul> |
4582
+ | Combinatorial OR / Dantzig-Wolfe | HiGHS (default) | `m.solveColumnGeneration()`, `pricing`, `m.binary()`, `m.constraint()`, `expr` (`sum`) | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
3697
4583
 
3698
4584
  The **Capacitated Vehicle Routing Problem (CVRP)** determines the minimum number of delivery vehicles needed to visit a set of customers, subject to vehicle cargo capacity, maximum customer stops per shift, and route duration limits.
3699
4585
 
@@ -3713,7 +4599,7 @@ We consider a distribution network with a central depot at $(0, 0)$ and **50 cus
3713
4599
  ## Implementation in WaSHI
3714
4600
 
3715
4601
  ```typescript
3716
- import { Model, expr, minimize, sum } from "@ohtaman/washi";
4602
+ import { Model, expr, minimize } from "@ohtaman/washi";
3717
4603
 
3718
4604
  // --- Extracted Routing Helpers ---
3719
4605
 
@@ -3830,13 +4716,12 @@ async function runCVRP() {
3830
4716
 
3831
4717
  // Initial naive routes: 1 dedicated vehicle per customer
3832
4718
  const initialRoutes = customers.map((c) => master.binary(`route_init_${c.id}`));
3833
- master.objective(minimize(sum(initialRoutes)));
4719
+ master.objective(minimize(expr`sum(${initialRoutes})`));
3834
4720
 
3835
4721
  // Each customer must be visited by exactly 1 vehicle
3836
- for (let i = 0; i < customers.length; i++) {
3837
- master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${customers[i].id}`);
3838
- }
3839
- const visitConstrs = master.constraints;
4722
+ const visitConstrs = customers.map((c, i) =>
4723
+ master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${c.id}`)
4724
+ );
3840
4725
 
3841
4726
  console.log(`Initial state: 50 naive single-customer routes (50 vehicles).`);
3842
4727
  console.log("Solving via Column Generation with dual-directed heuristic pricing...");
@@ -3876,7 +4761,7 @@ async function runCVRP() {
3876
4761
  console.log(`Total Columns Generated: ${result.columnsAdded}`);
3877
4762
 
3878
4763
  console.log("\nSample routes selected in fleet:");
3879
- const activeRoutes = result.generatedColumns.filter((c) => (c.variable.value ?? 0) > 0.5);
4764
+ const activeRoutes = result.generatedColumns.filter((c) => c.variable.value === 1);
3880
4765
  for (const r of activeRoutes.slice(0, 5)) {
3881
4766
  const meta = r.proposal.meta;
3882
4767
  console.log(` ${meta?.tour.join(" -> ")} (Transit: ${meta?.travelTime}m, Total: ${meta?.totalTime}m)`);
@@ -3891,6 +4776,9 @@ runCVRP();
3891
4776
  - **Master Problem and Pricing Separation**: The master problem solves the LP relaxation and final set-partitioning MIP, while the `pricing` callback searches for negative-reduced-cost routes using cheapest insertion and 2-opt local search.
3892
4777
  - **Dual Value Access**: Dual values from the master LP relaxation are read from `visitConstrs[i].dual` to prioritize customers with higher shadow prices during route construction.
3893
4778
  - **Route Metadata**: Each proposed column attaches `{ tour, travelTime, totalTime }` under `meta`, allowing the ordered stop sequence to be inspected from `result.generatedColumns` after the solve completes.
4779
+ - **Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)**: This example uses `== 1` so that the final MIP never covers a customer twice. In large-scale column generation, formulating coverage as `>= 1` restricts the dual prices to $\pi_i \ge 0$, avoiding negative dual oscillations; if the final MIP selects overlapping routes, duplicate visits can be removed by post-processing whenever distances satisfy the triangle inequality.
4780
+ - **Heuristic Pricing vs. Exact ESPPRC**: Because `findImprovingRoute` uses a fast greedy heuristic (cheapest insertion + 2-opt) instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver, returning `null` means no further improving columns were found by the heuristic rather than proving global LP optimality.
4781
+ - **Price-and-Branch (`finalizeAsMIP: true`)**: Solving the Restricted Master Problem as a MIP over the columns generated at the root node is known as the *Restricted Master Heuristic* (Price-and-Branch). It produces near-optimal integer fleets quickly without requiring full Branch-and-Price tree search.
3894
4782
 
3895
4783
  ---
3896
4784
 
@@ -3898,7 +4786,7 @@ runCVRP();
3898
4786
 
3899
4787
  | Problem Class | Solver | Key APIs | Links |
3900
4788
  | :--- | :--- | :--- | :--- |
3901
- | Combinatorial OR / Benders | HiGHS (default) | `m.solveBenders()`, `subproblem`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts">Source Code</a></li><li><a href="../guide/decomposition.md">Decomposition Guide</a></li></ul> |
4789
+ | Combinatorial OR / Benders | HiGHS (default) | `m.solveBenders()`, `subproblem`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
3902
4790
 
3903
4791
  The **Traveling Salesperson Problem (TSP)** seeks the shortest closed tour that visits every city in a given set once and returns to the starting city.
3904
4792
 
@@ -3908,7 +4796,7 @@ $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S
3908
4796
 
3909
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:
3910
4798
  1. **Master Problem**: Solves the degree-assignment relaxation (each city has 1 incoming and 1 outgoing edge).
3911
- 2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds a **Benders Feasibility Cut** eliminating the smallest cycle and resolves until a single connected tour is obtained.
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.
3912
4800
 
3913
4801
  ## Problem Inputs
3914
4802
 
@@ -3925,7 +4813,7 @@ We consider **5 cities** on a 2D Euclidean coordinate grid:
3925
4813
  ## Implementation in WaSHI
3926
4814
 
3927
4815
  ```typescript
3928
- import { Model, expr, minimize, LinExpr } from "@ohtaman/washi";
4816
+ import { Model, expr, minimize } from "@ohtaman/washi";
3929
4817
 
3930
4818
  async function runTSP() {
3931
4819
  const cities = [
@@ -3946,39 +4834,26 @@ async function runTSP() {
3946
4834
  // 1. Master Problem: Degree assignment relaxation
3947
4835
  const master = new Model("TSP_BendersMaster");
3948
4836
  const x = {};
4837
+ const distMatrix = {};
3949
4838
 
3950
4839
  for (let i = 0; i < n; i++) {
3951
4840
  x[i] = {};
4841
+ distMatrix[i] = {};
3952
4842
  for (let j = 0; j < n; j++) {
3953
4843
  if (i !== j) {
3954
4844
  x[i][j] = master.binary(`x_${i}_${j}`);
4845
+ distMatrix[i][j] = dist(i, j);
3955
4846
  }
3956
4847
  }
3957
4848
  }
3958
4849
 
3959
4850
  // Objective: Minimize total tour distance
3960
- let totalDistance = new LinExpr();
3961
- for (let i = 0; i < n; i++) {
3962
- for (let j = 0; j < n; j++) {
3963
- if (i !== j) {
3964
- totalDistance = totalDistance.add(x[i][j].mul(dist(i, j)));
3965
- }
3966
- }
3967
- }
3968
- master.objective(minimize(totalDistance));
4851
+ master.objective(minimize(expr`dot(${distMatrix}, ${x})`));
3969
4852
 
3970
4853
  // Each city must have 1 outgoing and 1 incoming edge
3971
4854
  for (let i = 0; i < n; i++) {
3972
- let outExpr = new LinExpr();
3973
- let inExpr = new LinExpr();
3974
- for (let j = 0; j < n; j++) {
3975
- if (i !== j) {
3976
- outExpr = outExpr.add(x[i][j]);
3977
- inExpr = inExpr.add(x[j][i]);
3978
- }
3979
- }
3980
- master.constraint(expr`${outExpr} == 1`, `out_${i}`);
3981
- master.constraint(expr`${inExpr} == 1`, `in_${i}`);
4855
+ master.constraint(expr`sum(${x[i]}) == 1`, `out_${i}`);
4856
+ master.constraint(expr`sum(${n}, ${(j) => x[j][i]}) == 1`, `in_${i}`);
3982
4857
  }
3983
4858
 
3984
4859
  console.log("Solving TSP with Benders lazy subtour elimination...");
@@ -3991,7 +4866,7 @@ async function runTSP() {
3991
4866
  const succ = {};
3992
4867
  for (let i = 0; i < n; i++) {
3993
4868
  for (let j = 0; j < n; j++) {
3994
- if (i !== j && Math.round(x[i][j].value ?? 0) === 1) {
4869
+ if (i !== j && x[i][j].value === 1) {
3995
4870
  succ[i] = j;
3996
4871
  }
3997
4872
  }
@@ -4013,27 +4888,22 @@ async function runTSP() {
4013
4888
  }
4014
4889
  }
4015
4890
 
4016
- // If more than 1 cycle, subtours exist: inject Benders feasibility cut
4891
+ // If more than 1 cycle, subtours exist: inject Benders feasibility cuts for all cycles
4017
4892
  if (cycles.length > 1) {
4018
- const smallestCycle = cycles.reduce((min, c) => (c.length < min.length ? c : min));
4019
- const S = new Set(smallestCycle);
4020
- cutCounter++;
4021
- console.log(`Subtour detected: [${smallestCycle.map(k => cities[k].name).join(" -> ")}]. Adding Benders cut #${cutCounter}.`);
4022
-
4023
- let cutLhs = new LinExpr();
4024
- for (const i of S) {
4025
- for (let j = 0; j < n; j++) {
4026
- if (!S.has(j)) {
4027
- cutLhs = cutLhs.add(x[i][j]);
4028
- }
4029
- }
4030
- }
4031
-
4032
- return {
4033
- kind: "feasibility",
4034
- constraint: expr`${cutLhs} >= 1`,
4035
- name: `subtour_cut_${cutCounter}`,
4036
- };
4893
+ return cycles.map((cycle) => {
4894
+ const S = new Set(cycle);
4895
+ cutCounter++;
4896
+ console.log(`Subtour detected: [${cycle.map(k => cities[k].name).join(" -> ")}]. Adding Benders cut #${cutCounter}.`);
4897
+
4898
+ const outCities = Array.from({ length: n }, (_, j) => j).filter((j) => !S.has(j));
4899
+ const cutEdges = cycle.flatMap((i) => outCities.map((j) => x[i][j]));
4900
+
4901
+ return {
4902
+ kind: "feasibility",
4903
+ constraint: expr`sum(${cutEdges}) >= 1`,
4904
+ name: `subtour_cut_${cutCounter}`,
4905
+ };
4906
+ });
4037
4907
  }
4038
4908
 
4039
4909
  return null; // Single connected tour found
@@ -4048,7 +4918,7 @@ async function runTSP() {
4048
4918
  console.log("\nOptimal tour edges:");
4049
4919
  for (let i = 0; i < n; i++) {
4050
4920
  for (let j = 0; j < n; j++) {
4051
- if (i !== j && (result.values[`x_${i}_${j}`] ?? 0) > 0.5) {
4921
+ if (i !== j && result.values[`x_${i}_${j}`] === 1) {
4052
4922
  console.log(` ${cities[i].name} -> ${cities[j].name} (distance: ${dist(i, j).toFixed(3)})`);
4053
4923
  }
4054
4924
  }
@@ -4061,5 +4931,7 @@ runTSP();
4061
4931
  ## Notes
4062
4932
 
4063
4933
  - **Lazy Subtour Elimination**: The master problem starts with only the $2n$ degree constraints, and subtour elimination cuts are added on demand when disconnected cycles appear in the master solution.
4064
- - **Separation Callback**: The `subproblem` callback reads candidate edge values via `x[i][j].value`, traces connected components in $O(n)$, and returns `{ kind: "feasibility", constraint: ... }` when multiple cycles are present.
4934
+ - **Multi-Cut Separation**: Returning an array of cuts (`cycles.map(...)`) from `subproblem` eliminates all disconnected cycles discovered in the current candidate solution simultaneously, reducing the number of master MIP re-solves.
4935
+ - **Two Equivalent DFJ Cut Forms**: Because every city has out-degree $\sum_{j \ne i} x_{ij} = 1$, summing over $i \in S$ gives $\sum_{i \in S, j \in S} x_{ij} + \sum_{i \in S, j \notin S} x_{ij} = |S|$. Thus the cut-set inequality $\sum_{i \in S, j \notin S} x_{ij} \ge 1$ used above and the internal-edge inequality $\sum_{i \in S, j \in S} x_{ij} \le |S| - 1$ used in [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts) are algebraically identical.
4936
+ - **Upfront 2-City Subtour Elimination**: In larger TSP instances, mutual 2-cycles ($i \leftrightarrow j$) are the most frequent initial subtours. Adding the $\binom{n}{2}$ pairwise constraints $x_{ij} + x_{ji} \le 1$ directly to the initial master problem often cuts the number of Benders iterations substantially.
4065
4937
  - **Termination Condition**: Returning `null` from `subproblem` indicates that no violated subtour constraints remain.