@ohtaman/washi 0.7.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.
Files changed (162) hide show
  1. package/README.ja.md +60 -23
  2. package/README.md +59 -22
  3. package/README.zh-CN.md +62 -25
  4. package/THIRD_PARTY_LICENSES.md +34 -1
  5. package/dist/browser/solvers/glpk.js +289 -238
  6. package/dist/browser/solvers/glpk.min.js +1 -1
  7. package/dist/browser/solvers/highs-__vite-browser-external-Dn-83hnF.js +7 -0
  8. package/dist/browser/solvers/highs-browser-runtime-0Bgq5ksG.js +2021 -0
  9. package/dist/browser/{loader-DewlSho8.js → solvers/highs-loader-BLY3wzDH.js} +190 -149
  10. package/dist/browser/solvers/highs-worker.js +54 -0
  11. package/dist/browser/solvers/highs.js +1414 -0
  12. package/dist/browser/solvers/highs.wasm +0 -0
  13. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  14. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  15. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  16. package/dist/browser/solvers/pumpkin.js +1777 -0
  17. package/dist/browser/solvers/pumpkin.wasm +0 -0
  18. package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
  19. package/dist/browser/solvers/z3.js +1600 -1335
  20. package/dist/browser/solvers/z3.min.js +2 -2
  21. package/dist/browser/washi.js +3313 -1699
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/solvers/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/solvers/glpk.js +174 -132
  25. package/dist/lib/solvers/highs-browser-runtime.js +2413 -0
  26. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  27. package/dist/lib/solvers/highs-runtime.js +16 -0
  28. package/dist/lib/solvers/highs-worker.js +54 -0
  29. package/dist/lib/solvers/highs.js +410 -0
  30. package/dist/lib/solvers/highs.wasm +0 -0
  31. package/dist/lib/{loader-BZUQNvh4.js → solvers/loader-CDpPXN_F.js} +138 -116
  32. package/dist/lib/solvers/loader-Ow74Fa1B.js +311 -0
  33. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  34. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  35. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  36. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  37. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  38. package/dist/lib/solvers/pumpkin.js +868 -0
  39. package/dist/lib/solvers/pumpkin.wasm +0 -0
  40. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  41. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  42. package/dist/lib/solvers/rolldown-runtime-DtPi1Y-2.js +13 -0
  43. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  44. package/dist/lib/solvers/z3.js +489 -307
  45. package/dist/lib/washi.js +3905 -1410
  46. package/dist/types/decomposition/benders.d.ts.map +1 -1
  47. package/dist/types/index.d.ts +4 -5
  48. package/dist/types/index.d.ts.map +1 -1
  49. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  50. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  51. package/dist/types/modeler/constraint.d.ts +40 -4
  52. package/dist/types/modeler/constraint.d.ts.map +1 -1
  53. package/dist/types/modeler/expression.d.ts +129 -2
  54. package/dist/types/modeler/expression.d.ts.map +1 -1
  55. package/dist/types/modeler/index.d.ts +4 -6
  56. package/dist/types/modeler/index.d.ts.map +1 -1
  57. package/dist/types/modeler/linearizer.d.ts +11 -2
  58. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  59. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  60. package/dist/types/modeler/model.d.ts +86 -126
  61. package/dist/types/modeler/model.d.ts.map +1 -1
  62. package/dist/types/modeler/parser.d.ts.map +1 -1
  63. package/dist/types/modeler/quad-expr.d.ts +8 -2
  64. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  65. package/dist/types/modeler/solution-validator.d.ts +12 -12
  66. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  67. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  68. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  69. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  70. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  72. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  73. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  74. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  75. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  76. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  77. package/dist/types/modeler/solvers/index.d.ts +2 -1
  78. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  79. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  80. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  81. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  82. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  83. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  84. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  85. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  86. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  87. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  88. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  89. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  90. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  91. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  92. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  93. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  94. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  95. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  96. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  97. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  98. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  99. package/dist/types/modeler/solvers/types.d.ts +7 -9
  100. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  101. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  102. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  103. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  104. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  105. package/dist/types/modeler/types.d.ts +12 -15
  106. package/dist/types/modeler/types.d.ts.map +1 -1
  107. package/dist/types/modeler/validation.d.ts +26 -2
  108. package/dist/types/modeler/validation.d.ts.map +1 -1
  109. package/dist/types/modeler/variable.d.ts +9 -5
  110. package/dist/types/modeler/variable.d.ts.map +1 -1
  111. package/docs/examples/diet-sensitivity.md +33 -14
  112. package/docs/examples/ecommerce-coupons.md +17 -9
  113. package/docs/examples/index.md +36 -27
  114. package/docs/examples/knapsack.md +11 -5
  115. package/docs/examples/portfolio-qp.md +21 -8
  116. package/docs/examples/production.md +10 -5
  117. package/docs/examples/project-scheduling.md +119 -0
  118. package/docs/examples/shift-scheduling.md +29 -18
  119. package/docs/examples/smt-security.md +27 -11
  120. package/docs/examples/transportation.md +23 -13
  121. package/docs/examples/traveling-salesperson.md +34 -22
  122. package/docs/examples/unsat-core.md +27 -14
  123. package/docs/examples/vehicle-routing.md +74 -28
  124. package/docs/getting-started/ai-agents.md +190 -82
  125. package/docs/getting-started/coding-agents.md +177 -0
  126. package/docs/getting-started/cross-origin.md +27 -14
  127. package/docs/getting-started/index.md +49 -43
  128. package/docs/getting-started/runtimes.md +94 -40
  129. package/docs/guide/constraint-programming.md +171 -0
  130. package/docs/guide/constraints.md +115 -33
  131. package/docs/guide/decomposition.md +118 -88
  132. package/docs/guide/expressions.md +106 -43
  133. package/docs/guide/formulation-tips.md +47 -28
  134. package/docs/guide/objectives.md +102 -75
  135. package/docs/guide/unsat-core.md +62 -50
  136. package/docs/guide/variables.md +81 -35
  137. package/docs/solvers/custom-solver.md +163 -122
  138. package/docs/solvers/glpk.md +58 -17
  139. package/docs/solvers/highs.md +124 -57
  140. package/docs/solvers/index.md +33 -20
  141. package/docs/solvers/pumpkin.md +171 -0
  142. package/docs/solvers/z3.md +63 -25
  143. package/llms-full.txt +2232 -932
  144. package/llms.txt +144 -91
  145. package/package.json +55 -19
  146. package/skills/washi/SKILL.md +107 -34
  147. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  148. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  149. package/dist/browser/highs-worker.js +0 -39
  150. package/dist/browser/highs.wasm +0 -0
  151. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  152. package/dist/lib/highs-browser-runtime.js +0 -2185
  153. package/dist/lib/highs-runtime.js +0 -2
  154. package/dist/lib/highs-worker.js +0 -39
  155. package/dist/lib/highs.wasm +0 -0
  156. package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
  157. package/docs/ja/getting-started/ai-agents.md +0 -280
  158. package/docs/zh/getting-started/ai-agents.md +0 -280
  159. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  160. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  161. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  162. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
