@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
@@ -4,22 +4,24 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Convex Quadratic Programming (QP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot`, `QuadExpr` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=portfolio_qp">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/03-portfolio-qp.ts">Source Code</a></li></ul> |
6
6
 
7
- The Markowitz mean-variance portfolio optimization problem is the foundation of modern quantitative finance: allocate capital across risky assets to minimize overall portfolio variance (risk) subject to achieving a minimum required expected return.
7
+ The Markowitz mean-variance model is a classic problem in quantitative finance. It allocates capital across risky assets to minimize portfolio variance (risk) while meeting a minimum target return.
8
8
 
9
9
  <PortfolioQpDemo />
10
10
 
11
+ The interactive demo above uses a preset with a `60%` per-asset weight cap, while the formulation and code below solve the uncapped long-only model ($0 \le w_i \le 1$).
12
+
11
13
  ## Mathematical Formulation
12
14
 
13
- Let $w_i \ge 0$ denote the allocation weight for asset $i$:
15
+ Let $n$ be the number of assets, $w_i$ be the allocation weight for asset $i$ (written as vector $\mathbf{w}$), $r_i$ be its expected return, and $R_{\text{target}}$ be the minimum target return:
14
16
 
15
17
  $$\begin{aligned}
16
18
  \text{Minimize} \quad & \mathbf{w}^T \boldsymbol{\Sigma} \mathbf{w} & (\text{Portfolio Variance}) \\
17
19
  \text{Subject to} \quad & \sum_{i=1}^n w_i = 1 & (\text{Full Capital Budget}) \\
18
20
  & \sum_{i=1}^n r_i w_i \ge R_{\text{target}} & (\text{Minimum Target Return}) \\
19
- & 0 \le w_i \le 1 & (\text{Long-Only Weights})
21
+ & 0 \le w_i \le 1 \quad \forall i = 1, \dots, n & (\text{Long-Only Weights})
20
22
  \end{aligned}$$
21
23
 
22
- where $\boldsymbol{\Sigma}$ is the positive semi-definite asset return covariance matrix.
24
+ where $\boldsymbol{\Sigma}$ is the symmetric positive semi-definite asset return covariance matrix, making the objective a convex quadratic function.
23
25
 
24
26
  ## Implementation in WaSHI
25
27
 
@@ -55,7 +57,7 @@ async function solvePortfolio() {
55
57
  const portfolioReturn = dot(retMap, w);
56
58
  m.constraint(expr`${portfolioReturn} >= ${targetReturn}`, "target_return");
57
59
 
58
- // 3. Quadratic Objective: minimize risk w^T * Sigma * w
60
+ // 3. Quadratic Objective: minimize portfolio variance w^T * Sigma * w
59
61
  let risk = new QuadExpr();
60
62
  for (let i = 0; i < assets.length; i++) {
61
63
  for (let j = 0; j < assets.length; j++) {
@@ -66,7 +68,7 @@ async function solvePortfolio() {
66
68
  }
67
69
  m.objective(minimize(risk));
68
70
 
69
- // Solve natively with HiGHS Convex QP engine
71
+ // Solve with HiGHS QP solver
70
72
  const status = await m.solve();
71
73
 
72
74
  console.log(`Status: ${status}`);
@@ -86,5 +88,16 @@ solvePortfolio();
86
88
 
87
89
  ## Practical Notes
88
90
 
89
- - **Tracing the Efficient Frontier (`targetReturn` & `portfolioReturn.value`)**: Because the achieved return (`8.50%`) matches `targetReturn` exactly, the return constraint is tightly binding on the Markowitz efficient frontier. Varying `targetReturn` across `[0.05, 0.12]` traces out the full risk-return frontier.
90
- - **Risk-Aversion Scalarization vs. Target Return Constraint**: If `targetReturn` is set above the highest single-asset return ($12\%$ for `Tech` under long-only weights), the hard constraint $\mathbf{r}^T \mathbf{w} \ge R_{\text{target}}$ becomes `"Infeasible"`. An alternative formulation that is always feasible for any risk appetite $\lambda > 0$ is to minimize the risk-adjusted objective $\min (\lambda \, \mathbf{w}^T \boldsymbol{\Sigma} \mathbf{w} - \mathbf{r}^T \mathbf{w})$.
91
+ At `8.50%` target return, optimal variance is `0.014229` (`11.93%` volatility): `52.68%` `Tech` and `30.57%` `Bonds` balance return and risk, while `GlobalEq` drops to `0.00%` due to high covariance with `Tech`.
92
+
93
+ ### Tracing the Efficient Frontier
94
+
95
+ The solved `portfolioReturn.value` matches `targetReturn` (`8.50%`) exactly, showing that the target return constraint is binding and the solution lies on the Markowitz efficient frontier for `8.50%`. Sweeping `targetReturn` from the minimum-variance portfolio's expected return (about `4.52%`) up to the maximum single-asset return (`12%`) traces the entire efficient frontier.
96
+
97
+ ### Target Return Constraint vs. Risk-Aversion Scalarization
98
+
99
+ Under long-only weights ($0 \le w_i \le 1$), setting `targetReturn` above the highest single-asset return (`12%` for `Tech`) makes the hard return constraint `"Infeasible"`.
100
+
101
+ To drop the hard target-return constraint and keep the model feasible for any risk-aversion coefficient $\lambda > 0$, minimize the risk-adjusted objective using the expected return vector $\mathbf{r}$:
102
+
103
+ $$\min_{\mathbf{w}} \; \lambda \, \mathbf{w}^T \boldsymbol{\Sigma} \mathbf{w} - \mathbf{r}^T \mathbf{w}$$
@@ -1,14 +1,14 @@
1
- # Production Planning (LP / MIP)
1
+ # Production Planning (Integer Programming / MIP)
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Linear / Integer Programming (LP / MIP) | HiGHS (default) | `m.integer()`, `m.constraint()`, `expr` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=production">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/01-production-planning.ts">Source Code</a></li></ul> |
5
+ | Integer Programming (MIP) | HiGHS (default) | `m.integer()`, `m.constraint()`, `expr`, `maximize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=production">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/01-production-planning.ts">Source Code</a></li></ul> |
6
6
 
7
- Production planning is a classic Linear Programming problem: determine the optimal quantity of each product to manufacture in order to maximize total profit while respecting resource constraints (raw materials, machine time, labor hours).
7
+ Production planning is a classic optimization problem. You choose how many units of each product to make to maximize profit without exceeding resource limits such as raw materials or labor hours.
8
8
 
9
9
  ## Mathematical Formulation
10
10
 
11
- Let $x$ be the number of chairs and $y$ be the number of tables.
11
+ Let $x$ be the number of chairs (profit `$45` each) and $y$ be the number of tables (profit `$80` each).
12
12
 
13
13
  $$\begin{aligned}
14
14
  \text{Maximize} \quad & 45x + 80y & (\text{Profit}) \\
@@ -34,7 +34,7 @@ async function runProductionOptimization() {
34
34
  // Objective: Maximize total profit ($45 per chair, $80 per table)
35
35
  m.objective(maximize(expr`45 * ${chairs} + 80 * ${tables}`));
36
36
 
37
- // Resource constraints: declarative formulas via expr and constraint()
37
+ // Resource constraints: mahogany wood and carpentry labor limits
38
38
  m.constraint(expr`5 * ${chairs} + 20 * ${tables} <= 400`, "mahogany_limit");
39
39
  m.constraint(expr`10 * ${chairs} + 15 * ${tables} <= 450`, "labor_limit");
40
40
 
@@ -49,3 +49,8 @@ runProductionOptimization();
49
49
  ```
50
50
 
51
51
  </CodeRunner>
52
+
53
+ ## Key Takeaways
54
+
55
+ - **Optimal Result**: Producing `chairs = 24` and `tables = 14` yields the maximum profit of `$2,200`. Both resources are fully used: mahogany wood is $5(24) + 20(14) = 400$ and carpentry labor is $10(24) + 15(14) = 450$.
56
+ - **Why `m.integer()` instead of `m.continuous()`**: Chairs and tables are discrete items that cannot be shipped in fractions. Although this instance happens to have an integer LP optimum, `m.integer()` guarantees whole-number outputs even when limits or prices change.
@@ -0,0 +1,119 @@
1
+ # Resource-Constrained Project Scheduling (CP / Pumpkin)
2
+
3
+ | Problem Class | Solver | Key APIs | Links |
4
+ | :--- | :--- | :--- | :--- |
5
+ | Constraint Programming (RCPSP) / Unsat Core Diagnosis | Pumpkin (`{ solver: "pumpkin" }`) | `m.integer()`, `disjoint()`, `cumulative()`, `max()`, `and()`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=project_scheduling">Playground (Schedule)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=project_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts">Source Code</a></li><li><a href="/guide/constraint-programming">CP Modeling Guide</a></li></ul> |
6
+
7
+ The **Resource-Constrained Project Scheduling Problem (RCPSP)** schedules project tasks to minimize the maximum completion time, known as the **makespan**. It balances task precedence order, exclusive single-machine equipment, and limited team headcount at the same time.
8
+
9
+ Using WaSHI's bundled **Pumpkin** solver (`{ solver: "pumpkin" }`, zero extra imports):
10
+ 1. Each task needs only one integer start variable (`start[task]`), avoiding binary variables for every `(task, hour)` pair.
11
+ 2. When a maintenance window or tight deadline makes the schedule `"Infeasible"`, `m.check()` isolates the conflicting rules (`unsatCore`) on the same model.
12
+
13
+ ## Problem Inputs
14
+
15
+ We schedule **6 hardware prototype tasks** with a start-time horizon of `24` hours (`horizon = 24`). The team has `crewCapacity = 3` engineers and 1 shared test and calibration rig:
16
+
17
+ | Task | Duration | Crew | Dependencies | Shared Rig (`disjoint`) |
18
+ | :--- | :--- | :--- | :--- | :--- |
19
+ | `chassis` | 4h | 2 | — | No |
20
+ | `board` | 3h | 2 | — | No |
21
+ | `firmware` | 4h | 1 | — | **Yes** |
22
+ | `assembly` | 3h | 2 | `chassis`, `board` | No |
23
+ | `calib` | 3h | 1 | `board` | **Yes** |
24
+ | `test` | 2h | 2 | `assembly`, `firmware`, `calib` | **Yes** |
25
+
26
+ Ignoring the crew limit, `chassis` and `board` can start together at `0h`, giving a `9h` critical path (`chassis 4h -> assembly 3h -> test 2h`). Because `crewCapacity = 3`, `chassis` and `board` each need 2 engineers and cannot overlap (`2 + 2 = 4 > 3`). Running them back-to-back delays `assembly` until `7h`, raising the minimum makespan from `9h` to **`12h`**.
27
+
28
+ ## Implementation in WaSHI
29
+
30
+ <CodeRunner preset="project_scheduling">
31
+
32
+ ```typescript
33
+ import { Model, expr, disjoint, cumulative, max, and, minimize } from "@ohtaman/washi";
34
+
35
+ async function runProjectScheduling() {
36
+ const horizon = 24;
37
+ const crewCapacity = 3;
38
+ const tasks = [
39
+ { id: "chassis", duration: 4, crew: 2, usesRig: false },
40
+ { id: "board", duration: 3, crew: 2, usesRig: false },
41
+ { id: "firmware", duration: 4, crew: 1, usesRig: true },
42
+ { id: "assembly", duration: 3, crew: 2, usesRig: false },
43
+ { id: "calib", duration: 3, crew: 1, usesRig: true },
44
+ { id: "test", duration: 2, crew: 2, usesRig: true },
45
+ ] as const;
46
+
47
+ const m = new Model("PrototypeRCPSP", { solver: "pumpkin" });
48
+ const start = m.integer(tasks.map((t) => t.id), { lb: 0, ub: horizon, prefix: "start" });
49
+
50
+ // 1. Precedence network
51
+ m.constraint(expr`${start.chassis} + 4 <= ${start.assembly}`, "assembly_after_chassis");
52
+ m.constraint(expr`${start.board} + 3 <= ${start.assembly}`, "assembly_after_board");
53
+ m.constraint(expr`${start.board} + 3 <= ${start.calib}`, "calib_after_board");
54
+ m.constraint(expr`${start.assembly} + 3 <= ${start.test}`, "test_after_assembly");
55
+ m.constraint(expr`${start.firmware} + 4 <= ${start.test}`, "test_after_firmware");
56
+ m.constraint(expr`${start.calib} + 3 <= ${start.test}`, "test_after_calib");
57
+
58
+ // 2. Exclusive shared rig & 3-engineer cumulative limit
59
+ m.constraint(
60
+ disjoint(tasks.filter((t) => t.usesRig).map((t) => ({ start: start[t.id], duration: t.duration }))),
61
+ "single_rig"
62
+ );
63
+ m.constraint(
64
+ cumulative(
65
+ tasks.map((t) => ({ start: start[t.id], duration: t.duration, demand: t.crew })),
66
+ crewCapacity
67
+ ),
68
+ "crew_limit"
69
+ );
70
+
71
+ // 3. Minimize project makespan: max_t (start[t] + duration[t])
72
+ const makespan = max(tasks.map((t) => expr`${start[t.id]} + ${t.duration}`));
73
+ m.objective(minimize(makespan));
74
+
75
+ const status = await m.solve();
76
+ const optMakespan = m.objectiveValue;
77
+ const report = m.verify();
78
+ console.log(`Status: ${status} (valid: ${report.valid}), Minimum Makespan: ${optMakespan}h`);
79
+ for (const t of tasks) {
80
+ const s = start[t.id].value ?? 0;
81
+ console.log(` ${t.id}: [${s}h, ${s + t.duration}h) crew=${t.crew}${t.usesRig ? " [Rig]" : ""}`);
82
+ }
83
+
84
+ // 4. Diagnose an impossible rush deadline when the rig is offline for maintenance [0, 6)
85
+ // (restricting firmware and calib to start >= 6; test is already >= 7 via precedence)
86
+ m.constraint(
87
+ and(expr`${start.firmware} >= 6`, expr`${start.calib} >= 6`),
88
+ "rig_maintenance_window"
89
+ );
90
+ m.constraint(expr`${makespan} <= 13`, "rush_ship_deadline");
91
+
92
+ const diag = await m.check();
93
+ console.log(`Deadline Check: ${diag.status}`);
94
+ console.log(`Unsat Core: ${(diag.unsatCore ?? []).join(", ")}`);
95
+ }
96
+
97
+ runProjectScheduling();
98
+ ```
99
+
100
+ </CodeRunner>
101
+
102
+ ## Practical Notes
103
+
104
+ ### Compact Scheduling with Global Constraints
105
+
106
+ In Constraint Programming, **global constraints** express recurring scheduling patterns directly over groups of variables. Here, `disjoint()` keeps tasks on the shared rig from overlapping, and `cumulative()` caps simultaneous crew usage at `3`. Because start times are bounded integers rather than hourly binary flags, the model stays small even with a longer horizon or finer time units.
107
+
108
+ ### Snapshot `m.objectiveValue` Before `m.check()`
109
+
110
+ Calling `await m.check()` on the same `Model` clears the previous `solve()` outputs, resetting `m.objectiveValue` to `null`. Always store optimization results in local variables before running a conflict check.
111
+
112
+ ### Why the `13h` Rush Deadline Is Infeasible (`unsatCore`)
113
+
114
+ When the maintenance window and `<= 13h` deadline are added, `m.check()` returns `"Unsat"` and isolates the 5 conflicting constraints in `unsatCore`. It excludes unrelated rules such as `crew_limit`, even though crew capacity was the bottleneck in Part 1:
115
+
116
+ 1. `rig_maintenance_window` delays both `firmware` and `calib` until at least `6h`.
117
+ 2. Because `chassis` takes `4h` and `assembly` takes `3h`, `assembly_after_chassis` and `test_after_assembly` delay `test` until at least `7h`.
118
+ 3. Under `single_rig`, the three rig tasks (`firmware` 4h, `calib` 3h, `test` 2h) need `9h` of non-overlapping rig time, and none can start before `6h`.
119
+ 4. As a result, the earliest possible finish is `6 + 9 = 15h`, which conflicts with `rush_ship_deadline` (`<= 13h`).
@@ -2,36 +2,44 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Binary MIP & SMT Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/11-shift-scheduling.ts">Source Code</a></li></ul> |
5
+ | Binary MIP & SMT Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `m.check()`, `m.unsatCore` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/11-shift-scheduling.ts">Source Code</a></li></ul> |
6
6
 
7
- Staff shift scheduling is a classic real-world application of Mixed-Integer Programming in SaaS and workforce management tools. However, in real applications, **staff vacation requests frequently collide with minimum coverage or leadership rules**, causing the solver to return `Infeasible`.
7
+ In staff shift scheduling, vacation requests often collide with minimum headcount or senior coverage rules, causing a Mixed-Integer Programming (MIP) solver to return `"Infeasible"`.
8
8
 
9
- This example demonstrates a practical production workflow:
10
- 1. **Try HiGHS MIP Optimization First:** Solve the shift model under the given vacation requests and operational constraints.
11
- 2. **Accept Solution if Optimal:** If a feasible roster is found, display the schedule and minimized payroll cost without unnecessary diagnostic overhead.
12
- 3. **Diagnose with Z3 `unsatCore` Only When Infeasible:** If HiGHS reports `Infeasible`, diagnose the **exact same model and constraints** with Z3 to isolate the conflicting constraint subset (`unsatCore`), pinpointing which day's coverage rules and which staff requests collided.
9
+ This example shows an optimize-then-diagnose workflow on the same model:
10
+ 1. **Optimize with HiGHS first:** Minimize weekly payroll cost under all vacation requests and staffing rules.
11
+ 2. **Use the roster if `"Optimal"`:** Output the schedule and payroll cost with no extra diagnostic step.
12
+ 3. **Diagnose with Z3 if `"Infeasible"`:** Call `model.check({ solver: "z3" })` on the same model to extract the conflicting rule subset (`unsatCore`).
13
13
 
14
14
  > [!IMPORTANT]
15
- > **Vacation Requests are Hard Constraints:**
16
- > In this model, vacation requests are enforced as strict hard constraints (`shift[staff][day] == 0`), not soft constraints with penalty relaxation. When requests collide with mandatory staffing requirements, the model is strictly infeasible.
15
+ > **Vacation Requests Are Hard Constraints:**
16
+ > Each vacation request is modeled as a strict rule (`shift[staff][day] == 0`), not a penalized preference. When requests clash with mandatory coverage, the model is strictly `"Infeasible"`.
17
17
 
18
18
  <ShiftSchedulingDemo />
19
19
 
20
20
  ## Scenario & Rules
21
21
 
22
- We schedule **5 staff members** (`Alice`, `Bob`, `Charlie`, `Diana`, `Evan`) across **7 days** (`Mon`–`Sun`):
22
+ While the interactive widget above expands to 8 staff members, the runnable walkthrough below uses a compact 5-staff × 7-day model.
23
+
24
+ We schedule **5 staff members** across **7 days** from `Mon` to `Sun` — seniors `Alice` (`$220/day`) and `Bob` (`$210/day`), plus `Charlie` (`$160/day`), `Diana` (`$160/day`), and `Evan` (`$150/day`):
23
25
 
24
26
  - **Daily Headcount:** `Mon–Thu`: 3 staff, `Fri`: 4 staff, `Sat`: 3 staff, `Sun`: 2 staff.
25
- - **Senior Duty:** At least 1 senior staff member (`Alice` or `Bob`) must be on duty every day.
27
+ - **Senior Duty:** At least 1 senior staff member (`Alice` or `Bob`) must work every day.
26
28
  - **Work Limit:** Each staff member works at most **5 days** per week.
27
- - **Weekend Premium:** Weekend shifts (`Sat`, `Sun`) incur an extra `+$30` shift premium on top of base daily wage.
29
+ - **Weekend Premium:** `Sat` and `Sun` shifts add `+$30` to the base daily wage.
30
+
31
+ We run two scenarios to show both outcomes:
28
32
 
29
- We evaluate two distinct, named scenarios with different vacation inputs to illustrate the full workflow:
30
- - **Scenario A (Balanced Requests — Feasible):** Alice (Sun), Bob (Mon), Charlie (Sat), Diana (Wed). All constraints can be satisfied simultaneously. HiGHS outputs an optimal roster.
31
- - **Scenario B (Conflicting Requests — Infeasible & Diagnosis):** Alice (Sat), Bob (Sat), Charlie (Sat), Diana (Wed). Because both senior leaders (Alice and Bob) request Saturday off simultaneously, the rule requiring at least 1 senior on duty every day cannot be satisfied. HiGHS reports `Infeasible`, triggering Z3 conflict diagnosis.
33
+ | Scenario | Hard Day-Off Requests | Outcome |
34
+ | :--- | :--- | :--- |
35
+ | **Scenario A (Feasible)** | `Alice (Sun)`, `Bob (Mon)`, `Charlie (Sat)`, `Diana (Wed)` | HiGHS returns `"Optimal"` (`$3,830` weekly payroll). |
36
+ | **Scenario B (Conflict)** | `Alice (Sat)`, `Bob (Sat)`, `Charlie (Sat)`, `Diana (Wed)` | Both seniors request Saturday off, so HiGHS returns `"Infeasible"` and Z3 extracts `unsatCore`. |
32
37
 
33
38
  ## Implementation in WaSHI
34
39
 
40
+ > [!NOTE]
41
+ > **Z3 Prerequisites:** Importing `@ohtaman/washi/solvers/z3` requires the optional `z3-solver` peer dependency (`npm install z3-solver`). Running Z3 in a browser also requires Cross-Origin Isolation (`COOP` / `COEP`) headers — see [Cross-Origin Isolation](../getting-started/cross-origin.md).
42
+
35
43
  <CodeRunner preset="shift_scheduling">
36
44
 
37
45
  ```typescript
@@ -138,7 +146,7 @@ async function runScenario(
138
146
  console.log("Conflicting Constraint Subset (unsatCore):", model.unsatCore);
139
147
  console.log(
140
148
  "Note: unsatCore returns a conflicting subset (minimality/order not guaranteed). " +
141
- "Independent requests like Diana's Wednesday off are excluded.\n"
149
+ "In this run, unrelated requests like Diana's Wednesday off are excluded.\n"
142
150
  );
143
151
  }
144
152
  }
@@ -174,9 +182,9 @@ main();
174
182
 
175
183
  </CodeRunner>
176
184
 
177
- ## Auto-Repairing Conflicts with Soft Constraints (Elastic Requests)
185
+ ## Relaxing Conflicts with Soft Constraints
178
186
 
179
- Once Z3 `unsatCore` diagnoses that `senior_duty_Sat` conflicts with `day_off_Alice_Sat` and `day_off_Bob_Sat`, you can offer managers an automatic repair option by relaxing day-off requests from hard constraints (`shift[staff][day] == 0`) into **soft preferences** penalized in the objective (e.g., `+$500` per overridden day off):
187
+ After Z3 isolates the conflict among `senior_duty_Sat`, `day_off_Alice_Sat`, and `day_off_Bob_Sat`, you can generate a fallback schedule by relaxing the hard day-off constraints (Rule 4) into **soft preferences** that add a `$500` penalty per overridden request:
180
188
 
181
189
  ```typescript
182
190
  // Soft constraint pattern: penalize working on a requested day off by $500
@@ -185,4 +193,7 @@ const requestedShiftVars = dayOffRequests.map((req) => shift[req.staff][req.day]
185
193
  m.objective(minimize(expr`dot(${costMatrix}, ${shift}) + 500 * sum(${requestedShiftVars})`));
186
194
  ```
187
195
 
188
- With this soft formulation on Scenario B, HiGHS automatically finds a valid roster that honors 3 of the 4 requests (`Alice (Sat)`, `Charlie (Sat)`, and `Diana (Wed)`) and overrides only `Bob (Sat)`—choosing Bob over Alice because Bob's daily wage (`$210`) is `$10` lower than Alice's (`$220`).
196
+ On Scenario B, HiGHS returns `"Optimal"` with an objective value of **`$4,330`** (`$3,830` payroll plus one `$500` penalty). It honors 3 of the 4 requests and overrides only 1 senior request (`Alice (Sat)` in the HiGHS output). Because `Bob` has the lower daily wage, the cheapest staffing assigns him up to his 5-day limit (`maxShifts = 5`) and `Alice` to the remaining 2 senior days. Overriding either `Alice (Sat)` or `Bob (Sat)` therefore yields the exact same total cost of `$4,330`.
197
+
198
+ > [!TIP]
199
+ > This model uses only binary variables (`m.binary()`) and constraints with integer coefficients. You can also extract `unsatCore` via `await model.check({ solver: "pumpkin" })` out of the box without installing `z3-solver` or adding extra imports.
@@ -4,20 +4,25 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Propositional Logic & SMT | Z3 (`@ohtaman/washi/solvers/z3`) | `m.bool()`, `m.integer()`, `implies()`, `m.constraint()`, `expr`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=smt_security">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts">Source Code</a></li></ul> |
6
6
 
7
- Satisfiability Modulo Theories (SMT) combines propositional logic (Boolean SAT) with first-order theories (linear integer arithmetic, real inequalities).
7
+ **Satisfiability Modulo Theories (SMT)** combines Boolean logic with arithmetic inequalities such as integer bounds and linear comparisons.
8
8
 
9
- This example demonstrates how to formally verify and deduce system states in an IoT home security system using WaSHI and the Z3 solver engine.
9
+ This example verifies safety rules and deduces system states for a smart-home security system using WaSHI and Z3.
10
10
 
11
11
  ## The Scenario
12
12
 
13
- We model a security rule system with sensor readings and logic rules:
14
- 1. When ambient light $\le 50$, it implies night time (`isNight`).
15
- 2. When motion is detected at night and the alarm is armed, the siren must sound.
16
- 3. If the alarm is armed, the front door must never be unlocked.
17
- 4. When motion is detected at night, comfort lights should turn on.
13
+ We model a security rule system driven by sensor readings and logical policies:
14
+ 1. When ambient light (`luxLevel`) is at most `50 lux`, the system enters night mode (`isNight`).
15
+ 2. When motion (`motionDetected`) is detected at night (`isNight`) while the alarm is armed (`alarmArmed`), the siren (`sirenActive`) must sound.
16
+ 3. While the alarm is armed (`alarmArmed`), the front door (`frontDoorUnlocked`) must stay locked.
17
+ 4. When motion (`motionDetected`) is detected at night (`isNight`), comfort lights (`lightsOn`) turn on.
18
+
19
+ Given the observed sensor state — `luxLevel <= 20`, `alarmArmed`, and `motionDetected` — we first deduce the resulting system state. We then formally prove that under these readings, the siren (`sirenActive`) cannot remain off.
18
20
 
19
21
  ## Implementation in WaSHI
20
22
 
23
+ > [!NOTE]
24
+ > **Z3 Prerequisites:** Importing `@ohtaman/washi/solvers/z3` requires the optional `z3-solver` peer dependency (`npm install z3-solver`). Running Z3 in a browser also requires Cross-Origin Isolation (`COOP` / `COEP`) headers — see [Cross-Origin Isolation](../getting-started/cross-origin.md).
25
+
21
26
  <CodeRunner preset="smt_security">
22
27
 
23
28
  ```typescript
@@ -59,7 +64,7 @@ async function verifySecurityRules() {
59
64
  m.constraint(motionDetected, "sensor_motion_triggered");
60
65
 
61
66
  // Check satisfiability and deduce state
62
- const res = await m.check({ solver: "z3" });
67
+ const res = await m.check();
63
68
 
64
69
  console.log(`Status: ${res.status}`);
65
70
  console.log(`Siren Active : ${sirenActive.value}`);
@@ -70,7 +75,7 @@ async function verifySecurityRules() {
70
75
  // 4. Formal Safety Verification (Counterexample Search):
71
76
  // Prove that the siren CANNOT remain off under these sensor readings
72
77
  m.constraint(not(sirenActive), "counterexample_siren_off");
73
- const proof = await m.check({ solver: "z3" });
78
+ const proof = await m.check();
74
79
  console.log(`Can siren stay off? ${proof.status} (Proven safe when Unsat)`);
75
80
  console.log(`Active proof core : ${(proof.conflicts ?? []).join(", ")}`);
76
81
  }
@@ -82,5 +87,16 @@ verifySecurityRules();
82
87
 
83
88
  ## Practical Notes
84
89
 
85
- - **Proof by Refutation (Counterexample Search)**: A single `Sat` check shows that *a* valid assignment exists. To formally prove that a safety property $P$ (such as `sirenActive`) **must** hold in *every* valid state, assert its negation `not(P)` and verify that `m.check()` returns `"Unsat"`. If it returns `"Sat"`, the solver's variable values give you a concrete counterexample (security loophole).
86
- - **One-Way Implication (`implies`) vs. Equivalence**: In classical logic, `` implies(expr`${luxLevel} <= 50`, isNight) `` only constrains `isNight` when `luxLevel <= 50`. During daytime (`luxLevel > 50`), `isNight` is unconstrained ("open-world" assumption) and could be assigned either `true` or `false` unless you also add the converse rule `` implies(expr`${luxLevel} >= 51`, not(isNight)) ``.
90
+ ### Proof by Refutation (Counterexample Search)
91
+
92
+ A single `"Sat"` result only shows that at least one valid assignment exists. To prove that a safety property `P` (such as `sirenActive`) always holds, add its negation `not(P)` and call `m.check()`. If the solver returns `"Unsat"`, no counterexample exists; if it returns `"Sat"`, the variable values show a concrete loophole.
93
+
94
+ In this example, the first check returns `"Sat"` with `sirenActive = true`, `lightsOn = true`, `isNight = true`, and the front door locked. Adding `not(sirenActive)` produces `"Unsat"` with a 6-rule proof core, automatically excluding the unrelated `lock_safety_rule` and `comfort_lights`.
95
+
96
+ ### One-Way Implication (`implies`) vs. Equivalence
97
+
98
+ The rule `` implies(expr`${luxLevel} <= 50`, isNight) `` only constrains `isNight` when `luxLevel <= 50` is true. When `luxLevel > 50`, `isNight` is unconstrained and may be assigned either `true` or `false`. To enforce an exact two-way equivalence, also add the converse rule `` implies(isNight, expr`${luxLevel} <= 50`) `` (or its logically equivalent inverse, `` implies(expr`${luxLevel} >= 51`, not(isNight)) ``).
99
+
100
+ ### Alternative Solver for Discrete Models
101
+
102
+ This model contains only `BoolVar` variables and bounded integers (`luxLevel` in `[0, 1000]`). As a result, the same deduction and counterexample proof also work out of the box with bundled Pumpkin via `m.check({ solver: "pumpkin" })`.
@@ -2,26 +2,26 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=transportation">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts">Source Code</a></li></ul> |
5
+ | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `constr.dual` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=transportation">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts">Source Code</a></li></ul> |
6
6
 
7
- The transportation problem is one of the most fundamental network optimization models: determine how many units to ship from each supply origin (factory) to each destination (store) to minimize total shipping cost while respecting factory supply limits and meeting store demands.
7
+ The **transportation problem** decides how many units to ship from each factory to each store. The goal is to minimize total shipping cost while respecting factory supply limits and meeting every store's demand.
8
8
 
9
- This example demonstrates how to construct a **2D matrix of decision variables** using `m.continuous(factories, stores)` and write aggregated constraints declaratively via `dot()` and `m.constraint(expr`...`)`.
9
+ This example builds a 2D decision-variable matrix with `m.continuous(factories, stores)`, writes the total cost objective with `dot()`, and expresses the row and column supply/demand constraints with `sum()` and ``m.constraint(expr`...`)``.
10
10
 
11
11
  ## Problem Inputs
12
12
 
13
- We have **3 factories** (`Tokyo`, `Nagoya`, `Osaka`) shipping to **4 regional stores** (`North`, `East`, `West`, `South`):
13
+ Three factories (`Tokyo`, `Nagoya`, `Osaka`) ship to four regional stores: `North`, `East`, `West`, and `South`.
14
14
 
15
- | Factory \ Store | North ($/unit) | East ($/unit) | West ($/unit) | South ($/unit) | Supply Capacity |
15
+ | Factory / Store | North ($/unit) | East ($/unit) | West ($/unit) | South ($/unit) | Supply Capacity |
16
16
  | :--- | :---: | :---: | :---: | :---: | :---: |
17
17
  | **Tokyo** | $4 | $2 | $7 | $8 | **120** units |
18
18
  | **Nagoya** | $6 | $4 | $3 | $5 | **100** units |
19
19
  | **Osaka** | $9 | $7 | $2 | $3 | **80** units |
20
- | **Store Demand** | **70** units | **90** units | **60** units | **60** units | Total: 280 / 300 |
20
+ | **Store Demand** | **70** units | **90** units | **60** units | **60** units | Demand 280 / Supply 300 |
21
21
 
22
22
  ## Mathematical Formulation
23
23
 
24
- Let $x_{f, s} \ge 0$ be the quantity shipped from factory $f \in F$ to store $s \in S$, and $c_{f, s}$ be the unit shipping cost.
24
+ Let $F$ be the set of factories, $S$ be the set of stores, $\text{Supply}_f$ be factory $f$'s supply capacity, $\text{Demand}_s$ be store $s$'s demand, $x_{f, s} \ge 0$ be the quantity shipped from $f \in F$ to $s \in S$, and $c_{f, s}$ be the unit shipping cost.
25
25
 
26
26
  $$\begin{aligned}
27
27
  \text{Minimize} \quad & \sum_{f \in F} \sum_{s \in S} c_{f,s} \, x_{f,s} \\
@@ -93,10 +93,10 @@ async function solveScenario(label: string, cap: typeof supplies) {
93
93
  }
94
94
 
95
95
  async function runTransportation() {
96
- // Scenario A: Baseline capacities ($920)
96
+ // Scenario A: Baseline capacities (Optimal: $880)
97
97
  await solveScenario("Scenario A: Baseline", supplies);
98
98
 
99
- // Scenario B: Tokyo capacity reduced (120 -> 80) due to maintenance ($1,000)
99
+ // Scenario B: Tokyo reduced (120 -> 80); Nagoya (100 -> 120) & Osaka (80 -> 100) expanded (Optimal: $940)
100
100
  await solveScenario("Scenario B: Tokyo Maintenance", {
101
101
  Tokyo: 80,
102
102
  Nagoya: 120,
@@ -111,7 +111,17 @@ runTransportation();
111
111
 
112
112
  ## Practical Notes
113
113
 
114
- - **Interpreting Supply & Demand Shadow Prices (`.dual`)**:
115
- - **`demand_s.dual` ($\ge 0$)**: The marginal delivered cost of supplying 1 additional unit to store $s$.
116
- - **`supply_f.dual` ($\le 0$)**: How much total network shipping cost would decrease if factory $f$'s capacity were expanded by 1 unit. In Scenario B, when Tokyo is constrained at 80 units, `supply_Tokyo.dual` becomes negative (`-$2/u`), indicating that each extra unit of capacity in Tokyo saves \$2 by avoiding rerouting through Nagoya.
117
- - **Total Supply vs. Total Demand ($\sum \text{Supply}_f \ge \sum \text{Demand}_s$)**: If store demands exceed aggregate factory capacity, the hard demand constraints become `"Infeasible"`. In production logistics systems, add an elastic "spot-carrier / backorder" variable $u_s \ge 0$ to each store's demand constraint ($\sum_f x_{f,s} + u_s \ge \text{Demand}_s$) with a high penalty cost so the solver allocates scarce inventory optimally rather than failing.
114
+ ### Supply & Demand Shadow Prices (`.dual`)
115
+
116
+ In a minimization LP, each constraint's **shadow price** (`.dual`) measures how much total cost changes when its right-hand side increases by 1 unit:
117
+
118
+ - **`demand_s.dual` ($\ge 0$):** Marginal delivered cost of supplying 1 extra unit to store $s$.
119
+ - **`supply_f.dual` ($\le 0$):** Marginal change in total shipping cost when factory $f$'s capacity increases by 1 unit (a negative value indicates cost savings).
120
+
121
+ Scenario A reaches an optimal cost of `$880`, and Scenario B reaches `$940`. In both scenarios, `Tokyo` is already at full capacity with `supply_Tokyo.dual = -$2/unit`. Each extra unit of capacity in Tokyo saves `$2` by replacing more expensive shipments from Nagoya. `Osaka` is also at its supply limit with a shadow price of `-$1/unit`.
122
+
123
+ ### Handling Supply Shortages
124
+
125
+ Hard demand constraints require total supply capacity to cover total demand ($\sum_{f \in F} \text{Supply}_f \ge \sum_{s \in S} \text{Demand}_s$). If total demand exceeds total factory capacity, HiGHS returns `"Infeasible"`.
126
+
127
+ To avoid hard failures during shortages, add a non-negative spot-carrier or backorder variable $u_s \ge 0$ to each store's demand constraint ($\sum_{f \in F} x_{f,s} + u_s \ge \text{Demand}_s$) and add a high penalty cost for $u_s$ to the objective. This lets the solver allocate scarce supply capacity optimally across stores.
@@ -4,15 +4,15 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Combinatorial OR / Benders | HiGHS (default) | `m.solveBenders()`, `subproblem`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
6
6
 
7
- The **Traveling Salesperson Problem (TSP)** seeks the shortest closed tour that visits every city in a given set once and returns to the starting city.
7
+ The **Traveling Salesperson Problem (TSP)** finds the shortest closed tour that visits every city once and returns to the starting city.
8
8
 
9
- In the **Dantzig-Fulkerson-Johnson (DFJ)** formulation, preventing disconnected cycles (**subtours**) requires subtour elimination constraints for every non-empty proper subset of cities $S \subset V$:
9
+ Let $V$ be the set of $n$ cities ($|V| = n$) and $x_{ij} \in \{0, 1\}$ indicate whether the tour travels directly from city $i$ to city $j$. In the **Dantzig-Fulkerson-Johnson (DFJ)** formulation, preventing disconnected cycles called **subtours** requires a subtour elimination constraint for every subset $S \subset V$ with $2 \le |S| \le n - 1$:
10
10
 
11
- $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S| \le |V| - 1$$
11
+ $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S| \le n - 1$$
12
12
 
13
- Because there are $2^n - 2$ subsets, enumerating all subtour constraints upfront is impractical as $n$ grows. With **Benders Decomposition (Lazy Constraint Separation)**, constraints are added only when violated:
14
- 1. **Master Problem**: Solves the degree-assignment relaxation (each city has 1 incoming and 1 outgoing edge).
15
- 2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds a **Benders Feasibility Cut** eliminating the smallest cycle and resolves until a single connected tour is obtained.
13
+ Because there are $2^n - n - 2$ such subsets, enumerating all subtour constraints upfront is impractical as $n$ grows. With **Lazy Constraint Separation (combinatorial Benders cuts via `solveBenders()`)**, constraints are added only when violated:
14
+ 1. **Master Problem**: Solves the degree-assignment relaxation, where each city has 1 incoming edge and 1 outgoing edge.
15
+ 2. **Separation Subproblem**: Traces cycles in the master solution. When disconnected cycles appear, it returns **Benders Feasibility Cuts** for all detected subtours at once (multi-cut separation) until a single tour remains.
16
16
 
17
17
  ## Problem Inputs
18
18
 
@@ -31,7 +31,7 @@ We consider **5 cities** on a 2D Euclidean coordinate grid:
31
31
  <CodeRunner>
32
32
 
33
33
  ```typescript
34
- import { Model, expr, minimize } from "@ohtaman/washi";
34
+ import { Model, expr, minimize, type Var } from "@ohtaman/washi";
35
35
 
36
36
  async function runTSP() {
37
37
  const cities = [
@@ -43,7 +43,7 @@ async function runTSP() {
43
43
  ];
44
44
  const n = cities.length;
45
45
 
46
- function dist(i, j) {
46
+ function dist(i: number, j: number): number {
47
47
  const dx = cities[i].x - cities[j].x;
48
48
  const dy = cities[i].y - cities[j].y;
49
49
  return Math.hypot(dx, dy);
@@ -51,8 +51,8 @@ async function runTSP() {
51
51
 
52
52
  // 1. Master Problem: Degree assignment relaxation
53
53
  const master = new Model("TSP_BendersMaster");
54
- const x = {};
55
- const distMatrix = {};
54
+ const x: Record<number, Record<number, Var>> = {};
55
+ const distMatrix: Record<number, Record<number, number>> = {};
56
56
 
57
57
  for (let i = 0; i < n; i++) {
58
58
  x[i] = {};
@@ -71,7 +71,7 @@ async function runTSP() {
71
71
  // Each city must have 1 outgoing and 1 incoming edge
72
72
  for (let i = 0; i < n; i++) {
73
73
  master.constraint(expr`sum(${x[i]}) == 1`, `out_${i}`);
74
- master.constraint(expr`sum(${n}, ${(j) => x[j][i]}) == 1`, `in_${i}`);
74
+ master.constraint(expr`sum(${n}, ${(j: number) => x[j][i]}) == 1`, `in_${i}`);
75
75
  }
76
76
 
77
77
  console.log("Solving TSP with Benders lazy subtour elimination...");
@@ -81,7 +81,7 @@ async function runTSP() {
81
81
  const result = await master.solveBenders({
82
82
  subproblem: () => {
83
83
  // Find active directed edges in the master solution
84
- const succ = {};
84
+ const succ: Record<number, number> = {};
85
85
  for (let i = 0; i < n; i++) {
86
86
  for (let j = 0; j < n; j++) {
87
87
  if (i !== j && x[i][j].value === 1) {
@@ -91,11 +91,11 @@ async function runTSP() {
91
91
  }
92
92
 
93
93
  // Trace connected cycles
94
- const visited = new Set();
95
- const cycles = [];
94
+ const visited = new Set<number>();
95
+ const cycles: number[][] = [];
96
96
  for (let i = 0; i < n; i++) {
97
97
  if (!visited.has(i)) {
98
- const cycle = [];
98
+ const cycle: number[] = [];
99
99
  let curr = i;
100
100
  while (!visited.has(curr)) {
101
101
  visited.add(curr);
@@ -117,7 +117,7 @@ async function runTSP() {
117
117
  const cutEdges = cycle.flatMap((i) => outCities.map((j) => x[i][j]));
118
118
 
119
119
  return {
120
- kind: "feasibility",
120
+ kind: "feasibility" as const,
121
121
  constraint: expr`sum(${cutEdges}) >= 1`,
122
122
  name: `subtour_cut_${cutCounter}`,
123
123
  };
@@ -148,10 +148,22 @@ runTSP();
148
148
 
149
149
  </CodeRunner>
150
150
 
151
- ## Notes
151
+ ## Key Takeaways
152
152
 
153
- - **Lazy Subtour Elimination**: The master problem starts with only the $2n$ degree constraints, and subtour elimination cuts are added on demand when disconnected cycles appear in the master solution.
154
- - **Multi-Cut Separation**: Returning an array of cuts (`cycles.map(...)`) from `subproblem` eliminates all disconnected cycles discovered in the current candidate solution simultaneously, reducing the number of master MIP re-solves.
155
- - **Two Equivalent DFJ Cut Forms**: Because every city has out-degree $\sum_{j \ne i} x_{ij} = 1$, summing over $i \in S$ gives $\sum_{i \in S, j \in S} x_{ij} + \sum_{i \in S, j \notin S} x_{ij} = |S|$. Thus the cut-set inequality $\sum_{i \in S, j \notin S} x_{ij} \ge 1$ used above and the internal-edge inequality $\sum_{i \in S, j \in S} x_{ij} \le |S| - 1$ used in [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts) are algebraically identical.
156
- - **Upfront 2-City Subtour Elimination**: In larger TSP instances, mutual 2-cycles ($i \leftrightarrow j$) are the most frequent initial subtours. Adding the $\binom{n}{2}$ pairwise constraints $x_{ij} + x_{ji} \le 1$ directly to the initial master problem often cuts the number of Benders iterations substantially.
157
- - **Termination Condition**: Returning `null` from `subproblem` indicates that no violated subtour constraints remain.
153
+ This 5-city instance converges in **2 iterations**. In Iteration 1, the assignment relaxation splits the cities into two subtours (`[A -> B]` and `[C -> E -> D]`), and multi-cut separation adds 2 Benders feasibility cuts at once. In Iteration 2, the master problem finds the optimal single tour with total distance `7.236` ($5 + \sqrt{5}$).
154
+
155
+ ### Lazy Subtour Elimination & Multi-Cut Separation
156
+
157
+ The master problem starts with only $2n$ degree constraints, and `subproblem` adds cuts only when disconnected cycles appear. Returning an array of cuts (`cycles.map(...)`) eliminates every subtour in the current candidate at once, reducing master MIP re-solves. Returning `null` stops the loop once a single connected tour is found.
158
+
159
+ ### Two Equivalent DFJ Cut Forms
160
+
161
+ Every city satisfies the out-degree equation $\sum_{j \ne i} x_{ij} = 1$. Summing this identity over all $i \in S$ gives:
162
+
163
+ $$\sum_{i \in S, \, j \in S, \, j \ne i} x_{ij} + \sum_{i \in S, \, j \notin S} x_{ij} = |S|$$
164
+
165
+ Therefore, the cut-set inequality $\sum_{i \in S, j \notin S} x_{ij} \ge 1$ used above is algebraically identical to the internal-edge form $\sum_{i \in S, \, j \in S, \, j \ne i} x_{ij} \le |S| - 1$ used in [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts).
166
+
167
+ ### Upfront 2-City Subtour Elimination
168
+
169
+ In larger TSP instances, mutual 2-cycles ($i \leftrightarrow j$) are the most frequent early subtours. Adding the $\binom{n}{2}$ pairwise constraints $x_{ij} + x_{ji} \le 1$ ($i < j$) to the initial master problem often cuts the number of Benders iterations substantially.