@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.
- package/README.ja.md +139 -418
- package/README.md +139 -418
- package/README.zh-CN.md +139 -418
- package/THIRD_PARTY_LICENSES.md +39 -4
- 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 +3828 -1315
- 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 +3054 -1202
- 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 +176 -28
- package/dist/types/modeler/expression.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +5 -6
- 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 +97 -130
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/parser.d.ts +25 -5
- 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 +9 -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/diet-sensitivity.md +15 -14
- package/docs/examples/ecommerce-coupons.md +15 -22
- package/docs/examples/index.md +20 -13
- package/docs/examples/knapsack.md +8 -7
- package/docs/examples/portfolio-qp.md +11 -4
- package/docs/examples/production.md +4 -4
- package/docs/examples/project-scheduling.md +106 -0
- package/docs/examples/shift-scheduling.md +23 -7
- package/docs/examples/smt-security.md +17 -4
- package/docs/examples/transportation.md +46 -19
- package/docs/examples/traveling-salesperson.md +29 -45
- package/docs/examples/unsat-core.md +16 -5
- package/docs/examples/vehicle-routing.md +10 -8
- package/docs/getting-started/ai-agents.md +114 -34
- package/docs/getting-started/coding-agents.md +158 -0
- package/docs/getting-started/cross-origin.md +56 -28
- package/docs/getting-started/index.md +36 -66
- package/docs/getting-started/runtimes.md +98 -69
- package/docs/guide/constraint-programming.md +141 -0
- package/docs/guide/constraints.md +100 -44
- package/docs/guide/decomposition.md +141 -273
- package/docs/guide/expressions.md +125 -42
- package/docs/guide/formulation-tips.md +212 -0
- package/docs/guide/objectives.md +70 -64
- package/docs/guide/unsat-core.md +44 -23
- package/docs/guide/variables.md +56 -48
- package/docs/solvers/custom-solver.md +18 -13
- package/docs/solvers/highs.md +41 -25
- package/docs/solvers/index.md +13 -7
- package/docs/solvers/pumpkin.md +163 -0
- package/docs/solvers/z3.md +4 -1
- package/llms-full.txt +1732 -860
- package/llms.txt +59 -36
- package/package.json +40 -13
- package/skills/washi/SKILL.md +91 -35
- 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-C20sxTwm.js +0 -964
- package/docs/ja/getting-started/ai-agents.md +0 -270
- package/docs/zh/getting-started/ai-agents.md +0 -270
package/docs/guide/objectives.md
CHANGED
|
@@ -25,22 +25,25 @@ m.constraint(expr`2 * ${x} + 3 * ${y} <= 100`, "resource_limit");
|
|
|
25
25
|
|
|
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
|
+
> [!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 (`relativeGap` / `absoluteGap`)**—see [Formulation Patterns & Optimization Tips](./formulation-tips.md#_4-multi-objective-mip-stopping-design).
|
|
30
|
+
|
|
28
31
|
---
|
|
29
32
|
|
|
30
|
-
##
|
|
33
|
+
## Solving the Model (`m.solve()` vs. `m.check()`)
|
|
31
34
|
|
|
32
35
|
WaSHI provides two asynchronous execution entrypoints:
|
|
33
36
|
|
|
34
37
|
| Method | Return Value | Purpose |
|
|
35
38
|
| :--- | :--- | :--- |
|
|
36
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. |
|
|
37
|
-
| **`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. |
|
|
38
41
|
|
|
39
42
|
```typescript
|
|
40
43
|
const status = await m.solve({
|
|
41
|
-
timeLimit: 10.0,
|
|
42
|
-
|
|
43
|
-
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)
|
|
44
47
|
});
|
|
45
48
|
```
|
|
46
49
|
|
|
@@ -48,14 +51,14 @@ const status = await m.solve({
|
|
|
48
51
|
|
|
49
52
|
| Option | Type | Default | Description |
|
|
50
53
|
| :--- | :--- | :--- | :--- |
|
|
51
|
-
| `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. |
|
|
52
55
|
| `timeLimit` | `number` | `undefined` | Maximum solve duration in seconds. |
|
|
53
|
-
| `
|
|
54
|
-
| `
|
|
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`). |
|
|
55
58
|
| `presolve` | `"on"` \| `"off"` \| `"choose"` | `"choose"` | Controls solver presolve reduction prior to optimization. |
|
|
56
59
|
| `outputFlag` / `verbose` | `boolean` | `false` | Emits internal solver iteration logs (`outputFlag` for HiGHS, `verbose` for GLPK). |
|
|
57
|
-
| `useWorker` | `boolean` | `true` (browser) | Offloads HiGHS to
|
|
58
|
-
| `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. |
|
|
59
62
|
| `signal` | `AbortSignal` | `undefined` | Cooperative cancellation signal (`AbortController.signal`). |
|
|
60
63
|
| `onProgress` | `(e: SolveProgressEvent) => void` | `undefined` | Callback receiving live solver progress snapshots. |
|
|
61
64
|
|
|
@@ -63,53 +66,7 @@ You can also pass a solver name directly as the first argument: `await m.solve("
|
|
|
63
66
|
|
|
64
67
|
---
|
|
65
68
|
|
|
66
|
-
##
|
|
67
|
-
|
|
68
|
-
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`:
|
|
69
|
-
|
|
70
|
-
```typescript
|
|
71
|
-
const controller = new AbortController();
|
|
72
|
-
|
|
73
|
-
// Example: cancel if the user clicks a "Stop" button or after a custom condition
|
|
74
|
-
const status = await m.solve({
|
|
75
|
-
signal: controller.signal,
|
|
76
|
-
onProgress: (event) => {
|
|
77
|
-
console.log(
|
|
78
|
-
`[${event.elapsedTime.toFixed(1)}s] ` +
|
|
79
|
-
`Best: ${event.objectiveValue ?? "—"}, ` +
|
|
80
|
-
`Bound: ${event.objectiveBound ?? "—"}, ` +
|
|
81
|
-
`Gap: ${event.mipGap !== undefined ? (event.mipGap * 100).toFixed(2) + "%" : "—"}`
|
|
82
|
-
);
|
|
83
|
-
|
|
84
|
-
// Optional: stop early as soon as a good-enough incumbent is found
|
|
85
|
-
if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
|
|
86
|
-
controller.abort();
|
|
87
|
-
}
|
|
88
|
-
},
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
console.log("Status:", m.status); // "Feasible" (if an incumbent was found before abort) or "Unknown"
|
|
92
|
-
console.log("Termination:", m.terminationStatus); // "Interrupted"
|
|
93
|
-
console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### `SolveProgressEvent` Fields
|
|
97
|
-
|
|
98
|
-
| Field | Type | Description |
|
|
99
|
-
| :--- | :--- | :--- |
|
|
100
|
-
| `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
|
|
101
|
-
| `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
|
|
102
|
-
| `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
|
|
103
|
-
| `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
|
|
104
|
-
| `relGap` / `mipGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
|
|
105
|
-
| `absGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
|
|
106
|
-
| `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
|
|
107
|
-
| `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
|
|
108
|
-
| `message` | `string \| undefined` | Raw progress line emitted by the solver. |
|
|
109
|
-
|
|
110
|
-
---
|
|
111
|
-
|
|
112
|
-
## 📊 Reading Results, Bounds & Solver Status
|
|
69
|
+
## Reading Results, Bounds & Solver Status
|
|
113
70
|
|
|
114
71
|
After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
|
|
115
72
|
|
|
@@ -123,14 +80,17 @@ console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value /
|
|
|
123
80
|
// Objective & MIP Gap Metrics
|
|
124
81
|
console.log("Objective Value:", m.objectiveValue); // Best primal objective (or null)
|
|
125
82
|
console.log("Objective Bound:", m.objectiveBound); // Best dual bound (or undefined)
|
|
126
|
-
console.log("Relative Gap:", m.
|
|
127
|
-
console.log("Absolute Gap:", m.
|
|
83
|
+
console.log("Relative Gap:", m.relativeGap); // Relative MIP gap
|
|
84
|
+
console.log("Absolute Gap:", m.absoluteGap); // |objectiveValue - objectiveBound|
|
|
128
85
|
|
|
129
|
-
//
|
|
86
|
+
// Variable Values (via .value or name-keyed m.values ReadonlyMap)
|
|
130
87
|
console.log("x =", x.value, "y =", y.value);
|
|
131
|
-
console.log(m.
|
|
88
|
+
console.log("x by name:", m.values.get("x"));
|
|
132
89
|
```
|
|
133
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
|
+
|
|
134
94
|
### Understanding `m.status` vs. `m.terminationStatus`
|
|
135
95
|
|
|
136
96
|
When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two distinct questions matter:
|
|
@@ -157,14 +117,60 @@ If an integer-feasible incumbent was found before hitting `timeLimit` or `signal
|
|
|
157
117
|
|
|
158
118
|
---
|
|
159
119
|
|
|
160
|
-
##
|
|
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
|
+
|
|
166
|
+
## Model Mutations & Execution Validity
|
|
161
167
|
|
|
162
168
|
A `Model` instance keeps its solution state synchronized across mutations made through `Model` methods and `Model` / `Var` / `Constraint` property setters:
|
|
163
169
|
|
|
164
|
-
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`.
|
|
165
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.
|
|
166
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.
|
|
167
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.
|
|
168
174
|
|
|
169
175
|
> [!NOTE]
|
|
170
|
-
> 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
|
-
When
|
|
14
|
-
By calling **`await m.check({ solver: "z3" })
|
|
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.
|
|
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,15 +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
|
|
|
71
|
+
### Comparing Pumpkin `unsatCore`, Z3 `unsatCore`, and HiGHS Elastic Slack `conflicts`
|
|
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) |
|
|
82
|
+
|
|
83
|
+
> [!TIP]
|
|
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.
|
|
85
|
+
|
|
65
86
|
---
|
|
66
87
|
|
|
67
|
-
##
|
|
88
|
+
## Independent Solution Verification (`m.verify()`)
|
|
68
89
|
|
|
69
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:
|
|
70
91
|
|
|
@@ -72,7 +93,7 @@ After solving a model (or supplying a custom candidate map via `values`), you ca
|
|
|
72
93
|
const status = await m.solve();
|
|
73
94
|
|
|
74
95
|
if (m.hasPrimalSolution) {
|
|
75
|
-
const report = m.
|
|
96
|
+
const report = m.verify({
|
|
76
97
|
feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
|
|
77
98
|
integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
|
|
78
99
|
evaluateLogicalConstraints: true,
|
|
@@ -89,22 +110,22 @@ if (m.hasPrimalSolution) {
|
|
|
89
110
|
}
|
|
90
111
|
```
|
|
91
112
|
|
|
92
|
-
### `
|
|
113
|
+
### `VerificationReport` Summary
|
|
93
114
|
|
|
94
115
|
| Property | Type | Description |
|
|
95
116
|
| :--- | :--- | :--- |
|
|
96
117
|
| `valid` | `boolean` | `true` iff `complete === true`, `uncheckedConstraints.length === 0`, and `violations.length === 0`. |
|
|
97
118
|
| `complete` | `boolean` | `true` when all variables, Boolean variables, linear constraints, and logical constraints were evaluated. |
|
|
98
119
|
| `maxViolation` | `number` | Largest numeric violation magnitude across all evaluated bounds, integrality checks, and constraints. |
|
|
99
|
-
| `violations` | `
|
|
100
|
-
| `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. |
|
|
101
122
|
| `uncheckedConstraints` | `string[]` | Names of constraints that could not be evaluated. |
|
|
102
123
|
| `missingVariables` | `string[]` | Names of numeric or Boolean variables whose values were `null` or `undefined`. |
|
|
103
|
-
| `summary` | `
|
|
124
|
+
| `summary` | `VerificationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
|
|
104
125
|
|
|
105
126
|
---
|
|
106
127
|
|
|
107
|
-
##
|
|
128
|
+
## Inspecting the LP Formulation (`m.toLpString()`)
|
|
108
129
|
|
|
109
130
|
When debugging coefficients, signs, or Big-M indicator expansions, call `m.toLpString()` to export the model in standard CPLEX/HiGHS `.lp` format:
|
|
110
131
|
|
|
@@ -130,7 +151,7 @@ End
|
|
|
130
151
|
|
|
131
152
|
---
|
|
132
153
|
|
|
133
|
-
##
|
|
154
|
+
## Unit Testing Application Logic with `MockSolver`
|
|
134
155
|
|
|
135
156
|
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:
|
|
136
157
|
|
package/docs/guide/variables.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Variables & Domains
|
|
2
2
|
|
|
3
|
-
Variables represent the mathematical decision variables in your optimization model.
|
|
3
|
+
Variables represent the mathematical decision variables in your optimization or logical model.
|
|
4
4
|
WaSHI provides domain-specific factory methods on the `Model` instance: `m.continuous()`, `m.integer()`, `m.binary()`, and `m.bool()`.
|
|
5
5
|
|
|
6
6
|
---
|
|
@@ -8,7 +8,7 @@ WaSHI provides domain-specific factory methods on the `Model` instance: `m.conti
|
|
|
8
8
|
## Decision Variable Types
|
|
9
9
|
|
|
10
10
|
### 1. Continuous Variables (`m.continuous`)
|
|
11
|
-
Can take any real number value within `[lb, ub]`.
|
|
11
|
+
Can take any real number value within `[lb, ub]`. Used for continuous quantities such as flow rates, weights, budgets, and portfolio allocations:
|
|
12
12
|
|
|
13
13
|
```typescript
|
|
14
14
|
import { Model } from "@ohtaman/washi";
|
|
@@ -20,7 +20,7 @@ const fuel = m.continuous("fuel", { lb: 0, ub: 1000 });
|
|
|
20
20
|
```
|
|
21
21
|
|
|
22
22
|
### 2. Integer Variables (`m.integer`)
|
|
23
|
-
Restricted to
|
|
23
|
+
Restricted to integer values within `[lb, ub]`. Used for discrete counts such as machines, vehicles, or headcount:
|
|
24
24
|
|
|
25
25
|
```typescript
|
|
26
26
|
// Single integer variable bounded in [0, 15]
|
|
@@ -28,48 +28,43 @@ const trucks = m.integer("trucks", { lb: 0, ub: 15 });
|
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
### 3. Binary Variables (`m.binary`)
|
|
31
|
-
Restricted to $\{0, 1\}$ as
|
|
31
|
+
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:
|
|
32
32
|
|
|
33
33
|
```typescript
|
|
34
|
-
// Single binary variable
|
|
34
|
+
// Single binary variable (lb = 0, ub = 1 automatically)
|
|
35
35
|
const openWarehouse = m.binary("open_warehouse");
|
|
36
|
-
// lb is automatically 0, ub is automatically 1
|
|
37
36
|
```
|
|
38
37
|
|
|
39
38
|
### 4. Propositional Boolean Variables (`m.bool`)
|
|
40
|
-
Pure boolean
|
|
39
|
+
Pure boolean propositions (`true` / `false`) for logical and SMT constraints:
|
|
41
40
|
|
|
42
41
|
```typescript
|
|
43
|
-
// Single propositional boolean
|
|
44
|
-
const
|
|
45
|
-
const
|
|
42
|
+
// Single propositional boolean variables
|
|
43
|
+
const isAdmin = m.bool("isAdmin");
|
|
44
|
+
const hasMfa = m.bool("hasMfa");
|
|
46
45
|
|
|
47
46
|
// First-class boolean operators: and, or, not, implies, xor
|
|
48
|
-
m.constraint(
|
|
47
|
+
m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
|
|
49
48
|
```
|
|
50
49
|
|
|
51
|
-
###
|
|
52
|
-
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).
|
|
50
|
+
### Choosing Between `m.binary()` and `m.bool()`
|
|
53
51
|
|
|
54
|
-
|
|
52
|
+
| Feature | `m.binary()` (`Var`) | `m.bool()` (`BoolVar`) |
|
|
53
|
+
| :--- | :--- | :--- |
|
|
54
|
+
| **Solved `.value` type** | `number \| null` (`0` or `1`) | `boolean \| null` (`true` or `false`) |
|
|
55
|
+
| **Linear arithmetic (`expr`, `sum`, `dot`, objective costs)** | ✅ Native (`` expr`30 * ${b}` ``) | ❌ Cannot be multiplied by numbers or summed directly |
|
|
56
|
+
| **Indicator constraints (`m.indicator(b, ...)` )** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
|
|
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 `{0, 1}` integer on Pumpkin/Z3 | Native boolean proposition on Pumpkin/Z3; auto-linearized to 0-1 MIP on HiGHS/GLPK |
|
|
55
59
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const m = new Model();
|
|
60
|
-
const batch = m.continuous("batch", { lb: 0, ub: 100 });
|
|
61
|
-
const isActive = m.binary("is_active");
|
|
62
|
-
|
|
63
|
-
// If isActive === 0, batch is forced to 0; if 1, batch is within [10, 100]
|
|
64
|
-
m.constraint(expr`${batch} >= 10 * ${isActive}`, "min_batch_run");
|
|
65
|
-
m.constraint(expr`${batch} <= 100 * ${isActive}`, "max_batch_run");
|
|
66
|
-
```
|
|
60
|
+
> [!TIP]
|
|
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.
|
|
67
62
|
|
|
68
63
|
---
|
|
69
64
|
|
|
70
65
|
## Multi-Dimensional & Array Creation
|
|
71
66
|
|
|
72
|
-
The domain factory methods (`continuous`, `integer`, `binary`, `bool`)
|
|
67
|
+
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.
|
|
73
68
|
|
|
74
69
|
### By Count
|
|
75
70
|
Pass a number to create an array of variables:
|
|
@@ -80,15 +75,15 @@ const flags = m.bool(3); // BoolVar[] (p_0, p_1, p_2)
|
|
|
80
75
|
```
|
|
81
76
|
|
|
82
77
|
### 1D Variable Dictionaries
|
|
83
|
-
Pass an array of keys to get a typed dictionary `Record<
|
|
78
|
+
Pass an array of keys to get a typed dictionary `Record<K, Var>` or `Record<K, BoolVar>`:
|
|
84
79
|
|
|
85
80
|
```typescript
|
|
86
|
-
const items = ["laptop", "phone", "tablet"];
|
|
81
|
+
const items = ["laptop", "phone", "tablet"] as const;
|
|
87
82
|
|
|
88
83
|
// Record<"laptop" | "phone" | "tablet", Var>
|
|
89
84
|
const selected = m.binary(items);
|
|
90
85
|
|
|
91
|
-
const perms = m.bool(["read", "write", "execute"]);
|
|
86
|
+
const perms = m.bool(["read", "write", "execute"] as const);
|
|
92
87
|
// perms.read, perms.write, perms.execute
|
|
93
88
|
```
|
|
94
89
|
|
|
@@ -122,16 +117,22 @@ const schedule = m.binary(factories, 7, { prefix: "open_day" });
|
|
|
122
117
|
|
|
123
118
|
| Option | Type | Default | Description |
|
|
124
119
|
| :--- | :--- | :--- | :--- |
|
|
125
|
-
| `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. |
|
|
126
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`). |
|
|
127
123
|
| `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Underlying variable domain category. |
|
|
128
|
-
| `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP start), kept distinct from solved `variable.value`. |
|
|
124
|
+
| `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP warm start), kept distinct from solved `variable.value`. |
|
|
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**.
|
|
129
130
|
|
|
130
131
|
---
|
|
131
132
|
|
|
132
133
|
## Primal Initial Values (Warm-Start Hints)
|
|
133
134
|
|
|
134
|
-
When rebuilding a model across iterations
|
|
135
|
+
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 = ...`):
|
|
135
136
|
|
|
136
137
|
```typescript
|
|
137
138
|
const prevValues: Record<string, number | null> = { trucks: 8, open_warehouse: 1 };
|
|
@@ -148,41 +149,48 @@ const openWarehouse2 = m2.binary("open_warehouse", {
|
|
|
148
149
|
const extraCapacity = m2.continuous("extra_capacity", { lb: 0 }); // Partial start: no initialValue needed
|
|
149
150
|
```
|
|
150
151
|
|
|
151
|
-
- **Hint vs. Hard Constraint**: `initialValue` is
|
|
152
|
-
- **Validation & Tolerance (`1e-6`)**: Supplied values must be finite numbers within `[lb - 1e-6, ub + 1e-6]` (and within `1e-6` of an integer
|
|
153
|
-
- **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`.
|
|
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).)*
|
|
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.
|
|
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`.
|
|
154
155
|
|
|
155
156
|
---
|
|
156
157
|
|
|
157
158
|
## Accessing Solution Values & Reduced Costs
|
|
158
159
|
|
|
159
|
-
After calling `await m.solve()` or `await m.check()`, assigned variable values
|
|
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`:
|
|
160
161
|
|
|
161
162
|
```typescript
|
|
162
163
|
await m.solve();
|
|
163
164
|
|
|
164
|
-
//
|
|
165
|
+
// Scalar variable primal & boolean values
|
|
165
166
|
console.log(`trucks: ${trucks.value}`);
|
|
167
|
+
console.log(`isAdmin: ${isAdmin.value}`);
|
|
166
168
|
|
|
167
|
-
//
|
|
168
|
-
|
|
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}`);
|
|
169
172
|
|
|
170
|
-
//
|
|
171
|
-
|
|
172
|
-
// { 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")}`);
|
|
173
175
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
+
// Reduced cost (LP sensitivity analysis)
|
|
177
|
+
console.log(`fuel reduced cost: ${fuel.reducedCost}`);
|
|
176
178
|
```
|
|
177
179
|
|
|
178
180
|
---
|
|
179
181
|
|
|
180
182
|
## Looking Up Variables by Name
|
|
181
183
|
|
|
182
|
-
|
|
184
|
+
All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are exposed through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
|
|
183
185
|
|
|
184
186
|
```typescript
|
|
185
|
-
const v = m.
|
|
186
|
-
const b = m.
|
|
187
|
-
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
|
+
}
|
|
188
196
|
```
|