@ohtaman/washi 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.ja.md +22 -24
  2. package/README.md +20 -22
  3. package/README.zh-CN.md +25 -27
  4. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  5. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  6. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  7. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  8. package/dist/browser/solvers/highs.js +1414 -0
  9. package/dist/browser/washi.js +1090 -1473
  10. package/dist/browser/washi.min.js +4 -4
  11. package/dist/lib/solvers/glpk.js +34 -32
  12. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  13. package/dist/lib/solvers/highs.js +410 -0
  14. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  15. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  16. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  17. package/dist/lib/solvers/pumpkin.js +247 -1146
  18. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  19. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  20. package/dist/lib/solvers/z3.js +125 -123
  21. package/dist/lib/washi.js +2426 -1340
  22. package/dist/types/index.d.ts +1 -2
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/modeler/index.d.ts +0 -1
  25. package/dist/types/modeler/index.d.ts.map +1 -1
  26. package/dist/types/modeler/model.d.ts +6 -7
  27. package/dist/types/modeler/model.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/index.d.ts +2 -1
  29. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  31. package/docs/examples/diet-sensitivity.md +33 -14
  32. package/docs/examples/ecommerce-coupons.md +17 -9
  33. package/docs/examples/index.md +34 -30
  34. package/docs/examples/knapsack.md +11 -5
  35. package/docs/examples/portfolio-qp.md +21 -8
  36. package/docs/examples/production.md +10 -5
  37. package/docs/examples/project-scheduling.md +25 -12
  38. package/docs/examples/shift-scheduling.md +27 -19
  39. package/docs/examples/smt-security.md +27 -12
  40. package/docs/examples/transportation.md +23 -13
  41. package/docs/examples/traveling-salesperson.md +34 -22
  42. package/docs/examples/unsat-core.md +27 -15
  43. package/docs/examples/vehicle-routing.md +74 -28
  44. package/docs/getting-started/ai-agents.md +129 -90
  45. package/docs/getting-started/coding-agents.md +60 -41
  46. package/docs/getting-started/cross-origin.md +27 -14
  47. package/docs/getting-started/index.md +23 -16
  48. package/docs/getting-started/runtimes.md +70 -40
  49. package/docs/guide/constraint-programming.md +74 -44
  50. package/docs/guide/constraints.md +71 -39
  51. package/docs/guide/decomposition.md +72 -42
  52. package/docs/guide/expressions.md +79 -48
  53. package/docs/guide/formulation-tips.md +46 -27
  54. package/docs/guide/objectives.md +55 -31
  55. package/docs/guide/unsat-core.md +56 -53
  56. package/docs/guide/variables.md +61 -28
  57. package/docs/solvers/custom-solver.md +155 -119
  58. package/docs/solvers/glpk.md +58 -17
  59. package/docs/solvers/highs.md +115 -43
  60. package/docs/solvers/index.md +33 -26
  61. package/docs/solvers/pumpkin.md +71 -63
  62. package/docs/solvers/z3.md +63 -25
  63. package/llms-full.txt +1623 -953
  64. package/llms.txt +125 -93
  65. package/package.json +29 -20
  66. package/skills/washi/SKILL.md +43 -22
  67. package/dist/browser/solvers/pumpkin.min.js +0 -1
  68. package/dist/lib/registry-dx7x4e5c.js +0 -1694
  69. /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
  70. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  71. /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
  72. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  73. /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
  74. /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
  75. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  76. /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
  77. /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
  78. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  79. /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
  80. /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
  81. /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
@@ -1,37 +1,38 @@
1
1
  # Pumpkin Constraint Programming Solver
2
2
 
