@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
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
| Problem Class | Solver | Key APIs | Links |
|
|
4
4
|
| :--- | :--- | :--- | :--- |
|
|
5
|
-
| Combinatorial OR / Benders | HiGHS (default) | `m.solveBenders()`, `subproblem`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts">Source Code</a></li><li><a href="
|
|
5
|
+
| Combinatorial OR / Benders | HiGHS (default) | `m.solveBenders()`, `subproblem`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
|
|
6
6
|
|
|
7
7
|
The **Traveling Salesperson Problem (TSP)** seeks the shortest closed tour that visits every city in a given set once and returns to the starting city.
|
|
8
8
|
|
|
@@ -12,7 +12,7 @@ $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S
|
|
|
12
12
|
|
|
13
13
|
Because there are $2^n - 2$ subsets, enumerating all subtour constraints upfront is impractical as $n$ grows. With **Benders Decomposition (Lazy Constraint Separation)**, constraints are added only when violated:
|
|
14
14
|
1. **Master Problem**: Solves the degree-assignment relaxation (each city has 1 incoming and 1 outgoing edge).
|
|
15
|
-
2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds
|
|
15
|
+
2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds **Benders Feasibility Cuts** eliminating all detected subtours simultaneously (multi-cut separation) and resolves until a single connected tour is obtained.
|
|
16
16
|
|
|
17
17
|
## Problem Inputs
|
|
18
18
|
|
|
@@ -31,7 +31,7 @@ We consider **5 cities** on a 2D Euclidean coordinate grid:
|
|
|
31
31
|
<CodeRunner>
|
|
32
32
|
|
|
33
33
|
```typescript
|
|
34
|
-
import { Model, expr, minimize
|
|
34
|
+
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
35
35
|
|
|
36
36
|
async function runTSP() {
|
|
37
37
|
const cities = [
|
|
@@ -52,39 +52,26 @@ async function runTSP() {
|
|
|
52
52
|
// 1. Master Problem: Degree assignment relaxation
|
|
53
53
|
const master = new Model("TSP_BendersMaster");
|
|
54
54
|
const x = {};
|
|
55
|
+
const distMatrix = {};
|
|
55
56
|
|
|
56
57
|
for (let i = 0; i < n; i++) {
|
|
57
58
|
x[i] = {};
|
|
59
|
+
distMatrix[i] = {};
|
|
58
60
|
for (let j = 0; j < n; j++) {
|
|
59
61
|
if (i !== j) {
|
|
60
62
|
x[i][j] = master.binary(`x_${i}_${j}`);
|
|
63
|
+
distMatrix[i][j] = dist(i, j);
|
|
61
64
|
}
|
|
62
65
|
}
|
|
63
66
|
}
|
|
64
67
|
|
|
65
68
|
// Objective: Minimize total tour distance
|
|
66
|
-
|
|
67
|
-
for (let i = 0; i < n; i++) {
|
|
68
|
-
for (let j = 0; j < n; j++) {
|
|
69
|
-
if (i !== j) {
|
|
70
|
-
totalDistance = totalDistance.add(x[i][j].mul(dist(i, j)));
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
master.objective(minimize(totalDistance));
|
|
69
|
+
master.objective(minimize(expr`dot(${distMatrix}, ${x})`));
|
|
75
70
|
|
|
76
71
|
// Each city must have 1 outgoing and 1 incoming edge
|
|
77
72
|
for (let i = 0; i < n; i++) {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
for (let j = 0; j < n; j++) {
|
|
81
|
-
if (i !== j) {
|
|
82
|
-
outExpr = outExpr.add(x[i][j]);
|
|
83
|
-
inExpr = inExpr.add(x[j][i]);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
master.constraint(expr`${outExpr} == 1`, `out_${i}`);
|
|
87
|
-
master.constraint(expr`${inExpr} == 1`, `in_${i}`);
|
|
73
|
+
master.constraint(expr`sum(${x[i]}) == 1`, `out_${i}`);
|
|
74
|
+
master.constraint(expr`sum(${n}, ${(j) => x[j][i]}) == 1`, `in_${i}`);
|
|
88
75
|
}
|
|
89
76
|
|
|
90
77
|
console.log("Solving TSP with Benders lazy subtour elimination...");
|
|
@@ -97,7 +84,7 @@ async function runTSP() {
|
|
|
97
84
|
const succ = {};
|
|
98
85
|
for (let i = 0; i < n; i++) {
|
|
99
86
|
for (let j = 0; j < n; j++) {
|
|
100
|
-
if (i !== j &&
|
|
87
|
+
if (i !== j && x[i][j].value === 1) {
|
|
101
88
|
succ[i] = j;
|
|
102
89
|
}
|
|
103
90
|
}
|
|
@@ -119,27 +106,22 @@ async function runTSP() {
|
|
|
119
106
|
}
|
|
120
107
|
}
|
|
121
108
|
|
|
122
|
-
// If more than 1 cycle, subtours exist: inject Benders feasibility
|
|
109
|
+
// If more than 1 cycle, subtours exist: inject Benders feasibility cuts for all cycles
|
|
123
110
|
if (cycles.length > 1) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
return {
|
|
139
|
-
kind: "feasibility",
|
|
140
|
-
constraint: expr`${cutLhs} >= 1`,
|
|
141
|
-
name: `subtour_cut_${cutCounter}`,
|
|
142
|
-
};
|
|
111
|
+
return cycles.map((cycle) => {
|
|
112
|
+
const S = new Set(cycle);
|
|
113
|
+
cutCounter++;
|
|
114
|
+
console.log(`Subtour detected: [${cycle.map(k => cities[k].name).join(" -> ")}]. Adding Benders cut #${cutCounter}.`);
|
|
115
|
+
|
|
116
|
+
const outCities = Array.from({ length: n }, (_, j) => j).filter((j) => !S.has(j));
|
|
117
|
+
const cutEdges = cycle.flatMap((i) => outCities.map((j) => x[i][j]));
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
kind: "feasibility",
|
|
121
|
+
constraint: expr`sum(${cutEdges}) >= 1`,
|
|
122
|
+
name: `subtour_cut_${cutCounter}`,
|
|
123
|
+
};
|
|
124
|
+
});
|
|
143
125
|
}
|
|
144
126
|
|
|
145
127
|
return null; // Single connected tour found
|
|
@@ -154,7 +136,7 @@ async function runTSP() {
|
|
|
154
136
|
console.log("\nOptimal tour edges:");
|
|
155
137
|
for (let i = 0; i < n; i++) {
|
|
156
138
|
for (let j = 0; j < n; j++) {
|
|
157
|
-
if (i !== j &&
|
|
139
|
+
if (i !== j && result.values[`x_${i}_${j}`] === 1) {
|
|
158
140
|
console.log(` ${cities[i].name} -> ${cities[j].name} (distance: ${dist(i, j).toFixed(3)})`);
|
|
159
141
|
}
|
|
160
142
|
}
|
|
@@ -169,5 +151,7 @@ runTSP();
|
|
|
169
151
|
## Notes
|
|
170
152
|
|
|
171
153
|
- **Lazy Subtour Elimination**: The master problem starts with only the $2n$ degree constraints, and subtour elimination cuts are added on demand when disconnected cycles appear in the master solution.
|
|
172
|
-
- **Separation
|
|
154
|
+
- **Multi-Cut Separation**: Returning an array of cuts (`cycles.map(...)`) from `subproblem` eliminates all disconnected cycles discovered in the current candidate solution simultaneously, reducing the number of master MIP re-solves.
|
|
155
|
+
- **Two Equivalent DFJ Cut Forms**: Because every city has out-degree $\sum_{j \ne i} x_{ij} = 1$, summing over $i \in S$ gives $\sum_{i \in S, j \in S} x_{ij} + \sum_{i \in S, j \notin S} x_{ij} = |S|$. Thus the cut-set inequality $\sum_{i \in S, j \notin S} x_{ij} \ge 1$ used above and the internal-edge inequality $\sum_{i \in S, j \in S} x_{ij} \le |S| - 1$ used in [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts) are algebraically identical.
|
|
156
|
+
- **Upfront 2-City Subtour Elimination**: In larger TSP instances, mutual 2-cycles ($i \leftrightarrow j$) are the most frequent initial subtours. Adding the $\binom{n}{2}$ pairwise constraints $x_{ij} + x_{ji} \le 1$ directly to the initial master problem often cuts the number of Benders iterations substantially.
|
|
173
157
|
- **Termination Condition**: Returning `null` from `subproblem` indicates that no violated subtour constraints remain.
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
| Problem Class | Solver | Key APIs | Links |
|
|
4
4
|
| :--- | :--- | :--- | :--- |
|
|
5
|
-
| Infeasibility Diagnosis / Unsat Core | Z3 (`@ohtaman/washi/solvers/z3`) | `m.integer()`, `m.continuous()`, `m.constraint()`, `expr`, `m.check()`, `m.conflicts` | <ul><li><a href="https://ohtaman.
|
|
5
|
+
| Infeasibility Diagnosis / Unsat Core | Z3 (`@ohtaman/washi/solvers/z3`) | `m.integer()`, `m.continuous()`, `implies()`, `m.constraint()`, `expr`, `m.check()`, `m.conflicts` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=conflict_diagnosis_unsat">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts">Source Code</a></li></ul> |
|
|
6
6
|
|
|
7
|
-
When business rules, budgets, and operational policies grow complex, constraints
|
|
7
|
+
When business rules, budgets, and operational policies grow complex, constraints can easily conflict. Because a standard optimization call (`m.solve()`) only reports `"Infeasible"`, WaSHI provides `m.check()` to pinpoint conflicting rules without manual trial-and-error.
|
|
8
8
|
|
|
9
9
|
This example shows how to isolate the conflicting constraint subset using Z3 Unsat Core extraction.
|
|
10
10
|
|
|
@@ -26,7 +26,7 @@ $$8 \text{ engineers} \times \$8,000 = \$64,000 > \$50,000 \text{ budget!}$$
|
|
|
26
26
|
<CodeRunner preset="conflict_diagnosis_unsat">
|
|
27
27
|
|
|
28
28
|
```typescript
|
|
29
|
-
import { Model, expr } from "@ohtaman/washi";
|
|
29
|
+
import { Model, implies, expr } from "@ohtaman/washi";
|
|
30
30
|
import "@ohtaman/washi/solvers/z3";
|
|
31
31
|
|
|
32
32
|
async function diagnoseConflicts() {
|
|
@@ -43,7 +43,7 @@ async function diagnoseConflicts() {
|
|
|
43
43
|
m.constraint(rushDelivery, "rush_required");
|
|
44
44
|
|
|
45
45
|
// Rule 3: Rush delivery requires at least 8 engineers
|
|
46
|
-
m.constraint(
|
|
46
|
+
m.constraint(implies(rushDelivery, expr`${engineers} >= 8`), "rush_staffing_rule");
|
|
47
47
|
|
|
48
48
|
// Rule 4: Board budget cap of $50,000 (Conflict!)
|
|
49
49
|
m.constraint(expr`${budget} <= 50000`, "strict_board_budget_cap");
|
|
@@ -55,10 +55,21 @@ async function diagnoseConflicts() {
|
|
|
55
55
|
const res = await m.check({ solver: "z3" });
|
|
56
56
|
|
|
57
57
|
console.log(`Status: ${res.status}`);
|
|
58
|
-
console.log("
|
|
58
|
+
console.log("Z3 Unsat Core (scale-invariant):", m.conflicts);
|
|
59
|
+
|
|
60
|
+
// Built-in HiGHS can also diagnose conflicts via single-solve L1 elastic slack relaxation:
|
|
61
|
+
const highsDiag = await m.check({ solver: "highs" });
|
|
62
|
+
console.log("HiGHS Elastic Repair Set:", highsDiag.conflicts);
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
diagnoseConflicts();
|
|
62
66
|
```
|
|
63
67
|
|
|
64
68
|
</CodeRunner>
|
|
69
|
+
|
|
70
|
+
## Practical Notes
|
|
71
|
+
|
|
72
|
+
- **Choosing Between Pumpkin, Z3, and HiGHS for Conflict Diagnosis**:
|
|
73
|
+
- **Pumpkin (`m.check({ solver: "pumpkin" })`)** is bundled with `@ohtaman/washi/solvers/pumpkin` (zero external dependencies, no `COOP` / `COEP` headers) and extracts scale-invariant `unsatCore` subsets for discrete models where all variables are bounded `Integer`, `Binary`, or `BoolVar` (for example, when `budget` above is modeled with `m.integer("budget", ...)`).
|
|
74
|
+
- **Z3 (`m.check({ solver: "z3" })`)** supports `Continuous` variables (like `budget` above) and fractional arithmetic, returning all four rules that jointly form the contradiction (`budget_limit`, `rush_required`, `rush_staffing_rule`, `strict_board_budget_cap`), while excluding the innocent `minimum_one_employee` rule.
|
|
75
|
+
- **HiGHS (`m.check({ solver: "highs" })`)** solves a single $L_1$ elastic slack minimization problem ($\min \sum s_i$). Because relaxing `rush_staffing_rule` (or `rush_required`) requires a slack of only `1`–`2` units whereas relaxing `strict_board_budget_cap` requires a slack of `14,000` dollars, unweighted $L_1$ minimization naturally highlights the smallest-magnitude repair (`rush_required`) needed to restore feasibility.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
| Problem Class | Solver | Key APIs | Links |
|
|
4
4
|
| :--- | :--- | :--- | :--- |
|
|
5
|
-
| Combinatorial OR / Dantzig-Wolfe | HiGHS (default) | `m.solveColumnGeneration()`, `pricing`, `
|
|
5
|
+
| Combinatorial OR / Dantzig-Wolfe | HiGHS (default) | `m.solveColumnGeneration()`, `pricing`, `m.binary()`, `m.constraint()`, `expr` (`sum`) | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
|
|
6
6
|
|
|
7
7
|
The **Capacitated Vehicle Routing Problem (CVRP)** determines the minimum number of delivery vehicles needed to visit a set of customers, subject to vehicle cargo capacity, maximum customer stops per shift, and route duration limits.
|
|
8
8
|
|
|
@@ -24,7 +24,7 @@ We consider a distribution network with a central depot at $(0, 0)$ and **50 cus
|
|
|
24
24
|
<CodeRunner>
|
|
25
25
|
|
|
26
26
|
```typescript
|
|
27
|
-
import { Model, expr, minimize
|
|
27
|
+
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
28
28
|
|
|
29
29
|
// --- Extracted Routing Helpers ---
|
|
30
30
|
|
|
@@ -141,13 +141,12 @@ async function runCVRP() {
|
|
|
141
141
|
|
|
142
142
|
// Initial naive routes: 1 dedicated vehicle per customer
|
|
143
143
|
const initialRoutes = customers.map((c) => master.binary(`route_init_${c.id}`));
|
|
144
|
-
master.objective(minimize(sum(initialRoutes)));
|
|
144
|
+
master.objective(minimize(expr`sum(${initialRoutes})`));
|
|
145
145
|
|
|
146
146
|
// Each customer must be visited by exactly 1 vehicle
|
|
147
|
-
|
|
148
|
-
master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${
|
|
149
|
-
|
|
150
|
-
const visitConstrs = master.constraints;
|
|
147
|
+
const visitConstrs = customers.map((c, i) =>
|
|
148
|
+
master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${c.id}`)
|
|
149
|
+
);
|
|
151
150
|
|
|
152
151
|
console.log(`Initial state: 50 naive single-customer routes (50 vehicles).`);
|
|
153
152
|
console.log("Solving via Column Generation with dual-directed heuristic pricing...");
|
|
@@ -187,7 +186,7 @@ async function runCVRP() {
|
|
|
187
186
|
console.log(`Total Columns Generated: ${result.columnsAdded}`);
|
|
188
187
|
|
|
189
188
|
console.log("\nSample routes selected in fleet:");
|
|
190
|
-
const activeRoutes = result.generatedColumns.filter((c) =>
|
|
189
|
+
const activeRoutes = result.generatedColumns.filter((c) => c.variable.value === 1);
|
|
191
190
|
for (const r of activeRoutes.slice(0, 5)) {
|
|
192
191
|
const meta = r.proposal.meta;
|
|
193
192
|
console.log(` ${meta?.tour.join(" -> ")} (Transit: ${meta?.travelTime}m, Total: ${meta?.totalTime}m)`);
|
|
@@ -204,3 +203,6 @@ runCVRP();
|
|
|
204
203
|
- **Master Problem and Pricing Separation**: The master problem solves the LP relaxation and final set-partitioning MIP, while the `pricing` callback searches for negative-reduced-cost routes using cheapest insertion and 2-opt local search.
|
|
205
204
|
- **Dual Value Access**: Dual values from the master LP relaxation are read from `visitConstrs[i].dual` to prioritize customers with higher shadow prices during route construction.
|
|
206
205
|
- **Route Metadata**: Each proposed column attaches `{ tour, travelTime, totalTime }` under `meta`, allowing the ordered stop sequence to be inspected from `result.generatedColumns` after the solve completes.
|
|
206
|
+
- **Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)**: This example uses `== 1` so that the final MIP never covers a customer twice. In large-scale column generation, formulating coverage as `>= 1` restricts the dual prices to $\pi_i \ge 0$, avoiding negative dual oscillations; if the final MIP selects overlapping routes, duplicate visits can be removed by post-processing whenever distances satisfy the triangle inequality.
|
|
207
|
+
- **Heuristic Pricing vs. Exact ESPPRC**: Because `findImprovingRoute` uses a fast greedy heuristic (cheapest insertion + 2-opt) instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver, returning `null` means no further improving columns were found by the heuristic rather than proving global LP optimality.
|
|
208
|
+
- **Price-and-Branch (`finalizeAsMIP: true`)**: Solving the Restricted Master Problem as a MIP over the columns generated at the root node is known as the *Restricted Master Heuristic* (Price-and-Branch). It produces near-optimal integer fleets quickly without requiring full Branch-and-Price tree search.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# AI Coding Agent Quick-Reference Guide
|
|
2
2
|
|
|
3
3
|
> **Scope Note**: This document is the **consumer modeling quick-reference** for AI coding agents and developers building optimization or satisfiability models with `@ohtaman/washi`.
|
|
4
|
-
> - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `
|
|
4
|
+
> - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `verify()` verification, and Pumpkin / Z3 `unsatCore` conflict-diagnosis workflow skill (compatible with Claude Code, Antigravity, Cursor, Codex, and other `SKILL.md`-aware agents), use [`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md) (also shipped in the npm package at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`):
|
|
5
5
|
> ```bash
|
|
6
6
|
> # Install directly via the skills CLI (skills.sh / vercel-labs/skills)
|
|
7
7
|
> npx skills add ohtaman/washi
|
|
@@ -24,6 +24,14 @@ import {
|
|
|
24
24
|
expr,
|
|
25
25
|
sum,
|
|
26
26
|
dot,
|
|
27
|
+
abs,
|
|
28
|
+
max,
|
|
29
|
+
min,
|
|
30
|
+
at,
|
|
31
|
+
distinct,
|
|
32
|
+
disjoint,
|
|
33
|
+
cumulative,
|
|
34
|
+
allowed,
|
|
27
35
|
maximize,
|
|
28
36
|
minimize,
|
|
29
37
|
and,
|
|
@@ -34,6 +42,8 @@ import {
|
|
|
34
42
|
setHighsWasmUrl,
|
|
35
43
|
} from "@ohtaman/washi";
|
|
36
44
|
|
|
45
|
+
// Bundled CP/LCG solver plugin (zero external dependencies; registers "pumpkin"):
|
|
46
|
+
import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
|
|
37
47
|
// Optional solver plugins (require installing peer dependencies first):
|
|
38
48
|
// npm install z3-solver
|
|
39
49
|
import "@ohtaman/washi/solvers/z3";
|
|
@@ -45,10 +55,12 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
45
55
|
|
|
46
56
|
- **Browser ESM**:
|
|
47
57
|
- Core (HiGHS built-in): `import { Model, expr, maximize } from "./washi/washi.js";`
|
|
58
|
+
- Pumpkin plugin: `import "./washi/solvers/pumpkin.js";`
|
|
48
59
|
- GLPK plugin: `import "./washi/solvers/glpk.js";`
|
|
49
60
|
- Z3 plugin: `import "./washi/solvers/z3.js";`
|
|
50
61
|
- **Classic `<script>` / CodePen (IIFE)**:
|
|
51
62
|
- Core: `<script src="./washi/washi.min.js"></script>` (exposes global `Washi`)
|
|
63
|
+
- Pumpkin plugin: `<script src="./washi/solvers/pumpkin.min.js"></script>` (registers `"pumpkin"`, exposes `WashiPumpkin`)
|
|
52
64
|
- GLPK plugin: `<script src="./washi/solvers/glpk.min.js"></script>` (registers `"glpk"`, exposes `WashiGLPK`)
|
|
53
65
|
- Z3 plugin: `<script src="./washi/solvers/z3.min.js"></script>` (registers `"z3"`, exposes `WashiZ3`)
|
|
54
66
|
|
|
@@ -57,7 +69,8 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
57
69
|
1. **Bundled WASM by default (no implicit CDN fallback)**:
|
|
58
70
|
- In Node.js and modern bundlers, WebAssembly assets resolve relative to the module automatically.
|
|
59
71
|
- In browser deployments, deploy the full `dist/browser/` directory (JS, Worker, and `.wasm` files) together. If a local WASM URL is missing or returns an HTML SPA fallback, initialization fails immediately and reports the attempted URL—it **never** silently switches to a public CDN.
|
|
60
|
-
- In browser runtimes, to load `highs.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` or
|
|
72
|
+
- In browser runtimes, to load `highs.wasm` or `pumpkin.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` (or `await m.solve({ wasmUrl: "https://.../highs.wasm" })`) for HiGHS, or `setPumpkinWasmUrl("https://.../pumpkin.wasm")` (or `await m.solve({ solver: "pumpkin", wasmUrl: "https://.../pumpkin.wasm" })`) for Pumpkin (ignored in Node.js for HiGHS; for Pumpkin in Node.js, bundled local `pumpkin.wasm` is used by default unless overridden with a `file://` URL).
|
|
73
|
+
- **Pumpkin runs without `COOP`/`COEP`**: Unlike Z3, Pumpkin (`@ohtaman/washi/solvers/pumpkin`) uses single-threaded WASM inside a regular Web Worker and does **not** require `SharedArrayBuffer` or Cross-Origin Isolation headers (`COOP`/`COEP`). It requires bounded finite integer/binary variables (`lb`, `ub` in `[-(2^30 - 1), 2^30 - 1]`) and integer linear coefficients/RHS, and supports `initialValue` warm starts across `solve()` and `check()` (no `Continuous`, `QuadExpr`, or `relax: true`).
|
|
61
74
|
2. **Z3 requires a Secure Context, Cross-Origin Isolation, and CORS in browsers**:
|
|
62
75
|
- Z3 WebAssembly uses `SharedArrayBuffer` multithreading. Browser pages running Z3 must run in a secure context (`window.isSecureContext === true`, i.e., HTTPS or `localhost`) and be cross-origin isolated (`window.crossOriginIsolated === true`) by serving:
|
|
63
76
|
- `Cross-Origin-Opener-Policy: same-origin` (on the document)
|
|
@@ -66,8 +79,8 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
66
79
|
- Importing `@ohtaman/washi` never auto-injects a Service Worker. When a secure context or cross-origin isolation is absent in a browser, Z3 rejects immediately with a descriptive error.
|
|
67
80
|
3. **Web Workers & Cancellation (`AbortSignal`)**:
|
|
68
81
|
- Pre-solve cancellation (`signal.aborted` before execution starts) is supported across all solvers.
|
|
69
|
-
- In browsers where `Worker` is available, HiGHS
|
|
70
|
-
- On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
|
|
82
|
+
- In browsers where `Worker` is available on a non-opaque effective origin (`window.origin !== "null"`), both **HiGHS** and **Pumpkin** run in dedicated Web Workers by default (`useWorker: true`). On opaque effective origins (`window.origin === "null"`, such as `file:` URLs or `sandbox="allow-scripts"` `<iframe>` embeds without `allow-same-origin`), both default to main-thread execution (`useWorker: false`). Passing `{ signal }` to `m.solve({ signal })` or `m.check({ signal })` preemptively terminates an in-flight Worker run (or cancels queued Worker requests).
|
|
83
|
+
- On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Main-thread / Node.js Pumpkin checks `should_abort` checkpoints across branching and termination hooks. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
|
|
71
84
|
|
|
72
85
|
---
|
|
73
86
|
|
|
@@ -82,9 +95,10 @@ const m = new Model("ExampleModel");
|
|
|
82
95
|
|
|
83
96
|
// Scalar variables
|
|
84
97
|
const x = m.continuous("x", { lb: 0, ub: 100 });
|
|
98
|
+
const y = m.continuous("y", { lb: 0, ub: 100 });
|
|
85
99
|
const n = m.integer("n", { lb: 0, ub: 10 });
|
|
86
100
|
const b = m.binary("b");
|
|
87
|
-
const flag = m.bool("flag"); // Propositional boolean (
|
|
101
|
+
const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native LCG/SMT on Pumpkin/Z3)
|
|
88
102
|
|
|
89
103
|
// Indexed variable containers:
|
|
90
104
|
// - Numeric dimension -> Array
|
|
@@ -98,47 +112,49 @@ const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
|
|
|
98
112
|
- **Optional Primal Initial Values (`initialValue?: number`)**:
|
|
99
113
|
- Numeric variable constructors (`m.continuous`, `m.integer`, `m.binary`, and `new Var`) and the mutable `v.initialValue` property accept an optional finite primal hint (validated with tolerance `1e-6` against bounds `[lb, ub]` and integer/binary domains), kept distinct from the solved `v.value`.
|
|
100
114
|
- A start may be complete or partial (e.g., transferred by stable variable names when rebuilding a MIP model). Supplying `initialValue` is a hint only—it does **not** fix the variable, add a hard constraint, or guarantee solver acceptance or a runtime speedup.
|
|
101
|
-
- Supported by **HiGHS** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
|
|
115
|
+
- Supported by **HiGHS** and **Pumpkin** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
|
|
102
116
|
|
|
103
|
-
### Step 2: Build Expressions (`expr`, `sum`, `dot`)
|
|
117
|
+
### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
|
|
104
118
|
|
|
105
119
|
- **Unified `expr` template tag**:
|
|
106
|
-
- Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${n} - 10` ``
|
|
107
|
-
-
|
|
108
|
-
-
|
|
109
|
-
-
|
|
110
|
-
|
|
111
|
-
- `
|
|
120
|
+
- Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${n} - 10` ``, `` expr`dot(${profit}, ${byItem}) - 20 * ${b}` ``, `` expr`sum((${price} - ${cost}) * ${byItem})` ``
|
|
121
|
+
- Piecewise-linear & element primitives (`max`, `min`, `abs`, `at`, usable inside `expr` or standalone): `` expr`max(${vec}) + sum(abs(${vec} - ${target}))` ``, `` expr`max(abs(${pred} - ${actual}))` ``, `` expr`at(${costs}, ${idx})` `` (0-based integer `idx`, automatically enforcing $0 \le \text{idx} < \text{costs.length}$). On HiGHS/GLPK, convex directions (`minimize` or `<=` on `max`/`abs`, `maximize` or `>=` on `min`) lower to pure continuous LP epigraphs with zero binary variables, while non-convex/equality contexts use exact bounded MIP formulations (finite bounds required); Pumpkin lowers natively (`maximum`/`minimum`/`absolute`/`element`) and Z3 uses native `If` (ITE).
|
|
122
|
+
- Quadratic expression (`QuadExpr`): `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${vec} - ${target})^2)` `` (supported for convex QP objectives on purely continuous models using `m.continuous`; built-in HiGHS does not support MIQP models containing integer, binary, or boolean variables).
|
|
123
|
+
- Constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` (supports `<=`, `>=`, `==`, `=`, plus discrete integer-only `<`, `>`, `!=`).
|
|
124
|
+
- **Aggregations & Element-Wise Container Arithmetic**:
|
|
125
|
+
- `sum(containerOrItems, mapper?)` (usable inside `` expr`sum(...)` `` or standalone `sum(...)`) sums a 1D/2D `Array`, `Iterable`, or plain `Record` of `Var` / `LinExpr` / `number` (without needing `Object.values(record)`), or maps over items/counts via `sum(items, (item, i) => ...)`. Inside `` expr`sum(...)` ``, element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`) and `abs(...)` mapping are also supported.
|
|
126
|
+
- `dot(a, b)` (usable inside `` expr`dot(${a}, ${b})` `` or standalone `dot(a, b)`) computes the inner product of matching 1D arrays, 2D arrays (`number[][]` / `Var[][]`, computing the Frobenius inner product $\sum_{i,j} A_{i,j} B_{i,j}$), plain records (`Record<string, ...>`), or mixed Array/Record containers in either operand order.
|
|
112
127
|
- **Fluent methods**:
|
|
113
128
|
- Arithmetic (on `LinExpr` and `QuadExpr`; `Var` supports `.add()`, `.sub()`, `.mul()`, `.neg()`): `.add(other)`, `.sub(other)`, `.mul(other)`, `.div(scalar)`, `.neg()`
|
|
114
|
-
- Comparisons (on `Var` and `
|
|
115
|
-
-
|
|
129
|
+
- Comparisons (on `Var`, `LinExpr`, and `QuadExpr`): `.le(rhs, name?)`, `.ge(rhs, name?)`, `.eq(rhs, name?)`, plus discrete integer-only `.lt(rhs, name?)`, `.gt(rhs, name?)`, `.ne(rhs, name?)` (Continuous / fractional operands throw immediately)
|
|
130
|
+
- CP global constraints (`BoolExpr` predicates composable with logical operators): `distinct(...args)` (pairwise `!=` on HiGHS/GLPK, `all_different` via pairwise `binary_not_equals` on Pumpkin `0.5.0`, `ctx.Distinct` on Z3), `disjoint(tasks)` (`{ start, duration }`, native `disjunctive_strict` Vilím edge-finding on Pumpkin), `cumulative(tasks, capacity)` (`{ start, duration, demand }`, native `cumulative` time-table on Pumpkin; MIP time-indexed formulation enforces a horizon memory guard recommending `{ solver: "pumpkin" }`), and `allowed(vars, tuples)` (`table` / `negative_table` on Pumpkin)
|
|
131
|
+
- Boolean logic (on `BoolVar`, `BoolExpr`, and `Constraint`): standalone `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, `xor(a, b)` and fluent `.and(...)`, `.or(...)`, `.not()`, `.implies(...)`, `.xor(...)`—solved natively on Z3 and Pumpkin (bounded integers) and automatically linearized to 0-1 MIP on HiGHS/GLPK (negated comparison `Constraint`s in `implies` antecedents, `not`, or `xor` use exact $\pm 1$ shifts over integer-valued `Integer`/`Binary` expressions; `Continuous` or non-integer negated `Constraint`s throw on MIP solvers—use `{ solver: "z3" }`, or write ``or(expr`... >= ... + eps`, ...)`` / `m.bool()`)
|
|
116
132
|
|
|
117
133
|
### Step 3: Register Objective & Constraints on the Model
|
|
118
134
|
|
|
119
|
-
Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)
|
|
135
|
+
Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)` (when `options.M` is omitted in `m.indicator()`, HiGHS/GLPK use tight derived Big-M and preserve `toLpString()`, while Pumpkin lowers natively via `implied_by` and Z3 via `ctx.Implies` unless the returned `Constraint` row is subsequently mutated):
|
|
120
136
|
|
|
121
137
|
```ts
|
|
122
138
|
// Set objective using maximize() or minimize()
|
|
123
139
|
m.objective(maximize(expr`30 * ${x} + 50 * ${n}`));
|
|
124
140
|
|
|
125
|
-
// Register constraints on the model
|
|
126
|
-
m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
|
|
141
|
+
// Register constraints on the model (returns the registered Constraint / BoolExpr or array)
|
|
142
|
+
const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
|
|
127
143
|
|
|
128
144
|
// Indicator constraint (MIP Big-M reformulation: b === 1 => x <= 50)
|
|
129
145
|
m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
|
|
130
146
|
```
|
|
131
147
|
|
|
132
|
-
### Step 4: Execute (`solve` or `check`) & Verify (`
|
|
148
|
+
### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
|
|
133
149
|
|
|
134
150
|
- **Optimization (`await m.solve(options?)`)**:
|
|
135
151
|
- Returns `SolverStatus` (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`, `"Sat"`, or `"Unsat"`). Built-in optimization solvers return the optimization statuses (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`), where a time-, iteration-, or solution-limited run (or an interrupted solve) that found a valid primal incumbent returns `"Feasible"`; `"Sat"` and `"Unsat"` are included in `SolverStatus` for satisfiability/custom solver adapters (such as `MockSolver`).
|
|
136
|
-
- Read values via `x.value`, `expr`...`.value`, `m.
|
|
137
|
-
- Call `m.
|
|
152
|
+
- Read values via `x.value`, `expr`...`.value`, `m.values`, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`, and inspect registered entities via `m.variables` (`ReadonlyMap<string, Var | BoolVar>`) and `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`).
|
|
153
|
+
- Call `m.verify()` after solving to independently verify variable finiteness, variable bounds (`lb`/`ub`), integer/binary/boolean domains, linear constraint residuals, and logical constraints (`VerificationReport`: `{ valid, complete, maxViolation, violations, ... }`). Note that `verify()` checks primal feasibility of variables and constraints; it does not recompute or compare `m.objectiveValue`.
|
|
138
154
|
- **Satisfiability & Conflict Diagnosis (`await m.check(options?)`)**:
|
|
139
155
|
- Returns `CheckResult` (`{ status: "Sat" | "Unsat" | "Unknown", values: Record<string, number | boolean>, conflicts?: readonly string[], unsatCore?: readonly string[], runTime?: number }`), where `conflicts` is populated when the model is proven `"Unsat"`.
|
|
140
|
-
- For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `implies`, `xor`), `m.check()` works with any solver (including the default HiGHS and GLPK via single-solve elastic slack relaxation, automatically linearizing logical constraints into 0-1 MIP formulation) and diagnoses conflicting constraints as `conflicts` (leaving `unsatCore: undefined` for semantic rigor).
|
|
141
|
-
- Exact
|
|
156
|
+
- For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`), `m.check()` works with any solver (including the default HiGHS and GLPK via single-solve elastic slack relaxation, automatically linearizing logical constraints into 0-1 MIP formulation) and diagnoses conflicting constraints as `conflicts` (leaving `unsatCore: undefined` for semantic rigor).
|
|
157
|
+
- Exact unsatisfiable-core extraction (`result.unsatCore` and `result.conflicts`) is provided when using `{ solver: "z3" }` or `{ solver: "pumpkin" }`. Use `"pumpkin"` (`@ohtaman/washi/solvers/pumpkin`) for bounded-integer/propositional models in environments without `COOP`/`COEP` headers, and use `"z3"` when `Continuous` variables or fractional arithmetic are involved. Because Z3 and Pumpkin assert variable bounds (`lb`/`ub`) and binary `{0, 1}` domains directly while tracking registered constraints, `unsatCore` reports a subset of registered constraint names that conflicts *together with the model's fixed variable bounds/domains* (and is not guaranteed minimal).
|
|
142
158
|
- **No concurrent mutation during async solve/check**:
|
|
143
159
|
- Mutating variables, constraints, or the objective while `await m.solve()` or `await m.check()` is pending invalidates the in-flight execution and rejects the stale promise.
|
|
144
160
|
|
|
@@ -161,14 +177,17 @@ export async function runMipExample() {
|
|
|
161
177
|
const qty = m.integer(products, { lb: 0, ub: 100 });
|
|
162
178
|
const setup = m.binary("setup");
|
|
163
179
|
|
|
164
|
-
m.objective(maximize(expr
|
|
165
|
-
m.constraint(expr
|
|
166
|
-
m.constraint(expr
|
|
167
|
-
m.
|
|
180
|
+
m.objective(maximize(expr`dot(${profit}, ${qty}) - 20 * ${setup}`));
|
|
181
|
+
m.constraint(expr`dot(${woodPerUnit}, ${qty}) <= 40`, "wood_cap");
|
|
182
|
+
m.constraint(expr`dot(${laborPerUnit}, ${qty}) <= 50`, "labor_cap");
|
|
183
|
+
m.indicator(setup, expr`sum(${qty}) <= 0`, {
|
|
184
|
+
activeValue: 0,
|
|
185
|
+
name: "require_setup",
|
|
186
|
+
});
|
|
168
187
|
|
|
169
188
|
const status = await m.solve();
|
|
170
|
-
const report = m.
|
|
171
|
-
const values =
|
|
189
|
+
const report = m.verify();
|
|
190
|
+
const values = { desk: qty.desk.value, chair: qty.chair.value };
|
|
172
191
|
|
|
173
192
|
return {
|
|
174
193
|
status,
|
|
@@ -198,7 +217,7 @@ export async function runQpExample() {
|
|
|
198
217
|
m.constraint(expr`${x} + ${y} >= 4`, "budget");
|
|
199
218
|
|
|
200
219
|
const status = await m.solve();
|
|
201
|
-
const report = m.
|
|
220
|
+
const report = m.verify();
|
|
202
221
|
|
|
203
222
|
return {
|
|
204
223
|
status,
|
|
@@ -233,6 +252,57 @@ export async function runZ3Example() {
|
|
|
233
252
|
}
|
|
234
253
|
```
|
|
235
254
|
|
|
255
|
+
### Example D: Pumpkin CP Disjunctive Scheduling & Zero-COOP/COEP Unsat Core
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
|
|
259
|
+
import "@ohtaman/washi/solvers/pumpkin";
|
|
260
|
+
|
|
261
|
+
export async function runPumpkinExample() {
|
|
262
|
+
// Part 1: Bounded-integer CP scheduling with native global propagators
|
|
263
|
+
const cpModel = new Model("WorkshopSchedule", { solver: "pumpkin" });
|
|
264
|
+
const start = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 0, ub: 20, prefix: "start" });
|
|
265
|
+
const bench = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 1, ub: 3, prefix: "bench" });
|
|
266
|
+
|
|
267
|
+
cpModel.constraint(
|
|
268
|
+
disjoint([
|
|
269
|
+
{ start: start.cut, duration: 4 },
|
|
270
|
+
{ start: start.weld, duration: 3 },
|
|
271
|
+
{ start: start.paint, duration: 2 },
|
|
272
|
+
]),
|
|
273
|
+
"single_line"
|
|
274
|
+
);
|
|
275
|
+
cpModel.constraint(expr`${start.cut} + 4 <= ${start.weld}`, "cut_before_weld");
|
|
276
|
+
cpModel.constraint(expr`${start.weld} + 3 <= ${start.paint}`, "weld_before_paint");
|
|
277
|
+
cpModel.constraint(distinct(bench), "unique_benches");
|
|
278
|
+
cpModel.objective(minimize(expr`${start.paint} + 2`));
|
|
279
|
+
|
|
280
|
+
const status = await cpModel.solve();
|
|
281
|
+
const report = cpModel.verify();
|
|
282
|
+
|
|
283
|
+
// Part 2: Zero-COOP/COEP unsatCore diagnosis on bounded integers & booleans
|
|
284
|
+
const unsatModel = new Model("DiscreteConflict", { solver: "pumpkin" });
|
|
285
|
+
const vip = unsatModel.bool("vip");
|
|
286
|
+
const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
|
|
287
|
+
|
|
288
|
+
unsatModel.constraint(vip, "customer_is_vip");
|
|
289
|
+
unsatModel.constraint(implies(vip, expr`${discount} >= 20`), "vip_min_discount");
|
|
290
|
+
unsatModel.constraint(expr`${discount} <= 10`, "campaign_cap");
|
|
291
|
+
|
|
292
|
+
const unsatResult = await unsatModel.check();
|
|
293
|
+
return {
|
|
294
|
+
status,
|
|
295
|
+
makespan: cpModel.objectiveValue,
|
|
296
|
+
starts: { cut: start.cut.value, weld: start.weld.value, paint: start.paint.value },
|
|
297
|
+
benches: { cut: bench.cut.value, weld: bench.weld.value, paint: bench.paint.value },
|
|
298
|
+
valid: report.valid,
|
|
299
|
+
unsatStatus: unsatResult.status,
|
|
300
|
+
conflicts: unsatResult.conflicts,
|
|
301
|
+
unsatCore: unsatResult.unsatCore,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
236
306
|
---
|
|
237
307
|
|
|
238
308
|
## 4. Negative Examples & Common Pitfalls
|
|
@@ -257,15 +327,25 @@ export function verifyNegativePatterns() {
|
|
|
257
327
|
// 3. DO NOT use quadratic terms inside linear constraints:
|
|
258
328
|
// WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
|
|
259
329
|
|
|
260
|
-
// 4. DO NOT use retired aliases (removed in #59 / #81):
|
|
330
|
+
// 4. DO NOT use retired aliases (removed in #59 / #81 / #236 / #273):
|
|
261
331
|
// - Use `expr` instead of retired `c` template tag
|
|
262
332
|
// - Use `m.constraint(...)` instead of `m.constrain(...)` or `m.add(...)`
|
|
263
|
-
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)`
|
|
333
|
+
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` / `m.objective()` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)` / `m.objectiveExpr`
|
|
264
334
|
// - Use `await m.solve()` instead of `await m.optimize()`
|
|
335
|
+
// - Use `m.verify()` instead of `m.validateSolution()` (and rely on automatic integrity validation in `solve()` / `check()` / `toLpString()` instead of `m.validateIntegrity()`)
|
|
336
|
+
// - Use `m.column(...)` instead of `m.addColumn(...)`
|
|
265
337
|
// - Use `.le()`, `.ge()`, `.eq()` instead of `.lessThanOrEqual()`, `.greaterThanOrEqual()`, `.equalTo()`
|
|
266
|
-
// - Use `.value`
|
|
267
|
-
// - Use `m.variables` / `m.constraints` instead of `m.vars` / `m.constrs`
|
|
338
|
+
// - Use `.value` instead of `m.getValues(...)` or `expr.getValue()`
|
|
339
|
+
// - Use `m.variables` / `m.constraints` (`ReadonlyMap` with `.get()` / `.size`) instead of `m.vars` / `m.constrs` / `m.boolVars` / `m.logicalConstraints` / `m.numVars` / `m.numConstrs` / `get*ByName()`
|
|
340
|
+
// - Use `relativeGap` / `absoluteGap` instead of `relGap` / `mipGap` / `absGap`
|
|
268
341
|
return { m, x, y, maximize };
|
|
269
342
|
}
|
|
270
343
|
```
|
|
271
344
|
|
|
345
|
+
### Practical OR Modeling Guardrails
|
|
346
|
+
|
|
347
|
+
- **Prefer inequalities (`>=` / `<=`) over exact equalities (`==`)** for demand coverage and resource limits when objective costs are positive; reserve `==` for physical conservation laws (e.g., flow balance, portfolio weights summing to `1`).
|
|
348
|
+
- **Always provide finite `lb` and `ub` bounds** on variables referenced inside `m.indicator(...)` and omit `M` so WaSHI automatically derives the tightest valid Big-M (`m.indicator()` throws if required bounds are infinite and no explicit `M` is provided).
|
|
349
|
+
- **Use soft constraints (elastic slack variables)** for non-rigid business targets (e.g., preferred staffing, safety stock, day-off requests) by adding a non-negative slack variable (`lb: 0`) with a tiered objective penalty, reserving hard constraints for physical or legal invariants.
|
|
350
|
+
|
|
351
|
+
|