@@ -1,28 +1,30 @@
1
- # Conflict Diagnosis (`unsatCore`) & Solution Validation
1
+ # Conflict Diagnosis (`unsatCore`), Validation & Debugging
2
2
 
3
- When building real-world optimization and configuration systems, two verification questions arise constantly:
4
- 1. **Why is my model infeasible?** Which specific business rules contradict each other?
5
- 2. **Does the solver's solution genuinely satisfy every constraint?** How do I verify tolerances, integrality, and formulations?
3
+ When a model has no feasible solution (`"Infeasible"`), or when you want to verify solver output before using it in production, WaSHI provides four diagnostic and debugging tools:
6
4
 
7
- WaSHI provides built-in tools for both: **conflict diagnosis** via built-in HiGHS elastic relaxation or Z3 Unsat Core (`m.check()`), **independent solution validation** (`m.validateSolution()`), **LP formulation export** (`m.toLpString()`), and **fast unit testing** (`MockSolver`).
5
+ - **Conflict diagnosis (`m.check()`)**: Pinpoints which named constraints cause infeasibility.
6
+ - **Solution verification (`m.verify()`)**: Independently checks variable bounds, integrality, and all constraints.
7
+ - **Formulation inspection (`m.toLpString()`)**: Exports CPLEX `.lp` text to inspect signs, coefficients, and names.
8
+ - **Deterministic testing (`MockSolver`)**: Returns fixed results in unit tests without loading WebAssembly.
8
9
 
9
10
  ---
10
11
 
11
- ## Conflict Diagnosis (`unsatCore` / `conflicts`)
12
+ ## Finding Conflicting Constraints (`m.check()`)
12
13
 
13
- When an optimization run (`m.solve()`) returns **`"Infeasible"`**, the status alone tells you that no solution satisfies every constraint—not *which* rules conflict with each other.
14
- By calling **`await m.check({ solver: "z3" })`**, WaSHI uses Z3's `assertAndTrack` mechanism to compute an **Unsatisfiable Core (`unsatCore`)**—a conflicting subset of named constraints that cannot be satisfied simultaneously:
14
+ When `m.solve()` returns `"Infeasible"`, it proves that no solution satisfies every rule, but does not tell you *which* rules clash.
15
+ To diagnose the cause, call `m.check()`.
16
+ A logical **Unsat Core** is a subset of named constraints that cannot hold simultaneously—even if every other named constraint in the model were removed (keeping variable bounds), those rules would still conflict.
17
+
18
+ Pass `{ solver: "pumpkin" }` for models with only bounded integer and Boolean variables, or `{ solver: "z3" }` for models with `Continuous` variables or non-integer coefficients/constants:
15
19
 