3
- **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.
3
+ **Pumpkin** is an open-source Constraint Programming (CP) solver written in Rust and maintained by [ConSol-Lab/Pumpkin](https://github.com/ConSol-Lab/Pumpkin). WaSHI bundles Pumpkin (`v0.5.0`, `pumpkin.wasm`, ~2.1 MB) under the MIT license alongside HiGHS with zero extra packages—pass `{ solver: "pumpkin" }` out of the box without any extra plugin import (advanced APIs such as `PumpkinSolver` and `setPumpkinWasmUrl()` are available from `@ohtaman/washi/solvers/pumpkin`).
4
4
 
5
- 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.
5
+ Because Pumpkin runs single-threaded, browsers do not need `SharedArrayBuffer` or `COOP`/`COEP` headers (see [Cross-Origin Isolation](../getting-started/cross-origin.md)).
6
6
 
7
7
  ---
8
8
 
9
- ## Key Features in WaSHI
9
+ ## When to Choose Pumpkin
10
10
 
11
- - **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.
12
- - **Permissive MIT License**: 100% commercially friendly, including all transitive Rust WASM dependencies (`MIT`, `Apache-2.0`, `Unicode-3.0`).
13
- - **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.
14
- - **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.
15
- - **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.
16
- - **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`).
11
+ | Problem Type | Recommended Solver | Why |
12
+ | :--- | :--- | :--- |
13
+ | **Scheduling, resource caps, & discrete global constraints** | **Pumpkin** (`{ solver: "pumpkin" }`) | Native propagation for `disjoint`, `cumulative`, `distinct`, and `allowed` with zero extra setup. |
14
+ | **Browser `unsatCore` without `COOP`/`COEP`** | **Pumpkin** (`m.check({ solver: "pumpkin" })`) | Extracts conflicting named constraints on bounded integer and boolean models in any static site or iframe. |
15
+ | **Linear, Mixed-Integer, & Convex Quadratic Programming** | **[HiGHS](./highs.md)** (default) | Supports continuous variables, duals and slacks, convex quadratic objectives, and continuous relaxation. |
16
+ | **Logical rules with `Continuous` variables** | **[Z3](./z3.md)** | Handles real-valued inequalities inside logical operators and mixed continuous/integer `unsatCore`. |
17
17
 
18
18
  ---
19
19
 
20
- ## Supported Problem Classes
20
+ ## Supported Modeling Primitives
21
21
 
22
- > [!TIP]
23
- > **HiGHS vs. Pumpkin vs. Z3**:
24
- > - Use **HiGHS** (`{ solver: "highs" }`) for Continuous LPs, Convex QPs, or large linear-relaxation-dominated MILPs.
25
- > - Use **Pumpkin** (`{ solver: "pumpkin" }`) for disjunctive scheduling, CP global constraints, bounded integer + propositional logic models, and zero-`COOP`/`COEP` `unsatCore` extraction.
26
- > - Use **Z3** (`{ solver: "z3" }`) when you need continuous variables inside `implies(...)` / `not(...)` or arbitrary real-valued SMT arithmetic.
22
+ - **Native CP & global constraints**: `disjoint()`, `cumulative()`, `distinct()`, `allowed()`, `at()`, `max()`, `min()`, `abs()`, discrete `!=`, and `m.indicator()`.
23
+ - **Native propositional logic**: `model.bool()`, `and()`, `or()`, `not()`, `implies()`, and `xor()`.
24
+ - **Warm starts (`initialValue`)**: Accepts starting value hints on `model.integer()` and `model.binary()` variables.
27
25
 
28
- ### 1. Disjunctive Scheduling & Global CP Constraints (`model.solve()`)
26
+ ---
27
+
28
+ ## Usage Examples
29
+
30
+ Pumpkin is pre-registered in `@ohtaman/washi` with no extra import required—just pass `{ solver: "pumpkin" }` to `new Model()`, `model.solve()`, or `model.check()`. Use `model.solve()` to optimize an integer objective over bounded integer and boolean variables, or use `model.check()` to verify satisfiability and inspect conflicting constraints.
29
31
 
30
- Model unary/cumulative resource scheduling, precedence logic (`implies`, `not`), and global predicates (`disjoint`, `distinct`, `cumulative`, `allowed`, `at`, `max`, `min`, `abs`) directly over bounded integers:
32
+ ### 1. Scheduling & Global Constraints (`model.solve()`)
31
33
 
32
34
  ```typescript
33
35
  import { Model, disjoint, expr, implies, minimize, not } from "@ohtaman/washi";
34
- import "@ohtaman/washi/solvers/pumpkin";
35
36
 
36
37
  const model = new Model("SchedulingStep", { solver: "pumpkin" });
37
38
 
@@ -46,6 +47,7 @@ model.constraint(
46
47
  ]),
