@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,25 +4,28 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Infeasibility Diagnosis / Unsat Core | Z3 (`@ohtaman/washi/solvers/z3`) | `m.integer()`, `m.continuous()`, `implies()`, `m.constraint()`, `expr`, `m.check()`, `m.conflicts` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=conflict_diagnosis_unsat">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts">Source Code</a></li></ul> |
6
6
 
7
- When business rules, budgets, and operational policies grow complex, constraints can easily conflict. Because a standard optimization call (`m.solve()`) only reports `"Infeasible"`, WaSHI provides `m.check()` to pinpoint conflicting rules without manual trial-and-error.
7
+ A standard optimization call (`m.solve()`) only reports `"Infeasible"` when constraints clash. Calling `m.check()` returns `"Unsat"` along with conflicting constraint names: SMT/CP solvers such as Z3 and Pumpkin extract an **Unsat Core** (a mutually inconsistent subset), whereas MIP solvers such as HiGHS return an **Elastic Repair Set**.
8
8
 
9
- This example shows how to isolate the conflicting constraint subset using Z3 Unsat Core extraction.
9
+ This example diagnoses a staffing-vs-budget conflict with Z3 and HiGHS and reads the result from `res.conflicts` (also stored on `m.conflicts`). Here Z3 excludes the unrelated rule, though in general a returned Unsat Core is not guaranteed to be minimal.
10
10
 
11
11
  ## The Conflicting Scenario
12
12
 
13
13
  A tech team is staffing a customer project:
14
- 1. Each engineer costs $8,000 against the project budget (`budget_limit`).
14
+ 1. Each engineer costs $8,000, and total staffing cost must stay within the project budget (`budget_limit`).
15
15
  2. The customer requires rush delivery (`rush_required`).
16
16
  3. Rush delivery mandates at least 8 engineers (`rush_staffing_rule`).
17
- 4. The board has imposed a strict budget cap of $50,000 (`strict_board_budget_cap`).
18
- 5. Labor law requires at least 1 employee on staff (`minimum_one_employee`).
17
+ 4. The board sets a strict budget cap of $50,000 (`strict_board_budget_cap`).
18
+ 5. Labor law requires at least 1 engineer on staff (`minimum_one_employee`).
19
19
 
20
- Notice that:
20
+ These rules contradict each other:
21
21
 
22
- $$8 \text{ engineers} \times \$8,000 = \$64,000 > \$50,000 \text{ budget!}$$
22
+ $$8 \text{ engineers} \times \$8,000 = \$64,000 > \$50,000$$
23
23
 
24
24
  ## Implementation in WaSHI
25
25
 
26
+ > [!NOTE]
27
+ > **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).
28
+
26
29
  <CodeRunner preset="conflict_diagnosis_unsat">
27
30
 
