@ohtaman/washi 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.ja.md +139 -418
  2. package/README.md +139 -418
  3. package/README.zh-CN.md +139 -418
  4. package/THIRD_PARTY_LICENSES.md +39 -4
  5. package/dist/browser/__vite-browser-external-rTVKos2U.js +7 -0
  6. package/dist/browser/browser-runtime-AG5QFtKf.js +2021 -0
  7. package/dist/browser/highs-worker.js +26 -11
  8. package/dist/browser/highs.wasm +0 -0
  9. package/dist/browser/{loader-DewlSho8.js → loader-i3FnqMes.js} +183 -149
  10. package/dist/browser/solvers/glpk.js +289 -238
  11. package/dist/browser/solvers/glpk.min.js +1 -1
  12. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  13. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  14. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  15. package/dist/browser/solvers/pumpkin.js +1777 -0
  16. package/dist/browser/solvers/pumpkin.min.js +1 -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 +3828 -1315
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/highs-browser-runtime.js +1846 -1618
  25. package/dist/lib/highs-runtime.js +16 -2
  26. package/dist/lib/highs-worker.js +26 -11
  27. package/dist/lib/highs.wasm +0 -0
  28. package/dist/lib/{loader-BZUQNvh4.js → loader-CDpPXN_F.js} +138 -116
  29. package/dist/lib/registry-dx7x4e5c.js +1694 -0
  30. package/dist/lib/rolldown-runtime-DtPi1Y-2.js +13 -0
  31. package/dist/lib/solvers/glpk.js +161 -121
  32. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  33. package/dist/lib/solvers/pumpkin-loader-Ow74Fa1B.js +311 -0
  34. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  35. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  36. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  37. package/dist/lib/solvers/pumpkin.js +1767 -0
  38. package/dist/lib/solvers/pumpkin.wasm +0 -0
  39. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  40. package/dist/lib/solvers/z3.js +486 -306
  41. package/dist/lib/washi.js +3054 -1202
  42. package/dist/types/decomposition/benders.d.ts.map +1 -1
  43. package/dist/types/index.d.ts +3 -3
  44. package/dist/types/index.d.ts.map +1 -1
  45. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  46. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  47. package/dist/types/modeler/constraint.d.ts +40 -4
  48. package/dist/types/modeler/constraint.d.ts.map +1 -1
  49. package/dist/types/modeler/expression.d.ts +176 -28
  50. package/dist/types/modeler/expression.d.ts.map +1 -1
  51. package/dist/types/modeler/index.d.ts +5 -6
  52. package/dist/types/modeler/index.d.ts.map +1 -1
  53. package/dist/types/modeler/linearizer.d.ts +11 -2
  54. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  55. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  56. package/dist/types/modeler/model.d.ts +97 -130
  57. package/dist/types/modeler/model.d.ts.map +1 -1
  58. package/dist/types/modeler/parser.d.ts +25 -5
  59. package/dist/types/modeler/parser.d.ts.map +1 -1
  60. package/dist/types/modeler/quad-expr.d.ts +8 -2
  61. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  62. package/dist/types/modeler/solution-validator.d.ts +12 -12
  63. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  64. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  65. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  66. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  67. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  68. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  69. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  70. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  72. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  73. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  74. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  75. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  76. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  77. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  78. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  79. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  80. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  81. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  82. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  83. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  84. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  85. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  86. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  87. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  88. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  89. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  90. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  91. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  92. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  93. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  94. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  95. package/dist/types/modeler/solvers/types.d.ts +9 -9
  96. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  97. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  98. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  99. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  100. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  101. package/dist/types/modeler/types.d.ts +12 -15
  102. package/dist/types/modeler/types.d.ts.map +1 -1
  103. package/dist/types/modeler/validation.d.ts +26 -2
  104. package/dist/types/modeler/validation.d.ts.map +1 -1
  105. package/dist/types/modeler/variable.d.ts +9 -5
  106. package/dist/types/modeler/variable.d.ts.map +1 -1
  107. package/docs/examples/diet-sensitivity.md +15 -14
  108. package/docs/examples/ecommerce-coupons.md +15 -22
  109. package/docs/examples/index.md +20 -13
  110. package/docs/examples/knapsack.md +8 -7
  111. package/docs/examples/portfolio-qp.md +11 -4
  112. package/docs/examples/production.md +4 -4
  113. package/docs/examples/project-scheduling.md +106 -0
  114. package/docs/examples/shift-scheduling.md +23 -7
  115. package/docs/examples/smt-security.md +17 -4
  116. package/docs/examples/transportation.md +46 -19
  117. package/docs/examples/traveling-salesperson.md +29 -45
  118. package/docs/examples/unsat-core.md +16 -5
  119. package/docs/examples/vehicle-routing.md +10 -8
  120. package/docs/getting-started/ai-agents.md +114 -34
  121. package/docs/getting-started/coding-agents.md +158 -0
  122. package/docs/getting-started/cross-origin.md +56 -28
  123. package/docs/getting-started/index.md +36 -66
  124. package/docs/getting-started/runtimes.md +98 -69
  125. package/docs/guide/constraint-programming.md +141 -0
  126. package/docs/guide/constraints.md +100 -44
  127. package/docs/guide/decomposition.md +141 -273
  128. package/docs/guide/expressions.md +125 -42
  129. package/docs/guide/formulation-tips.md +212 -0
  130. package/docs/guide/objectives.md +70 -64
  131. package/docs/guide/unsat-core.md +44 -23
  132. package/docs/guide/variables.md +56 -48
  133. package/docs/solvers/custom-solver.md +18 -13
  134. package/docs/solvers/highs.md +41 -25
  135. package/docs/solvers/index.md +13 -7
  136. package/docs/solvers/pumpkin.md +163 -0
  137. package/docs/solvers/z3.md +4 -1
  138. package/llms-full.txt +1732 -860
  139. package/llms.txt +59 -36
  140. package/package.json +40 -13
  141. package/skills/washi/SKILL.md +91 -35
  142. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  143. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  144. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  145. package/dist/lib/registry-C20sxTwm.js +0 -964
  146. package/docs/ja/getting-started/ai-agents.md +0 -270
  147. package/docs/zh/getting-started/ai-agents.md +0 -270