47
48
  "single_machine"
48
49
  );
50
+ // Optional: reify the chosen order in job1First (disjoint already enforces non-overlap)
49
51
  model.constraint(implies(job1First, expr`${s1} + 6 <= ${s2}`), "job1_before_job2");
50
52
  model.constraint(implies(not(job1First), expr`${s2} + 4 <= ${s1}`), "job2_before_job1");
51
53
 
@@ -53,15 +55,13 @@ model.objective(minimize(expr`${s1} + ${s2}`));
53
55
  await model.solve();
54
56
 
55
57
  console.log(`Status: ${model.status}, s1=${s1.value}, s2=${s2.value}`);
58
+ // Status: Optimal, s1=4, s2=0
56
59
  ```
57
60
 
58
- ### 2. Satisfiability & Unsat Core Diagnosis (`model.check()`)
59
-
60
- 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:
61
+ ### 2. Conflict Diagnosis (`model.check()`)
61
62
 
62
63
  ```typescript
63
64
  import { Model, expr, implies } from "@ohtaman/washi";
64
- import "@ohtaman/washi/solvers/pumpkin";
65
65
 
66
66
  const model = new Model("PolicyConflict", { solver: "pumpkin" });
67
67
  const vip = model.bool("vip");
@@ -73,7 +73,8 @@ model.constraint(expr`${seats} <= 5`, "room_cap");
73
73
 
74
74
  const result = await model.check();
75
75
  if (result.status === "Unsat") {
76
- console.log("Conflicting rules:", result.conflicts); // also on result.unsatCore / model.unsatCore
76
+ console.log("Conflicting rules:", result.conflicts); // or result.unsatCore / model.unsatCore
77
+ // ["vip_active", "vip_seats", "room_cap"]
77
78
  }
78
79
  ```
79
80
 
@@ -81,23 +82,41 @@ if (result.status === "Unsat") {
81
82
 
82
83
  ## Solver Options
83
84
 
84
- Pass solver options into `model.solve()` or `model.check()`:
85
+ Pass execution options into `model.solve()`, `model.check()`, or `new PumpkinSolver(options)`:
86
+
87
+ | Option | Type | Description |
88
+ | :--- | :--- | :--- |
89
+ | `timeLimit` | `number` | Maximum solve or check time in seconds. |
90
+ | `useWorker` | `boolean` | Runs Pumpkin in a browser Web Worker (`true` by default in browsers; falls back to `false` on `file:` URLs or opaque origins). Passing `useWorker: true` in Node.js throws an `Error`. |
91
+ | `wasmUrl` | `string \| null` | Overrides the `pumpkin.wasm` asset URL (`null` uses the bundled binary; call `setPumpkinWasmUrl()` to set a global URL). |
92
+ | `signal` | `AbortSignal` | Cancels an in-flight call. In a browser Web Worker, aborts preemptively and preserves the last captured incumbent if available; on the main thread or in Node.js, cancels cooperatively at checkpoints. |
93
+ | `onProgress` | `(ev) => void` | Receives live elapsed time and incumbent objective updates (`solve()` only; ignored by `check()`). |
94
+
95
+ > [!NOTE]
96
+ > Pumpkin is a discrete CP solver: LP sensitivity fields (`c.dual`, `c.slack`, `v.reducedCost`) remain `null`, and MIP bound/gap fields (`objectiveBound`, `relativeGap`, `absoluteGap`) remain `undefined`.
85
97
 
86
98
  ```typescript
99
+ import { Model, expr, minimize } from "@ohtaman/washi";
100
+
101
+ const model = new Model("TimedSearch", { solver: "pumpkin" });
102
+ const x = model.integer("x", { lb: 0, ub: 100 });
103
+ const y = model.integer("y", { lb: 0, ub: 100 });
104
+ model.constraint(expr`${x} + ${y} >= 40`, "min_total");
105
+ model.objective(minimize(expr`2 * ${x} + 3 * ${y}`));
106
+
87
107
  const controller = new AbortController();