28
31
  ```typescript
@@ -45,7 +48,7 @@ async function diagnoseConflicts() {
45
48
  // Rule 3: Rush delivery requires at least 8 engineers
46
49
  m.constraint(implies(rushDelivery, expr`${engineers} >= 8`), "rush_staffing_rule");
47
50
 
48
- // Rule 4: Board budget cap of $50,000 (Conflict!)
51
+ // Rule 4: Board budget cap of $50,000 (conflicts with Rules 1-3)
49
52
  m.constraint(expr`${budget} <= 50000`, "strict_board_budget_cap");
50
53
 
51
54
  // Rule 5: Innocent bystander rule
@@ -54,12 +57,14 @@ async function diagnoseConflicts() {
54
57
  // Run diagnosis
55
58
  const res = await m.check({ solver: "z3" });
56
59
 
57
- console.log(`Status: ${res.status}`);
58
- console.log("Z3 Unsat Core (scale-invariant):", m.conflicts);
60
+ console.log(`Status: ${res.status}`); // Status: Unsat
61
+ console.log("Z3 Unsat Core (scale-invariant):", res.conflicts); // also available via m.conflicts
62
+ // ["budget_limit", "rush_required", "rush_staffing_rule", "strict_board_budget_cap"]
59
63
 
60
- // Built-in HiGHS can also diagnose conflicts via single-solve L1 elastic slack relaxation:
64
+ // Built-in HiGHS can also diagnose conflicts by finding constraints to relax:
61
65
  const highsDiag = await m.check({ solver: "highs" });
62
66
  console.log("HiGHS Elastic Repair Set:", highsDiag.conflicts);
67
+ // ["rush_required"]
63
68
  }
64
69
 
65
70
  diagnoseConflicts();
@@ -69,6 +74,14 @@ diagnoseConflicts();
69
74
 
70
75
  ## Practical Notes
71
76
 
72
- - **Z3 `unsatCore` vs. HiGHS Elastic Slack `conflicts`**:
73
- - **Z3 (`m.check({ solver: "z3" })`)** performs logical assumption tracking and returns all four rules that jointly form the contradiction (`budget_limit`, `rush_required`, `rush_staffing_rule`, `strict_board_budget_cap`), while excluding the innocent `minimum_one_employee` rule.
74
- - **HiGHS (`m.check({ solver: "highs" })`)** solves a single $L_1$ elastic slack minimization problem ($\min \sum s_i$). Because relaxing `rush_staffing_rule` (or `rush_required`) requires a slack of only `1`–`2` units whereas relaxing `strict_board_budget_cap` requires a slack of `14,000` dollars, unweighted $L_1$ minimization naturally highlights the smallest-magnitude repair (`rush_required`) needed to restore feasibility.
77
+ ### Z3 (`m.check({ solver: "z3" })`)
78
+
79
+ Z3 supports continuous variables (`m.continuous()`, such as `budget` above) and decimal coefficients. It returns all four conflicting rules while excluding `minimum_one_employee`, regardless of numeric scale.
80
+
81
+ ### Pumpkin (`m.check({ solver: "pumpkin" })`)
82
+
83
+ Pumpkin is bundled with `@ohtaman/washi` (no extra import required) and needs neither `z3-solver` nor browser `COOP` / `COEP` headers. If every variable is a bounded integer or boolean (for example, changing `budget` to `m.integer()`), Pumpkin also extracts a scale-invariant Unsat Core.
84
+
85
+ ### HiGHS (`m.check({ solver: "highs" })`)
86
+
87
+ Rather than an Unsat Core, HiGHS returns an **Elastic Repair Set** — constraints whose total slack (relaxation) needed to restore feasibility is minimized. It populates `conflicts` and leaves `unsatCore` as `undefined`, whereas Z3 and Pumpkin populate both. Because relaxing `rush_required` takes `1` unit while relaxing the budget cap takes `$14,000`, HiGHS flags `rush_required`.
@@ -4,20 +4,20 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Combinatorial OR / Dantzig-Wolfe | HiGHS (default) | `m.solveColumnGeneration()`, `pricing`, `m.binary()`, `m.constraint()`, `expr` (`sum`) | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
6
6
 
7
- The **Capacitated Vehicle Routing Problem (CVRP)** determines the minimum number of delivery vehicles needed to visit a set of customers, subject to vehicle cargo capacity, maximum customer stops per shift, and route duration limits.
7
+ This **Capacitated Vehicle Routing Problem (CVRP)** variant minimizes the number of delivery vehicles needed to serve every customer. In addition to vehicle cargo capacity, each route must respect maximum stops per shift and route duration limits.
8
8
 
9
- In a monolithic MIP formulation, enumerating all possible customer combinations and visit sequences leads to $O(2^n)$ binary variables. With **Column Generation (Dantzig-Wolfe Decomposition)**, routes are generated on demand:
10
- 1. **Restricted Master Problem (RMP)**: Solves a set partitioning problem that selects a subset of candidate routes so that every customer is visited once.
11
- 2. **Pricing Subproblem**: Uses the dual values (shadow prices) from the master LP relaxation to construct improving routes with negative reduced cost ($\bar{c} = 1 - \sum \pi_i < 0$) via cheapest insertion and 2-opt local search.
9
+ Enumerating all feasible routes upfront in a monolithic MIP causes the number of binary variables to explode as the number of customers $n$ grows—unordered subsets alone scale as $O(2^n)$, and ordered routes grow even faster. **Column Generation (Dantzig-Wolfe Decomposition)** avoids this by generating routes on demand:
10
+ 1. **Restricted Master Problem (RMP)**: Solves the set-partitioning **LP relaxation** over generated routes so every customer is visited exactly once, then solves the final MIP.
11
+ 2. **Pricing Subproblem**: Reads each customer's dual value (shadow price) $\pi_i$ from the master LP relaxation and uses cheapest insertion with 2-opt search to build a route $r$ with negative reduced cost $\bar{c}_r = 1 - \sum_{i \in r} \pi_i < 0$.
12
12
 
13
13
  ## Problem Inputs
14
14
 
15
- We consider a distribution network with a central depot at $(0, 0)$ and **50 customer locations**:
15
+ We consider a distribution network with a central depot at $(0, 0)$ and **50 customer locations** (demands of **1 to 4 units** each):
16
16
 
17
17
  - **Vehicle Cargo Capacity**: At most **10 units** per vehicle.
18
18
  - **Maximum Stops**: At most **4 customers** per route.
19
19
  - **Maximum Shift Duration**: At most **200 minutes** (transit time + service time) per route.
20
- - **Transit & Service Times**: Euclidean distances between nodes (1 unit = 1 minute) plus **10 minutes** of unloading service time per customer.
20
+ - **Transit & Service Times**: Integer-rounded Euclidean distances (`Math.round`) between nodes (1 unit = 1 minute) plus **10 minutes** of unloading time per customer.
21
21
 
22
22
  ## Implementation in WaSHI
23
23
 
@@ -26,10 +26,30 @@ We consider a distribution network with a central depot at $(0, 0)$ and **50 cus
26
26
  ```typescript