16
20
  ```typescript
17
21
  import { Model, expr } from "@ohtaman/washi";
18
- // Register the Z3 solver plugin
19
22
  import "@ohtaman/washi/solvers/z3";
20
23
 
21
24
  const m = new Model();
22
-
23
25
  const x = m.continuous("reserve", { lb: 0 });
24
26
 
25
- // Add named business requirements
27
+ // Register named constraints
26
28
  m.constraint(expr`${x} >= 100`, "minimum_regulatory_reserve");
27
29
  m.constraint(expr`${x} <= 50`, "budget_ceiling");
28
30
  m.constraint(expr`${x} >= 10`, "routine_operating_cost");
@@ -30,63 +32,70 @@ m.constraint(expr`${x} >= 10`, "routine_operating_cost");
30
32
  const result = await m.check({ solver: "z3" });
31
33
 
32
34
  if (result.status === "Unsat") {
33
- console.log("Contradictory constraints identified:");
34
- console.log(m.conflicts); // or result.conflicts / result.unsatCore / m.unsatCore
35
+ console.log("Conflicting constraints:", result.unsatCore); // also available via m.conflicts
35
36
  // Output: ["minimum_regulatory_reserve", "budget_ceiling"]
36
37
  }
37
38
  ```
38
39
 
39
- Notice that `routine_operating_cost` is **not** in the core, because only `minimum_regulatory_reserve` ($x \ge 100$) and `budget_ceiling` ($x \le 50$) directly contradict each other.
40
+ In this example, `routine_operating_cost` is excluded because only `minimum_regulatory_reserve` and `budget_ceiling` directly contradict each other.
40
41
 
41
42
  > [!IMPORTANT]
42
- > - **Use `m.check({ solver: "z3" })` for Unsat Core extraction**: `m.solve()` runs optimization (`Z3.Optimize`), whereas `m.check()` runs tracked satisfiability checking (`Z3.Solver.assertAndTrack`) and populates `result.conflicts` / `m.conflicts` (and alias `m.unsatCore`).
43
- > - **Name your constraints**: Variable bounds (`lb`, `ub`) act as background domain declarations. To include a bound or business rule in the reported `unsatCore` list, register it as a named constraint via `m.constraint(expr`...`, "rule_name")`.
43
+ > - **Use `m.check()` for diagnosis**: When a model is infeasible, `m.solve()` only returns `"Infeasible"` without identifying the conflicting rules. When `m.check()` returns `"Unsat"`, it populates `conflicts` on all solvers, plus `unsatCore` on Pumpkin and Z3 (`undefined` on HiGHS/GLPK).
44
+ > - **Name every rule you want diagnosed**: Variable `lb`/`ub` bounds are unnamed and never appear in `conflicts`. Register any bound you want diagnosed with ``m.constraint(expr`...`, "rule_name")``.
45
+
46
+ ### Choosing a Diagnosis Solver
44
47
 
45
- ### Workflow: Infeasibility Diagnosis with HiGHS or Z3
48
+ After `m.solve()` returns `"Infeasible"`, choose among three backends based on your variable types and scale sensitivity:
46
49
 
47
- Because WaSHI models are solver-independent, you can diagnose infeasibilities using either solver:
48
- 1. **Built-in HiGHS & GLPK (default)**: `await m.check()` uses a single-solve elastic slack formulation ($\min \sum s_i$) to identify which constraints required relaxation (`diag.conflicts`), requiring no extra dependencies.
49
- 2. **Z3 SMT Solver**: `await m.check({ solver: "z3" })` uses SMT tracking to extract an exact unsatisfiable core (`diag.unsatCore` / `diag.conflicts`).
50
+ | Criterion | Pumpkin (`m.check({ solver: "pumpkin" })`) | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()` / `{ solver: "glpk" }`) |
51
+ | :--- | :--- | :--- | :--- |
52
+ | **Best for** | Bounded integer & Boolean models | Models with `Continuous` or non-integer values | General LP / MIP models (HiGHS needs zero extra imports) |
53
+ | **Setup** | Bundled (no extra import) | Optional (`z3-solver` + `@ohtaman/washi/solvers/z3`) | Bundled (HiGHS, default) / optional (`glpk.js`) |
54
+ | **Browser headers** | None | Requires `COOP` / `COEP` headers | None |
55
+ | **Result fields** | `unsatCore` and `conflicts` | `unsatCore` and `conflicts` | `conflicts` only (`unsatCore` is `undefined`) |
56
+ | **What it returns** | Unsat Core (mutually incompatible rules) | Unsat Core (mutually incompatible rules) | Elastic-relaxation set (rules to relax to restore feasibility) |
57
+ | **Unit-scale sensitivity** | Scale-invariant | Scale-invariant | Scale-sensitive (prefers relaxing smaller-scale constraints) |
50
58
 
51
59
  ```typescript
