@ohtaman/washi 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +22 -24
- package/README.md +20 -22
- package/README.zh-CN.md +25 -27
- package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
- package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
- package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
- package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
- package/dist/browser/solvers/highs.js +1414 -0
- package/dist/browser/washi.js +1090 -1473
- package/dist/browser/washi.min.js +4 -4
- package/dist/lib/solvers/glpk.js +34 -32
- package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
- package/dist/lib/solvers/highs.js +410 -0
- package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
- package/dist/lib/solvers/pumpkin-worker.js +1 -1
- package/dist/lib/solvers/pumpkin.js +247 -1146
- package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
- package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
- package/dist/lib/solvers/z3.js +125 -123
- package/dist/lib/washi.js +2426 -1340
- package/dist/types/index.d.ts +1 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +0 -1
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +6 -7
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/solvers/index.d.ts +2 -1
- package/dist/types/modeler/solvers/index.d.ts.map +1 -1
- package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
- package/docs/examples/diet-sensitivity.md +33 -14
- package/docs/examples/ecommerce-coupons.md +17 -9
- package/docs/examples/index.md +34 -30
- package/docs/examples/knapsack.md +11 -5
- package/docs/examples/portfolio-qp.md +21 -8
- package/docs/examples/production.md +10 -5
- package/docs/examples/project-scheduling.md +25 -12
- package/docs/examples/shift-scheduling.md +27 -19
- package/docs/examples/smt-security.md +27 -12
- package/docs/examples/transportation.md +23 -13
- package/docs/examples/traveling-salesperson.md +34 -22
- package/docs/examples/unsat-core.md +27 -15
- package/docs/examples/vehicle-routing.md +74 -28
- package/docs/getting-started/ai-agents.md +129 -90
- package/docs/getting-started/coding-agents.md +60 -41
- package/docs/getting-started/cross-origin.md +27 -14
- package/docs/getting-started/index.md +23 -16
- package/docs/getting-started/runtimes.md +70 -40
- package/docs/guide/constraint-programming.md +74 -44
- package/docs/guide/constraints.md +71 -39
- package/docs/guide/decomposition.md +72 -42
- package/docs/guide/expressions.md +79 -48
- package/docs/guide/formulation-tips.md +46 -27
- package/docs/guide/objectives.md +55 -31
- package/docs/guide/unsat-core.md +56 -53
- package/docs/guide/variables.md +61 -28
- package/docs/solvers/custom-solver.md +155 -119
- package/docs/solvers/glpk.md +58 -17
- package/docs/solvers/highs.md +115 -43
- package/docs/solvers/index.md +33 -26
- package/docs/solvers/pumpkin.md +71 -63
- package/docs/solvers/z3.md +63 -25
- package/llms-full.txt +1623 -953
- package/llms.txt +125 -93
- package/package.json +29 -20
- package/skills/washi/SKILL.md +43 -22
- package/dist/browser/solvers/pumpkin.min.js +0 -1
- package/dist/lib/registry-dx7x4e5c.js +0 -1694
- /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
- /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
- /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
- /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
- /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
- /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
- /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
- /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
- /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
- /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
- /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
|
@@ -4,20 +4,20 @@
|
|
|
4
4
|
| :--- | :--- | :--- | :--- |
|
|
5
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
|
+
This **Capacitated Vehicle Routing Problem (CVRP)** variant minimizes the number of delivery vehicles needed to serve every customer. In addition to vehicle cargo capacity, each route must respect maximum stops per shift and route duration limits.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
1. **Restricted Master Problem (RMP)**: Solves
|
|
11
|
-
2. **Pricing Subproblem**:
|
|
9
|
+
Enumerating all feasible routes upfront in a monolithic MIP causes the number of binary variables to explode as the number of customers $n$ grows—unordered subsets alone scale as $O(2^n)$, and ordered routes grow even faster. **Column Generation (Dantzig-Wolfe Decomposition)** avoids this by generating routes on demand:
|
|
10
|
+
1. **Restricted Master Problem (RMP)**: Solves the set-partitioning **LP relaxation** over generated routes so every customer is visited exactly once, then solves the final MIP.
|
|
11
|
+
2. **Pricing Subproblem**: Reads each customer's dual value (shadow price) $\pi_i$ from the master LP relaxation and uses cheapest insertion with 2-opt search to build a route $r$ with negative reduced cost $\bar{c}_r = 1 - \sum_{i \in r} \pi_i < 0$.
|
|
12
12
|
|
|
13
13
|
## Problem Inputs
|
|
14
14
|
|
|
15
|
-
We consider a distribution network with a central depot at $(0, 0)$ and **50 customer locations
|
|
15
|
+
We consider a distribution network with a central depot at $(0, 0)$ and **50 customer locations** (demands of **1 to 4 units** each):
|
|
16
16
|
|
|
17
17
|
- **Vehicle Cargo Capacity**: At most **10 units** per vehicle.
|
|
18
18
|
- **Maximum Stops**: At most **4 customers** per route.
|
|
19
19
|
- **Maximum Shift Duration**: At most **200 minutes** (transit time + service time) per route.
|
|
20
|
-
- **Transit & Service Times**: Euclidean distances between nodes (1 unit = 1 minute) plus **10 minutes** of unloading
|
|
20
|
+
- **Transit & Service Times**: Integer-rounded Euclidean distances (`Math.round`) between nodes (1 unit = 1 minute) plus **10 minutes** of unloading time per customer.
|
|
21
21
|
|
|
22
22
|
## Implementation in WaSHI
|
|
23
23
|
|
|
@@ -26,10 +26,30 @@ We consider a distribution network with a central depot at $(0, 0)$ and **50 cus
|
|
|
26
26
|
```typescript
|
|
27
27
|
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
28
28
|
|
|
29
|
+
interface RouteMeta {
|
|
30
|
+
tour: string[];
|
|
31
|
+
travelTime: number;
|
|
32
|
+
totalTime: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface CandidateCustomer {
|
|
36
|
+
id: string;
|
|
37
|
+
demand: number;
|
|
38
|
+
dual: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface RouteConstraints {
|
|
42
|
+
dist: (a: string, b: string) => number;
|
|
43
|
+
serviceTimes: Record<string, number>;
|
|
44
|
+
vehicleCapacity: number;
|
|
45
|
+
maxStops: number;
|
|
46
|
+
maxRouteTime: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
29
49
|
// --- Extracted Routing Helpers ---
|
|
30
50
|
|
|
31
51
|
// 2-opt local search to eliminate crossing paths in a tour
|
|
32
|
-
function optimize2Opt(tour, dist) {
|
|
52
|
+
function optimize2Opt(tour: string[], dist: (a: string, b: string) => number): string[] {
|
|
33
53
|
let best = [...tour];
|
|
34
54
|
let improved = true;
|
|
35
55
|
|
|
@@ -49,8 +69,8 @@ function optimize2Opt(tour, dist) {
|
|
|
49
69
|
return best;
|
|
50
70
|
}
|
|
51
71
|
|
|
52
|
-
// Inserts a customer into the tour at the position that minimizes
|
|
53
|
-
function insertCheapest(tour, id, dist) {
|
|
72
|
+
// Inserts a customer into the tour at the position that minimizes added distance
|
|
73
|
+
function insertCheapest(tour: string[], id: string, dist: (a: string, b: string) => number): string[] {
|
|
54
74
|
let bestPos = 1;
|
|
55
75
|
let minCost = Infinity;
|
|
56
76
|
|
|
@@ -65,7 +85,11 @@ function insertCheapest(tour, id, dist) {
|
|
|
65
85
|
}
|
|
66
86
|
|
|
67
87
|
// Calculates transit time and total duration (transit + service) for a tour
|
|
68
|
-
function calcRouteTime(
|
|
88
|
+
function calcRouteTime(
|
|
89
|
+
tour: string[],
|
|
90
|
+
dist: (a: string, b: string) => number,
|
|
91
|
+
serviceTimes: Record<string, number>
|
|
92
|
+
) {
|
|
69
93
|
let travelTime = 0;
|
|
70
94
|
for (let i = 0; i < tour.length - 1; i++) {
|
|
71
95
|
travelTime += dist(tour[i], tour[i + 1]);
|
|
@@ -75,8 +99,8 @@ function calcRouteTime(tour, dist, serviceTimes) {
|
|
|
75
99
|
}
|
|
76
100
|
|
|
77
101
|
// Pricing subproblem: Finds an improving route with negative reduced cost (1 - dualSum < 0)
|
|
78
|
-
function findImprovingRoute(candidates, config) {
|
|
79
|
-
let bestRoute = null;
|
|
102
|
+
function findImprovingRoute(candidates: CandidateCustomer[], config: RouteConstraints): string[] | null {
|
|
103
|
+
let bestRoute: string[] | null = null;
|
|
80
104
|
let minReducedCost = -1e-4;
|
|
81
105
|
|
|
82
106
|
for (const seed of candidates.slice(0, 15)) {
|
|
@@ -130,11 +154,11 @@ async function runCVRP() {
|
|
|
130
154
|
});
|
|
131
155
|
|
|
132
156
|
const nodes = Object.fromEntries([depot, ...customers].map((n) => [n.id, n]));
|
|
133
|
-
const dist = (a, b) =>
|
|
157
|
+
const dist = (a: string, b: string) =>
|
|
134
158
|
Math.round(Math.hypot(nodes[a].x - nodes[b].x, nodes[a].y - nodes[b].y));
|
|
135
159
|
const serviceTimes = Object.fromEntries(customers.map((c) => [c.id, c.serviceTime]));
|
|
136
160
|
|
|
137
|
-
const routeConfig = { dist, serviceTimes, vehicleCapacity, maxStops, maxRouteTime };
|
|
161
|
+
const routeConfig: RouteConstraints = { dist, serviceTimes, vehicleCapacity, maxStops, maxRouteTime };
|
|
138
162
|
|
|
139
163
|
// 1. Build Restricted Master Problem (RMP)
|
|
140
164
|
const master = new Model("CVRP_FleetMaster");
|
|
@@ -143,7 +167,7 @@ async function runCVRP() {
|
|
|
143
167
|
const initialRoutes = customers.map((c) => master.binary(`route_init_${c.id}`));
|
|
144
168
|
master.objective(minimize(expr`sum(${initialRoutes})`));
|
|
145
169
|
|
|
146
|
-
//
|
|
170
|
+
// Set-partitioning constraints: each customer must be visited by exactly 1 vehicle
|
|
147
171
|
const visitConstrs = customers.map((c, i) =>
|
|
148
172
|
master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${c.id}`)
|
|
149
173
|
);
|
|
@@ -152,7 +176,7 @@ async function runCVRP() {
|
|
|
152
176
|
console.log("Solving via Column Generation with dual-directed heuristic pricing...");
|
|
153
177
|
|
|
154
178
|
// 2. Solve via Column Generation
|
|
155
|
-
const result = await master.solveColumnGeneration({
|
|
179
|
+
const result = await master.solveColumnGeneration<RouteMeta>({
|
|
156
180
|
finalizeAsMIP: true,
|
|
157
181
|
pricing: async () => {
|
|
158
182
|
// 1. Sort customers by shadow price (dual profit) descending
|
|
@@ -167,14 +191,14 @@ async function runCVRP() {
|
|
|
167
191
|
|
|
168
192
|
// 3. Propose new column to Restricted Master Problem
|
|
169
193
|
const { travelTime, totalTime } = calcRouteTime(bestRoute, dist, serviceTimes);
|
|
170
|
-
const coefficients = {};
|
|
194
|
+
const coefficients: Record<string, number> = {};
|
|
171
195
|
for (const id of bestRoute.slice(1, -1)) {
|
|
172
196
|
coefficients[`visit_${id}`] = 1;
|
|
173
197
|
}
|
|
174
198
|
|
|
175
199
|
return {
|
|
176
200
|
cost: 1,
|
|
177
|
-
type: "Binary",
|
|
201
|
+
type: "Binary" as const,
|
|
178
202
|
coefficients,
|
|
179
203
|
meta: { tour: bestRoute, travelTime, totalTime },
|
|
180
204
|
};
|
|
@@ -186,10 +210,21 @@ async function runCVRP() {
|
|
|
186
210
|
console.log(`Total Columns Generated: ${result.columnsAdded}`);
|
|
187
211
|
|
|
188
212
|
console.log("\nSample routes selected in fleet:");
|
|
189
|
-
const activeRoutes =
|
|
213
|
+
const activeRoutes: RouteMeta[] = [];
|
|
214
|
+
for (const c of result.generatedColumns) {
|
|
215
|
+
if (c.variable.value === 1 && c.proposal.meta) {
|
|
216
|
+
activeRoutes.push(c.proposal.meta);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
for (let i = 0; i < customers.length; i++) {
|
|
220
|
+
if (initialRoutes[i].value === 1) {
|
|
221
|
+
const tour = ["Depot", customers[i].id, "Depot"];
|
|
222
|
+
const { travelTime, totalTime } = calcRouteTime(tour, dist, serviceTimes);
|
|
223
|
+
activeRoutes.push({ tour, travelTime, totalTime });
|
|
224
|
+
}
|
|
225
|
+
}
|
|
190
226
|
for (const r of activeRoutes.slice(0, 5)) {
|
|
191
|
-
|
|
192
|
-
console.log(` ${meta?.tour.join(" -> ")} (Transit: ${meta?.travelTime}m, Total: ${meta?.totalTime}m)`);
|
|
227
|
+
console.log(` ${r.tour.join(" -> ")} (Transit: ${r.travelTime}m, Total: ${r.totalTime}m)`);
|
|
193
228
|
}
|
|
194
229
|
}
|
|
195
230
|
|
|
@@ -198,11 +233,22 @@ runCVRP();
|
|
|
198
233
|
|
|
199
234
|
</CodeRunner>
|
|
200
235
|
|
|
201
|
-
##
|
|
236
|
+
## Key Takeaways
|
|
237
|
+
|
|
238
|
+
Starting from `50` single-customer vehicles, heuristic pricing generates `63` additional route columns and lowers the LP relaxation to about `12.65`. Finalizing that column pool as a MIP (root-node Price-and-Branch) yields a `19`-vehicle fleet made up of `11` multi-stop routes and `8` single-customer routes.
|
|
239
|
+
|
|
240
|
+
### Master Problem, Pricing & Route Metadata
|
|
241
|
+
|
|
242
|
+
The master problem handles the LP relaxation and final set-partitioning MIP. Inside `pricing`, `visitConstrs[i].dual` supplies each customer's dual value (shadow price) to guide route construction. Storing `{ tour, travelTime, totalTime }` in `meta` lets you inspect the chosen stop sequence via `result.generatedColumns` after solving.
|
|
243
|
+
|
|
244
|
+
### Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)
|
|
245
|
+
|
|
246
|
+
This example uses `== 1` so no customer is visited twice in the final MIP. In larger instances, using `>= 1` keeps dual values non-negative ($\pi_i \ge 0$) and stabilizes LP convergence. When travel distances satisfy the triangle inequality, duplicate visits can be stripped after solving without increasing travel time, load, stop count, or fleet size. Note that rounding distances with `Math.round`, as in this example, can introduce small rounding violations of the triangle inequality.
|
|
247
|
+
|
|
248
|
+
### Heuristic Pricing vs. Exact ESPPRC
|
|
249
|
+
|
|
250
|
+
Here `findImprovingRoute` runs a greedy cheapest-insertion and 2-opt heuristic instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver. Returning `null` therefore means the heuristic found no further improving route, rather than proving global LP optimality.
|
|
251
|
+
|
|
252
|
+
### Price-and-Branch (`finalizeAsMIP: true`)
|
|
202
253
|
|
|
203
|
-
|
|
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.
|
|
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.
|
|
254
|
+
Solving the Restricted Master Problem as a MIP over the columns generated at the root node is called the **Restricted Master Heuristic** (Price-and-Branch). It produces strong integer fleets quickly without implementing a full Branch-and-Price search tree.
|
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
# AI Coding Agent Quick-Reference Guide
|
|
2
2
|
|
|
3
|
-
> **Scope Note**: This document is the **
|
|
4
|
-
>
|
|
3
|
+
> **Scope Note**: This document is the **modeling quick reference** for AI coding agents and developers building optimization or satisfiability models with `@ohtaman/washi`.
|
|
4
|
+
>
|
|
5
|
+
> - **Portable Agent Skill**: Install the WaSHI Agent Skill ([`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md), also shipped at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`) for an end-to-end modeling, verification, and conflict-diagnosis workflow:
|
|
5
6
|
> ```bash
|
|
6
7
|
> # Install directly via the skills CLI (skills.sh / vercel-labs/skills)
|
|
7
8
|
> npx skills add ohtaman/washi
|
|
8
9
|
>
|
|
9
|
-
> # Or
|
|
10
|
+
> # Or copy the packaged skill into your project's agent skills directory
|
|
10
11
|
> mkdir -p .agents/skills/washi
|
|
11
12
|
> cp node_modules/@ohtaman/washi/skills/washi/SKILL.md .agents/skills/washi/SKILL.md
|
|
12
13
|
> ```
|
|
13
|
-
> - **Repository Review Guidelines**:
|
|
14
|
+
> - **Repository Development & Code Review Guidelines**: See [`AGENTS.md`](https://github.com/ohtaman/washi/blob/main/AGENTS.md) in the repository root.
|
|
14
15
|
|
|
15
16
|
---
|
|
16
17
|
|
|
17
18
|
## 1. Package Imports & Deployment
|
|
18
19
|
|
|
19
|
-
### Node.js
|
|
20
|
+
### Node.js, Bun, & Bundlers (Vite, Webpack, Next.js)
|
|
20
21
|
|
|
21
22
|
```ts
|
|
22
23
|
import {
|
|
@@ -39,11 +40,13 @@ import {
|
|
|
39
40
|
not,
|
|
40
41
|
implies,
|
|
41
42
|
xor,
|
|
42
|
-
setHighsWasmUrl,
|
|
43
43
|
} from "@ohtaman/washi";
|
|
44
44
|
|
|
45
|
-
// Bundled
|
|
46
|
-
|
|
45
|
+
// Bundled solvers: HiGHS (default) and Pumpkin (`{ solver: "pumpkin" }`) work out of the box with zero extra imports.
|
|
46
|
+
// Import solver subpaths only when configuring engine-specific classes or custom WASM URLs:
|
|
47
|
+
// import { HighsSolver, setHighsWasmUrl } from "@ohtaman/washi/solvers/highs";
|
|
48
|
+
// import { PumpkinSolver, setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
|
|
49
|
+
|
|
47
50
|
// Optional solver plugins (require installing peer dependencies first):
|
|
48
51
|
// npm install z3-solver
|
|
49
52
|
import "@ohtaman/washi/solvers/z3";
|
|
@@ -53,34 +56,47 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
53
56
|
|
|
54
57
|
### Browser ESM & Classic Script Tags
|
|
55
58
|
|
|
56
|
-
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
- Z3 plugin: `<script src="./washi/solvers/z3.min.js"></script>` (registers `"z3"`, exposes `WashiZ3`)
|
|
59
|
+
Classic `<script>` tags load immediately invoked function expression (`IIFE`) bundles that attach a global namespace to `window` (optional solver plugins auto-register when `window.Washi` is present). Assuming `dist/browser/` is hosted at `./washi/`:
|
|
60
|
+
|
|
61
|
+
| Solver | Browser ESM (`<script type="module">`) | Classic `<script>` IIFE |
|
|
62
|
+
| --- | --- | --- |
|
|
63
|
+
| **Core (HiGHS & Pumpkin)** | `import { Model, expr, maximize } from "./washi/washi.js";` | `<script src="./washi/washi.min.js"></script>` (global `Washi`) |
|
|
64
|
+
| **HiGHS** *(subpath API)* | `import { HighsSolver, setHighsWasmUrl } from "./washi/solvers/highs.js";` | Bundled in `washi.min.js` (pass `{ wasmUrl }` per call) |
|
|
65
|
+
| **Pumpkin** *(subpath API)* | `import { PumpkinSolver, setPumpkinWasmUrl } from "./washi/solvers/pumpkin.js";` | Bundled in `washi.min.js` (pass `{ wasmUrl }` per call) |
|
|
66
|
+
| **GLPK** *(optional)* | `import "./washi/solvers/glpk.js";` | `<script src="./washi/solvers/glpk.min.js"></script>` (`WashiGLPK`) |
|
|
67
|
+
| **Z3** *(optional)* | `import "./washi/solvers/z3.js";` | `<script src="./washi/solvers/z3.min.js"></script>` (`WashiZ3`) |
|
|
66
68
|
|
|
67
69
|
### WebAssembly Asset & Runtime Rules
|
|
68
70
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
71
|
+
#### Bundled WASM & Custom Asset URLs
|
|
72
|
+
|
|
73
|
+
- **Automatic resolution**: In Node.js and bundler builds, WaSHI resolves `.wasm` assets under `solvers/` relative to the module with no CDN fallback.
|
|
74
|
+
- **Browser self-hosting**: Deploy `dist/browser/` intact (entry scripts, `solvers/` runtime/worker/WASM assets, and chunks). Requests that hit missing URLs or HTML SPA fallbacks fail immediately and report the attempted URL.
|
|
75
|
+
- **Custom browser URLs**: Call `setHighsWasmUrl(url)` (from `@ohtaman/washi/solvers/highs`) or `setPumpkinWasmUrl(url)` (from `@ohtaman/washi/solvers/pumpkin`), or pass `{ wasmUrl }` to `m.solve()` / `m.check()`. This override is ignored for HiGHS in Node.js, while Pumpkin accepts `file://` URLs in Node.js. For Z3, call `setZ3Assets({ jsUrl, wasmUrl })` (from `@ohtaman/washi/solvers/z3`) or pass `{ z3JsUrl, z3WasmUrl }`.
|
|
76
|
+
|
|
77
|
+
#### Browser Security & Cross-Origin Isolation
|
|
78
|
+
|
|
79
|
+
- **HiGHS, Pumpkin, and GLPK**: Run in standard browser contexts without `SharedArrayBuffer` or isolation headers.
|
|
80
|
+
- **Z3 browser preconditions**: Z3 uses `SharedArrayBuffer` multithreading, so browsers require a Secure Context (`window.isSecureContext === true`, HTTPS or `localhost`) and `window.crossOriginIsolated === true`.
|
|
81
|
+
- **Required Z3 headers**: Serve the document with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (`COOP`/`COEP`). Cross-origin script and WASM assets also require `Cross-Origin-Resource-Policy: cross-origin` (`CORP`) or valid CORS headers (`Access-Control-Allow-Origin`), depending on the request mode.
|
|
82
|
+
- **Fail-fast check & no auto-injected Service Worker**: Importing `@ohtaman/washi` never injects a Service Worker. `m.solve()` and `m.check()` with Z3 reject immediately if a secure context or Cross-Origin Isolation is missing.
|
|
83
|
+
|
|
84
|
+
#### Web Workers & Cancellation (`AbortSignal`)
|
|
85
|
+
|
|
86
|
+
- **Default Workers**: On standard browser origins (`window.origin !== "null"`), HiGHS and Pumpkin default to Web Workers (`useWorker: true`). On opaque origins (`window.origin === "null"`, such as `file://` pages or sandboxed iframes without `allow-same-origin`), both default to `useWorker: false`.
|
|
87
|
+
- **Worker cancellation**: Pre-solve cancellation (`signal.aborted`) works on all solvers, and `{ signal }` terminates in-flight HiGHS and Pumpkin Workers immediately.
|
|
88
|
+
- **Main-thread & Node.js cancellation**: HiGHS checks `signal` during `onProgress` callbacks, Pumpkin polls `signal` at search checkpoints, and GLPK/Z3 only check `signal` before starting.
|
|
89
|
+
|
|
90
|
+
#### Solver Capabilities, Options, & Validation Errors
|
|
91
|
+
|
|
92
|
+
| Solver | Problem Classes | Accepted Options | Throws On |
|
|
93
|
+
| --- | --- | --- | --- |
|
|
94
|
+
| **HiGHS** *(default)* | Linear (`LP`), mixed-integer (`MIP`), and convex quadratic (`QP`) | `timeLimit`, `presolve`, `relativeGap`, `absoluteGap`, `outputFlag`, `relax`, `useWorker`, `wasmUrl`, `signal`, `onProgress` | `threads`, `verbose` (use `outputFlag`), unknown keys, MIQP (quadratic objective with integer/binary/boolean variables) |
|
|
95
|
+
| **Pumpkin** | Constraint Programming (`CP`), bounded discrete `unsatCore` | `timeLimit`, `useWorker`, `wasmUrl`, `signal`, `onProgress` | `relax: true`, `presolve`, `relativeGap`, `absoluteGap`, `threads`, `verbose`, `outputFlag`, unknown keys, `Continuous` variables, unbounded variables or bounds outside `[-(2^30 - 1), 2^30 - 1]`, fractional coefficients/RHS, `QuadExpr` |
|
|
96
|
+
| **Z3** | Satisfiability Modulo Theories (`SMT`), continuous/discrete `unsatCore` | `signal`, `onProgress`, `z3JsUrl`, `z3WasmUrl` | `relax: true`, `useWorker: true`, `timeLimit`, `presolve`, `relativeGap`, `absoluteGap`, `threads`, `verbose`, `outputFlag`, unknown keys, `QuadExpr`, variable `initialValue` |
|
|
97
|
+
| **GLPK** | `LP`, `MIP` | `timeLimit`, `presolve`, `relativeGap`, `verbose`, `relax`, `signal`, `onProgress` | `useWorker: true`, `absoluteGap`, `threads`, `outputFlag` (use `verbose`), unknown keys, `QuadExpr`, variable `initialValue` |
|
|
98
|
+
|
|
99
|
+
Warm-start hints live on variables (`initialValue`), not `solve()`/`check()` options; see Step 1 below for solver support.
|
|
84
100
|
|
|
85
101
|
---
|
|
86
102
|
|
|
@@ -98,7 +114,7 @@ const x = m.continuous("x", { lb: 0, ub: 100 });
|
|
|
98
114
|
const y = m.continuous("y", { lb: 0, ub: 100 });
|
|
99
115
|
const n = m.integer("n", { lb: 0, ub: 10 });
|
|
100
116
|
const b = m.binary("b");
|
|
101
|
-
const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native
|
|
117
|
+
const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native CP/SMT on Pumpkin/Z3)
|
|
102
118
|
|
|
103
119
|
// Indexed variable containers:
|
|
104
120
|
// - Numeric dimension -> Array
|
|
@@ -109,30 +125,40 @@ const byItem = m.integer(["desk", "chair"] as const, { lb: 0 }); // Record<"desk
|
|
|
109
125
|
const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
|
|
110
126
|
```
|
|
111
127
|
|
|
112
|
-
- **
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
- Supported by **HiGHS** and **Pumpkin** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
|
|
128
|
+
- **Primal hints**: Numeric variable constructors and `v.initialValue` accept a finite starting value, validated against `[lb, ub]` and checked for integrality (tolerance `1e-6`), and kept distinct from the solved `v.value`.
|
|
129
|
+
- **Hint semantics**: Complete or partial warm starts do not fix variables, add hard constraints, or guarantee solver acceptance or speedup.
|
|
130
|
+
- **Warm-start support**: Supported by HiGHS and Pumpkin (`supportsWarmStart: true`). GLPK and Z3 throw if any variable has `initialValue` set.
|
|
116
131
|
|
|
117
132
|
### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
|
|
118
133
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
134
|
+
#### Unified `expr` Template Tag
|
|
135
|
+
|
|
136
|
+
| Form | Examples | Notes |
|
|
137
|
+
| --- | --- | --- |
|
|
138
|
+
| Linear (`LinExpr`) | `` expr`30 * ${x} + 50 * ${n} - 10` ``, `` expr`dot(${profit}, ${byItem}) - 20 * ${b}` `` | Also supports `` expr`sum((${price} - ${cost}) * ${byItem})` ``. |
|
|
139
|
+
| Piecewise & element | `` expr`max(${vec}) + sum(abs(${vec} - ${target}))` ``, `` expr`at(${costs}, ${idx})` `` | `at()` enforces `0 <= idx < costs.length` on 0-based integer `idx`. Convex uses (e.g., minimizing `max`/`abs`) stay pure LP on HiGHS/GLPK; non-convex contexts require finite bounds. |
|
|
140
|
+
| Quadratic (`QuadExpr`) | `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${vec} - ${target})^2)` `` | Supported on HiGHS for convex QP objectives over continuous variables (`m.continuous`); MIQP and quadratic constraints are rejected, and other solvers reject `QuadExpr`. |
|
|
141
|
+
| Constraint (`Constraint`) | `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` | Supports `<=`, `>=`, `==`, `=`, plus integer-only `<`, `>`, `!=`. |
|
|
142
|
+
|
|
143
|
+
#### Aggregations & Fluent Methods
|
|
144
|
+
|
|
145
|
+
- **`sum(containerOrItems, mapper?)`**: Sums a 1D/2D `Array`, `Iterable`, or plain object (`Record`) of variables, expressions, or numbers, optionally transforming each item with `mapper`. Inside `` expr`sum(...)` ``, element-wise `+`, `-`, `*`, `/`, `^2`, and `abs(...)` also work.
|
|
146
|
+
- **`dot(a, b)`**: Computes the inner product of matching 1D arrays, 2D arrays (Frobenius inner product $\sum_{i,j} A_{i,j} B_{i,j}$), plain objects, or mixed `Array`/`Record` containers.
|
|
147
|
+
- **Fluent arithmetic & comparisons**: `.add()`, `.sub()`, `.mul()`, `.div(scalar)`, `.neg()`, plus `.le()`, `.ge()`, `.eq()`, and integer-only `.lt()`, `.gt()`, `.ne()` (all taking `(rhs, name?)`; continuous/fractional operands throw on strict/not-equal comparisons).
|
|
148
|
+
|
|
149
|
+
#### CP Global Constraints & Boolean Logic
|
|
150
|
+
|
|
151
|
+
| Helper | Purpose | Solver Lowering |
|
|
152
|
+
| --- | --- | --- |
|
|
153
|
+
| `distinct(...args)` | All variables take pairwise distinct values | Native on Pumpkin and Z3; pairwise `!=` on HiGHS/GLPK. |
|
|
154
|
+
| `disjoint(tasks)` | Non-overlapping intervals (`{ start, duration }`) | Native scheduling propagator on Pumpkin; linearized on MIP solvers. |
|
|
155
|
+
| `cumulative(tasks, capacity)` | Shared resource capacity (`{ start, duration, demand }`) | Native propagator on Pumpkin; MIP time-indexed encoding enforces a horizon memory guard. |
|
|
156
|
+
| `allowed(vars, tuples)` | Restrict variable tuples to an allowed table | Native table propagator on Pumpkin; linearized on MIP solvers. |
|
|
157
|
+
| `and`, `or`, `not`, `implies`, `xor` | Composable boolean logic (standalone or fluent) | Native on Pumpkin and Z3; linearized to 0-1 MIP on HiGHS/GLPK (negated continuous constraints throw on MIP—use `{ solver: "z3" }` or reformulate with boolean variables). |
|
|
132
158
|
|
|
133
159
|
### Step 3: Register Objective & Constraints on the Model
|
|
134
160
|
|
|
135
|
-
Constructing an `expr` or `.le()`
|
|
161
|
+
Constructing an expression or constraint via `expr` or `.le()` does **not** attach it to the model until you call `m.constraint(...)` or `m.objective(...)`. In `m.indicator()`, omitting `options.M` derives tight Big-M bounds for MIP solvers while keeping native indicator lowering on Pumpkin and Z3:
|
|
136
162
|
|
|
137
163
|
```ts
|
|
138
164
|
// Set objective using maximize() or minimize()
|
|
@@ -141,28 +167,35 @@ m.objective(maximize(expr`30 * ${x} + 50 * ${n}`));
|
|
|
141
167
|
// Register constraints on the model (returns the registered Constraint / BoolExpr or array)
|
|
142
168
|
const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
|
|
143
169
|
|
|
144
|
-
// Indicator constraint (
|
|
170
|
+
// Indicator constraint (b === 1 => x <= 50; Big-M on MIP, native on Pumpkin/Z3)
|
|
145
171
|
m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
|
|
146
172
|
```
|
|
147
173
|
|
|
148
174
|
### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
|
|
149
175
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
- **
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
176
|
+
#### Optimization (`await m.solve(options?)`)
|
|
177
|
+
|
|
178
|
+
- **Return value**: Returns `SolverStatus` (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`, `"Sat"`, or `"Unsat"`).
|
|
179
|
+
- **Status semantics**: Optimization solvers return `"Feasible"` when a limit or abort terminates the solve with a valid primal incumbent. `"Sat"` and `"Unsat"` apply to satisfiability or custom solver adapters.
|
|
180
|
+
- **Reading results**: Check `m.hasPrimalSolution`, then read `x.value`, `` expr`...`.value ``, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`. `m.values` (like `m.variables` and `m.constraints`) is a `ReadonlyMap<string, number | boolean>` (use `.get(name)`), unlike `CheckResult.values` and `m.solution.values` (`Record`).
|
|
181
|
+
- **Independent verification**: `m.verify()` checks primal feasibility—finiteness, bounds, integrality, and constraints—returning `VerificationReport` (`{ valid, complete, maxViolation, violations }`) without recomputing `m.objectiveValue`.
|
|
182
|
+
|
|
183
|
+
#### Satisfiability & Conflict Diagnosis (`await m.check(options?)`)
|
|
184
|
+
|
|
185
|
+
- **Return value**: Returns `CheckResult` (`{ status: "Sat" | "Unsat" | "Unknown", values: Record<string, number | boolean>, conflicts?: readonly string[], unsatCore?: readonly string[], runTime?: number }`).
|
|
186
|
+
- **HiGHS & GLPK**: Diagnose linear and logical conflicts in `conflicts` via slack relaxation, leaving `unsatCore` as `undefined`.
|
|
187
|
+
- **Pumpkin & Z3**: Extract an exact unsatisfiable core into both `unsatCore` and `conflicts`. Use Pumpkin for bounded integer/boolean models and Z3 when continuous or fractional constraints are present.
|
|
188
|
+
- **Bounds caveat**: Variable bounds `lb`/`ub` and binary domains are asserted directly, so `unsatCore` reports constraint names that conflict *together with those variable bounds* (not guaranteed minimal).
|
|
189
|
+
|
|
190
|
+
#### Concurrent Mutation Rule
|
|
191
|
+
|
|
192
|
+
- Mutating variables, constraints, or the objective while an `m.solve()` or `m.check()` call is pending invalidates the in-flight run and rejects the stale promise.
|
|
160
193
|
|
|
161
194
|
---
|
|
162
195
|
|
|
163
196
|
## 3. Executable Examples
|
|
164
197
|
|
|
165
|
-
### Example A: Mixed-Integer Linear Programming (MIP) with Indexed Containers & Solution
|
|
198
|
+
### Example A: Mixed-Integer Linear Programming (MIP) with Indexed Containers & Solution Verification
|
|
166
199
|
|
|
167
200
|
```ts
|
|
168
201
|
import { Model, expr, dot, sum, maximize } from "@ohtaman/washi";
|
|
@@ -186,23 +219,25 @@ export async function runMipExample() {
|
|
|
186
219
|
});
|
|
187
220
|
|
|
188
221
|
const status = await m.solve();
|
|
189
|
-
const report = m.verify();
|
|
190
|
-
const values =
|
|
222
|
+
const report = m.hasPrimalSolution ? m.verify() : null;
|
|
223
|
+
const values = m.hasPrimalSolution
|
|
224
|
+
? { desk: qty.desk.value, chair: qty.chair.value }
|
|
225
|
+
: null;
|
|
191
226
|
|
|
192
227
|
return {
|
|
193
228
|
status,
|
|
194
229
|
objectiveValue: m.objectiveValue,
|
|
195
230
|
values,
|
|
196
|
-
setup: setup.value,
|
|
197
|
-
valid: report
|
|
198
|
-
maxViolation: report
|
|
231
|
+
setup: m.hasPrimalSolution ? setup.value : null,
|
|
232
|
+
valid: report?.valid ?? false,
|
|
233
|
+
maxViolation: report?.maxViolation ?? null,
|
|
199
234
|
};
|
|
200
235
|
}
|
|
201
236
|
```
|
|
202
237
|
|
|
203
238
|
### Example B: Convex Quadratic Programming (QP)
|
|
204
239
|
|
|
205
|
-
|
|
240
|
+
Products of two variables (`${x} * ${y}`) and squares (`${x}^2`) are supported in `expr` for quadratic objectives:
|
|
206
241
|
|
|
207
242
|
```ts
|
|
208
243
|
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
@@ -217,14 +252,14 @@ export async function runQpExample() {
|
|
|
217
252
|
m.constraint(expr`${x} + ${y} >= 4`, "budget");
|
|
218
253
|
|
|
219
254
|
const status = await m.solve();
|
|
220
|
-
const report = m.verify();
|
|
255
|
+
const report = m.hasPrimalSolution ? m.verify() : null;
|
|
221
256
|
|
|
222
257
|
return {
|
|
223
258
|
status,
|
|
224
259
|
objectiveValue: m.objectiveValue,
|
|
225
|
-
x: x.value,
|
|
226
|
-
y: y.value,
|
|
227
|
-
valid: report
|
|
260
|
+
x: m.hasPrimalSolution ? x.value : null,
|
|
261
|
+
y: m.hasPrimalSolution ? y.value : null,
|
|
262
|
+
valid: report?.valid ?? false,
|
|
228
263
|
};
|
|
229
264
|
}
|
|
230
265
|
```
|
|
@@ -248,15 +283,15 @@ export async function runZ3Example() {
|
|
|
248
283
|
return {
|
|
249
284
|
status: unsatResult.status,
|
|
250
285
|
conflicts: unsatResult.conflicts,
|
|
286
|
+
unsatCore: unsatResult.unsatCore,
|
|
251
287
|
};
|
|
252
288
|
}
|
|
253
289
|
```
|
|
254
290
|
|
|
255
|
-
### Example D: Pumpkin CP
|
|
291
|
+
### Example D: Pumpkin CP Scheduling & Discrete Unsat Core
|
|
256
292
|
|
|
257
293
|
```ts
|
|
258
294
|
import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
|
|
259
|
-
import "@ohtaman/washi/solvers/pumpkin";
|
|
260
295
|
|
|
261
296
|
export async function runPumpkinExample() {
|
|
262
297
|
// Part 1: Bounded-integer CP scheduling with native global propagators
|
|
@@ -278,9 +313,15 @@ export async function runPumpkinExample() {
|
|
|
278
313
|
cpModel.objective(minimize(expr`${start.paint} + 2`));
|
|
279
314
|
|
|
280
315
|
const status = await cpModel.solve();
|
|
281
|
-
const report = cpModel.verify();
|
|
282
|
-
|
|
283
|
-
|
|
316
|
+
const report = cpModel.hasPrimalSolution ? cpModel.verify() : null;
|
|
317
|
+
const starts = cpModel.hasPrimalSolution
|
|
318
|
+
? { cut: start.cut.value, weld: start.weld.value, paint: start.paint.value }
|
|
319
|
+
: null;
|
|
320
|
+
const benches = cpModel.hasPrimalSolution
|
|
321
|
+
? { cut: bench.cut.value, weld: bench.weld.value, paint: bench.paint.value }
|
|
322
|
+
: null;
|
|
323
|
+
|
|
324
|
+
// Part 2: Discrete unsatCore diagnosis on bounded integers & booleans
|
|
284
325
|
const unsatModel = new Model("DiscreteConflict", { solver: "pumpkin" });
|
|
285
326
|
const vip = unsatModel.bool("vip");
|
|
286
327
|
const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
|
|
@@ -293,9 +334,9 @@ export async function runPumpkinExample() {
|
|
|
293
334
|
return {
|
|
294
335
|
status,
|
|
295
336
|
makespan: cpModel.objectiveValue,
|
|
296
|
-
starts
|
|
297
|
-
benches
|
|
298
|
-
valid: report
|
|
337
|
+
starts,
|
|
338
|
+
benches,
|
|
339
|
+
valid: report?.valid ?? false,
|
|
299
340
|
unsatStatus: unsatResult.status,
|
|
300
341
|
conflicts: unsatResult.conflicts,
|
|
301
342
|
unsatCore: unsatResult.unsatCore,
|
|
@@ -321,13 +362,13 @@ export function verifyNegativePatterns() {
|
|
|
321
362
|
// WRONG: m.objective(maximize(expr`${x} <= 10` as any)); -> throws Error
|
|
322
363
|
// WRONG: expr`${x} + 1`.add(expr`${y} <= 5` as any); -> throws Error
|
|
323
364
|
|
|
324
|
-
// 2. DO NOT pass
|
|
365
|
+
// 2. DO NOT pass a bare arithmetic expression without a comparison operator (<=, >=, ==, etc.) to m.constraint():
|
|
325
366
|
// WRONG: m.constraint(expr`${x} + ${y}` as any); -> throws Error
|
|
326
367
|
|
|
327
|
-
// 3. DO NOT use quadratic terms
|
|
368
|
+
// 3. DO NOT use quadratic terms in constraints:
|
|
328
369
|
// WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
|
|
329
370
|
|
|
330
|
-
// 4. DO NOT use retired aliases
|
|
371
|
+
// 4. DO NOT use retired aliases:
|
|
331
372
|
// - Use `expr` instead of retired `c` template tag
|
|
332
373
|
// - Use `m.constraint(...)` instead of `m.constrain(...)` or `m.add(...)`
|
|
333
374
|
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` / `m.objective()` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)` / `m.objectiveExpr`
|
|
@@ -344,8 +385,6 @@ export function verifyNegativePatterns() {
|
|
|
344
385
|
|
|
345
386
|
### Practical OR Modeling Guardrails
|
|
346
387
|
|
|
347
|
-
- **Prefer inequalities
|
|
348
|
-
- **
|
|
349
|
-
- **
|
|
350
|
-
|
|
351
|
-
|
|
388
|
+
- **Prefer inequalities over equalities**: Use `>=` for demand coverage (when minimizing positive costs) and `<=` for resource caps (when maximizing positive returns). Reserve `==` for conservation laws such as flow balance or weights summing to `1`.
|
|
389
|
+
- **Provide finite bounds for `m.indicator()`**: Give referenced variables finite `lb` and `ub` bounds and omit `M` so WaSHI derives a tight Big-M. Omitting `M` when any referenced variable has an infinite bound throws an error.
|
|
390
|
+
- **Model flexible targets as soft constraints**: Add a non-negative slack variable (`lb: 0`) penalized in the objective for preferences like safety stock or day-off requests. Reserve hard constraints for physical or legal invariants.
|