27
27
  import { Model, expr, minimize } from "@ohtaman/washi";
28
28
 
29
+ interface RouteMeta {
30
+ tour: string[];
31
+ travelTime: number;
32
+ totalTime: number;
33
+ }
34
+
35
+ interface CandidateCustomer {
36
+ id: string;
37
+ demand: number;
38
+ dual: number;
39
+ }
40
+
41
+ interface RouteConstraints {
42
+ dist: (a: string, b: string) => number;
43
+ serviceTimes: Record<string, number>;
44
+ vehicleCapacity: number;
45
+ maxStops: number;
46
+ maxRouteTime: number;
47
+ }
48
+
29
49
  // --- Extracted Routing Helpers ---
30
50
 
31
51
  // 2-opt local search to eliminate crossing paths in a tour
32
- function optimize2Opt(tour, dist) {
52
+ function optimize2Opt(tour: string[], dist: (a: string, b: string) => number): string[] {
33
53
  let best = [...tour];
34
54
  let improved = true;
35
55
 
@@ -49,8 +69,8 @@ function optimize2Opt(tour, dist) {
49
69
  return best;
50
70
  }
51
71
 
52
- // Inserts a customer into the tour at the position that minimizes detour distance
53
- function insertCheapest(tour, id, dist) {
72
+ // Inserts a customer into the tour at the position that minimizes added distance
73
+ function insertCheapest(tour: string[], id: string, dist: (a: string, b: string) => number): string[] {
54
74
  let bestPos = 1;
55
75
  let minCost = Infinity;
56
76
 
@@ -65,7 +85,11 @@ function insertCheapest(tour, id, dist) {
65
85
  }
66
86
 
67
87
  // Calculates transit time and total duration (transit + service) for a tour
68
- function calcRouteTime(tour, dist, serviceTimes) {
88
+ function calcRouteTime(
89
+ tour: string[],
90
+ dist: (a: string, b: string) => number,
91
+ serviceTimes: Record<string, number>
92
+ ) {
69
93
  let travelTime = 0;
70
94
  for (let i = 0; i < tour.length - 1; i++) {
71
95
  travelTime += dist(tour[i], tour[i + 1]);
@@ -75,8 +99,8 @@ function calcRouteTime(tour, dist, serviceTimes) {
75
99
  }
76
100
 
77
101
  // Pricing subproblem: Finds an improving route with negative reduced cost (1 - dualSum < 0)
78
- function findImprovingRoute(candidates, config) {
79
- let bestRoute = null;
102
+ function findImprovingRoute(candidates: CandidateCustomer[], config: RouteConstraints): string[] | null {
103
+ let bestRoute: string[] | null = null;
80
104
  let minReducedCost = -1e-4;
81
105
 
82
106
  for (const seed of candidates.slice(0, 15)) {
@@ -130,11 +154,11 @@ async function runCVRP() {
130
154
  });
131
155
 
132
156
  const nodes = Object.fromEntries([depot, ...customers].map((n) => [n.id, n]));
133
- const dist = (a, b) =>
157
+ const dist = (a: string, b: string) =>
134
158
  Math.round(Math.hypot(nodes[a].x - nodes[b].x, nodes[a].y - nodes[b].y));
135
159
  const serviceTimes = Object.fromEntries(customers.map((c) => [c.id, c.serviceTime]));
136
160
 
137
- const routeConfig = { dist, serviceTimes, vehicleCapacity, maxStops, maxRouteTime };
161
+ const routeConfig: RouteConstraints = { dist, serviceTimes, vehicleCapacity, maxStops, maxRouteTime };
138
162
 
139
163
  // 1. Build Restricted Master Problem (RMP)
140
164
  const master = new Model("CVRP_FleetMaster");
@@ -143,7 +167,7 @@ async function runCVRP() {
143
167
  const initialRoutes = customers.map((c) => master.binary(`route_init_${c.id}`));
144
168
  master.objective(minimize(expr`sum(${initialRoutes})`));
145
169
 
146
- // Each customer must be visited by exactly 1 vehicle
170
+ // Set-partitioning constraints: each customer must be visited by exactly 1 vehicle
147
171
  const visitConstrs = customers.map((c, i) =>
148
172
  master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${c.id}`)
149
173
  );
@@ -152,7 +176,7 @@ async function runCVRP() {
152
176
  console.log("Solving via Column Generation with dual-directed heuristic pricing...");
153
177
 
154
178
  // 2. Solve via Column Generation
155
- const result = await master.solveColumnGeneration({
179
+ const result = await master.solveColumnGeneration<RouteMeta>({
156
180
  finalizeAsMIP: true,
157
181
  pricing: async () => {
158
182
  // 1. Sort customers by shadow price (dual profit) descending
@@ -167,14 +191,14 @@ async function runCVRP() {
167
191
 
168
192
  // 3. Propose new column to Restricted Master Problem
169
193
  const { travelTime, totalTime } = calcRouteTime(bestRoute, dist, serviceTimes);
170
- const coefficients = {};
194
+ const coefficients: Record<string, number> = {};
171
195
  for (const id of bestRoute.slice(1, -1)) {
172
196
  coefficients[`visit_${id}`] = 1;
173
197
  }
174
198
 
175
199
  return {
176
200
  cost: 1,
177
- type: "Binary",
201
+ type: "Binary" as const,
178
202
  coefficients,
179
203
  meta: { tour: bestRoute, travelTime, totalTime },
180
204
  };
@@ -186,10 +210,21 @@ async function runCVRP() {
186
210
  console.log(`Total Columns Generated: ${result.columnsAdded}`);
187
211
 
188
212
  console.log("\nSample routes selected in fleet:");
189
- const activeRoutes = result.generatedColumns.filter((c) => c.variable.value === 1);
213
+ const activeRoutes: RouteMeta[] = [];
214
+ for (const c of result.generatedColumns) {
215
+ if (c.variable.value === 1 && c.proposal.meta) {
216
+ activeRoutes.push(c.proposal.meta);
217
+ }
218
+ }
219
+ for (let i = 0; i < customers.length; i++) {
220
+ if (initialRoutes[i].value === 1) {
221
+ const tour = ["Depot", customers[i].id, "Depot"];
222
+ const { travelTime, totalTime } = calcRouteTime(tour, dist, serviceTimes);
223
+ activeRoutes.push({ tour, travelTime, totalTime });
224
+ }
225
+ }
190
226
  for (const r of activeRoutes.slice(0, 5)) {
191
- const meta = r.proposal.meta;
192
- console.log(` ${meta?.tour.join(" -> ")} (Transit: ${meta?.travelTime}m, Total: ${meta?.totalTime}m)`);
227
+ console.log(` ${r.tour.join(" -> ")} (Transit: ${r.travelTime}m, Total: ${r.totalTime}m)`);
193
228
  }
194
229
  }
195
230
 
@@ -198,11 +233,22 @@ runCVRP();
198
233
 
199
234
  </CodeRunner>
200
235
 
201
- ## Notes
236
+ ## Key Takeaways
237
+
238
+ Starting from `50` single-customer vehicles, heuristic pricing generates `63` additional route columns and lowers the LP relaxation to about `12.65`. Finalizing that column pool as a MIP (root-node Price-and-Branch) yields a `19`-vehicle fleet made up of `11` multi-stop routes and `8` single-customer routes.
239
+
240
+ ### Master Problem, Pricing & Route Metadata
241
+
242
+ The master problem handles the LP relaxation and final set-partitioning MIP. Inside `pricing`, `visitConstrs[i].dual` supplies each customer's dual value (shadow price) to guide route construction. Storing `{ tour, travelTime, totalTime }` in `meta` lets you inspect the chosen stop sequence via `result.generatedColumns` after solving.
243
+
244
+ ### Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)
245
+
246
+ This example uses `== 1` so no customer is visited twice in the final MIP. In larger instances, using `>= 1` keeps dual values non-negative ($\pi_i \ge 0$) and stabilizes LP convergence. When travel distances satisfy the triangle inequality, duplicate visits can be stripped after solving without increasing travel time, load, stop count, or fleet size. Note that rounding distances with `Math.round`, as in this example, can introduce small rounding violations of the triangle inequality.
247
+
248
+ ### Heuristic Pricing vs. Exact ESPPRC
249
+
250
+ Here `findImprovingRoute` runs a greedy cheapest-insertion and 2-opt heuristic instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver. Returning `null` therefore means the heuristic found no further improving route, rather than proving global LP optimality.
251
+
252
+ ### Price-and-Branch (`finalizeAsMIP: true`)
202
253
 
203
- - **Master Problem and Pricing Separation**: The master problem solves the LP relaxation and final set-partitioning MIP, while the `pricing` callback searches for negative-reduced-cost routes using cheapest insertion and 2-opt local search.
204
- - **Dual Value Access**: Dual values from the master LP relaxation are read from `visitConstrs[i].dual` to prioritize customers with higher shadow prices during route construction.
205
- - **Route Metadata**: Each proposed column attaches `{ tour, travelTime, totalTime }` under `meta`, allowing the ordered stop sequence to be inspected from `result.generatedColumns` after the solve completes.
206
- - **Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)**: This example uses `== 1` so that the final MIP never covers a customer twice. In large-scale column generation, formulating coverage as `>= 1` restricts the dual prices to $\pi_i \ge 0$, avoiding negative dual oscillations; if the final MIP selects overlapping routes, duplicate visits can be removed by post-processing whenever distances satisfy the triangle inequality.
207
- - **Heuristic Pricing vs. Exact ESPPRC**: Because `findImprovingRoute` uses a fast greedy heuristic (cheapest insertion + 2-opt) instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver, returning `null` means no further improving columns were found by the heuristic rather than proving global LP optimality.
208
- - **Price-and-Branch (`finalizeAsMIP: true`)**: Solving the Restricted Master Problem as a MIP over the columns generated at the root node is known as the *Restricted Master Heuristic* (Price-and-Branch). It produces near-optimal integer fleets quickly without requiring full Branch-and-Price tree search.
254
+ Solving the Restricted Master Problem as a MIP over the columns generated at the root node is called the **Restricted Master Heuristic** (Price-and-Branch). It produces strong integer fleets quickly without implementing a full Branch-and-Price search tree.