52
- const status = await m.solve(); // Fast MIP solve with default HiGHS
60
+ // Import Z3 at the top of your file if needed (HiGHS and Pumpkin require no extra import):
61
+ // import "@ohtaman/washi/solvers/z3";
62
+
63
+ const status = await m.solve();
53
64
 
54
65
  if (status === "Infeasible") {
55
- // Option 1: Built-in single-solve elastic diagnosis with HiGHS
66
+ // Option 1: Built-in HiGHS (no extra imports; scale-sensitive)
56
67
  const diag = await m.check();
57
- console.error("Model is infeasible due to conflicting rules:", diag.conflicts);
68
+ console.error("Constraints to relax:", diag.conflicts);
58
69
 
59
- // Option 2: Exact SMT unsat core diagnosis with Z3 (requires import "@ohtaman/washi/solvers/z3")
70
+ // Option 2: Bundled Pumpkin (bounded int/bool; scale-invariant Unsat Core)
71
+ // const pumpkinDiag = await m.check({ solver: "pumpkin" });
72
+ // console.error("Pumpkin Unsat Core:", pumpkinDiag.unsatCore);
73
+
74
+ // Option 3: Z3 (supports Continuous/decimal variables; requires z3-solver)
60
75
  // const z3Diag = await m.check({ solver: "z3" });
61
76
  // console.error("Z3 Unsat Core:", z3Diag.unsatCore);
62
77
  }
63
78
  ```
64
79
 
65
- ### Comparing Z3 `unsatCore` vs. HiGHS Elastic Slack `conflicts`
66
-
67
- | Property | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()`) |
68
- | :--- | :--- | :--- |
69
- | **Algorithm** | SMT assumption tracking (`assertAndTrack`) | Single-solve $L_1$ elastic slack relaxation ($\min \sum s_i$) |
70
- | **Populated Fields** | Both `result.unsatCore` and `result.conflicts` | `result.conflicts` (`unsatCore` is `undefined`) |
71
- | **Semantic Meaning** | A **contradictory subset** of rules that cannot all hold together | A **minimum-violation repair set** of constraints whose relaxation restores feasibility |
72
- | **Unit-Scaling Sensitivity** | **Scale-invariant** (pure logical/algebraic contradiction) | **Scale-sensitive** (minimizing unweighted $\sum s_i$ prefers relaxing a headcount constraint by `2` units over a budget constraint by `10,000` dollars) |
73
-
74
80
  > [!TIP]
75
- > When diagnosing models that mix constraints of vastly different magnitudes (e.g., headcount $\le 8$ alongside budget $\le 50{,}000$), use **`m.check({ solver: "z3" })`** if you want the complete scale-invariant set of mutually contradictory rules, or normalize constraint scales when relying on unweighted $L_1$ slack relaxation.
81
+ > **Why HiGHS / GLPK are scale-sensitive**: In HiGHS and GLPK, `m.check()` introduces non-negative relaxation slacks to each constraint (including auto-named ones)—subtracting on `<=`, adding on `>=`, and both on `==`—and minimizes their **unweighted sum**.
82
+ > When constraints mix very different numeric scales—such as headcount $\le 8$ alongside budget $\le 50{,}000$—relaxing the smaller-scale constraint adds far less to the total slack, so HiGHS/GLPK tends to flag it first.
83
+ > Normalize your constraint units to reduce scale bias in elastic relaxation, or use `pumpkin` or `z3` when you need a scale-invariant Unsat Core.
76
84
 
77
85
  ---
78
86
 
79
- ## Independent Solution Validation (`m.validateSolution()`)
87
+ ## Verifying Solutions (`m.verify()`)
80
88
 
81
- After solving a model (or supplying a custom candidate map via `values`), you can independently verify that all variable bounds, integer/binary domains, linear constraints, and logical SMT formulas hold against the original model definitions:
89
+ After solving a model, call `m.verify()` to check that every bound, integrality rule, linear constraint, and logical constraint holds within tolerance.
90
+ You can also pass a plain object via `values` (not a `Map`), such as `m.verify({ values: { x: 1, y: 2 } })`, to validate an externally produced assignment:
82
91
 
83
92
  ```typescript
84
93
  const status = await m.solve();
85
94
 
86
95
  if (m.hasPrimalSolution) {
87
- const report = m.validateSolution({
88
- feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
89
- integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
96
+ const report = m.verify({
97
+ feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
98
+ integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
90
99
  evaluateLogicalConstraints: true,
91
100
  });
92
101
 
@@ -101,26 +110,29 @@ if (m.hasPrimalSolution) {
101
110
  }
102
111
  ```
103
112
 
104
- ### `SolutionValidationReport` Summary
113
+ ### `VerificationReport` Fields
105
114
 
106
115
  | Property | Type | Description |
