@ohtaman/washi 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +58 -19
- package/README.md +58 -19
- package/README.zh-CN.md +58 -19
- package/THIRD_PARTY_LICENSES.md +34 -1
- package/dist/browser/__vite-browser-external-rTVKos2U.js +7 -0
- package/dist/browser/browser-runtime-AG5QFtKf.js +2021 -0
- package/dist/browser/highs-worker.js +26 -11
- package/dist/browser/highs.wasm +0 -0
- package/dist/browser/{loader-DewlSho8.js → loader-i3FnqMes.js} +183 -149
- package/dist/browser/solvers/glpk.js +289 -238
- package/dist/browser/solvers/glpk.min.js +1 -1
- package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
- package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
- package/dist/browser/solvers/pumpkin-worker.js +45 -0
- package/dist/browser/solvers/pumpkin.js +1777 -0
- package/dist/browser/solvers/pumpkin.min.js +1 -0
- package/dist/browser/solvers/pumpkin.wasm +0 -0
- package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/browser/solvers/z3.js +1600 -1335
- package/dist/browser/solvers/z3.min.js +2 -2
- package/dist/browser/washi.js +3374 -1377
- package/dist/browser/washi.min.js +5 -3
- package/dist/lib/__vite-browser-external-oLchLuMx.js +7 -0
- package/dist/lib/highs-browser-runtime.js +1846 -1618
- package/dist/lib/highs-runtime.js +16 -2
- package/dist/lib/highs-worker.js +26 -11
- package/dist/lib/highs.wasm +0 -0
- package/dist/lib/{loader-BZUQNvh4.js → loader-CDpPXN_F.js} +138 -116
- package/dist/lib/registry-dx7x4e5c.js +1694 -0
- package/dist/lib/rolldown-runtime-DtPi1Y-2.js +13 -0
- package/dist/lib/solvers/glpk.js +161 -121
- package/dist/lib/solvers/pumpkin-assets.js +1 -0
- package/dist/lib/solvers/pumpkin-loader-Ow74Fa1B.js +311 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
- package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
- package/dist/lib/solvers/pumpkin-worker.js +45 -0
- package/dist/lib/solvers/pumpkin.js +1767 -0
- package/dist/lib/solvers/pumpkin.wasm +0 -0
- package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/lib/solvers/z3.js +486 -306
- package/dist/lib/washi.js +2563 -1154
- package/dist/types/decomposition/benders.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/boolean-expr.d.ts +137 -29
- package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
- package/dist/types/modeler/constraint.d.ts +40 -4
- package/dist/types/modeler/constraint.d.ts.map +1 -1
- package/dist/types/modeler/expression.d.ts +129 -2
- package/dist/types/modeler/expression.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +4 -5
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/linearizer.d.ts +11 -2
- package/dist/types/modeler/linearizer.d.ts.map +1 -1
- package/dist/types/modeler/lp-writer.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +85 -124
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/parser.d.ts.map +1 -1
- package/dist/types/modeler/quad-expr.d.ts +8 -2
- package/dist/types/modeler/quad-expr.d.ts.map +1 -1
- package/dist/types/modeler/solution-validator.d.ts +12 -12
- package/dist/types/modeler/solution-validator.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
- package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
- package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
- package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
- package/dist/types/modeler/solvers/mock.d.ts +2 -3
- package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
- package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
- package/dist/types/modeler/solvers/types.d.ts +7 -9
- package/dist/types/modeler/solvers/types.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
- package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
- package/dist/types/modeler/types.d.ts +12 -15
- package/dist/types/modeler/types.d.ts.map +1 -1
- package/dist/types/modeler/validation.d.ts +26 -2
- package/dist/types/modeler/validation.d.ts.map +1 -1
- package/dist/types/modeler/variable.d.ts +9 -5
- package/dist/types/modeler/variable.d.ts.map +1 -1
- package/docs/examples/index.md +6 -1
- package/docs/examples/project-scheduling.md +106 -0
- package/docs/examples/shift-scheduling.md +3 -0
- package/docs/examples/smt-security.md +1 -0
- package/docs/examples/traveling-salesperson.md +1 -1
- package/docs/examples/unsat-core.md +3 -2
- package/docs/getting-started/ai-agents.md +94 -25
- package/docs/getting-started/coding-agents.md +158 -0
- package/docs/getting-started/cross-origin.md +2 -2
- package/docs/getting-started/index.md +40 -41
- package/docs/getting-started/runtimes.md +42 -18
- package/docs/guide/constraint-programming.md +141 -0
- package/docs/guide/constraints.md +64 -14
- package/docs/guide/decomposition.md +59 -59
- package/docs/guide/expressions.md +42 -10
- package/docs/guide/formulation-tips.md +6 -6
- package/docs/guide/objectives.md +65 -62
- package/docs/guide/unsat-core.md +36 -27
- package/docs/guide/variables.md +30 -17
- package/docs/solvers/custom-solver.md +18 -13
- package/docs/solvers/highs.md +18 -23
- package/docs/solvers/index.md +12 -6
- package/docs/solvers/pumpkin.md +163 -0
- package/docs/solvers/z3.md +2 -2
- package/llms-full.txt +944 -314
- package/llms.txt +43 -22
- package/package.json +38 -11
- package/skills/washi/SKILL.md +79 -27
- package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
- package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
- package/docs/ja/getting-started/ai-agents.md +0 -280
- package/docs/zh/getting-started/ai-agents.md +0 -280
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Formulation Patterns & Optimization Tips
|
|
2
2
|
|
|
3
|
-
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).
|
|
3
|
+
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](./constraint-programming.md).)*
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -77,7 +77,9 @@ m.objective(maximize(expr`10 * ${xA} + 10 * ${xB} + 5 * ${bothAB}`));
|
|
|
77
77
|
|
|
78
78
|
### Min-Max & Max-Min Objectives (Load Balancing)
|
|
79
79
|
|
|
80
|
-
|
|
80
|
+
WaSHI's built-in `max(...)` and `min(...)` primitives (see [Piecewise-Linear & Element Expressions](./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.
|
|
81
|
+
|
|
82
|
+
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):
|
|
81
83
|
|
|
82
84
|
$$\min z \quad \text{subject to} \quad \text{load}_i \le z \quad \forall i$$
|
|
83
85
|
|
|
@@ -97,8 +99,6 @@ m.constraint(expr`sum(${hours}) >= 60`, "total_required_work");
|
|
|
97
99
|
m.objective(minimize(maxHours));
|
|
98
100
|
```
|
|
99
101
|
|
|
100
|
-
*(Symmetrically, to **maximize the minimum** level $\max \min_i u_i$, impose $u_i \ge z$ for all $i$ and set `m.objective(maximize(z))`.)*
|
|
101
|
-
|
|
102
102
|
---
|
|
103
103
|
|
|
104
104
|
## 3. Constraint Design & Numerical Conditioning
|
|
@@ -195,8 +195,8 @@ await m.solve();
|
|
|
195
195
|
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**).
|
|
196
196
|
|
|
197
197
|
In interactive UIs and batch pipelines, combine `timeLimit` with business-meaningful tolerances in [`m.solve(options)`](./objectives.md#solve-options-solveoptions):
|
|
198
|
-
- **`
|
|
199
|
-
- **`
|
|
198
|
+
- **`relativeGap: 0.01`**: Stop immediately once the incumbent is proven within **1%** of the theoretical dual bound.
|
|
199
|
+
- **`absoluteGap: 100`**: Stop immediately once `|objectiveValue - objectiveBound| <= 100` in the objective's native units.
|
|
200
200
|
|
|
201
201
|
---
|
|
202
202
|
|
package/docs/guide/objectives.md
CHANGED
|
@@ -26,7 +26,7 @@ m.constraint(expr`2 * ${x} + 3 * ${y} <= 100`, "resource_limit");
|
|
|
26
26
|
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`.
|
|
27
27
|
|
|
28
28
|
> [!TIP]
|
|
29
|
-
> For objective formulation patterns—such as **Min-Max / Max-Min load balancing**, **weighted-sum vs. lexicographic multi-objective optimization**, and **MIP stopping tolerances (`
|
|
29
|
+
> 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](./formulation-tips.md#_4-multi-objective-mip-stopping-design).
|
|
30
30
|
|
|
31
31
|
---
|
|
32
32
|
|
|
@@ -37,13 +37,13 @@ WaSHI provides two asynchronous execution entrypoints:
|
|
|
37
37
|
| Method | Return Value | Purpose |
|
|
38
38
|
| :--- | :--- | :--- |
|
|
39
39
|
| **`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. |
|
|
40
|
-
| **`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. |
|
|
40
|
+
| **`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. |
|
|
41
41
|
|
|
42
42
|
```typescript
|
|
43
43
|
const status = await m.solve({
|
|
44
|
-
timeLimit: 10.0,
|
|
45
|
-
|
|
46
|
-
outputFlag: false,
|
|
44
|
+
timeLimit: 10.0, // Timeout in seconds
|
|
45
|
+
relativeGap: 0.01, // Stop within 1% of global optimum
|
|
46
|
+
outputFlag: false, // Enable/disable solver console logging (HiGHS: outputFlag, GLPK: verbose)
|
|
47
47
|
});
|
|
48
48
|
```
|
|
49
49
|
|
|
@@ -51,14 +51,14 @@ const status = await m.solve({
|
|
|
51
51
|
|
|
52
52
|
| Option | Type | Default | Description |
|
|
53
53
|
| :--- | :--- | :--- | :--- |
|
|
54
|
-
| `solver` | `string` \| `Solver` | Model's solver (`"highs"`) | Registered solver name (e.g. `"highs"`, `"z3"`, `"glpk"`, or custom) or `Solver` instance for this run. |
|
|
54
|
+
| `solver` | `string` \| `Solver` | Model's solver (`"highs"`) | Registered solver name (e.g. `"highs"`, `"pumpkin"`, `"z3"`, `"glpk"`, or custom) or `Solver` instance for this run. |
|
|
55
55
|
| `timeLimit` | `number` | `undefined` | Maximum solve duration in seconds. |
|
|
56
|
-
| `
|
|
57
|
-
| `
|
|
56
|
+
| `relativeGap` | `number` | `undefined` | Relative MIP optimality gap tolerance (e.g. `0.01` for 1%). |
|
|
57
|
+
| `absoluteGap` | `number` | `undefined` | Absolute MIP optimality gap tolerance (HiGHS `mip_abs_gap`). |
|
|
58
58
|
| `presolve` | `"on"` \| `"off"` \| `"choose"` | `"choose"` | Controls solver presolve reduction prior to optimization. |
|
|
59
59
|
| `outputFlag` / `verbose` | `boolean` | `false` | Emits internal solver iteration logs (`outputFlag` for HiGHS, `verbose` for GLPK). |
|
|
60
|
-
| `useWorker` | `boolean` | `true` (browser) | Offloads HiGHS to
|
|
61
|
-
| `wasmUrl` | `string` | Auto-resolved | Custom URL to load `highs.wasm` in browser deployments. |
|
|
60
|
+
| `useWorker` | `boolean` | `true` (browser) | Offloads **HiGHS** and **Pumpkin** to dedicated Web Workers in browsers. Set `false` for main-thread execution. |
|
|
61
|
+
| `wasmUrl` | `string` | Auto-resolved | Custom URL to load `highs.wasm` or `pumpkin.wasm` in browser deployments. |
|
|
62
62
|
| `signal` | `AbortSignal` | `undefined` | Cooperative cancellation signal (`AbortController.signal`). |
|
|
63
63
|
| `onProgress` | `(e: SolveProgressEvent) => void` | `undefined` | Callback receiving live solver progress snapshots. |
|
|
64
64
|
|
|
@@ -66,52 +66,6 @@ You can also pass a solver name directly as the first argument: `await m.solve("
|
|
|
66
66
|
|
|
67
67
|
---
|
|
68
68
|
|
|
69
|
-
## Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
|
|
70
|
-
|
|
71
|
-
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`:
|
|
72
|
-
|
|
73
|
-
```typescript
|
|
74
|
-
const controller = new AbortController();
|
|
75
|
-
|
|
76
|
-
// Example: cancel if the user clicks a "Stop" button or after a custom condition
|
|
77
|
-
const status = await m.solve({
|
|
78
|
-
signal: controller.signal,
|
|
79
|
-
onProgress: (event) => {
|
|
80
|
-
console.log(
|
|
81
|
-
`[${event.elapsedTime.toFixed(1)}s] ` +
|
|
82
|
-
`Best: ${event.objectiveValue ?? "—"}, ` +
|
|
83
|
-
`Bound: ${event.objectiveBound ?? "—"}, ` +
|
|
84
|
-
`Gap: ${event.mipGap !== undefined ? (event.mipGap * 100).toFixed(2) + "%" : "—"}`
|
|
85
|
-
);
|
|
86
|
-
|
|
87
|
-
// Optional: stop early as soon as a good-enough incumbent is found
|
|
88
|
-
if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
|
|
89
|
-
controller.abort();
|
|
90
|
-
}
|
|
91
|
-
},
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
console.log("Status:", m.status); // "Feasible" (if an incumbent was found before abort) or "Unknown"
|
|
95
|
-
console.log("Termination:", m.terminationStatus); // "Interrupted"
|
|
96
|
-
console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
### `SolveProgressEvent` Fields
|
|
100
|
-
|
|
101
|
-
| Field | Type | Description |
|
|
102
|
-
| :--- | :--- | :--- |
|
|
103
|
-
| `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
|
|
104
|
-
| `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
|
|
105
|
-
| `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
|
|
106
|
-
| `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
|
|
107
|
-
| `relGap` / `mipGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
|
|
108
|
-
| `absGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
|
|
109
|
-
| `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
|
|
110
|
-
| `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
|
|
111
|
-
| `message` | `string \| undefined` | Raw progress line emitted by the solver. |
|
|
112
|
-
|
|
113
|
-
---
|
|
114
|
-
|
|
115
69
|
## Reading Results, Bounds & Solver Status
|
|
116
70
|
|
|
117
71
|
After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
|
|
@@ -126,14 +80,17 @@ console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value /
|
|
|
126
80
|
// Objective & MIP Gap Metrics
|
|
127
81
|
console.log("Objective Value:", m.objectiveValue); // Best primal objective (or null)
|
|
128
82
|
console.log("Objective Bound:", m.objectiveBound); // Best dual bound (or undefined)
|
|
129
|
-
console.log("Relative Gap:", m.
|
|
130
|
-
console.log("Absolute Gap:", m.
|
|
83
|
+
console.log("Relative Gap:", m.relativeGap); // Relative MIP gap
|
|
84
|
+
console.log("Absolute Gap:", m.absoluteGap); // |objectiveValue - objectiveBound|
|
|
131
85
|
|
|
132
|
-
//
|
|
86
|
+
// Variable Values (via .value or name-keyed m.values ReadonlyMap)
|
|
133
87
|
console.log("x =", x.value, "y =", y.value);
|
|
134
|
-
console.log(m.
|
|
88
|
+
console.log("x by name:", m.values.get("x"));
|
|
135
89
|
```
|
|
136
90
|
|
|
91
|
+
> [!TIP]
|
|
92
|
+
> To independently check that the returned values satisfy all bounds, integrality requirements, and constraints within tolerance, call `m.verify()`—see [Diagnosis, Verification & Debugging](./unsat-core.md#independent-solution-verification-m-verify).
|
|
93
|
+
|
|
137
94
|
### Understanding `m.status` vs. `m.terminationStatus`
|
|
138
95
|
|
|
139
96
|
When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two distinct questions matter:
|
|
@@ -160,14 +117,60 @@ If an integer-feasible incumbent was found before hitting `timeLimit` or `signal
|
|
|
160
117
|
|
|
161
118
|
---
|
|
162
119
|
|
|
120
|
+
## Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
|
|
121
|
+
|
|
122
|
+
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`:
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
const controller = new AbortController();
|
|
126
|
+
|
|
127
|
+
// Example: cancel if the user clicks a "Stop" button or after a custom condition
|
|
128
|
+
const status = await m.solve({
|
|
129
|
+
signal: controller.signal,
|
|
130
|
+
onProgress: (event) => {
|
|
131
|
+
console.log(
|
|
132
|
+
`[${event.elapsedTime.toFixed(1)}s] ` +
|
|
133
|
+
`Best: ${event.objectiveValue ?? "—"}, ` +
|
|
134
|
+
`Bound: ${event.objectiveBound ?? "—"}, ` +
|
|
135
|
+
`Gap: ${event.relativeGap !== undefined ? (event.relativeGap * 100).toFixed(2) + "%" : "—"}`
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
// Optional: stop early as soon as a good-enough incumbent is found
|
|
139
|
+
if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
|
|
140
|
+
controller.abort();
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
console.log("Status:", m.status); // "Feasible" (if an incumbent was found before abort) or "Unknown"
|
|
146
|
+
console.log("Termination:", m.terminationStatus); // "Interrupted"
|
|
147
|
+
console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### `SolveProgressEvent` Fields
|
|
151
|
+
|
|
152
|
+
| Field | Type | Description |
|
|
153
|
+
| :--- | :--- | :--- |
|
|
154
|
+
| `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
|
|
155
|
+
| `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
|
|
156
|
+
| `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
|
|
157
|
+
| `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
|
|
158
|
+
| `relativeGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
|
|
159
|
+
| `absoluteGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
|
|
160
|
+
| `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
|
|
161
|
+
| `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
|
|
162
|
+
| `message` | `string \| undefined` | Raw progress line emitted by the solver. |
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
163
166
|
## Model Mutations & Execution Validity
|
|
164
167
|
|
|
165
168
|
A `Model` instance keeps its solution state synchronized across mutations made through `Model` methods and `Model` / `Var` / `Constraint` property setters:
|
|
166
169
|
|
|
167
|
-
1. **Post-Solve Mutations Reset Solution State**: Adding variables or constraints, updating the objective (`m.objective(...)`, `m.
|
|
170
|
+
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`.
|
|
168
171
|
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.
|
|
169
172
|
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.
|
|
170
173
|
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.
|
|
171
174
|
|
|
172
175
|
> [!NOTE]
|
|
173
|
-
> Renaming already-registered variables or constraints (e.g., reassigning `c.name` after registration) or mutating internal backing
|
|
176
|
+
> 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.
|
package/docs/guide/unsat-core.md
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
|
-
# Conflict Diagnosis (`unsatCore`) &
|
|
1
|
+
# Conflict Diagnosis (`unsatCore`), Validation & Debugging
|
|
2
2
|
|
|
3
|
-
When building real-world optimization and
|
|
4
|
-
1. **Why is my model infeasible?** Which specific business rules contradict each other?
|
|
5
|
-
2. **Does the solver's solution genuinely satisfy every constraint?** How do I verify tolerances, integrality, and formulations?
|
|
3
|
+
When building real-world optimization and rule systems, you need to diagnose infeasible models, verify returned solutions, and inspect or unit-test formulations cleanly.
|
|
6
4
|
|
|
7
|
-
WaSHI provides
|
|
5
|
+
WaSHI provides a unified verification and debugging toolkit for all three:
|
|
6
|
+
- **Conflict diagnosis (`m.check()`)**: Pinpoint contradictory constraints via built-in HiGHS elastic relaxation, bundled Pumpkin Unsat Core, or Z3 Unsat Core.
|
|
7
|
+
- **Solution verification & LP inspection (`m.verify()`, `m.toLpString()`)**: Independently verify variable bounds, integrality, and constraints, and export CPLEX `.lp` text to inspect generated equations.
|
|
8
|
+
- **Fast unit testing (`MockSolver`)**: Test application model-building and post-processing logic in CI without loading WebAssembly.
|
|
8
9
|
|
|
9
10
|
---
|
|
10
11
|
|
|
11
12
|
## Conflict Diagnosis (`unsatCore` / `conflicts`)
|
|
12
13
|
|
|
13
14
|
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.
|
|
14
|
-
By calling **`await m.check({ solver: "z3" })
|
|
15
|
+
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:
|
|
15
16
|
|
|
16
17
|
```typescript
|
|
17
18
|
import { Model, expr } from "@ohtaman/washi";
|
|
18
|
-
// Register the Z3 solver plugin
|
|
19
|
+
// Register the Z3 solver plugin (for Continuous / real-valued SMT models)
|
|
19
20
|
import "@ohtaman/washi/solvers/z3";
|
|
20
21
|
|
|
21
22
|
const m = new Model();
|
|
@@ -39,14 +40,15 @@ if (result.status === "Unsat") {
|
|
|
39
40
|
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.
|
|
40
41
|
|
|
41
42
|
> [!IMPORTANT]
|
|
42
|
-
> - **Use `m.check({ solver: "z3" })` for Unsat Core extraction**: `m.solve()` runs optimization
|
|
43
|
+
> - **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`).
|
|
43
44
|
> - **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")`.
|
|
44
45
|
|
|
45
|
-
### Workflow: Infeasibility Diagnosis with HiGHS or Z3
|
|
46
|
+
### Workflow: Infeasibility Diagnosis with HiGHS, Pumpkin, or Z3
|
|
46
47
|
|
|
47
|
-
Because WaSHI models are solver-independent, you can
|
|
48
|
-
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
|
|
49
|
-
2. **
|
|
48
|
+
Because WaSHI models are solver-independent, you can choose from three diagnosis strategies:
|
|
49
|
+
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.
|
|
50
|
+
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**.
|
|
51
|
+
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.
|
|
50
52
|
|
|
51
53
|
```typescript
|
|
52
54
|
const status = await m.solve(); // Fast MIP solve with default HiGHS
|
|
@@ -56,27 +58,34 @@ if (status === "Infeasible") {
|
|
|
56
58
|
const diag = await m.check();
|
|
57
59
|
console.error("Model is infeasible due to conflicting rules:", diag.conflicts);
|
|
58
60
|
|
|
59
|
-
// Option 2:
|
|
61
|
+
// Option 2: Bundled zero-COOP/COEP unsat core with Pumpkin (bounded int/bool models; requires import "@ohtaman/washi/solvers/pumpkin")
|
|
62
|
+
// const pumpkinDiag = await m.check({ solver: "pumpkin" });
|
|
63
|
+
// console.error("Pumpkin Unsat Core:", pumpkinDiag.unsatCore);
|
|
64
|
+
|
|
65
|
+
// Option 3: Exact SMT unsat core diagnosis with Z3 (supports Continuous/real vars; requires import "@ohtaman/washi/solvers/z3")
|
|
60
66
|
// const z3Diag = await m.check({ solver: "z3" });
|
|
61
67
|
// console.error("Z3 Unsat Core:", z3Diag.unsatCore);
|
|
62
68
|
}
|
|
63
69
|
```
|
|
64
70
|
|
|
65
|
-
### Comparing Z3 `unsatCore
|
|
71
|
+
### Comparing Pumpkin `unsatCore`, Z3 `unsatCore`, and HiGHS Elastic Slack `conflicts`
|
|
66
72
|
|
|
67
|
-
| Property | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()`) |
|
|
68
|
-
| :--- | :--- | :--- |
|
|
69
|
-
| **
|
|
70
|
-
| **
|
|
71
|
-
| **
|
|
72
|
-
| **
|
|
73
|
+
| Property | Pumpkin (`m.check({ solver: "pumpkin" })`) | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()`) |
|
|
74
|
+
| :--- | :--- | :--- | :--- |
|
|
75
|
+
| **Setup & Dependencies** | **Bundled** (`@ohtaman/washi/solvers/pumpkin`, zero peer deps) | Optional peer dependency (`z3-solver`) | **Built-in** (HiGHS) / optional `glpk.js` |
|
|
76
|
+
| **Browser Headers** | **None** (`COOP` / `COEP` not required) | Requires `COOP` / `COEP` (`SharedArrayBuffer`) | **None** |
|
|
77
|
+
| **Supported Variables** | Bounded `Integer`, `Binary`, `BoolVar` | `Continuous`, `Integer`, `Binary`, `BoolVar` | `Continuous`, `Integer`, `Binary`, `BoolVar` |
|
|
78
|
+
| **Algorithm** | LCG conflict analysis under constraint assumptions | SMT assumption tracking (`assertAndTrack`) | Single-solve $L_1$ elastic slack relaxation ($\min \sum s_i$) |
|
|
79
|
+
| **Populated Fields** | Both `result.unsatCore` and `result.conflicts` | Both `result.unsatCore` and `result.conflicts` | `result.conflicts` (`unsatCore` is `undefined`) |
|
|
80
|
+
| **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 |
|
|
81
|
+
| **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) |
|
|
73
82
|
|
|
74
83
|
> [!TIP]
|
|
75
|
-
> When diagnosing models that mix constraints of vastly different magnitudes (e.g., headcount $\le 8$ alongside budget $\le 50{,}000$), use **`m.check({ solver: "z3" })`** if you want
|
|
84
|
+
> 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.
|
|
76
85
|
|
|
77
86
|
---
|
|
78
87
|
|
|
79
|
-
## Independent Solution
|
|
88
|
+
## Independent Solution Verification (`m.verify()`)
|
|
80
89
|
|
|
81
90
|
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:
|
|
82
91
|
|
|
@@ -84,7 +93,7 @@ After solving a model (or supplying a custom candidate map via `values`), you ca
|
|
|
84
93
|
const status = await m.solve();
|
|
85
94
|
|
|
86
95
|
if (m.hasPrimalSolution) {
|
|
87
|
-
const report = m.
|
|
96
|
+
const report = m.verify({
|
|
88
97
|
feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
|
|
89
98
|
integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
|
|
90
99
|
evaluateLogicalConstraints: true,
|
|
@@ -101,18 +110,18 @@ if (m.hasPrimalSolution) {
|
|
|
101
110
|
}
|
|
102
111
|
```
|
|
103
112
|
|
|
104
|
-
### `
|
|
113
|
+
### `VerificationReport` Summary
|
|
105
114
|
|
|
106
115
|
| Property | Type | Description |
|
|
107
116
|
| :--- | :--- | :--- |
|
|
108
117
|
| `valid` | `boolean` | `true` iff `complete === true`, `uncheckedConstraints.length === 0`, and `violations.length === 0`. |
|
|
109
118
|
| `complete` | `boolean` | `true` when all variables, Boolean variables, linear constraints, and logical constraints were evaluated. |
|
|
110
119
|
| `maxViolation` | `number` | Largest numeric violation magnitude across all evaluated bounds, integrality checks, and constraints. |
|
|
111
|
-
| `violations` | `
|
|
112
|
-
| `violationsByName` | `Record<string,
|
|
120
|
+
| `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"`). |
|
|
121
|
+
| `violationsByName` | `Record<string, VerificationViolation[]>` | Violations grouped by variable or constraint name. |
|
|
113
122
|
| `uncheckedConstraints` | `string[]` | Names of constraints that could not be evaluated. |
|
|
114
123
|
| `missingVariables` | `string[]` | Names of numeric or Boolean variables whose values were `null` or `undefined`. |
|
|
115
|
-
| `summary` | `
|
|
124
|
+
| `summary` | `VerificationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
|
|
116
125
|
|
|
117
126
|
---
|
|
118
127
|
|
package/docs/guide/variables.md
CHANGED
|
@@ -55,7 +55,7 @@ m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
|
|
|
55
55
|
| **Linear arithmetic (`expr`, `sum`, `dot`, objective costs)** | ✅ Native (`` expr`30 * ${b}` ``) | ❌ Cannot be multiplied by numbers or summed directly |
|
|
56
56
|
| **Indicator constraints (`m.indicator(b, ...)` )** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
|
|
57
57
|
| **Propositional logic (`and`, `or`, `not`, `implies`, `xor`)** | Via comparison (`` expr`${b} == 1` ``) | ✅ Native first-class methods (`.implies()`, `.and()`) |
|
|
58
|
-
| **Solver execution** | Native 0-1 MIP on HiGHS/GLPK; bounded integer on Z3 | Native boolean proposition on Z3; auto-linearized to 0-1 MIP on HiGHS/GLPK |
|
|
58
|
+
| **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 |
|
|
59
59
|
|
|
60
60
|
> [!TIP]
|
|
61
61
|
> 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.
|
|
@@ -117,11 +117,17 @@ const schedule = m.binary(factories, 7, { prefix: "open_day" });
|
|
|
117
117
|
|
|
118
118
|
| Option | Type | Default | Description |
|
|
119
119
|
| :--- | :--- | :--- | :--- |
|
|
120
|
-
| `lb` | `number` | `0` | Lower bound. Defaults to `0` (non-negative). |
|
|
120
|
+
| `lb` | `number` | `0` | Lower bound. Defaults to `0` (non-negative). Pass `-Infinity` for free lower bounds. |
|
|
121
121
|
| `ub` | `number` | `Infinity` (or `1` for binary) | Upper bound. |
|
|
122
|
+
| `prefix` | `string` | `"x"` (`"p"` for `m.bool()`) | Name prefix for unnamed scalar variables and indexed arrays/matrices (e.g., `queen_0_0`). |
|
|
122
123
|
| `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Underlying variable domain category. |
|
|
123
124
|
| `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP warm start), kept distinct from solved `variable.value`. |
|
|
124
125
|
|
|
126
|
+
### Designing Bounds (`lb` & `ub`)
|
|
127
|
+
|
|
128
|
+
- **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 }`.
|
|
129
|
+
- **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**.
|
|
130
|
+
|
|
125
131
|
---
|
|
126
132
|
|
|
127
133
|
## Primal Initial Values (Warm-Start Hints)
|
|
@@ -143,41 +149,48 @@ const openWarehouse2 = m2.binary("open_warehouse", {
|
|
|
143
149
|
const extraCapacity = m2.continuous("extra_capacity", { lb: 0 }); // Partial start: no initialValue needed
|
|
144
150
|
```
|
|
145
151
|
|
|
146
|
-
- **Hint vs. Hard Constraint**: `initialValue` is an optional solver hint (passed to HiGHS via `setSolution`). It does **not** fix the variable or add a constraint, and `variable.value` remains `null` until solved. *(To penalize deviations from a previous plan, see [Formulation Patterns & Tips](./formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).)*
|
|
152
|
+
- **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](./formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).)*
|
|
147
153
|
- **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.
|
|
148
|
-
- **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`.
|
|
154
|
+
- **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`.
|
|
149
155
|
|
|
150
156
|
---
|
|
151
157
|
|
|
152
158
|
## Accessing Solution Values & Reduced Costs
|
|
153
159
|
|
|
154
|
-
After calling `await m.solve()` or `await m.check()`, assigned variable values are accessible via `variable.value` (returns `number | null` for `Var`, or `boolean | null` for `BoolVar`) or
|
|
160
|
+
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`:
|
|
155
161
|
|
|
156
162
|
```typescript
|
|
157
163
|
await m.solve();
|
|
158
164
|
|
|
159
|
-
//
|
|
165
|
+
// Scalar variable primal & boolean values
|
|
160
166
|
console.log(`trucks: ${trucks.value}`);
|
|
167
|
+
console.log(`isAdmin: ${isAdmin.value}`);
|
|
161
168
|
|
|
162
|
-
//
|
|
163
|
-
|
|
169
|
+
// Indexed 1D & 2D variable containers
|
|
170
|
+
const packedItems = items.filter((it) => selected[it].value === 1);
|
|
171
|
+
console.log(`Tokyo -> StoreA: ${ship.Tokyo.StoreA.value}`);
|
|
164
172
|
|
|
165
|
-
//
|
|
166
|
-
|
|
167
|
-
// { laptop: 1, phone: 0, tablet: 1 }
|
|
173
|
+
// Name-keyed ReadonlyMap lookup (ReadonlyMap<string, number | boolean>)
|
|
174
|
+
console.log(`trucks by name: ${m.values.get("trucks")}`);
|
|
168
175
|
|
|
169
|
-
|
|
170
|
-
|
|
176
|
+
// Reduced cost (LP sensitivity analysis)
|
|
177
|
+
console.log(`fuel reduced cost: ${fuel.reducedCost}`);
|
|
171
178
|
```
|
|
172
179
|
|
|
173
180
|
---
|
|
174
181
|
|
|
175
182
|
## Looking Up Variables by Name
|
|
176
183
|
|
|
177
|
-
|
|
184
|
+
All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are exposed through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
|
|
178
185
|
|
|
179
186
|
```typescript
|
|
180
|
-
const v = m.
|
|
181
|
-
const b = m.
|
|
182
|
-
console.log("
|
|
187
|
+
const v = m.variables.get("trucks"); // Var | BoolVar | undefined
|
|
188
|
+
const b = m.variables.get("isAdmin"); // Var | BoolVar | undefined
|
|
189
|
+
console.log("Has trucks:", m.variables.has("trucks"));
|
|
190
|
+
console.log("Total variables:", m.variables.size);
|
|
191
|
+
|
|
192
|
+
// Narrow by v.type ("Continuous" | "Integer" | "Binary" | "Boolean"):
|
|
193
|
+
if (v && v.type !== "Boolean") {
|
|
194
|
+
console.log("Bounds:", v.lb, v.ub);
|
|
195
|
+
}
|
|
183
196
|
```
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
This guide describes how to build, test, and distribute custom solver plugins for **WaSHI** (`@ohtaman/washi`).
|
|
4
4
|
|
|
5
|
-
WaSHI features a pluggable, decoupled solver architecture. Core `@ohtaman/washi` bundles
|
|
5
|
+
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.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -13,6 +13,7 @@ graph TD
|
|
|
13
13
|
A[WaSHI Model] --> B[Solver Registry Map Symbol.for]
|
|
14
14
|
B --> C[HiGHS WASM Engine Core]
|
|
15
15
|
B --> D[Mock Solver Core]
|
|
16
|
+
B --> H[Pumpkin WASM Plugin @ohtaman/washi/solvers/pumpkin]
|
|
16
17
|
B --> E[GLPK Plugin @ohtaman/washi/solvers/glpk]
|
|
17
18
|
B --> F[Z3 SMT Plugin @ohtaman/washi/solvers/z3]
|
|
18
19
|
B --> G[Your Custom Solver Plugin]
|
|
@@ -69,7 +70,7 @@ export interface Solver {
|
|
|
69
70
|
* Main solve method for LP, MIP, QP, and SMT optimization models.
|
|
70
71
|
*
|
|
71
72
|
* @param modelData Typed in-memory model structure (variables, constraints, objective, sense, boolVars, logicalConstraints)
|
|
72
|
-
* @param options Runtime execution options (timeLimit,
|
|
73
|
+
* @param options Runtime execution options (timeLimit, relativeGap, absoluteGap, verbose, signal, onProgress, etc.)
|
|
73
74
|
*/
|
|
74
75
|
solve(
|
|
75
76
|
modelData: SolveModelData,
|
|
@@ -119,7 +120,7 @@ export interface SolveModelData extends CheckModelData {
|
|
|
119
120
|
|
|
120
121
|
Custom solvers declare their supported features using `capabilities`. Before dispatching `solve()` or `check()`, `Model` validates:
|
|
121
122
|
- `supportsQP === false` when the objective contains quadratic terms (`QuadExpr`),
|
|
122
|
-
- when the model contains logical constraints (`m.logicalConstraints`) and the solver
|
|
123
|
+
- 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
|
|
123
124
|
- `supportsWarmStart !== true` when any variable has a primal `initialValue` set.
|
|
124
125
|
|
|
125
126
|
```typescript
|
|
@@ -136,6 +137,9 @@ export interface SolverCapabilities {
|
|
|
136
137
|
/** Supports satisfiability modulo theories / boolean logic constraints */
|
|
137
138
|
supportsSMT?: boolean;
|
|
138
139
|
|
|
140
|
+
/** Supports native boolean/propositional logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`) without SMT continuous theories */
|
|
141
|
+
supportsLogicalConstraints?: boolean;
|
|
142
|
+
|
|
139
143
|
/** Supports extracting an unsatisfiable core (conflicting constraint subset) */
|
|
140
144
|
supportsUnsatCore?: boolean;
|
|
141
145
|
|
|
@@ -153,8 +157,11 @@ export interface SolverOptions {
|
|
|
153
157
|
/** Time limit in seconds */
|
|
154
158
|
timeLimit?: number;
|
|
155
159
|
|
|
156
|
-
/** Relative MIP optimality gap tolerance */
|
|
157
|
-
|
|
160
|
+
/** Relative MIP optimality gap tolerance (e.g. 0.01 for 1%) */
|
|
161
|
+
relativeGap?: number;
|
|
162
|
+
|
|
163
|
+
/** Absolute MIP optimality gap tolerance */
|
|
164
|
+
absoluteGap?: number;
|
|
158
165
|
|
|
159
166
|
/** Enable solver console logging */
|
|
160
167
|
verbose?: boolean;
|
|
@@ -172,7 +179,7 @@ export interface SolverOptions {
|
|
|
172
179
|
|
|
173
180
|
### Optional LP Serialization & Symbol-Mapping Helpers
|
|
174
181
|
|
|
175
|
-
Solvers that consume structured JS/WASM data (such as `GLPKSolver
|
|
182
|
+
Solvers that consume structured JS/WASM data (such as `PumpkinSolver`, `GLPKSolver`, and `Z3Solver`) work directly with `SolveModelData` / `CheckModelData`.
|
|
176
183
|
If your adapter targets a backend that requires CPLEX/HiGHS LP text or restricted identifier syntax, WaSHI exports opt-in helpers:
|
|
177
184
|
|
|
178
185
|
- `generateLpString(modelData): LpExportResult` — serializes `modelData` into a CPLEX LP format string (`lpString`) along with collision-safe symbol lookup maps (`nameToVar`, `nameToConstraint`).
|
|
@@ -215,13 +222,10 @@ export interface SolverResult {
|
|
|
215
222
|
objectiveBound?: number;
|
|
216
223
|
|
|
217
224
|
/** Relative MIP optimality gap when provided by the solver */
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
/** Alias for relGap: relative MIP optimality gap when provided by the solver */
|
|
221
|
-
mipGap?: number;
|
|
225
|
+
relativeGap?: number;
|
|
222
226
|
|
|
223
227
|
/** Absolute MIP optimality gap |objectiveValue - objectiveBound| (computed automatically when both are finite) */
|
|
224
|
-
|
|
228
|
+
absoluteGap?: number;
|
|
225
229
|
|
|
226
230
|
/** Variable primal values keyed by canonical variable name (non-finite values are ignored) */
|
|
227
231
|
values: Record<string, number>;
|
|
@@ -317,7 +321,8 @@ export class CloudSolver implements Solver {
|
|
|
317
321
|
body: JSON.stringify({
|
|
318
322
|
lp: lpString,
|
|
319
323
|
timeLimit: options.timeLimit,
|
|
320
|
-
|
|
324
|
+
relativeGap: options.relativeGap,
|
|
325
|
+
absoluteGap: options.absoluteGap,
|
|
321
326
|
}),
|
|
322
327
|
signal: options.signal,
|
|
323
328
|
});
|
|
@@ -515,7 +520,7 @@ describe("Custom Solver Integration", () => {
|
|
|
515
520
|
const status = await model.solve();
|
|
516
521
|
expect(status).toBe("Optimal");
|
|
517
522
|
expect(x.value).toBe(2);
|
|
518
|
-
const c1 = model.
|
|
523
|
+
const c1 = model.constraints.get("budget");
|
|
519
524
|
expect(c1?.dual).toBe(2);
|
|
520
525
|
} finally {
|
|
521
526
|
fetchSpy.mockRestore();
|