88
108
 
89
109
  await model.solve({
90
- timeLimit: 30.0, // Maximum solve time in seconds
110
+ timeLimit: 30.0,
91
111
  signal: controller.signal,
92
112
  onProgress: (ev) => {
93
113
  console.log(`Elapsed: ${ev.elapsedTime.toFixed(1)}s, Best: ${ev.objectiveValue}`);
94
114
  },
95
115
  });
96
116
 
97
- // Always check hasPrimalSolution when timeLimit or AbortSignal is used:
98
117
  if (model.hasPrimalSolution) {
99
118
  console.log(
100
- `Usable solution (${model.status}, termination: ${model.terminationStatus}):`,
119
+ `Solution (${model.status}, termination: ${model.terminationStatus}):`,
101
120
  `obj = ${model.objectiveValue}`
102
121
  );
103
122
  }
@@ -105,59 +124,48 @@ if (model.hasPrimalSolution) {
105
124
 
106
125
  ---
107
126
 
108
- ## Domain & API Preconditions
127
+ ## Requirements & Limitations {#domain-api-preconditions}
109
128
 
110
- Pumpkin is strictly a **bounded integer & boolean CP/LCG solver**. Unsupported constructs are rejected with explicit errors rather than silent rounding or fallbacks:
129
+ Pumpkin solves **bounded integer and boolean** models only. Unsupported variables, values, or options fail fast by throwing a runtime `Error`:
111
130
 
112
- - **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.
113
- - **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.
114
- - **Unsupported features**: `QuadExpr` objectives/constraints, `Continuous` variables, unbounded variables, and `relax: true` throw explicit errors.
131
+ - **Bounded integers only**: Every `Integer` variable must have finite integer bounds in $[-(2^{30} - 1),\, 2^{30} - 1]$ (`Binary` variables are bounded to 0/1); `Continuous` variables and infinite bounds on `Integer` variables throw an `Error`.
132
+ - **Integer coefficients & scaled bounds**: Constraint coefficients, adjusted right-hand sides (`rhs - lhs.constant`), and scaled variable bounds must be exact integers in $[-(2^{30} - 1),\, 2^{30} - 1]$.
133
+ - **Constraint magnitude sum**: In each constraint, the adjusted right-hand side magnitude plus the sum of worst-case term magnitudes ($|\text{coeff}| \times \max(|\mathrm{lb}|, |\mathrm{ub}|)$) must not exceed $2^{31} - 2$.
134
+ - **Stricter objective bound**: Objective coefficients must be integers whose worst-case scaled term magnitudes sum to at most $2^{30} - 1$; objective constants may be fractional.
135
+ - **Unsupported model features**: `QuadExpr` objectives or constraints and `relax: true` throw a runtime `Error`.
136
+ - **Unsupported options**: `relativeGap`, `absoluteGap`, `presolve`, `threads`, `verbose`, `outputFlag`, and unknown option keys throw a runtime `Error`.
115
137
 
116
138
  ---
117
139
 
118
- ## Worker & WASM Configuration in Browsers
140
+ ## Browser Worker & WASM Hosting
119
141
 
120
- 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).
142
+ By default in browsers, Pumpkin loads `pumpkin.wasm` inside a dedicated Web Worker. On `file:` URLs or sandboxed iframes without an origin, it falls back to the main thread automatically.
121
143
 
122
- 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`:
144
+ To force main-thread execution or serve `pumpkin.wasm` from a custom URL:
123
145
 
124
146
  ```typescript