107
116
  | :--- | :--- | :--- |
108
- | `valid` | `boolean` | `true` iff `complete === true`, `uncheckedConstraints.length === 0`, and `violations.length === 0`. |
109
- | `complete` | `boolean` | `true` when all variables, Boolean variables, linear constraints, and logical constraints were evaluated. |
110
- | `maxViolation` | `number` | Largest numeric violation magnitude across all evaluated bounds, integrality checks, and constraints. |
111
- | `violations` | `SolutionViolation[]` | Flat list of violations (`"missing_value"`, `"non_finite_value"`, `"invalid_boolean_value"`, `"lower_bound"`, `"upper_bound"`, `"integrality"`, `"linear_constraint"`, `"logical_constraint"`, `"unchecked_constraint"`). |
112
- | `violationsByName` | `Record<string, SolutionViolation[]>` | Violations grouped by variable or constraint name. |
117
+ | `valid` | `boolean` | `true` when `complete === true`, `uncheckedConstraints` is empty, and `violations` is empty. |
118
+ | `complete` | `boolean` | `true` when every variable and constraint in the model was evaluated. |
119
+ | `maxViolation` | `number` | Largest numeric violation across all checked bounds, integrality rules, and constraints. |
120
+ | `violations` | `VerificationViolation[]` | List of detected violations (bounds, integrality, linear/logical constraints, or missing/invalid values). |
121
+ | `violationsByName` | `Record<string, VerificationViolation[]>` | Violations grouped by variable or constraint name. |
113
122
  | `uncheckedConstraints` | `string[]` | Names of constraints that could not be evaluated. |
114
- | `missingVariables` | `string[]` | Names of numeric or Boolean variables whose values were `null` or `undefined`. |
115
- | `summary` | `SolutionValidationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
123
+ | `missingVariables` | `string[]` | Names of variables whose values were `null` or `undefined`. |
124
+ | `summary` | `VerificationSummary` | Counts of checked vs. total variables and constraints. |
116
125
 
117
126
  ---
118
127
 
119
128
  ## Inspecting the LP Formulation (`m.toLpString()`)
120
129
 
121
- When debugging coefficients, signs, or Big-M indicator expansions, call `m.toLpString()` to export the model in standard CPLEX/HiGHS `.lp` format:
130
+ To inspect coefficients, signs, or constraint names, call `m.toLpString()` to export the model in standard CPLEX `.lp` format.
131
+ It exports numeric variables, linear/quadratic objectives, linear constraints, and lowered `max`/`min`/`abs`/`at`/`!=` expressions, while omitting propositional `BoolVar`s and logical constraints:
122
132
 
123
133
  ```typescript
134
+ import { Model, expr, maximize } from "@ohtaman/washi";
135
+
124
136
  const m = new Model("DebugModel");
125
137
  const x = m.integer("x", { lb: 0, ub: 10 });
126
138
  m.objective(maximize(expr`5 * ${x}`));
@@ -142,9 +154,9 @@ End
142
154
 
143
155
  ---
144
156
 
145
- ## Unit Testing Application Logic with `MockSolver`
157
+ ## Unit Testing Without WebAssembly (`MockSolver`)
146
158
 
147
- When running unit tests for application code that builds or consumes a WaSHI `Model`, you can use the built-in `MockSolver` (`solver: "mock"`) to return deterministic results instantaneously without loading WebAssembly:
159
+ In unit tests for application code that builds or reads a `Model`, pass `MockSolver` to return fixed results immediately without loading WebAssembly:
148
160
 
149
161
  ```typescript
150
162
  import { Model, MockSolver, expr, maximize } from "@ohtaman/washi";
@@ -1,14 +1,16 @@
1
1
  # Variables & Domains
2
2
 
3
- Variables represent the mathematical decision variables in your optimization or logical model.
4
- WaSHI provides domain-specific factory methods on the `Model` instance: `m.continuous()`, `m.integer()`, `m.binary()`, and `m.bool()`.
3
+ Variables represent the unknown decision quantities in an optimization or logical model.
4
+ On a `Model` instance, WaSHI provides four domain-specific factory methods: `m.continuous()`, `m.integer()`, `m.binary()`, and `m.bool()`.
5
5
 
6
6
  ---
7
7
 
8
8
  ## Decision Variable Types
9
9
 
10
10
  ### 1. Continuous Variables (`m.continuous`)
11
- Can take any real number value within `[lb, ub]`. Used for continuous quantities such as flow rates, weights, budgets, and portfolio allocations:
11
+
12
+ Continuous variables take any real number bounded by `lb` and `ub` (default: `lb = 0`, `ub = Infinity`).
13
+ Use them for divisible quantities such as flow rates, weights, budgets, and portfolio weights:
12
14
 
13
15
  ```typescript
14
16
  import { Model } from "@ohtaman/washi";
