@ohtaman/washi 0.8.0 → 0.8.2
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.md +32 -34
- 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 -22
- package/skills/washi/SKILL.md +43 -22
- package/README.ja.md +0 -248
- package/README.zh-CN.md +0 -248
- 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
package/skills/washi/SKILL.md
CHANGED
|
@@ -5,7 +5,7 @@ description: Formulate, inspect, solve, and verify mathematical optimization (LP
|
|
|
5
5
|
|
|
6
6
|
# WaSHI Modeling & Verification Skill
|
|
7
7
|
|
|
8
|
-
Use this skill when building, debugging, or verifying mathematical optimization (LP, MIP, convex QP, CP
|
|
8
|
+
Use this skill when building, debugging, or verifying mathematical optimization (LP, MIP, convex QP, CP) or satisfiability (SMT / SAT) models with `@ohtaman/washi`. For the full API reference and browser/bundler deployment rules, see [`docs/getting-started/ai-agents.md`](https://github.com/ohtaman/washi/blob/main/docs/getting-started/ai-agents.md) (available locally at `node_modules/@ohtaman/washi/docs/getting-started/ai-agents.md` in consumer projects or `docs/getting-started/ai-agents.md` in the repository).
|
|
9
9
|
|
|
10
10
|
---
|
|
11
11
|
|
|
@@ -15,15 +15,16 @@ Select the solver engine and execution method that match the problem class:
|
|
|
15
15
|
|
|
16
16
|
| Problem Class | Recommended Solver | Setup & Import | Execution Method |
|
|
17
17
|
| :--- | :--- | :--- | :--- |
|
|
18
|
-
| **LP / MIP / Convex QP** (
|
|
19
|
-
| **CP/LCG Bounded Integer, Scheduling & Global Constraints** (`distinct`, `disjoint`, `cumulative`, `allowed`, `at`, `max`/`min`/`abs`, `!=`, `
|
|
20
|
-
| **SMT Propositional Logic** (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`) | **HiGHS** (auto 0-1 MIP), **Pumpkin** (bounded int), or **Z3** (native SMT incl. `Continuous`) |
|
|
21
|
-
| **Infeasibility / Conflict Diagnosis** (`conflicts` / `unsatCore`) | **HiGHS** (
|
|
22
|
-
| **LP / MIP with GLPK** (GPL-3.0; no QP or `
|
|
18
|
+
| **LP / MIP / Convex QP** (`m.indicator()` Big-M, `initialValue` warm starts; only HiGHS supports `QuadExpr` objectives) | **HiGHS** (default) | Bundled (`import { Model } from "@ohtaman/washi"`) | `await m.solve()` |
|
|
19
|
+
| **CP / Lazy Clause Generation (LCG) Bounded Integer, Scheduling & Global Constraints** (`distinct`, `disjoint`, `cumulative`, `allowed`, `at`, `max`/`min`/`abs`, `!=`, `initialValue` warm starts; integer bounds `[-(2^30 - 1), 2^30 - 1]`, throws on `Continuous`/fractional) | **Pumpkin** | Bundled (`import { Model } from "@ohtaman/washi"`, no extra import) | `await m.solve({ solver: "pumpkin" })` or `await m.check({ solver: "pumpkin" })` |
|
|
20
|
+
| **SMT Propositional Logic** (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`) | **HiGHS** (auto 0-1 MIP), **Pumpkin** (bounded int), or **Z3** (native SMT incl. `Continuous`) | Bundled for HiGHS & Pumpkin; `npm install z3-solver` + `import "@ohtaman/washi/solvers/z3"` for Z3 | `await m.solve()` or `await m.check()` |
|
|
21
|
+
| **Infeasibility / Conflict Diagnosis** (`conflicts` / `unsatCore`) | **HiGHS** (relaxation `conflicts`), **Pumpkin** (bounded int/bool `unsatCore`), or **Z3** (`unsatCore`) | Bundled for HiGHS & Pumpkin; `import "@ohtaman/washi/solvers/z3"` for Z3 | `await m.check()` |
|
|
22
|
+
| **LP / MIP with GLPK** (GPL-3.0; no QP, `initialValue`, or `useWorker: true`) | **GLPK** plugin | `npm install glpk.js` + `import "@ohtaman/washi/solvers/glpk"` | `await m.solve({ solver: "glpk" })` |
|
|
23
23
|
|
|
24
24
|
- **Browser runtime notes**:
|
|
25
|
-
- HiGHS
|
|
26
|
-
-
|
|
25
|
+
- **HiGHS** and **Pumpkin** load bundled `.wasm` and Worker assets relative to the bundle (no external CDN fallback; `useWorker: false` by default on opaque origins such as `file://`).
|
|
26
|
+
- **HiGHS**, **Pumpkin**, and **GLPK** all run without `COOP`/`COEP` headers (**GLPK** is an optional peer dependency that rejects `useWorker: true`).
|
|
27
|
+
- **Z3** uses `SharedArrayBuffer` pthreads and requires `window.isSecureContext === true` and `window.crossOriginIsolated === true` (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`).
|
|
27
28
|
|
|
28
29
|
---
|
|
29
30
|
|
|
@@ -36,15 +37,18 @@ Select the solver engine and execution method that match the problem class:
|
|
|
36
37
|
- Provide finite `lb` and `ub` bounds whenever known—especially on variables used in `m.indicator()` so WaSHI can automatically derive a tight Big-M when `M` is omitted.
|
|
37
38
|
2. **Build expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)**:
|
|
38
39
|
- Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${y} - 10` ``, `` expr`dot(${profit}, ${qty}) - 20 * ${lineOpen}` ``
|
|
39
|
-
- Piecewise-linear &
|
|
40
|
-
-
|
|
40
|
+
- Piecewise-linear & element lookup: `abs(...)`, `max(...)`, `min(...)`, and 0-based `at(array, index)` work standalone or inside `expr` (including element-wise containers such as `` expr`sum(abs(${w} - ${target}))` `` and `` expr`max(abs(${pred} - ${actual}))` ``).
|
|
41
|
+
- Piecewise lowering: Convex directions (`minimize`/`<=` on `max`/`abs`, `maximize`/`>=` on `min`) lower to pure LP epigraphs with zero binaries on HiGHS/GLPK. Non-convex or equality contexts require finite bounds in MIP, and map natively to Pumpkin (`maximum`/`minimum`/`absolute`/`element`) and Z3 (`If`).
|
|
42
|
+
- Quadratic expression (`QuadExpr`, **objectives only**): `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${xVec} - ${target})^2)` `` (purely continuous models on HiGHS; `Pumpkin`, `Z3`, and `GLPK` throw, and MIQP with integer/binary/boolean variables is not supported).
|
|
41
43
|
- Constraint (`Constraint`): `` expr`${x} + 2 * ${y} <= 40` ``, `` expr`sum(${qty}) <= 100` `` (supports `<=`, `>=`, `==`, `=`, plus discrete integer-only `<`, `>`, `!=` and `.lt()`, `.gt()`, `.ne()`).
|
|
42
|
-
- Vector & Record aggregations: `sum(containerOrItems, mapper?)`
|
|
43
|
-
- CP global constraints &
|
|
44
|
+
- Vector & Record aggregations: `sum(containerOrItems, mapper?)` accepts 1D/2D `Array`, `Iterable`, and `Record` directly (no `Object.values()` needed), and `expr` supports element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`). `dot(a, b)` computes 1D inner products or 2D Frobenius inner products.
|
|
45
|
+
- CP global constraints & logic: `distinct(...)`, `disjoint(tasks)`, `cumulative(tasks, capacity)`, and `allowed(vars, tuples)` return composable `BoolExpr`s alongside `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, and `xor(a, b)`.
|
|
46
|
+
- Backend lowering: Z3 and Pumpkin solve global/logical constraints natively, while HiGHS/GLPK auto-linearize them into MIP (`cumulative` enforces a MIP horizon memory guard above 5,000 span or 25,000 pulse variables and recommends `{ solver: "pumpkin" }`).
|
|
44
47
|
3. **Register objective and named constraints**:
|
|
45
48
|
- Constructing an `expr` or `.le()` / `.ge()` / `.eq()` / `.lt()` / `.gt()` / `.ne()` object does **not** attach it to the model.
|
|
46
49
|
- Register the objective with `m.objective(maximize(e))` or `m.objective(minimize(e))`.
|
|
47
|
-
- Register every constraint with a descriptive name
|
|
50
|
+
- Named constraints: Register every constraint with a descriptive name via `const limit = m.constraint(c, "resource_limit")` (returns the registered `Constraint` / `BoolExpr`, or an array for batch inputs). Names are essential for LP inspection and conflict diagnosis (`conflicts` / `unsatCore`).
|
|
51
|
+
- Indicator constraints: Register conditional constraints via `m.indicator(binVar, c, { activeValue: 1, name: "cap_when_open" })`. When `options.M` is omitted, HiGHS/GLPK and `toLpString()` derive a tight Big-M from finite bounds, while Pumpkin lowers natively via `implied_by` and Z3 via `ctx.Implies`.
|
|
48
52
|
|
|
49
53
|
---
|
|
50
54
|
|
|
@@ -52,7 +56,9 @@ Select the solver engine and execution method that match the problem class:
|
|
|
52
56
|
|
|
53
57
|
Before solving or when debugging formulation bugs:
|
|
54
58
|
|
|
55
|
-
-
|
|
59
|
+
- **Integrity check & LP export**: `m.toLpString()` validates model integrity (variable ownership across `Model` instances, `lb <= ub`, finite `initialValue` within bounds/integrality tolerance `1e-6`, and finite coefficients) and exports the numeric LP / MIP / QP formulation in CPLEX LP format (`Maximize` / `Minimize`, `Subject To`, `Bounds`, `General`, `Binary`, `End`).
|
|
60
|
+
- **What to check**: Inspect the exported text to confirm objective sense, signs, coefficients, and right-hand sides match the mathematical specification.
|
|
61
|
+
- **Scope caveat**: Propositional `BoolVar`s and logical/CP constraints (`BoolExpr`) are omitted from CPLEX LP output.
|
|
56
62
|
|
|
57
63
|
---
|
|
58
64
|
|
|
@@ -66,8 +72,9 @@ Never report a model solution as final without executing the verification step:
|
|
|
66
72
|
- If `report.valid === false`, inspect `report.violations`, `report.missingVariables`, `report.uncheckedConstraints`, and `report.maxViolation`.
|
|
67
73
|
- Note: `m.verify()` independently checks variable finiteness, variable bounds (`lb`/`ub`), integrality (`Integer`, `Binary`, `BoolVar`), linear constraint residuals, and logical constraints. It does **not** recompute `m.objectiveValue` or verify natural-language problem coverage.
|
|
68
74
|
2. **When a model is infeasible (`"Infeasible"` or `"Unsat"`)**:
|
|
69
|
-
- Run `const res = await m.check()`
|
|
70
|
-
- When `res.status === "Unsat"`, inspect `res.conflicts` (also stored on `m.conflicts`). On
|
|
75
|
+
- Run `const res = await m.check()` for built-in HiGHS diagnosis (single-solve elastic slack relaxation), `await m.check({ solver: "pumpkin" })` for bounded integer/boolean `unsatCore`, or `await m.check({ solver: "z3" })` for exact SMT `unsatCore` including `Continuous`/fractional constraints.
|
|
76
|
+
- When `res.status === "Unsat"`, inspect `res.conflicts` (also stored on `m.conflicts`). On Z3 and Pumpkin, both `res.unsatCore` and `res.conflicts` report a contradictory subset of constraints.
|
|
77
|
+
- On HiGHS, `res.conflicts` lists constraints whose relaxation restores feasibility, and `res.unsatCore` is intentionally `undefined` because an elastic relaxation repair set is not an unsatisfiable core proof.
|
|
71
78
|
- Because Z3 and Pumpkin assert variable bounds (`lb`/`ub`) and binary `{0, 1}` domains directly while tracking named constraints, `res.conflicts` returns a subset of registered constraint names that conflicts *together with the model's fixed variable bounds/domains* (not guaranteed minimal).
|
|
72
79
|
|
|
73
80
|
---
|
|
@@ -187,11 +194,10 @@ export async function diagnoseAndVerifyWithZ3() {
|
|
|
187
194
|
}
|
|
188
195
|
```
|
|
189
196
|
|
|
190
|
-
### Recipe 4: Pumpkin CP Scheduling (`disjoint`, `distinct`) &
|
|
197
|
+
### Recipe 4: Pumpkin CP Scheduling (`disjoint`, `distinct`) & `unsatCore` Verification
|
|
191
198
|
|
|
192
199
|
```ts
|
|
193
200
|
import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
|
|
194
|
-
import "@ohtaman/washi/solvers/pumpkin";
|
|
195
201
|
|
|
196
202
|
export async function solveAndDiagnoseWithPumpkin() {
|
|
197
203
|
// Part A: Bounded-integer CP scheduling with native global propagators
|
|
@@ -215,7 +221,7 @@ export async function solveAndDiagnoseWithPumpkin() {
|
|
|
215
221
|
const status = await cpModel.solve();
|
|
216
222
|
const report = cpModel.verify();
|
|
217
223
|
|
|
218
|
-
// Part B:
|
|
224
|
+
// Part B: Bounded-integer & boolean unsatCore diagnosis
|
|
219
225
|
const unsatModel = new Model("PolicyConflict", { solver: "pumpkin" });
|
|
220
226
|
const vip = unsatModel.bool("vip");
|
|
221
227
|
const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
|
|
@@ -243,11 +249,26 @@ export async function solveAndDiagnoseWithPumpkin() {
|
|
|
243
249
|
|
|
244
250
|
## 6. Guardrails & Common Pitfalls
|
|
245
251
|
|
|
246
|
-
- **No quadratic constraints or MIQP**: Quadratic terms (`${x}^2`, `${x} * ${y}`) are only valid in `m.objective(...)` (using them in `m.constraint(...)` throws `"Quadratic constraints are not supported"`), and
|
|
252
|
+
- **No quadratic constraints or MIQP**: Quadratic terms (`${x}^2`, `${x} * ${y}`) are only valid in `m.objective(...)` (using them in `m.constraint(...)` throws `"Quadratic constraints are not supported"`). Only HiGHS supports `QuadExpr` objectives (`Pumpkin`, `Z3`, and `GLPK` throw), and HiGHS requires Convex QP models to contain only continuous variables (`m.continuous`).
|
|
247
253
|
- **Do not confuse `LinExpr` and `Constraint`**: `m.objective(maximize(...))` requires a `LinExpr`, `QuadExpr`, `Var`, or `number` (never a `Constraint`). `m.constraint(...)` requires a `Constraint` (with `<=`, `>=`, `==`, `=`, or integer-only `<`, `>`, `!=`) or `BoolExpr` (`distinct`, `disjoint`, `cumulative`, `allowed`, `and`, `or`, `not`, `implies`, `xor`), never a bare `LinExpr`.
|
|
248
254
|
- **Do not mutate during async solve/check**: Modifying variables, bounds, constraints, or the objective while `await m.solve()` or `await m.check()` is pending invalidates the in-flight run and rejects the promise.
|
|
249
|
-
- **Do not use retired aliases**: Always use `expr` (not `c`), `m.constraint(...)` (not `m.constrain` or `m.add`), `m.objective(maximize(...))` / `m.objective()` (not `m.maximize`, `m.setObjective`, or `m.objectiveExpr`), `await m.solve()` (not `m.optimize`), `m.verify()` (not `m.validateSolution()`), `m.column(...)` (not `m.addColumn(...)`), `.le()` / `.ge()` / `.eq()` / `.lt()` / `.gt()` / `.ne()` (not `.lessThanOrEqual()`), `.value` (not `m.getValues(...)` or `.getValue()`), `m.variables` / `m.constraints` as `ReadonlyMap` with `.get(...)` / `.size` (not `m.vars`, `m.constrs`, `m.boolVars`, `m.logicalConstraints`, `m.numVars`, `m.numConstrs`, or `get*ByName()`), and `relativeGap` / `absoluteGap` (not `relGap` / `mipGap` / `absGap`). Also never call retired `m.validateIntegrity()` (integrity validation runs automatically inside `solve()`, `check()`, and `toLpString()`).
|
|
250
255
|
- **Practical OR formulation guardrails**:
|
|
251
256
|
- **Prefer inequalities (`>=` / `<=`) over `==`** for demand coverage and capacity limits when costs are non-negative; reserve `==` for flow conservation or normalization identities.
|
|
252
|
-
- **Provide finite `lb` and `ub` bounds** on variables inside `m.indicator(...)` and omit `M
|
|
257
|
+
- **Provide finite `lb` and `ub` bounds** on variables inside `m.indicator(...)` and omit `M`: WaSHI derives a tight Big-M from finite bounds and **throws an error** if any required bound is infinite.
|
|
253
258
|
- **Use soft constraints (non-negative slack variables)** with tiered objective penalties for non-rigid business targets (preferred staffing, safety stock, day-off requests) so minor data contention produces a prioritized trade-off rather than `"Infeasible"`.
|
|
259
|
+
|
|
260
|
+
### Retired Aliases (Do Not Use)
|
|
261
|
+
|
|
262
|
+
| Use | Avoid (Retired) |
|
|
263
|
+
| :--- | :--- |
|
|
264
|
+
| `expr` | `c` |
|
|
265
|
+
| `m.constraint(...)` | `m.constrain`, `m.add` |
|
|
266
|
+
| `m.objective(maximize(...))` / `m.objective()` | `m.maximize`, `m.setObjective`, `m.objectiveExpr` |
|
|
267
|
+
| `await m.solve()` | `m.optimize` |
|
|
268
|
+
| `m.verify()` | `m.validateSolution()` |
|
|
269
|
+
| `m.column(...)` | `m.addColumn(...)` |
|
|
270
|
+
| `.le()` / `.ge()` / `.eq()` / `.lt()` / `.gt()` / `.ne()` | `.lessThanOrEqual()` |
|
|
271
|
+
| `.value` | `m.getValues(...)`, `.getValue()` |
|
|
272
|
+
| `m.variables` / `m.constraints` (`ReadonlyMap` with `.get(...)` / `.size`) | `m.vars`, `m.constrs`, `m.boolVars`, `m.logicalConstraints`, `m.numVars`, `m.numConstrs`, `get*ByName()` |
|
|
273
|
+
| `relativeGap` / `absoluteGap` | `relGap`, `mipGap`, `absGap` |
|
|
274
|
+
| Automatic validation in `solve()`, `check()`, `toLpString()` | `m.validateIntegrity()` |
|
package/README.ja.md
DELETED
|
@@ -1,248 +0,0 @@
|
|
|
1
|
-
<div align="center">
|
|
2
|
-
<picture>
|
|
3
|
-
<source media="(prefers-color-scheme: dark)" srcset="./assets/washi-header-dark.png">
|
|
4
|
-
<source media="(prefers-color-scheme: light)" srcset="./assets/washi-header-light.png">
|
|
5
|
-
<img alt="WaSHI - TypeScript 数理最適化モデラー" src="./assets/washi-header-light.png" width="420" />
|
|
6
|
-
</picture>
|
|
7
|
-
<p><strong>TypeScript 数理最適化モデラー</strong></p>
|
|
8
|
-
<p>
|
|
9
|
-
<em>線形計画 (LP) • 混合整数計画 (MIP) • 凸二次計画 (QP) • 制約プログラミング (CP) • SMT論理制約 & 矛盾診断</em>
|
|
10
|
-
</p>
|
|
11
|
-
<p>
|
|
12
|
-
<a href="./README.md">English</a> •
|
|
13
|
-
<a href="./README.ja.md">日本語</a> •
|
|
14
|
-
<a href="./README.zh-CN.md">简体中文</a>
|
|
15
|
-
</p>
|
|
16
|
-
<p>
|
|
17
|
-
<a href="https://www.npmjs.com/package/@ohtaman/washi"><img src="https://img.shields.io/npm/v/@ohtaman/washi?color=crimson&label=npm" alt="npm version" /></a>
|
|
18
|
-
<a href="https://github.com/ohtaman/washi/actions/workflows/distribution.yml"><img src="https://github.com/ohtaman/washi/actions/workflows/distribution.yml/badge.svg" alt="CI Status" /></a>
|
|
19
|
-
<a href="https://washi.ohtaman.dev/ja/"><img src="https://img.shields.io/badge/docs-online-blue" alt="docs" /></a>
|
|
20
|
-
<a href="https://washi.ohtaman.dev/demo/"><img src="https://img.shields.io/badge/demo-playground-brightgreen" alt="live demo" /></a>
|
|
21
|
-
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="license" /></a>
|
|
22
|
-
</p>
|
|
23
|
-
</div>
|
|
24
|
-
|
|
25
|
-
---
|
|
26
|
-
|
|
27
|
-
**WaSHI**(WebAssembly-backed, Solver-independent, High-level modeling Interface)は、Python の **PuLP** に着想を得た、数理最適化と制約プログラミングのための TypeScript / JavaScript 向け代数モデラーです。変数・目的関数・制約をアプリケーションコードで記述し、Node.js やブラウザ上で標準同梱の **HiGHS**(デフォルト)・**Pumpkin**(`@ohtaman/washi/solvers/pumpkin`)、あるいはオプションの **Z3**・**GLPK** を使ってそのまま求解できます。
|
|
28
|
-
|
|
29
|
-
## ✨ 主な特徴
|
|
30
|
-
|
|
31
|
-
- **直感的な数式記述**: `` expr`30 * ${x} + 50 * ${y} <= 40` `` や総和・内積(`sum`, `dot`)で数式と制約を簡潔に書けます。
|
|
32
|
-
- **Node.js・ブラウザで完結**: WebAssembly ベースのため、Python サーバーや C/C++ のネイティブビルドなしで動作します。
|
|
33
|
-
- **ソルバー非依存**: 追加依存なしの同梱 **HiGHS**(LP/MIP/QP)・**Pumpkin**(CP/LCG)に加え、オプションの **Z3**・**GLPK** や独自ソルバーへ切り替えられます。
|
|
34
|
-
- **充足判定と矛盾診断**: 論理・数値制約の充足可能性判定や、実行不能(Infeasible)になった原因制約の特定に対応しています。
|
|
35
|
-
- **大規模問題の分解法**: 列生成法やベンダーズ分解などの分解アルゴリズムをサポートしています。
|
|
36
|
-
|
|
37
|
-
## 📚 ドキュメント & リンク
|
|
38
|
-
|
|
39
|
-
- **[ドキュメント](https://washi.ohtaman.dev/ja/)**: モデリングガイド・ソルバー仕様・環境別の導入手順
|
|
40
|
-
- **[ショーケース](https://washi.ohtaman.dev/ja/showcase/) · [ブラウザデモ](https://washi.ohtaman.dev/demo/) · [数理最適化N本ノック](https://washi.ohtaman.dev/exercises/?lang=ja)**: ブラウザ上で動くデモアプリ集・プレイグラウンド・N本ノックを体験できます
|
|
41
|
-
- **[サンプル集](https://washi.ohtaman.dev/ja/examples/)**: 課題別の実践レシピと実行可能なサンプルコード([`examples/`](examples/README.md))
|
|
42
|
-
- **[Agent Skill (`SKILL.md`)](skills/washi/SKILL.md) · [`llms.txt`](https://washi.ohtaman.dev/llms.txt) / [`llms-full.txt`](https://washi.ohtaman.dev/llms-full.txt)**: AI コーディングエージェント向けのスキル定義・機械可読ドキュメント
|
|
43
|
-
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
## 📦 インストール & クイックスタート
|
|
47
|
-
|
|
48
|
-
```bash
|
|
49
|
-
npm install @ohtaman/washi
|
|
50
|
-
# HiGHS (LP/MIP/QP) と Pumpkin (CP/LCG, @ohtaman/washi/solvers/pumpkin) は追加依存なしで同梱されています
|
|
51
|
-
|
|
52
|
-
# オプションの peer-dependency ソルバープラグイン
|
|
53
|
-
npm install z3-solver # SMT 論理制約・実数を含む厳密 Unsat Core 診断を使う場合
|
|
54
|
-
npm install glpk.js # GLPK ソルバーを使う場合 (GPL-3.0)
|
|
55
|
-
|
|
56
|
-
# AI コーディングエージェント用スキル (Claude Code, Cursor, Codex 等)
|
|
57
|
-
npx skills add ohtaman/washi
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
```ts
|
|
61
|
-
import { Model, expr, maximize } from "@ohtaman/washi";
|
|
62
|
-
|
|
63
|
-
const m = new Model("木工製品の利益最大化");
|
|
64
|
-
const x = m.integer("机", { lb: 0 });
|
|
65
|
-
const y = m.integer("椅子", { lb: 0 });
|
|
66
|
-
|
|
67
|
-
m.objective(maximize(expr`30 * ${x} + 50 * ${y}`));
|
|
68
|
-
m.constraint(expr`${x} + 2 * ${y} <= 40`, "木材上限");
|
|
69
|
-
m.constraint(expr`2 * ${x} + ${y} <= 50`, "労働力上限");
|
|
70
|
-
|
|
71
|
-
await m.solve();
|
|
72
|
-
console.log(`生産量: x=${x.value}, y=${y.value} (最大利益: $${m.objectiveValue})`);
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
---
|
|
76
|
-
|
|
77
|
-
## ⚙️ 対応ソルバー
|
|
78
|
-
|
|
79
|
-
| ソルバー | ライセンス | 対応クラス | 主な用途 | 導入方法 |
|
|
80
|
-
| :--- | :--- | :--- | :--- | :--- |
|
|
81
|
-
| **[HiGHS](https://github.com/ERGO-Code/HiGHS)** | MIT | LP, MIP, 凸QP | 数値最適化・エラスティック矛盾修復 | 標準搭載(追加依存なし) |
|
|
82
|
-
| **[Pumpkin](https://github.com/ConSol-Lab/Pumpkin)** | MIT | CP, LCG, 論理, 有界整数 | スケジューリング・COOP/COEP不要の `unsatCore` | `import "@ohtaman/washi/solvers/pumpkin"`(WASM同梱・追加依存なし) |
|
|
83
|
-
| **[Z3](https://github.com/Z3Prover/z3)** | MIT | SMT, SAT, 論理, MIP | 論理ルール・充足判定・厳密な `unsatCore` | `npm install z3-solver` + `import "@ohtaman/washi/solvers/z3"` |
|
|
84
|
-
| **[GLPK](https://www.gnu.org/software/glpk/)** | GPL-3.0 | LP, MIP | 線形・混合整数最適化 | `npm install glpk.js` + `import "@ohtaman/washi/solvers/glpk"` |
|
|
85
|
-
| **Mock** | MIT | — | テスト用の決定論的な模擬応答 | 標準搭載 (`MockSolver`) |
|
|
86
|
-
|
|
87
|
-
プラグインを import した上で、`new Model(...)`・`m.solve(...)`・`m.check(...)` に `{ solver: "pumpkin" }`・`{ solver: "z3" }`・`{ solver: "glpk" }` を渡して切り替えます。
|
|
88
|
-
|
|
89
|
-
---
|
|
90
|
-
|
|
91
|
-
## 🚀 基本的な使い方
|
|
92
|
-
|
|
93
|
-
### 1. 総和・内積(`sum` / `dot`)と条件付き制約
|
|
94
|
-
|
|
95
|
-
`dot` / `sum` による線形式の記述と、`m.indicator()` による条件付き制約:
|
|
96
|
-
|
|
97
|
-
```ts
|
|
98
|
-
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
99
|
-
|
|
100
|
-
const m = new Model("TransportPlanning");
|
|
101
|
-
const factories = ["Tokyo", "Osaka"];
|
|
102
|
-
const stores = ["StoreA", "StoreB"];
|
|
103
|
-
const costs = {
|
|
104
|
-
Tokyo: { StoreA: 4, StoreB: 7 },
|
|
105
|
-
Osaka: { StoreA: 8, StoreB: 3 },
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
const open = m.binary(factories);
|
|
109
|
-
const ship = m.continuous(factories, stores, { lb: 0, ub: 500 });
|
|
110
|
-
|
|
111
|
-
// 東京工場が閉鎖 (open["Tokyo"] == 0) なら東京工場からの総輸送量は 0
|
|
112
|
-
m.indicator(open["Tokyo"], expr`sum(${ship["Tokyo"]}) <= 0`, { activeValue: 0 });
|
|
113
|
-
m.constraint(expr`${ship["Tokyo"]["StoreA"]} + ${ship["Osaka"]["StoreA"]} >= 100`, "demand_A");
|
|
114
|
-
|
|
115
|
-
m.objective(minimize(expr`dot(${costs}, ${ship})`));
|
|
116
|
-
await m.solve();
|
|
117
|
-
|
|
118
|
-
console.log("Tokyo -> StoreA:", ship["Tokyo"]["StoreA"].value);
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
### 2. 凸二次計画 (QP)
|
|
122
|
-
|
|
123
|
-
線形制約のもとで二次の目的関数を最小化:
|
|
124
|
-
|
|
125
|
-
```ts
|
|
126
|
-
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
127
|
-
|
|
128
|
-
const m = new Model("PortfolioQP");
|
|
129
|
-
const x = m.continuous("tech", { lb: 0, ub: 1 });
|
|
130
|
-
const y = m.continuous("bonds", { lb: 0, ub: 1 });
|
|
131
|
-
|
|
132
|
-
m.constraint(expr`${x} + ${y} == 1`, "budget");
|
|
133
|
-
m.constraint(expr`0.14 * ${x} + 0.04 * ${y} >= 0.08`, "min_return");
|
|
134
|
-
m.objective(minimize(expr`0.04 * ${x}^2 + 0.005 * ${y}^2`));
|
|
135
|
-
|
|
136
|
-
await m.solve();
|
|
137
|
-
console.log(`Tech: ${x.value?.toFixed(2)}, Bonds: ${y.value?.toFixed(2)}`);
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
### 3. 制約プログラミング & スケジューリング (Pumpkin)
|
|
141
|
-
|
|
142
|
-
同梱の **Pumpkin**(`@ohtaman/washi/solvers/pumpkin`)を使うと、追加依存なしで有界整数スケジューリングや CP グローバル制約(`disjoint`, `distinct`, `cumulative`, `allowed`)を求解できます:
|
|
143
|
-
|
|
144
|
-
```ts
|
|
145
|
-
import { Model, expr, disjoint, distinct, minimize } from "@ohtaman/washi";
|
|
146
|
-
import "@ohtaman/washi/solvers/pumpkin";
|
|
147
|
-
|
|
148
|
-
const m = new Model("WorkshopCP", { solver: "pumpkin" });
|
|
149
|
-
const start = m.integer(["cut", "weld", "paint"] as const, { lb: 0, ub: 20, prefix: "start" });
|
|
150
|
-
const bench = m.integer(["cut", "weld", "paint"] as const, { lb: 1, ub: 3, prefix: "bench" });
|
|
151
|
-
|
|
152
|
-
m.constraint(
|
|
153
|
-
disjoint([
|
|
154
|
-
{ start: start.cut, duration: 4 },
|
|
155
|
-
{ start: start.weld, duration: 3 },
|
|
156
|
-
{ start: start.paint, duration: 2 },
|
|
157
|
-
]),
|
|
158
|
-
"single_line"
|
|
159
|
-
);
|
|
160
|
-
m.constraint(expr`${start.cut} + 4 <= ${start.weld}`, "cut_before_weld");
|
|
161
|
-
m.constraint(expr`${start.weld} + 3 <= ${start.paint}`, "weld_before_paint");
|
|
162
|
-
m.constraint(distinct(bench), "unique_benches");
|
|
163
|
-
|
|
164
|
-
m.objective(minimize(expr`${start.paint} + 2`));
|
|
165
|
-
await m.solve();
|
|
166
|
-
console.log(`Makespan: ${m.objectiveValue}h (paint starts at ${start.paint.value}h)`);
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
### 4. 論理ルール & 矛盾診断 (`m.check`)
|
|
170
|
-
|
|
171
|
-
論理条件(`m.bool`, `implies`)を含むモデルの充足可能性を判定し、矛盾時の原因制約を特定します:
|
|
172
|
-
- **HiGHS(標準)**: 緩和すれば実行可能になる**修復集合**(`res.conflicts`)を特定します。
|
|
173
|
-
- **Pumpkin(同梱)**: 有界整数・真偽値モデルに対して、**COOP/COEP ヘッダー不要**でスケール不変な**充足不能コア**(`res.unsatCore` / `res.conflicts`)を抽出します。
|
|
174
|
-
- **Z3**: 連続変数・実数演算を含む厳密な SMT **充足不能コア**(`res.unsatCore` / `res.conflicts`)を抽出します。
|
|
175
|
-
|
|
176
|
-
```ts
|
|
177
|
-
import { Model, implies, expr } from "@ohtaman/washi";
|
|
178
|
-
// import "@ohtaman/washi/solvers/pumpkin"; // COOP/COEP 不要の unsatCore(有界整数・真偽値)
|
|
179
|
-
// import "@ohtaman/washi/solvers/z3"; // Continuous 変数を含む厳密 SMT unsatCore
|
|
180
|
-
|
|
181
|
-
const m = new Model("StaffingRules");
|
|
182
|
-
const engineers = m.integer("engineers", { lb: 0, ub: 20 });
|
|
183
|
-
const budget = m.continuous("budget", { lb: 0, ub: 100000 });
|
|
184
|
-
const rush = m.bool("rush");
|
|
185
|
-
|
|
186
|
-
m.constraint(expr`8000 * ${engineers} <= ${budget}`, "budget_limit");
|
|
187
|
-
m.constraint(rush, "rush_required");
|
|
188
|
-
m.constraint(implies(rush, expr`${engineers} >= 8`), "rush_staffing");
|
|
189
|
-
m.constraint(expr`${budget} <= 50000`, "budget_cap"); // 矛盾: 8人 * $8,000 > $50,000
|
|
190
|
-
m.constraint(expr`${engineers} >= 1`, "min_staff"); // 無関係な制約
|
|
191
|
-
|
|
192
|
-
const res = await m.check(); // または await m.check({ solver: "z3" })
|
|
193
|
-
console.log(res.status); // "Unsat"
|
|
194
|
-
console.log(res.conflicts); // HiGHS: ["rush_required"]
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
---
|
|
198
|
-
|
|
199
|
-
## 🌐 ブラウザ & Web Worker での利用方法
|
|
200
|
-
|
|
201
|
-
- **バンドラー (Vite / webpack 5)**: `import { Model } from "@ohtaman/washi"` でそのまま動作します。**HiGHS** と **Pumpkin** はいずれもブラウザで標準で専用 Web Worker 上で実行され(メインスレッドで実行する場合は `{ useWorker: false }` を指定)、**COOP/COEP ヘッダーは不要**です。
|
|
202
|
-
- **単体 ESM / script タグ / CDN**: `dist/browser/` 一式(`highs.wasm`、`solvers/pumpkin.wasm` や Worker を含む)を配信するか、CDN の URL を指定して読み込みます。
|
|
203
|
-
|
|
204
|
-
```html
|
|
205
|
-
<!-- ブラウザ ESM -->
|
|
206
|
-
<script type="module">
|
|
207
|
-
import { Model } from "./washi/washi.js";
|
|
208
|
-
// 同梱・オプションプラグイン:
|
|
209
|
-
// import "./washi/solvers/pumpkin.js"; // 同梱 CP/LCG (COOP/COEP 不要)
|
|
210
|
-
// import "./washi/solvers/glpk.js"; // オプション GLPK プラグイン
|
|
211
|
-
// import "./washi/solvers/z3.js"; // オプション Z3 プラグイン (COOP/COEP 必要)
|
|
212
|
-
const m = new Model();
|
|
213
|
-
await m.solve();
|
|
214
|
-
</script>
|
|
215
|
-
|
|
216
|
-
<!-- script タグ / CodePen (グローバル Washi を公開) -->
|
|
217
|
-
<script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.min.js"></script>
|
|
218
|
-
<!-- オプションプラグインスクリプト (window.Washi に自動登録): -->
|
|
219
|
-
<!-- <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin.min.js"></script> -->
|
|
220
|
-
```
|
|
221
|
-
|
|
222
|
-
> [!NOTE]
|
|
223
|
-
> **ブラウザでの Z3 利用**: Z3 の WebAssembly は `SharedArrayBuffer` を使用するため、Cross-Origin Isolation(`COOP: same-origin` / `COEP: require-corp`)が必要です。詳細は [Cross-Origin Isolation 設定](docs/ja/getting-started/cross-origin.md) および [`examples/distribution/`](examples/distribution/README.md) を参照してください。**HiGHS**、**Pumpkin**(有界整数・真偽値に対する `unsatCore` を含む)、および **GLPK** は Cross-Origin Isolation ヘッダーなしで動作します。
|
|
224
|
-
|
|
225
|
-
---
|
|
226
|
-
|
|
227
|
-
## 🤝 コントリビューション・開発
|
|
228
|
-
|
|
229
|
-
ローカル開発、テスト・ベンチマークの実行、WebAssembly アセットの再ビルド、およびリリース手順については [CONTRIBUTING.md](./CONTRIBUTING.md) を参照してください。
|
|
230
|
-
|
|
231
|
-
---
|
|
232
|
-
|
|
233
|
-
## 🙏 謝辞
|
|
234
|
-
|
|
235
|
-
WaSHI は、数理最適化および自動推論分野の素晴らしいオープンソースソフトウェアの上に成り立っています:
|
|
236
|
-
|
|
237
|
-
- **[HiGHS](https://highs.dev/)**([`ERGO-Code/HiGHS`](https://github.com/ERGO-Code/HiGHS))— エディンバラ大学の Julian Hall 氏、Qi Huangfu 氏、Ivet Galabova 氏、Leona Gottwald 氏、Michael Feldmeier 氏をはじめとする開発チームによる高性能なオープンソース LP / MIP / 凸 QP ソルバーであり、WaSHI の標準エンジンを支えています(*Huangfu & Hall, Mathematical Programming Computation, 2018*, [DOI: 10.1007/s12532-017-0130-5](https://doi.org/10.1007/s12532-017-0130-5))。
|
|
238
|
-
- **[Pumpkin](https://github.com/ConSol-Lab/Pumpkin)** — デルフト工科大学 ConSol Lab により Rust で開発された LCG(Lazy Clause Generation)制約プログラミングソルバーであり、WaSHI の同梱 CP/LCG および COOP/COEP 不要な `unsatCore` エンジンを支えています。
|
|
239
|
-
- **[Z3 Theorem Prover](https://github.com/Z3Prover/z3)**([`z3-solver`](https://www.npmjs.com/package/z3-solver))— Microsoft Research により開発された SMT ソルバーであり、オプションの論理充足判定および `unsatCore` 矛盾診断プラグインを支えています。
|
|
240
|
-
- **[GLPK](https://www.gnu.org/software/glpk/) & [`glpk.js`](https://github.com/jvail/glpk.js)** — オプションの GPL-3.0 LP / MIP ソルバープラグインを支えています。
|
|
241
|
-
- **[PuLP](https://github.com/coin-or/pulp)** — WaSHI の直感的な代数モデリング API 設計に大きな着想を与えました。
|
|
242
|
-
|
|
243
|
-
---
|
|
244
|
-
|
|
245
|
-
## 📄 ライセンス
|
|
246
|
-
|
|
247
|
-
- **`@ohtaman/washi`**: [MIT ライセンス](./LICENSE)
|
|
248
|
-
- **同梱・外部ソルバー**: HiGHS (MIT)、Pumpkin (MIT)、Z3 (MIT)、GLPK (GPL-3.0)。詳細は [THIRD_PARTY_LICENSES.md](./THIRD_PARTY_LICENSES.md) を参照してください。
|