125
- import { Model } from "@ohtaman/washi";
147
+ import { Model, expr, minimize } from "@ohtaman/washi";
126
148
  import { PumpkinSolver, setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
127
149
 
128
- // Option 1: Per solve / check call
129
- await model.solve({ useWorker: false });
130
-
131
- // Option 2: When instantiating the solver
132
- const syncModel = new Model({
133
- solver: new PumpkinSolver({ useWorker: false }),
134
- });
135
-
136
- // Host pumpkin.wasm at a custom path or CDN (globally or per call via { wasmUrl }):
150
+ // Set a custom WASM URL globally (or pass { wasmUrl } to solve() / check())
137
151
  setPumpkinWasmUrl("/assets/wasm/pumpkin.wasm");
138
- ```
139
152
 
140
- 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**.
141
-
142
- ---
153
+ const model = new Model({ solver: "pumpkin" });
154
+ const x = model.integer("x", { lb: 0, ub: 10 });
155
+ model.objective(minimize(expr`${x}`));
143
156
 
144
- ## Architecture & WebAssembly Runtime
145
-
146
- 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.
147
-
148
- 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).
157
+ // Option 1: Force main-thread execution for a single call
158
+ await model.solve({ useWorker: false });
149
159
 
150
- ### Callbacks & Solver Interactivity
160
+ // Option 2: Configure defaults on a PumpkinSolver instance
161
+ const syncModel = new Model({ solver: new PumpkinSolver({ useWorker: false }) });
162
+ ```
151
163
 
152
- - **Progress Monitoring & Cancellation (Supported)**:
153
- 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.
154
- - **Exact Discrete Optimality**:
155
- 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`).
164
+ If `pumpkin.wasm` fails to load or returns an HTML fallback page, WaSHI throws an error with the attempted URL instead of silently falling back to a CDN.
156
165
 
157
166
  ---
158
167
 
159
- ## References & Upstream Links
168
+ ## References
160
169
 
161
- - **Modeling Guide & Walkthrough**: [Constraint Programming (CP) Modeling](../guide/constraint-programming.md) · [Resource-Constrained Project Scheduling (RCPSP)](../examples/project-scheduling.md)
162
- - **Source Repository**: [ConSol-Lab/Pumpkin](https://github.com/ConSol-Lab/Pumpkin) (MIT License — ConSol Lab, TU Delft)
163
- - **Rust Crate & API Docs**: [docs.rs/pumpkin-core](https://docs.rs/pumpkin-core) · [crates.io/crates/pumpkin-core](https://crates.io/crates/pumpkin-core)
170
+ - [Constraint Programming (CP) Modeling](../guide/constraint-programming.md) · [Resource-Constrained Project Scheduling (RCPSP)](../examples/project-scheduling.md)
171
+ - [ConSol-Lab/Pumpkin](https://github.com/ConSol-Lab/Pumpkin) · [`CONTRIBUTING.md` (rebuilding WASM)](https://github.com/ohtaman/washi/blob/main/CONTRIBUTING.md#4-rebuilding-webassembly-assets--release-workflow)
@@ -1,12 +1,12 @@
1
1
  # Z3 SMT Solver Engine
2
2
 
3
- **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.
3
+ **Z3** is an open-source theorem prover and Satisfiability Modulo Theories (SMT) solver from Microsoft Research. In WaSHI, Z3 handles logical rules involving `Continuous` variables or decimal coefficients/constants, exact arithmetic, and `unsatCore` conflict diagnosis.
4
4
 
5
5
  ---
6
6
 
7
7
  ## Installation
8
8
 
9
- Z3 is provided as an optional peer dependency:
9
+ `z3-solver` is an optional peer dependency:
10
10
 
11
11
  ```bash
12
12
  npm install z3-solver
@@ -14,45 +14,57 @@ npm install z3-solver
14
14
 
15
15
  ---
16
16
 
17
- ## When to Use Z3?
17
+ ## When to Choose Z3
18
18
 
19
- 1. **Unsat Core Conflict Diagnosis**:
20
- When your MIP model is infeasible and you need to isolate which constraints are contradictory.
21
- 2. **Boolean / Logical Formulations**:
22
- When solving problems containing complex logical relations (implications, XOR, nested Boolean expressions).
23
- 3. **Exact Mathematical Guarantees**:
24
- Z3 can perform exact rational arithmetic without floating-point inaccuracies.
19
+ | Goal | Recommended Solver | Why |
20
+ | :--- | :--- | :--- |
21
+ | **Logical rules with `Continuous` or decimal values** | **Z3** (`m.check({ solver: "z3" })`) | Evaluates real-valued inequalities natively inside `implies`, `not`, `and`, `or`, and `xor`. |
22
+ | **Conflict diagnosis (`unsatCore`) with `Continuous` vars** | **Z3** (`m.check({ solver: "z3" })`) | Extracts scale-invariant `unsatCore` subsets across mixed continuous and integer models. |
23
+ | **Bounded integer/boolean Constraint Programming** | **[Pumpkin](./pumpkin.md)** | Bundled with zero dependencies and needs no Cross-Origin Isolation headers. |
24
+ | **Numerical linear, mixed-integer, or convex quadratic optimization** | **[HiGHS](./highs.md)** (default) | Built-in simplex, interior-point, and branch-and-cut solver; much faster for objective optimization. |
25
25
 
26
26
  > [!TIP]
27
- > **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()`.
27
+ > A common workflow is to verify rules and diagnose conflicts via **Z3** `model.check()`, then optimize numerical costs via **HiGHS** `model.solve()`.
28
28
 
29
29
  ---
30
30
 
31
- ## Basic Usage
31
+ ## Basic Usage (`model.solve()` vs. `model.check()`)
32
+
33
+ Import `@ohtaman/washi/solvers/z3` once to register the `"z3"` solver. Z3 supports two execution modes on the same `Model`:
34
+
35
+ - **`model.check()`**: Checks satisfiability without an objective and returns `"Sat"`, `"Unsat"` (with `conflicts` / `unsatCore`), or `"Unknown"`.
36
+ - **`model.solve()`**: Optimizes a linear objective via Z3 Optimize. When no objective is set, `solve()` finds any feasible assignment and reports `"Optimal"` (or `"Feasible"` if `signal` was aborted while the call was completing).
37
+
38
+ The example below finds a feasible assignment for a continuous threshold rule controlled by a boolean flag:
32
39
 
33
40
  ```typescript
34
- import { Model, expr } from "@ohtaman/washi";
41
+ import { Model, expr, implies } from "@ohtaman/washi";
35
42
  import "@ohtaman/washi/solvers/z3";
36
43
 
37
44
  const model = new Model({ solver: "z3" });
38
45
 
39
- const x = model.integer("x", { lb: 0, ub: 10 });
40
- const y = model.integer("y", { lb: 0, ub: 10 });
46
+ const temp = model.continuous("temp", { lb: 0, ub: 100 });
47
+ const coolingOn = model.bool("cooling_on");
41
48
 
42
- model.constraint(expr`${x} + ${y} == 15`, "sum_15");
43
- model.constraint(expr`${x} >= 8`, "x_at_least_8");
49
+ model.constraint(coolingOn, "enable_cooling");
50
+ model.constraint(implies(coolingOn, expr`${temp} <= 22.5`), "cooling_target");
44
51
 
52
+ // Without an objective, solve() finds any feasible assignment.
53
+ // Call model.check() instead for "Sat" / "Unsat" and unsatCore diagnostics.
45
54
  await model.solve();
46
- console.log(`x = ${x.value}, y = ${y.value}`);
55
+ console.log(`Status: ${model.status}, temp = ${temp.value}`);
47
56
  ```
48
57
 
49
58
  ---
50
59
 
51
- ## Unsat Core Extraction (`model.check()`)
60
+ ## Conflict Diagnosis (`model.check()`)
52
61
 
53
- Use `await model.check()` with Z3 to verify satisfiability and extract the conflicting subset of named constraints (`conflicts` / `unsatCore`) when a model is unsatisfiable:
62
+ Call `await model.check()` to verify satisfiability across continuous, integer, or mixed rules. When the model is `"Unsat"`, Z3 returns a conflicting subset of named constraints via `result.conflicts` (also available as `result.unsatCore` and `model.unsatCore`):
54
63
 
55
64
  ```typescript
65
+ import { Model, expr } from "@ohtaman/washi";
66
+ import "@ohtaman/washi/solvers/z3";
67
+
56
68
  const model = new Model({ solver: "z3" });
57
69
  const a = model.continuous("a");
58
70
 
@@ -62,20 +74,46 @@ model.constraint(expr`${a} <= 5`, "req_B");
62
74
  const result = await model.check();
63
75
 
64
76
  if (result.status === "Unsat") {
65
- console.log("Conflicting constraints:", result.conflicts); // or model.conflicts / model.unsatCore
77
+ console.log("Conflicting constraints:", result.conflicts);
66
78
  // ["req_A", "req_B"]
67
79
  }
68
80
  ```
69
81
 
70
82
  ---
71
83
 
72
- ## Browser Security Note
84
+ ## Supported & Unsupported Options
85
+
86
+ Z3 validates options strictly and throws a runtime `Error` when unsupported options or model features are supplied.
73
87
 
74
- 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](../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](./pumpkin.md) (`@ohtaman/washi/solvers/pumpkin`) instead.
88
+ ### Supported Options
75
89
 
76
- ## Runtime Failures and Thread Cleanup
90
+ - `z3JsUrl` / `z3WasmUrl`: Override browser asset URLs for `z3-built.js` and `z3-built.wasm` (or configure globally with `setZ3Assets()`).
91
+ - `signal`: `AbortSignal` checked **before** Z3 starts solving (pre-solve cancellation only; it cannot interrupt an active Z3 call).
92
+ - `onProgress`: Applies to `solve()` only (ignored by `check()`). Invoked once after `solve()` completes with elapsed time and, when a solution exists, the final objective value.
77
93
 
78
- If a Z3 worker encounters a fatal runtime error, pending operations on that instance reject with an error and the broken runtime is invalidated; subsequent `solve()` or `check()` calls automatically initialize a fresh Z3 runtime rather than misclassifying failures as `Sat` or `Unsat`.
94
+ ### Unsupported Options & Features (Throw at Runtime)
79
95
 
80
- To explicitly terminate Z3 pthread workers when tearing down a browser view or worker pool, call `killZ3Threads()` from `@ohtaman/washi/solvers/z3`.
96
+ - **Unsupported tuning options**: `timeLimit`, `relativeGap`, `absoluteGap`, `presolve`, `threads`, `verbose`, `outputFlag`, and unknown option keys throw an `Error`.
97
+ - **Unsupported modes & features**: `relax: true`, `useWorker: true`, `initialValue` warm starts, and `QuadExpr` quadratic objectives throw an `Error`.
81
98
 
99
+ > [!NOTE]
100
+ > Z3 Optimize is an SMT engine without LP sensitivity or branch-and-bound dual bounds: `c.dual`, `c.slack`, and `v.reducedCost` remain `null`, and `objectiveBound`, `relativeGap`, and `absoluteGap` remain `undefined`.
101
+
102
+ ---
103
+
104
+ ## Browser Requirements & Thread Cleanup
105
+
106
+ In browsers, Z3 uses `SharedArrayBuffer` and Emscripten pthreads. Your page must satisfy two browser preconditions:
107
+
108
+ 1. **Secure Context**: Served over `HTTPS` or `localhost`.
109
+ 2. **Cross-Origin Isolation (`COOP`/`COEP`)**: Document responses must send `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`.
110
+
111
+ See the [Cross-Origin Isolation Guide](../getting-started/cross-origin.md) for server setup. If you cannot configure these headers and only need bounded integers and booleans, use [Pumpkin](./pumpkin.md) instead.
112
+
113
+ If a Z3 worker hits a fatal error, the pending promise rejects and the broken runtime is discarded so the next call starts cleanly. To shut down Z3 pthread workers explicitly—both in Node.js (so CLI scripts and processes exit cleanly) and in browsers (for example, when unmounting a view)—call:
114
+
115
+ ```typescript
116
+ import { killZ3Threads } from "@ohtaman/washi/solvers/z3";
117
+
118
+ await killZ3Threads();
119
+ ```