@@ -20,7 +22,9 @@ const fuel = m.continuous("fuel", { lb: 0, ub: 1000 });
20
22
  ```
21
23
 
22
24
  ### 2. Integer Variables (`m.integer`)
23
- Restricted to integer values within `[lb, ub]`. Used for discrete counts such as machines, vehicles, or headcount:
25
+
26
+ Integer variables take whole numbers bounded by `lb` and `ub` (default: `lb = 0`, `ub = Infinity`).
27
+ Use them for indivisible counts such as vehicles, machines, or staff headcount:
24
28
 
25
29
  ```typescript
26
30
  // Single integer variable bounded in [0, 15]
@@ -28,7 +32,9 @@ const trucks = m.integer("trucks", { lb: 0, ub: 15 });
28
32
  ```
29
33
 
30
34
  ### 3. Binary Variables (`m.binary`)
31
- Restricted to $\{0, 1\}$ as numeric values (`lb = 0`, `ub = 1`). Used for 0-1 MIP selection and yes/no decisions that appear in linear sums or objective costs:
35
+
36
+ Binary variables take numeric values in $\{0, 1\}$ with `lb = 0` and `ub = 1` set automatically.
37
+ Use them for yes/no decisions in Mixed-Integer Programming (MIP) that appear in linear sums or objective costs:
32
38
 
33
39
  ```typescript
34
40
  // Single binary variable (lb = 0, ub = 1 automatically)
@@ -36,7 +42,8 @@ const openWarehouse = m.binary("open_warehouse");
36
42
  ```
37
43
 
38
44
  ### 4. Propositional Boolean Variables (`m.bool`)
39
- Pure boolean propositions (`true` / `false`) for logical and SMT constraints:
45
+
46
+ Propositional Boolean variables take pure truth values (`true` or `false`) for logical and Satisfiability Modulo Theories (SMT) rules:
40
47
 
41
48
  ```typescript
42
49
  // Single propositional boolean variables
@@ -53,20 +60,19 @@ m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
53
60
  | :--- | :--- | :--- |
54
61
  | **Solved `.value` type** | `number \| null` (`0` or `1`) | `boolean \| null` (`true` or `false`) |
55
62
  | **Linear arithmetic (`expr`, `sum`, `dot`, objective costs)** | ✅ Native (`` expr`30 * ${b}` ``) | ❌ Cannot be multiplied by numbers or summed directly |
56
- | **Indicator constraints (`m.indicator(b, ...)` )** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
63
+ | **Indicator constraints (`m.indicator(b, ...)`)** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
57
64
  | **Propositional logic (`and`, `or`, `not`, `implies`, `xor`)** | Via comparison (`` expr`${b} == 1` ``) | ✅ Native first-class methods (`.implies()`, `.and()`) |
58
- | **Solver execution** | Native 0-1 MIP on HiGHS/GLPK; bounded integer on Z3 | Native boolean proposition on Z3; auto-linearized to 0-1 MIP on HiGHS/GLPK |
59
-
60
- > [!TIP]
61
- > Use **`m.binary()`** when a decision participates in arithmetic expressions—such as linear sums ($\sum x_i \ge 3$), objective cost terms ($c_i x_i$), or `m.indicator()`. Use **`m.bool()`** when expressing logical conditions with `implies()`, `and()`, and `or()` without numeric coefficients.
65
+ | **Best used for** | Arithmetic sums, objective costs, `m.indicator()` | Pure logical rules without numeric coefficients |
62
66
 
63
67
  ---
64
68
 
65
69
  ## Multi-Dimensional & Array Creation
66
70
 
67
- The domain factory methods (`continuous`, `integer`, `binary`, `bool`) accept a numeric count or an array of string keys to create 1D arrays, typed dictionaries, and 2D matrices in a single call.
71
+ All four factory methods (`continuous`, `integer`, `binary`, `bool`) accept counts or string-key arrays.
72
+ This lets you create 1D arrays, typed dictionaries, and 2D matrices in a single call.
68
73
 
69
74
  ### By Count
75
+
70
76
  Pass a number to create an array of variables:
71
77
 
72
78
  ```typescript
@@ -75,7 +81,8 @@ const flags = m.bool(3); // BoolVar[] (p_0, p_1, p_2)
75
81
  ```
76
82
 
77
83
  ### 1D Variable Dictionaries
78
- Pass an array of keys to get a typed dictionary `Record<K, Var>` or `Record<K, BoolVar>`:
84
+
85
+ Pass an array of string keys to create a typed dictionary (`Record<K, Var>` or `Record<K, BoolVar>`):
79
86
 
80
87
  ```typescript
81
88
  const items = ["laptop", "phone", "tablet"] as const;
@@ -88,7 +95,9 @@ const perms = m.bool(["read", "write", "execute"] as const);
88
95
  ```
89
96
 
90
97
  ### 2D Variable Matrices & Grids