@@ -1,20 +1,21 @@
1
1
  # Examples & API Finder
2
2
 
3
- Explore runnable optimization and logic formulations built with WaSHI. Every example can be executed directly inside its documentation page, or edited in the [Playground](https://ohtaman.github.io/washi/demo/).
3
+ Explore runnable optimization and logic formulations built with WaSHI. Every example can be executed directly inside its documentation page, or edited in the [Playground](https://washi.ohtaman.dev/demo/).
4
4
 
5
5
  ## Examples
6
6
 
7
- | Example | Problem Class | Solver | Key WaSHI APIs | Description | Code Editor |
7
+ | Example | Problem Class | Solver | Key WaSHI APIs | Description | Playground / Guide |
8
8
  | :--- | :--- | :--- | :--- | :--- | :--- |
9
- | **[Production Planning](./production.md)** | LP / MIP | HiGHS | `m.integer()`, `m.constraint()`, `expr` | Basic variables, tagged template literal equations, and maximizing profit under resource limits. | [Playground](https://ohtaman.github.io/washi/demo/?preset=production) |
10
- | **[0-1 Knapsack](./knapsack.md)** | Binary MIP | HiGHS | `m.binary(keys)`, `sum()`, `m.constraint()` | 1D dictionary of `Binary` variables and linear aggregation over item arrays. | [Playground](https://ohtaman.github.io/washi/demo/?preset=knapsack) |
11
- | **[Transportation Network](./transportation.md)** | LP | HiGHS | `m.continuous(rows, cols)`, `dot()`, `m.constraint()` | 2D matrix indexing (`ship[factory][store]`) and row/column flow balance constraints. | [Playground](https://ohtaman.github.io/washi/demo/?preset=transportation) |
12
- | **[Diet & Sensitivity Analysis](./diet-sensitivity.md)** | LP | HiGHS | `constr.dual`, `constr.slack`, `var.reducedCost` | Reading shadow prices (bottlenecks), constraint surpluses, and reduced costs after solving. | [Playground](https://ohtaman.github.io/washi/demo/?preset=diet_sensitivity) |
13
- | **[Staff Shift Scheduling](./shift-scheduling.md)** | Binary MIP + Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `check()`, `unsatCore` | 5×7 weekly roster planner (coverage, senior duty, max shifts, day-off requests) and diagnosing conflicting vacation requests with Z3 `unsatCore`. | [Playground](https://ohtaman.github.io/washi/demo/?preset=shift_scheduling) |
14
- | **[E-Commerce Coupon Optimizer](./ecommerce-coupons.md)** | Indicator MIP | HiGHS | `m.indicator()`, `sum()`, `m.constraint()` | Checkout optimizer using `m.indicator()` for minimum spend thresholds, exclusive vs. stackable rules, and smart filler add-on suggestions. | [Playground](https://ohtaman.github.io/washi/demo/?preset=cart_coupon) |
15
- | **[Portfolio Optimization](./portfolio-qp.md)** | Convex QP | HiGHS | `m.continuous()`, `m.constraint()`, `dot()`, `QuadExpr` | Markowitz mean-variance risk minimization ($w^T \Sigma w$) using `QuadExpr` subject to return targets. | [Playground](https://ohtaman.github.io/washi/demo/?preset=portfolio_qp) |
16
- | **[SMT Security Policies](./smt-security.md)** | SMT Logic | Z3 | `m.bool()`, `m.constraint()`, `m.check()` | Propositional variables (`BoolVar`) and logical connectives (`implies`, `and`, `not`, `xor`) mixed with integer bounds. | [Playground](https://ohtaman.github.io/washi/demo/?preset=smt_sat_scheduling) |
17
- | **[Conflict Diagnosis (`unsatCore`)](./unsat-core.md)** | Unsat Core | Z3 | `m.constraint()`, `m.check()`, `m.unsatCore` | Extracting a conflicting constraint subset (`unsatCore`) when staffing and budget rules contradict each other. | [Playground](https://ohtaman.github.io/washi/demo/?preset=conflict_diagnosis_unsat) |
9
+ | **[Production Planning](./production.md)** | LP / MIP | HiGHS | `m.integer()`, `m.constraint()`, `expr` | Basic variables, tagged template literal equations, and maximizing profit under resource limits. | [Playground](https://washi.ohtaman.dev/demo/?preset=production) |
10
+ | **[0-1 Knapsack](./knapsack.md)** | Binary MIP | HiGHS | `m.binary(keys)`, `expr` (`dot`), `m.constraint()` | 1D dictionary of `Binary` variables and linear aggregation over item arrays. | [Playground](https://washi.ohtaman.dev/demo/?preset=knapsack) |
11
+ | **[Transportation Network](./transportation.md)** | LP | HiGHS | `m.continuous(rows, cols)`, `expr` (`sum`, `dot`), `m.constraint()` | 2D matrix indexing (`ship[factory][store]`) and row/column flow balance constraints. | [Playground](https://washi.ohtaman.dev/demo/?preset=transportation) |
12
+ | **[Diet & Sensitivity Analysis](./diet-sensitivity.md)** | LP | HiGHS | `constr.dual`, `constr.slack`, `var.reducedCost` | Reading shadow prices (bottlenecks), constraint surpluses, and reduced costs after solving. | [Playground](https://washi.ohtaman.dev/demo/?preset=diet_sensitivity) |
13
+ | **[Staff Shift Scheduling](./shift-scheduling.md)** | Binary MIP + Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `check()`, `unsatCore` | 5×7 weekly roster planner (coverage, senior duty, max shifts, day-off requests) and diagnosing conflicting vacation requests with Z3 `unsatCore`. | [Playground](https://washi.ohtaman.dev/demo/?preset=shift_scheduling) |
14
+ | **[E-Commerce Coupon Optimizer](./ecommerce-coupons.md)** | Indicator MIP | HiGHS | `m.indicator()`, `expr` (`sum`, `dot`), `m.constraint()` | Checkout optimizer using `m.indicator()` for minimum spend thresholds, exclusive vs. stackable rules, and smart filler add-on suggestions. | [Playground](https://washi.ohtaman.dev/demo/?preset=cart_coupon) |
15
+ | **[Portfolio Optimization](./portfolio-qp.md)** | Convex QP | HiGHS | `m.continuous()`, `m.constraint()`, `dot()`, `QuadExpr` | Markowitz mean-variance risk minimization ($w^T \Sigma w$) using `QuadExpr` subject to return targets. | [Playground](https://washi.ohtaman.dev/demo/?preset=portfolio_qp) |
16
+ | **[Project Scheduling (RCPSP)](./project-scheduling.md)** | CP / LCG + Unsat Core | Pumpkin | `m.integer()`, `disjoint()`, `cumulative()`, `max()`, `m.check()` | 6-task resource-constrained schedule (unary rig + 3-engineer crew limit) and zero-`COOP`/`COEP` `unsatCore` deadline conflict check. | [Playground](https://washi.ohtaman.dev/demo/?preset=project_scheduling) |
17
+ | **[SMT Security Policies](./smt-security.md)** | SMT Logic | Z3 | `m.bool()`, `m.constraint()`, `m.check()` | Propositional variables (`BoolVar`) and logical connectives (`implies`, `and`, `not`, `xor`) mixed with integer bounds. | [Playground](https://washi.ohtaman.dev/demo/?preset=smt_security) |
18
+ | **[Conflict Diagnosis (`unsatCore`)](./unsat-core.md)** | Unsat Core | Z3 | `m.constraint()`, `m.check()`, `m.unsatCore` | Extracting a conflicting constraint subset (`unsatCore`) when staffing and budget rules contradict each other. | [Playground](https://washi.ohtaman.dev/demo/?preset=conflict_diagnosis_unsat) |
18
19
  | **[Vehicle Routing (CVRP)](./vehicle-routing.md)** | Combinatorial OR / Dantzig-Wolfe | HiGHS | `m.solveColumnGeneration()`, `pricing` | Dynamic route column generation from customer dual shadow prices to minimize total fleet vehicles. | [Decomposition Guide](../guide/decomposition.md) |
19
20
  | **[Traveling Salesperson (TSP)](./traveling-salesperson.md)** | Combinatorial OR / Benders | HiGHS | `m.solveBenders()`, `subproblem` | Subtour elimination on degree-assignment relaxation using dynamic Benders feasibility cuts. | [Decomposition Guide](../guide/decomposition.md) |
20
21
 
@@ -27,15 +28,18 @@ Looking for a specific modeling method or solver capability? Jump straight to th
27
28
  | ``m.constraint(expr`...`)`` | Tagged template literal constraints | [Production Planning](./production.md) | [`01-production-planning.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/01-production-planning.ts) |
28
29
  | `m.binary(keys)` / `m.continuous(keys)` | 1D dictionary of indexed variables | [0-1 Knapsack](./knapsack.md) | [`02-knapsack-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/02-knapsack-problem.ts) |
29
30
  | `m.continuous(rows, cols)` / `m.binary(rows, cols)` | 2D matrix of indexed variables | [Transportation Network](./transportation.md), [Shift Scheduling](./shift-scheduling.md) | [`09-transportation-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts) |
30
- | `dot(matrix, vars2d)` / `dot(vector, vars)` | Fast vector/matrix dot product | [Transportation Network](./transportation.md), [Portfolio Optimization](./portfolio-qp.md) | [`09-transportation-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts) |
31
+ | ``expr`dot(${A}, ${X})` `` / `dot(A, X)` | Fast vector/matrix dot product | [Transportation Network](./transportation.md), [Portfolio Optimization](./portfolio-qp.md) | [`09-transportation-problem.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts) |
31
32
  | `constr.dual` & `constr.slack` | Shadow prices & constraint surpluses | [Diet & Sensitivity Analysis](./diet-sensitivity.md) | [`10-diet-sensitivity.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/10-diet-sensitivity.ts) |
32
33
  | `var.reducedCost` | Variable reduced costs in LP | [Diet & Sensitivity Analysis](./diet-sensitivity.md) | [`10-diet-sensitivity.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/10-diet-sensitivity.ts) |
33
34
  | `m.indicator()` | Big-M conditional constraints (`binVar => constr`) | [E-Commerce Coupon Optimizer](./ecommerce-coupons.md) | [`12-ecommerce-coupon-optimizer.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/12-ecommerce-coupon-optimizer.ts) |
34
35
  | `new QuadExpr()` | Convex quadratic objectives ($x^T Q x$) | [Portfolio Optimization](./portfolio-qp.md) | [`03-portfolio-qp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/03-portfolio-qp.ts) |
35
- | `m.bool()` & `.implies()` | Propositional logic & SMT rules | [SMT Security Policies](./smt-security.md) | [`04-smt-security-rules.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts) |
36
+ | `m.bool()` & `implies()` | Propositional logic & SMT rules | [SMT Security Policies](./smt-security.md) | [`04-smt-security-rules.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts) |
36
37
  | `m.check()` & `m.unsatCore` | Feasibility check & conflict diagnosis | [Conflict Diagnosis](./unsat-core.md), [Shift Scheduling](./shift-scheduling.md) | [`05-unsat-core-diagnosis.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts) |
37
38
  | `m.solveColumnGeneration()` | Dantzig-Wolfe Column Generation | [Vehicle Routing](./vehicle-routing.md) | [`13-vehicle-routing-column-generation.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts) |
38
39
  | `m.solveBenders()` | Benders Decomposition & cut separation | [Traveling Salesperson](./traveling-salesperson.md) | [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts) |
40
+ | `distinct()` / `disjoint()` / `cumulative()` / `allowed()` | Backend-agnostic CP global constraints | [Project Scheduling](./project-scheduling.md), [CP Modeling Guide](../guide/constraint-programming.md) | [`15-project-scheduling-cp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts) |
41
+ | `max()` / `min()` / `abs()` / `at()` | Piecewise-linear & element lookup primitives | [Project Scheduling](./project-scheduling.md), [Expressions Guide](../guide/expressions.md) | [`15-project-scheduling-cp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts) |
42
+ | `solver: "pumpkin"` | Bundled CP/LCG scheduling & zero-`COOP`/`COEP` `unsatCore` | [Project Scheduling](./project-scheduling.md), [Pumpkin Solver Guide](../solvers/pumpkin.md) | [`15-project-scheduling-cp.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts) |
39
43
  | `solver: "glpk"` | Solving LP/MIP with GLPK plugin | [GLPK Solver Guide](../solvers/glpk.md) | [`08-glpk-solver-plugin.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/08-glpk-solver-plugin.ts) |
40
44
 
41
45
  ## Running Examples Locally in Node.js
@@ -54,4 +58,7 @@ npx tsx examples/node/09-transportation-problem.ts
54
58
  npx tsx examples/node/10-diet-sensitivity.ts
55
59
  npx tsx examples/node/11-shift-scheduling.ts
56
60
  npx tsx examples/node/12-ecommerce-coupon-optimizer.ts
61
+ npx tsx examples/node/13-vehicle-routing-column-generation.ts
62
+ npx tsx examples/node/14-traveling-salesperson-benders.ts
63
+ npx tsx examples/node/15-project-scheduling-cp.ts
57
64
  ```
@@ -2,7 +2,7 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | 0-1 Binary MIP | HiGHS (default) | `m.binary()`, `m.constraint()`, `expr`, `maximize`, `dot` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=knapsack">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/02-knapsack-problem.ts">Source Code</a></li></ul> |
5
+ | 0-1 Binary MIP | HiGHS (default) | `m.binary()`, `m.constraint()`, `expr` (`dot`), `maximize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=knapsack">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/02-knapsack-problem.ts">Source Code</a></li></ul> |
6
6
 
7
7
  The 0-1 Knapsack problem is an essential combinatorial optimization problem: given a set of items, each with a weight and a value, determine which items to include in a collection so that the total weight does not exceed a given limit and the total value is maximized.
8
8
 
@@ -21,7 +21,7 @@ $$\begin{aligned}
21
21
  <CodeRunner preset="knapsack">
22
22
 
23
23
  ```typescript
24
- import { Model, maximize, dot, expr } from "@ohtaman/washi";
24
+ import { Model, maximize, expr } from "@ohtaman/washi";
25
25
 
26
26
  async function solveKnapsack() {
27
27
  const m = new Model("Knapsack");
@@ -41,17 +41,18 @@ async function solveKnapsack() {
41
41
  const values = Object.fromEntries(items.map((it) => [it.name, it.value]));
42
42
  const weights = Object.fromEntries(items.map((it) => [it.name, it.weight]));
43
43
 
44
- // Maximize total value via dot product
45
- m.objective(maximize(dot(values, x)));
44
+ // Maximize total value via dot() inside expr
45
+ m.objective(maximize(expr`dot(${values}, ${x})`));
46
46
 
47
- // Weight capacity constraint using natural expr and constraint() syntax
48
- m.constraint(expr`${dot(weights, x)} <= ${maxCapacity}`, "capacity_limit");
47
+ // Weight capacity constraint using expr and constraint()
48
+ m.constraint(expr`dot(${weights}, ${x}) <= ${maxCapacity}`, "capacity_limit");
49
49
 
50
50
  const status = await m.solve();
51
51
 
52
52
  console.log(`Status: ${status}`);
53
53
  console.log(`Max Total Value: $${m.objectiveValue}`);
54
- console.log("Selected Items:", m.getValues(x));
54
+ const packed = items.filter((it) => x[it.name].value === 1).map((it) => it.name);
55
+ console.log("Packed Items:", packed.join(", "));
55
56
  }
56
57
 
57
58
  solveKnapsack();
@@ -2,7 +2,7 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Convex Quadratic Programming (QP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot`, `QuadExpr` | <ul><li><a href="https://ohtaman.github.io/washi/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> |
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
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.
8
8
 
@@ -26,7 +26,7 @@ where $\boldsymbol{\Sigma}$ is the positive semi-definite asset return covarianc
26
26
  <CodeRunner preset="portfolio_qp">
27
27
 
28
28
  ```typescript
29
- import { Model, QuadExpr, sum, dot, minimize, expr } from "@ohtaman/washi";
29
+ import { Model, QuadExpr, dot, minimize, expr } from "@ohtaman/washi";
30
30
 
31
31
  async function solvePortfolio() {
32
32
  const m = new Model("PortfolioQP");
@@ -48,11 +48,12 @@ async function solvePortfolio() {
48
48
  const w = m.continuous(assets, { lb: 0, ub: 1 });
49
49
 
50
50
  // 1. Budget constraint: sum(w_i) == 1.0 (100%)
51
- m.constraint(expr`${sum(assets, (a) => w[a])} == 1.0`, "budget_limit");
51
+ m.constraint(expr`sum(${w}) == 1.0`, "budget_limit");
52
52
 
53
53
  // 2. Expected return constraint: sum(r_i * w_i) >= 8.5%
54
54
  const retMap = Object.fromEntries(assets.map((a, i) => [a, expectedReturns[i]]));
55
- m.constraint(expr`${dot(retMap, w)} >= ${targetReturn}`, "target_return");
55
+ const portfolioReturn = dot(retMap, w);
56
+ m.constraint(expr`${portfolioReturn} >= ${targetReturn}`, "target_return");
56
57
 
57
58
  // 3. Quadratic Objective: minimize risk w^T * Sigma * w
58
59
  let risk = new QuadExpr();
@@ -71,6 +72,7 @@ async function solvePortfolio() {
71
72
  console.log(`Status: ${status}`);
72
73
  console.log(`Variance: ${m.objectiveValue?.toFixed(6)}`);
73
74
  console.log(`Volatility (Std Dev): ${((Math.sqrt(m.objectiveValue || 0)) * 100).toFixed(2)}%`);
75
+ console.log(`Expected Return: ${((portfolioReturn.value ?? 0) * 100).toFixed(2)}% (target >= ${(targetReturn * 100).toFixed(2)}%)`);
74
76
 
75
77
  assets.forEach((name) => {
76
78
  console.log(` ${name.padEnd(10)}: ${((w[name].value ?? 0) * 100).toFixed(2)}%`);
@@ -81,3 +83,8 @@ solvePortfolio();
81
83
  ```
82
84
 
83
85
  </CodeRunner>
86
+
87
+ ## Practical Notes
88
+
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})$.
@@ -2,7 +2,7 @@
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://ohtaman.github.io/washi/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
+ | 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> |
6
6
 
7
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).
8
8
 
@@ -34,9 +34,9 @@ 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 fluent constraint()
38
- m.constraint(expr`5 * ${chairs} + 20 * ${tables} <= 400`, "mahogany_limit")
39
- .constraint(expr`10 * ${chairs} + 15 * ${tables} <= 450`, "labor_limit");
37
+ // Resource constraints: declarative formulas via expr and constraint()
38
+ m.constraint(expr`5 * ${chairs} + 20 * ${tables} <= 400`, "mahogany_limit");
39
+ m.constraint(expr`10 * ${chairs} + 15 * ${tables} <= 450`, "labor_limit");
40
40
 
41
41
  const status = await m.solve();
42
42
 
@@ -0,0 +1,106 @@
1
+ # Resource-Constrained Project Scheduling (CP / Pumpkin)
2
+
3
+ | Problem Class | Solver | Key APIs | Links |
4
+ | :--- | :--- | :--- | :--- |
5
+ | CP / LCG (RCPSP & Unsat Core) | Pumpkin (`@ohtaman/washi/solvers/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)** models project tasks governed simultaneously by **precedence dependencies**, **unary shared equipment** (disjunctive resource), and **limited renewable team headcount** (cumulative resource).
8
+
9
+ Using WaSHI's bundled **Pumpkin** solver (`@ohtaman/washi/solvers/pumpkin`):
10
+ 1. Every task needs only **one finite-domain start variable** (`start[task]`), avoiding $O(|T| \cdot H)$ time-indexed binary variables.
11
+ 2. When adding tighter maintenance windows or rush shipping deadlines causes infeasibility, `m.check()` extracts the conflicting rule subset (`unsatCore`) client-side with **zero `COOP` / `COEP` headers**.
12
+
13
+ ## Problem Inputs
14
+
15
+ We schedule **6 hardware prototype tasks** over a 24-hour window (`crewCapacity = 3` engineers, 1 shared Hardware-in-the-Loop (HIL) 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
+ Notice that ignoring crew capacity gives a naive critical path of `9h` (`chassis 4h -> assembly 3h -> test 2h`), whereas respecting the `crewCapacity = 3` constraint prevents `{chassis, board, assembly}` (2 engineers each) from overlapping, making the true minimum makespan **`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
+ import "@ohtaman/washi/solvers/pumpkin";
35
+
36
+ async function runProjectScheduling() {
37
+ const horizon = 24;
38
+ const crewCapacity = 3;
39
+ const tasks = [
40
+ { id: "chassis", duration: 4, crew: 2, usesRig: false },
41
+ { id: "board", duration: 3, crew: 2, usesRig: false },
42
+ { id: "firmware", duration: 4, crew: 1, usesRig: true },
43
+ { id: "assembly", duration: 3, crew: 2, usesRig: false },
44
+ { id: "calib", duration: 3, crew: 1, usesRig: true },
45
+ { id: "test", duration: 2, crew: 2, usesRig: true },
46
+ ] as const;
47
+
48
+ const m = new Model("PrototypeRCPSP", { solver: "pumpkin" });
49
+ const start = m.integer(tasks.map((t) => t.id), { lb: 0, ub: horizon, prefix: "start" });
50
+
51
+ // 1. Precedence network
52
+ m.constraint(expr`${start.chassis} + 4 <= ${start.assembly}`, "assembly_after_chassis");
53
+ m.constraint(expr`${start.board} + 3 <= ${start.assembly}`, "assembly_after_board");
54
+ m.constraint(expr`${start.board} + 3 <= ${start.calib}`, "calib_after_board");
55
+ m.constraint(expr`${start.assembly} + 3 <= ${start.test}`, "test_after_assembly");
56
+ m.constraint(expr`${start.firmware} + 4 <= ${start.test}`, "test_after_firmware");
57
+ m.constraint(expr`${start.calib} + 3 <= ${start.test}`, "test_after_calib");
58
+
59
+ // 2. Exclusive HIL / calibration rig & 3-engineer cumulative limit
60
+ m.constraint(
61
+ disjoint(tasks.filter((t) => t.usesRig).map((t) => ({ start: start[t.id], duration: t.duration }))),
62
+ "single_rig"
63
+ );
64
+ m.constraint(
65
+ cumulative(
66
+ tasks.map((t) => ({ start: start[t.id], duration: t.duration, demand: t.crew })),
67
+ crewCapacity
68
+ ),
69
+ "crew_limit"
70
+ );
71
+
72
+ // 3. Minimize project makespan: max_t (start[t] + duration[t])
73
+ const makespan = max(tasks.map((t) => expr`${start[t.id]} + ${t.duration}`));
74
+ m.objective(minimize(makespan));
75
+
76
+ const status = await m.solve();
77
+ const optMakespan = m.objectiveValue;
78
+ const report = m.verify();
79
+ console.log(`Status: ${status} (valid: ${report.valid}), Minimum Makespan: ${optMakespan}h`);
80
+ for (const t of tasks) {
81
+ const s = start[t.id].value ?? 0;
82
+ console.log(` ${t.id}: [${s}h, ${s + t.duration}h) crew=${t.crew}${t.usesRig ? " [Rig]" : ""}`);
83
+ }
84
+
85
+ // 4. Diagnose an impossible rush deadline when the rig is offline for maintenance [0, 6)
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
+ - **Why Pumpkin shines here**: Combining `disjoint` (edge-finding) and `cumulative` (time-table propagation) directly on bounded integers lets Pumpkin learn why a schedule bottlenecks (`crew_limit` or `single_rig`) cleanly through Lazy Clause Generation, with zero time-indexed binary variables.
105
+ - **Snapshot `m.objectiveValue` before `m.check()`**: Calling `await m.check()` on the same `Model` clears prior `solve()` fields (`m.objectiveValue` becomes `null`), so capture optimization outputs before running feasibility/conflict checks.
106
+ - **Client-side `unsatCore` without `COOP` / `COEP`**: Notice that `diag.unsatCore` excludes unrelated `crew_limit` while isolating the rig maintenance (`firmware >= 6`, `calib >= 6`), `assembly -> test` chain (`test >= 7`), unary `single_rig` total of 9h ($\implies \text{completion} \ge 15 > 13$), and `rush_ship_deadline`.
@@ -2,7 +2,7 @@
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`, `minimize`, `dot`, `m.check()` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://ohtaman.github.io/washi/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()` | <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
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`.
8
8
 
@@ -35,7 +35,7 @@ We evaluate two distinct, named scenarios with different vacation inputs to illu
35
35
  <CodeRunner preset="shift_scheduling">
36
36
 
37
37
  ```typescript
38
- import { Model, sum, dot, minimize, expr } from "@ohtaman/washi";
38
+ import { Model, minimize, expr } from "@ohtaman/washi";
39
39
  import "@ohtaman/washi/solvers/z3";
40
40
 
41
41
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
@@ -68,12 +68,12 @@ function buildShiftModel(name: string, dayOffRequests: Array<{ staff: string; da
68
68
  ),
69
69
  ])
70
70
  );
71
- m.objective(minimize(dot(costMatrix, shift)));
71
+ m.objective(minimize(expr`dot(${costMatrix}, ${shift})`));
72
72
 
73
73
  // Rule 1: Daily headcount coverage
74
74
  for (const d of days) {
75
75
  m.constraint(
76
- expr`${sum(staffList, (s) => shift[s.name][d])} >= ${requiredCoverage[d]}`,
76
+ expr`sum(${staffList}, ${(s) => shift[s.name][d]}) >= ${requiredCoverage[d]}`,
77
77
  `coverage_${d}`
78
78
  );
79
79
  }
@@ -82,7 +82,7 @@ function buildShiftModel(name: string, dayOffRequests: Array<{ staff: string; da
82
82
  const seniors = staffList.filter((s) => s.isSenior);
83
83
  for (const d of days) {
84
84
  m.constraint(
85
- expr`${sum(seniors, (s) => shift[s.name][d])} >= 1`,
85
+ expr`sum(${seniors}, ${(s) => shift[s.name][d]}) >= 1`,
86
86
  `senior_duty_${d}`
87
87
  );
88
88
  }
@@ -90,7 +90,7 @@ function buildShiftModel(name: string, dayOffRequests: Array<{ staff: string; da
90
90
  // Rule 3: Max working days per staff member
91
91
  for (const s of staffList) {
92
92
  m.constraint(
93
- expr`${sum(days, (d) => shift[s.name][d])} <= ${s.maxShifts}`,
93
+ expr`sum(${shift[s.name]}) <= ${s.maxShifts}`,
94
94
  `max_shifts_${s.name}`
95
95
  );
96
96
  }
@@ -126,7 +126,7 @@ async function runScenario(
126
126
  if (status === "Optimal") {
127
127
  console.log(`Optimal Weekly Payroll: $${model.objectiveValue}`);
128
128
  for (const s of staffList) {
129
- const schedule = days.map((d) => (Math.round(shift[s.name][d].value ?? 0) === 1 ? "ON" : " ·"));
129
+ const schedule = days.map((d) => (shift[s.name][d].value === 1 ? "ON" : " ·"));
130
130
  console.log(` ${s.name.padEnd(8)}: ${schedule.join(" ")}`);
131
131
  }
132
132
  console.log("Schedule resolved successfully (no UNSAT diagnosis needed).\n");
@@ -173,3 +173,19 @@ main();
173
173
  ```
174
174
 
175
175
  </CodeRunner>
176
+
177
+ ## Auto-Repairing Conflicts with Soft Constraints (Elastic Requests)
178
+
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):
180
+
181
+ ```typescript
182
+ // Soft constraint pattern: penalize working on a requested day off by $500
183
+ // instead of enforcing hard shift[req.staff][req.day] == 0
184
+ const requestedShiftVars = dayOffRequests.map((req) => shift[req.staff][req.day]);
185
+ m.objective(minimize(expr`dot(${costMatrix}, ${shift}) + 500 * sum(${requestedShiftVars})`));
186
+ ```
187
+
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`).
189
+
190
+ > [!TIP]
191
+ > **Diagnosing `unsatCore` Without `COOP` / `COEP` Headers**: Because every variable in this roster model is a 0-1 binary (`m.binary(...)`) with integer coefficients, you can also run `await model.check({ solver: "pumpkin" })` (after `import "@ohtaman/washi/solvers/pumpkin"`) to extract `unsatCore` in standard browser environments without `COOP` / `COEP` headers or external peer dependencies.
@@ -2,7 +2,7 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Propositional Logic & SMT | Z3 (`@ohtaman/washi/solvers/z3`) | `m.bool()`, `m.integer()`, `m.constraint()`, `expr`, `m.check()` | <ul><li><a href="https://ohtaman.github.io/washi/demo/?preset=smt_sat_scheduling">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> |
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
7
  Satisfiability Modulo Theories (SMT) combines propositional logic (Boolean SAT) with first-order theories (linear integer arithmetic, real inequalities).
8
8
 
@@ -18,10 +18,10 @@ We model a security rule system with sensor readings and logic rules:
18
18
 
19
19
  ## Implementation in WaSHI
20
20
 
21
- <CodeRunner preset="smt_sat_scheduling">
21
+ <CodeRunner preset="smt_security">
22
22
 
23
23
  ```typescript
24
- import { Model, not, expr } from "@ohtaman/washi";
24
+ import { Model, implies, not, expr } from "@ohtaman/washi";
25
25
  import "@ohtaman/washi/solvers/z3";
26
26
 
27
27
  async function verifySecurityRules() {
@@ -39,7 +39,7 @@ async function verifySecurityRules() {
39
39
  const luxLevel = m.integer("luxLevel", { lb: 0, ub: 1000 });
40
40
 
41
41
  // Rule 1: luxLevel <= 50 implies isNight
42
- m.constraint(luxLevel.le(50).implies(isNight), "dark_implies_night");
42
+ m.constraint(implies(expr`${luxLevel} <= 50`, isNight), "dark_implies_night");
43
43
 
44
44
  // Rule 2: (motionDetected AND isNight AND alarmArmed) => sirenActive
45
45
  m.constraint(
@@ -66,9 +66,22 @@ async function verifySecurityRules() {
66
66
  console.log(`Lights On : ${lightsOn.value}`);
67
67
  console.log(`Door Locked : ${frontDoorUnlocked.value ? "No" : "Yes"}`);
68
68
  console.log(`Is Night : ${isNight.value}`);
69
+
70
+ // 4. Formal Safety Verification (Counterexample Search):
71
+ // Prove that the siren CANNOT remain off under these sensor readings
72
+ m.constraint(not(sirenActive), "counterexample_siren_off");
73
+ const proof = await m.check({ solver: "z3" });
74
+ console.log(`Can siren stay off? ${proof.status} (Proven safe when Unsat)`);
75
+ console.log(`Active proof core : ${(proof.conflicts ?? []).join(", ")}`);
69
76
  }
70
77
 
71
78
  verifySecurityRules();
72
79
  ```
73
80
 
74
81
  </CodeRunner>
82
+
83
+ ## Practical Notes
84
+
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)) ``.
87
+ - **Running Without `COOP` / `COEP` Headers (`solver: "pumpkin"`)**: Because all variables in this model are propositional `BoolVar`s and bounded integers (`luxLevel` in `[0, 1000]`), the exact same deduction and counterexample `unsatCore` proof works out of the box with bundled `@ohtaman/washi/solvers/pumpkin` (`m.check({ solver: "pumpkin" })`) without `COOP` / `COEP` headers or `z3-solver`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr`, `minimize`, `dot` | <ul><li><a href="https://ohtaman.github.io/washi/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` | <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
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.
8
8
 
@@ -35,7 +35,7 @@ $$\begin{aligned}
35
35
  <CodeRunner preset="transportation">
36
36
 
37
37
  ```typescript
38
- import { Model, sum, dot, minimize, expr } from "@ohtaman/washi";
38
+ import { Model, minimize, expr } from "@ohtaman/washi";
39
39
 
40
40
  const factories = ["Tokyo", "Nagoya", "Osaka"] as const;
41
41
  const stores = ["North", "East", "West", "South"] as const;
@@ -49,42 +49,69 @@ const shippingCost = {
49
49
  const supplies = { Tokyo: 120, Nagoya: 100, Osaka: 80 };
50
50
  const demands = { North: 70, East: 90, West: 60, South: 60 };
51
51
 
52
- async function runTransportation() {
52
+ async function solveScenario(label: string, cap: typeof supplies) {
53
53
  const m = new Model("TransportationNetwork");
54
54
 
55
55
  // 1. Create 2D continuous variables: ship[factory][store] >= 0
56
56
  const ship = m.continuous([...factories], [...stores], { lb: 0 });
57
57
 
58
58
  // 2. Objective: Minimize total shipping cost across all routes via 2D dot product
59
- m.objective(minimize(dot(shippingCost, ship)));
59
+ m.objective(minimize(expr`dot(${shippingCost}, ${ship})`));
60
60
 
61
- // 3. Supply constraints (row sums): outgoing from f <= supplies[f]
62
- for (const f of factories) {
63
- m.constraint(
64
- expr`${sum(stores, (s) => ship[f][s])} <= ${supplies[f]}`,
65
- `supply_${f}`
66
- );
67
- }
61
+ // 3. Supply constraints (row sums): outgoing from f <= cap[f]
62
+ const supplyConstrs = Object.fromEntries(
63
+ factories.map((f) => [
64
+ f,
65
+ m.constraint(expr`sum(${ship[f]}) <= ${cap[f]}`, `supply_${f}`),
66
+ ])
67
+ );
68
68
 
69
69
  // 4. Demand constraints (column sums): incoming to s >= demands[s]
70
- for (const s of stores) {
71
- m.constraint(
72
- expr`${sum(factories, (f) => ship[f][s])} >= ${demands[s]}`,
73
- `demand_${s}`
74
- );
75
- }
70
+ const demandConstrs = Object.fromEntries(
71
+ stores.map((s) => [
72
+ s,
73
+ m.constraint(
74
+ expr`sum(${factories}, ${(f) => ship[f][s]}) >= ${demands[s]}`,
75
+ `demand_${s}`
76
+ ),
77
+ ])
78
+ );
76
79
 
77
80
  const status = await m.solve();
78
- console.log(`Status: ${status}, Total Shipping Cost: $${m.objectiveValue}`);
81
+ console.log(`[${label}] Status: ${status}, Total Shipping Cost: $${m.objectiveValue}`);
79
82
  for (const f of factories) {
83
+ const dual = supplyConstrs[f].dual ?? 0;
80
84
  const routes = stores
81
85
  .map((s) => `${s}:${Math.round(ship[f][s].value ?? 0)}`)
82
86
  .join(", ");
83
- console.log(` ${f.padEnd(7)} -> ${routes}`);
87
+ console.log(` ${f.padEnd(7)} -> ${routes} (supply dual: $${dual}/u)`);
84
88
  }
89
+ const demandDuals = stores
90
+ .map((s) => `${s}:$${demandConstrs[s].dual ?? 0}`)
91
+ .join(", ");
92
+ console.log(` Marginal Delivered Cost (demand duals) -> ${demandDuals}`);
93
+ }
94
+
95
+ async function runTransportation() {
96
+ // Scenario A: Baseline capacities ($920)
97
+ await solveScenario("Scenario A: Baseline", supplies);
98
+
99
+ // Scenario B: Tokyo capacity reduced (120 -> 80) due to maintenance ($1,000)
100
+ await solveScenario("Scenario B: Tokyo Maintenance", {
101
+ Tokyo: 80,
102
+ Nagoya: 120,
103
+ Osaka: 100,
104
+ });
85
105
  }
86
106
 
87
107
  runTransportation();
88
108
  ```
89
109
 
90
110
  </CodeRunner>
111
+
112
+ ## Practical Notes
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.