91
- Each dimension follows a consistent rule: passing a numeric count (`number`) produces an `Array`, and passing a collection of keys produces a `Record`:
98
+
99
+ Each dimension follows one rule: a numeric count produces an `Array`, and a key list produces a `Record`.
100
+
92
101
  - `(rowsCount, colsCount)` $\rightarrow$ `Var[][]` (or `BoolVar[][]`)
93
102
  - `(rowKeys, colKeys)` $\rightarrow$ `Record<R, Record<C, Var>>` (or `Record<R, Record<C, BoolVar>>`)
94
103
  - `(rowsCount, colKeys)` $\rightarrow$ `Array<Record<C, Var>>`
@@ -115,18 +124,30 @@ const schedule = m.binary(factories, 7, { prefix: "open_day" });
115
124
 
116
125
  ## Variable Options
117
126
 
127
+ Each factory method accepts options matching its variable kind.
128
+ `m.continuous()` and `m.integer()` accept all factory options below, `m.binary()` omits `lb` and `ub`, and `m.bool()` accepts `name` and `prefix` only.
129
+
118
130
  | Option | Type | Default | Description |
119
131
  | :--- | :--- | :--- | :--- |
120
- | `lb` | `number` | `0` | Lower bound. Defaults to `0` (non-negative). |
121
- | `ub` | `number` | `Infinity` (or `1` for binary) | Upper bound. |
122
- | `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Underlying variable domain category. |
123
- | `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP warm start), kept distinct from solved `variable.value`. |
132
+ | `name` | `string` | Auto-generated | Explicit name for a scalar variable (alternative to passing the name as the first argument). |
133
+ | `lb` | `number` | `0` | Lower bound (`m.continuous()`, `m.integer()`). Pass a negative finite number or `-Infinity` to allow negative values. |
134
+ | `ub` | `number` | `Infinity` (`1` for binary) | Upper bound (`m.continuous()`, `m.integer()`). Fixed to `1` for `m.binary()`. |
135
+ | `prefix` | `string` | `"x"` (`"p"` for `m.bool()`) | Name prefix for unnamed scalars, arrays, dictionaries, and 2D containers (e.g., `queen_0_0`). |
136
+ | `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Numeric variable domain (applies to direct `new Var()` construction only). |
137
+ | `initialValue` | `number` | `undefined` | Warm-start hint for numeric variables (`m.continuous()`, `m.integer()`, `m.binary()`), stored separately from solved `variable.value`. |
138
+
139
+ ### Designing Bounds (`lb` & `ub`)
140
+
141
+ - **Allowing negative values**: Numeric variables are non-negative by default. For signed quantities such as net inventory change or deviation, explicitly pass a negative finite bound or `{ lb: -Infinity }`.
142
+ - **Strengthening MIP formulations**: Realistic finite `lb` and `ub` bounds improve MIP presolve and let `m.indicator()` compute tight Big-M constants automatically.
143
+ - **CP solver requirement**: Bounded-integer Constraint Programming (CP) solvers such as Pumpkin require finite integer bounds on every numeric variable.
124
144
 
125
145
  ---
126
146
 
127
147
  ## Primal Initial Values (Warm-Start Hints)
128
148
 
129
- When rebuilding a model across iterations, you can supply optional primal initial values (`initialValue`) on a subset or all numeric variables (`m.continuous`, `m.integer`, `m.binary`, or `v.initialValue = ...`):
149
+ When re-solving a modified model, you can supply a warm-start hint (`initialValue`) on some or all numeric variables.
150
+ Pass `initialValue` in the factory options or assign `v.initialValue = ...` directly:
130
151
 
131
152
  ```typescript
132
153
  const prevValues: Record<string, number | null> = { trucks: 8, open_warehouse: 1 };
@@ -143,41 +164,66 @@ const openWarehouse2 = m2.binary("open_warehouse", {
143
164
  const extraCapacity = m2.continuous("extra_capacity", { lb: 0 }); // Partial start: no initialValue needed
144
165
  ```
145
166
 
146
- - **Hint vs. Hard Constraint**: `initialValue` is an optional solver hint (passed to HiGHS via `setSolution`). It does **not** fix the variable or add a constraint, and `variable.value` remains `null` until solved. *(To penalize deviations from a previous plan, see [Formulation Patterns & Tips](./formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).)*
147
- - **Validation & Tolerance (`1e-6`)**: Supplied values must be finite numbers within `[lb - 1e-6, ub + 1e-6]` (and within `1e-6` of an integer for `"Integer"` and `"Binary"` variables). Partial starts are accepted without needing to satisfy every model constraint, though supplying a complete constraint-feasible assignment gives MIP solvers an immediate incumbent bound.
148
- - **Solver Support**: Supported by **HiGHS** (`capabilities.supportsWarmStart === true`). Solvers without warm-start support (**GLPK**, **Z3**, or custom adapters without `supportsWarmStart: true`) reject `solve()` and `check()` with a descriptive error rather than silently ignoring `initialValue`.
167
+ ### Hint vs. Hard Constraint
168
+
169
+ `initialValue` is an optional starting hint for the solver, not a constraint or variable fixation.
170
+ Before solving, `variable.value` remains `null`.
171
+ To penalize changes from an existing schedule in the objective instead, see [Formulation Patterns & Tips](./formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).
172
+
173
+ ### Validation & Tolerance (`1e-6`)
174
+
175
+ Every supplied `initialValue` must be a finite number within `[lb - 1e-6, ub + 1e-6]`.
176
+ For `"Integer"` and `"Binary"` variables, the value must also lie within `1e-6` of an integer.
177
+ Partial starts are allowed; providing a complete feasible assignment gives MIP solvers an immediate incumbent solution (a valid baseline objective value used to prune search branches).
178
+
179
+ ### Solver Support
180
+
181
+ - **Supported**: HiGHS supports warm starts on all numeric variables. Pumpkin supports them on bounded `Integer` and `Binary` variables in both `solve()` and `check()`.
182
+ - **Unsupported**: GLPK, Z3, and custom adapters without warm-start support reject `solve()` and `check()` with an explicit error instead of silently ignoring `initialValue`.
149
183
 
150
184
  ---
151
185
 
152
186
  ## Accessing Solution Values & Reduced Costs
153
187
 
154
- After calling `await m.solve()` or `await m.check()`, assigned variable values are accessible via `variable.value` (returns `number | null` for `Var`, or `boolean | null` for `BoolVar`) or the bulk accessor `m.getValues()`:
188
+ After calling `await m.solve()` or `await m.check()`, read assigned values directly from `variable.value` or look them up by name in `m.values`.
189
+ `variable.value` returns `number | null` for `Var` and `boolean | null` for `BoolVar`.
190
+
191
+ For continuous Linear Programming (LP) models—or LP relaxations solved via `m.relax()`—on HiGHS, `variable.reducedCost` exposes the variable's reduced cost as `number | null`.
192
+ The **reduced cost** indicates how much a non-basic variable's objective coefficient must improve before moving it away from its active bound (`lb` or `ub`) becomes worthwhile.
193
+ `reducedCost` is `null` before solving, when no optimal LP solution is found, on GLPK (which populates constraint `dual` only), on MIP models solved with `m.solve()`, and on CP and SMT models.
155
194
 
156
195
  ```typescript
157
196
  await m.solve();
158
197
 
159
- // Single variable primal value
198
+ // Scalar variable primal & boolean values
160
199
  console.log(`trucks: ${trucks.value}`);
200
+ console.log(`isAdmin: ${isAdmin.value}`);
161
201
 
162
- // Reduced cost (LP sensitivity analysis)
163
- console.log(`fuel reduced cost: ${fuel.reducedCost}`);
202
+ // Indexed 1D & 2D variable containers
203
+ const packedItems = items.filter((it) => selected[it].value === 1);
204
+ console.log(`Tokyo -> StoreA: ${ship.Tokyo.StoreA.value}`);
164
205
 
165
- // Bulk extraction for 1D or 2D collections (works for both Var and BoolVar collections)
166
- const selectedValues = m.getValues(selected);
167
- // { laptop: 1, phone: 0, tablet: 1 }
206
+ // Name-keyed ReadonlyMap lookup (ReadonlyMap<string, number | boolean>)
207
+ console.log(`trucks by name: ${m.values.get("trucks")}`);
168
208
 
169
- const flowValues = m.getValues(ship);
170
- // { Tokyo: { StoreA: 50, ... }, Osaka: { ... } }
209
+ // Reduced cost (LP sensitivity analysis; number | null)
210
+ console.log(`fuel reduced cost: ${fuel.reducedCost}`);
171
211
  ```
172
212
 
173
213
  ---
174
214
 
175
215
  ## Looking Up Variables by Name
176
216
 
177
- You can retrieve registered decision variables by name or inspect the total numeric variable count on the model:
217
+ All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are accessible through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
178
218
 
179
219
  ```typescript
180
- const v = m.getVarByName("trucks"); // Var | undefined
181
- const b = m.getBoolVarByName("isAdmin"); // BoolVar | undefined
182
- console.log("Total numeric variables:", m.numVars);
220
+ const v = m.variables.get("trucks"); // Var | BoolVar | undefined
221
+ const b = m.variables.get("isAdmin"); // Var | BoolVar | undefined
222
+ console.log("Has trucks:", m.variables.has("trucks"));
223
+ console.log("Total variables:", m.variables.size);
224
+
225
+ // Narrow by v.type ("Continuous" | "Integer" | "Binary" | "Boolean"):
226
+ if (v && v.type !== "Boolean") {
227
+ console.log("Bounds:", v.lb, v.ub);
228
+ }
183
229
  ```