@ohtaman/washi 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.ja.md +60 -23
  2. package/README.md +59 -22
  3. package/README.zh-CN.md +62 -25
  4. package/THIRD_PARTY_LICENSES.md +34 -1
  5. package/dist/browser/solvers/glpk.js +289 -238
  6. package/dist/browser/solvers/glpk.min.js +1 -1
  7. package/dist/browser/solvers/highs-__vite-browser-external-Dn-83hnF.js +7 -0
  8. package/dist/browser/solvers/highs-browser-runtime-0Bgq5ksG.js +2021 -0
  9. package/dist/browser/{loader-DewlSho8.js → solvers/highs-loader-BLY3wzDH.js} +190 -149
  10. package/dist/browser/solvers/highs-worker.js +54 -0
  11. package/dist/browser/solvers/highs.js +1414 -0
  12. package/dist/browser/solvers/highs.wasm +0 -0
  13. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  14. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  15. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  16. package/dist/browser/solvers/pumpkin.js +1777 -0
  17. package/dist/browser/solvers/pumpkin.wasm +0 -0
  18. package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
  19. package/dist/browser/solvers/z3.js +1600 -1335
  20. package/dist/browser/solvers/z3.min.js +2 -2
  21. package/dist/browser/washi.js +3313 -1699
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/solvers/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/solvers/glpk.js +174 -132
  25. package/dist/lib/solvers/highs-browser-runtime.js +2413 -0
  26. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  27. package/dist/lib/solvers/highs-runtime.js +16 -0
  28. package/dist/lib/solvers/highs-worker.js +54 -0
  29. package/dist/lib/solvers/highs.js +410 -0
  30. package/dist/lib/solvers/highs.wasm +0 -0
  31. package/dist/lib/{loader-BZUQNvh4.js → solvers/loader-CDpPXN_F.js} +138 -116
  32. package/dist/lib/solvers/loader-Ow74Fa1B.js +311 -0
  33. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  34. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  35. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  36. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  37. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  38. package/dist/lib/solvers/pumpkin.js +868 -0
  39. package/dist/lib/solvers/pumpkin.wasm +0 -0
  40. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  41. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  42. package/dist/lib/solvers/rolldown-runtime-DtPi1Y-2.js +13 -0
  43. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  44. package/dist/lib/solvers/z3.js +489 -307
  45. package/dist/lib/washi.js +3905 -1410
  46. package/dist/types/decomposition/benders.d.ts.map +1 -1
  47. package/dist/types/index.d.ts +4 -5
  48. package/dist/types/index.d.ts.map +1 -1
  49. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  50. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  51. package/dist/types/modeler/constraint.d.ts +40 -4
  52. package/dist/types/modeler/constraint.d.ts.map +1 -1
  53. package/dist/types/modeler/expression.d.ts +129 -2
  54. package/dist/types/modeler/expression.d.ts.map +1 -1
  55. package/dist/types/modeler/index.d.ts +4 -6
  56. package/dist/types/modeler/index.d.ts.map +1 -1
  57. package/dist/types/modeler/linearizer.d.ts +11 -2
  58. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  59. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  60. package/dist/types/modeler/model.d.ts +86 -126
  61. package/dist/types/modeler/model.d.ts.map +1 -1
  62. package/dist/types/modeler/parser.d.ts.map +1 -1
  63. package/dist/types/modeler/quad-expr.d.ts +8 -2
  64. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  65. package/dist/types/modeler/solution-validator.d.ts +12 -12
  66. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  67. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  68. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  69. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  70. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  72. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  73. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  74. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  75. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  76. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  77. package/dist/types/modeler/solvers/index.d.ts +2 -1
  78. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  79. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  80. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  81. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  82. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  83. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  84. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  85. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  86. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  87. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  88. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  89. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  90. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  91. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  92. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  93. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  94. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  95. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  96. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  97. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  98. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  99. package/dist/types/modeler/solvers/types.d.ts +7 -9
  100. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  101. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  102. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  103. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  104. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  105. package/dist/types/modeler/types.d.ts +12 -15
  106. package/dist/types/modeler/types.d.ts.map +1 -1
  107. package/dist/types/modeler/validation.d.ts +26 -2
  108. package/dist/types/modeler/validation.d.ts.map +1 -1
  109. package/dist/types/modeler/variable.d.ts +9 -5
  110. package/dist/types/modeler/variable.d.ts.map +1 -1
  111. package/docs/examples/diet-sensitivity.md +33 -14
  112. package/docs/examples/ecommerce-coupons.md +17 -9
  113. package/docs/examples/index.md +36 -27
  114. package/docs/examples/knapsack.md +11 -5
  115. package/docs/examples/portfolio-qp.md +21 -8
  116. package/docs/examples/production.md +10 -5
  117. package/docs/examples/project-scheduling.md +119 -0
  118. package/docs/examples/shift-scheduling.md +29 -18
  119. package/docs/examples/smt-security.md +27 -11
  120. package/docs/examples/transportation.md +23 -13
  121. package/docs/examples/traveling-salesperson.md +34 -22
  122. package/docs/examples/unsat-core.md +27 -14
  123. package/docs/examples/vehicle-routing.md +74 -28
  124. package/docs/getting-started/ai-agents.md +190 -82
  125. package/docs/getting-started/coding-agents.md +177 -0
  126. package/docs/getting-started/cross-origin.md +27 -14
  127. package/docs/getting-started/index.md +49 -43
  128. package/docs/getting-started/runtimes.md +94 -40
  129. package/docs/guide/constraint-programming.md +171 -0
  130. package/docs/guide/constraints.md +115 -33
  131. package/docs/guide/decomposition.md +118 -88
  132. package/docs/guide/expressions.md +106 -43
  133. package/docs/guide/formulation-tips.md +47 -28
  134. package/docs/guide/objectives.md +102 -75
  135. package/docs/guide/unsat-core.md +62 -50
  136. package/docs/guide/variables.md +81 -35
  137. package/docs/solvers/custom-solver.md +163 -122
  138. package/docs/solvers/glpk.md +58 -17
  139. package/docs/solvers/highs.md +124 -57
  140. package/docs/solvers/index.md +33 -20
  141. package/docs/solvers/pumpkin.md +171 -0
  142. package/docs/solvers/z3.md +63 -25
  143. package/llms-full.txt +2232 -932
  144. package/llms.txt +144 -91
  145. package/package.json +55 -19
  146. package/skills/washi/SKILL.md +107 -34
  147. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  148. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  149. package/dist/browser/highs-worker.js +0 -39
  150. package/dist/browser/highs.wasm +0 -0
  151. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  152. package/dist/lib/highs-browser-runtime.js +0 -2185
  153. package/dist/lib/highs-runtime.js +0 -2
  154. package/dist/lib/highs-worker.js +0 -39
  155. package/dist/lib/highs.wasm +0 -0
  156. package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
  157. package/docs/ja/getting-started/ai-agents.md +0 -280
  158. package/docs/zh/getting-started/ai-agents.md +0 -280
  159. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  160. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  161. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  162. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
@@ -1,90 +1,49 @@
1
1
  # Decomposition Methods (`solveColumnGeneration` & `solveBenders`)
2
2
 
3
- When monolithic Mixed-Integer Programming (MIP) models have exponentially many candidate patterns or large multi-stage subproblems, WaSHI provides two high-level decomposition orchestrators—`master.solveColumnGeneration()` and `master.solveBenders()`—along with low-level primitives for dual inspection and dynamic model updates.
3
+ When a single LP or MIP model has too many columns to enumerate upfront, or splits naturally into two decision stages, WaSHI provides two decomposition helpers:
4
4
 
5
- | Decomposition Method | WaSHI Orchestrator | Typical Use Case |
5
+ | Method | WaSHI API | When to use |
6
6
  | :--- | :--- | :--- |
7
- | **Column Generation** *(Dantzig-Wolfe)* | [`master.solveColumnGeneration()`](#column-generation-solvecolumngeneration) | Models with exponentially many patterns, routes, or schedules (e.g., Cutting Stock, Vehicle Routing, Crew Rostering). |
8
- | **Benders Decomposition** *(and Lazy Cuts)* | [`master.solveBenders()`](#benders-decomposition-solvebenders) | Two-stage or complicating-variable problems (e.g., Facility Location + Dispatch, Stochastic Planning, TSP Subtour Elimination). |
7
+ | **Column Generation** | [`master.solveColumnGeneration()`](#column-generation-solvecolumngeneration) | Models with exponentially many patterns, routes, or shifts (Cutting Stock, VRP, Crew Rostering). |
8
+ | **Benders Decomposition** | [`master.solveBenders()`](#benders-decomposition-solvebenders) | Two-stage problems (Facility Location + Dispatch) or lazy constraints added on demand (TSP Subtour Elimination). |
9
9
 
10
- ---
11
-
12
- ## Foundational Primitives
10
+ Both helpers are also exported as standalone functions—`solveColumnGeneration({ master, ... })` and `solveBenders({ master, ... })`—alongside the `Model` methods.
13
11
 
14
- WaSHI exposes four lower-level primitives used internally by the decomposition orchestrators and available directly for custom algorithms:
15
-
16
- ### 1. Constraint Duals (`c.dual`)
17
- After solving a continuous linear program (LP), read the shadow price (marginal impact on the objective per unit change in RHS) of each constraint:
18
-
19
- ```typescript
20
- import { Model, expr, maximize } from "@ohtaman/washi";
21
-
22
- const m = new Model();
23
- const x = m.continuous("x", { lb: 0 });
24
- const y = m.continuous("y", { lb: 0 });
25
-
26
- m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
27
- const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
28
- await m.solve();
29
-
30
- console.log(c.dual); // Dual value / shadow price
31
- console.log(m.solution?.duals.capacity); // Lookup by constraint name
32
- ```
33
-
34
- ### 2. Continuous LP Relaxation (`m.relax()`)
35
- `m.relax()` temporarily relaxes all `Integer` and `Binary` variables to continuous variables within their `[lb, ub]` bounds and solves the LP relaxation so constraint duals are populated:
36
-
37
- ```typescript
38
- // Solves the continuous LP relaxation and populates m.solution.duals
39
- const status = await m.relax();
40
- console.log("LP relaxation bound:", m.objectiveValue);
41
- ```
42
-
43
- ### 3. Dynamic Column Injection (`m.addColumn()`)
44
- Create a new decision variable, set its objective coefficient, and attach its non-zero coefficients to existing named constraints in a single call:
12
+ ---
45
13
 
46
- ```typescript
47
- const col = m.addColumn({
48
- name: "pattern_1",
49
- type: "Integer", // or "Continuous" / "Binary"
50
- lb: 0,
51
- cost: 1, // Objective coefficient
52
- coefficients: {
53
- capacity: 2,
54
- },
55
- });
56
- ```
14
+ ## Column Generation (`solveColumnGeneration`)
57
15
 
58
- ### 4. Dynamic Constraint Term Updates (`c.addTerm()` / `c.setTerm()`)
59
- Increment or overwrite the coefficient of a variable inside an existing linear constraint:
16
+ Column Generation solves large linear and integer models whose variables (columns) are too numerous to enumerate upfront.
17
+ It splits the problem into two parts:
60
18
 
61
- ```typescript
62
- const extra = m.continuous("extra", { lb: 0 });
63
- const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
19
+ - **Restricted Master Problem (RMP)**: The master `Model`, initialized with a small feasible subset of columns.
20
+ - **Pricing Subproblem**: A callback (`pricing`) that reads the RMP's LP dual values and searches for a new column that improves the objective.
64
21
 
65
- budget.addTerm(extra, 5); // Adds +5 * extra to the LHS
66
- budget.setTerm(extra, 0); // Setting 0 removes extra from the constraint
67
- ```
22
+ Each call to `master.solveColumnGeneration()` runs this loop:
68
23
 
69
- ---
24
+ 1. Solves the LP relaxation of the RMP (`master.relax()`) to obtain each constraint's **dual value** (shadow price).
25
+ 2. Passes those duals (`duals`, `getDual`) to your `pricing` callback.
26
+ 3. Checks whether each returned `ColumnProposal` improves the objective beyond `reducedCostTolerance` using its **reduced cost** (computed automatically as $\bar{c} = \text{cost} - \sum_i \pi_i a_i$ when `reducedCost` is omitted).
27
+ 4. Adds any improving column ($\bar{c} < -\varepsilon$ when minimizing, or $\bar{c} > \varepsilon$ when maximizing, with $\varepsilon$ = `reducedCostTolerance`). The loop repeats until `pricing` returns `null` / `[]`, no improving column remains, or `maxIterations` is reached.
28
+ 5. Optionally solves the final RMP with all generated columns as an integer program (`finalizeAsMIP: true`, enabled by default).
70
29
 
71
- ## Column Generation (`solveColumnGeneration`)
30
+ > [!IMPORTANT]
31
+ > **Preconditions & Guarantees**:
32
+ > - **Feasible & bounded initial RMP**: Starting columns (or penalized artificial slacks) must make the initial LP relaxation feasible and bounded so a finite optimum and valid duals exist.
33
+ > - **LP-dual solver required**: Requires HiGHS or GLPK; Pumpkin and Z3 do not produce LP duals.
34
+ > - **Price-and-Branch heuristic**: `finalizeAsMIP: true` solves one MIP over root-LP columns only—fast and practical, but not exact Branch-and-Price.
72
35
 
73
- `master.solveColumnGeneration(options)` starts from a **Restricted Master Problem (RMP)** containing an initial feasible subset of columns and executes the column generation loop:
74
- 1. Solves the continuous LP relaxation of the master problem via `master.relax()`.
75
- 2. Invokes your `pricing` callback with the current dual shadow prices (`duals`, `getDual`).
76
- 3. Evaluates candidate columns (`ColumnProposal` or `ColumnProposal[]`), dynamically injecting those with improving reduced costs ($\bar{c} = \text{cost} - \sum_i \pi_i a_i < 0$ when minimizing).
77
- 4. Repeats until `pricing` returns `null` / `[]` or no column improves the objective beyond `reducedCostTolerance`.
78
- 5. Optionally solves the final master model as a MIP (`finalizeAsMIP: true`, the default) to obtain an integer solution over all generated columns.
36
+ ### Example: Pricing with a Subproblem `Model`
79
37
 
80
- ### Pricing with a WaSHI Subproblem Model
38
+ In the Cutting Stock problem below, the RMP starts with three single-item patterns and the pricing subproblem solves a knapsack model to find better roll patterns.
39
+ Because `solveColumnGeneration()` checks reduced cost automatically, `pricing` can simply return the best pattern found by the subproblem:
81
40
 
82
41
  ```typescript
83
42
  import { Model, expr, minimize, maximize } from "@ohtaman/washi";
84
43
 
85
44
  const rollWidth = 100;
86
45
 
87
- // 1. Restricted Master Problem (RMP) with simple single-item initial patterns
46
+ // 1. Master problem: start with simple single-item cutting patterns
88
47
  const master = new Model("CuttingStockMaster");
89
48
  const pA = master.integer("init_A", { lb: 0 }); // 2 of A (width 45) per roll
90
49
  const pB = master.integer("init_B", { lb: 0 }); // 2 of B (width 36) per roll
@@ -98,16 +57,16 @@ const demandC = master.constraint(expr`6 * ${pC} >= 20`, "demand_C");
98
57
  // 2. Run Column Generation
99
58
  const result = await master.solveColumnGeneration({
100
59
  finalizeAsMIP: true,
101
- pricing: async () => {
102
- // Knapsack pricing subproblem: find a pattern maximizing total dual value
60
+ pricing: async ({ getDual }) => {
61
+ // Subproblem: find a valid roll pattern maximizing total dual value
103
62
  const sub = new Model("KnapsackPricing");
104
63
  const aA = sub.integer("a_A", { lb: 0, ub: 2 });
105
64
  const aB = sub.integer("a_B", { lb: 0, ub: 2 });
106
65
  const aC = sub.integer("a_C", { lb: 0, ub: 6 });
107
66
 
108
- const dualA = demandA.dual ?? 0;
109
- const dualB = demandB.dual ?? 0;
110
- const dualC = demandC.dual ?? 0;
67
+ const dualA = getDual(demandA);
68
+ const dualB = getDual(demandB);
69
+ const dualC = getDual(demandC);
111
70
  sub.objective(maximize(expr`${dualA} * ${aA} + ${dualB} * ${aB} + ${dualC} * ${aC}`));
112
71
  sub.constraint(expr`45 * ${aA} + 36 * ${aB} + 16 * ${aC} <= ${rollWidth}`);
113
72
 
@@ -130,9 +89,10 @@ console.log("Iterations:", result.iterations);
130
89
  console.log("Columns added:", result.columnsAdded);
131
90
  ```
132
91
 
133
- ### Pricing with a Custom Algorithm (`getDual`)
92
+ ### Example: Pricing with Plain TypeScript (`getDual`)
134
93
 
135
- Because `pricing` is a standard callback receiving `PricingContext`, you can also solve the pricing problem directly in TypeScript (e.g., via combinatorial search, dynamic programming, or shortest-path routines) instead of constructing a subproblem `Model`:
94
+ You do not need to build a subproblem `Model` inside `pricing`.
95
+ You can run any TypeScript algorithm—such as dynamic programming or a search loop—using `getDual(constraintName)`:
136
96
 
137
97
  ```typescript
138
98
  const customResult = await master.solveColumnGeneration({
@@ -143,7 +103,7 @@ const customResult = await master.solveColumnGeneration({
143
103
  const dB = getDual("demand_B");
144
104
  const dC = getDual("demand_C");
145
105
 
146
- // Search feasible patterns (45*aA + 36*aB + 16*aC <= rollWidth) for negative reduced cost (1 - dualSum < -1e-6)
106
+ // Search for a pattern with negative reduced cost (1 - dualSum < -1e-6)
147
107
  let bestDualSum = 1 + 1e-6;
148
108
  let best: { demand_A: number; demand_B: number; demand_C: number } | null = null;
149
109
  for (let aA = 0; 45 * aA <= rollWidth; aA++) {
@@ -166,11 +126,16 @@ const customResult = await master.solveColumnGeneration({
166
126
 
167
127
  ## Benders Decomposition (`solveBenders`)
168
128
 
169
- `master.solveBenders(options)` partitions a problem into a **Master Problem** (holding first-stage or complicating variables) and a **Subproblem** evaluated at each master candidate solution to generate **Optimality Cuts** or **Feasibility Cuts**.
129
+ `master.solveBenders(options)` splits a problem into a **master problem** for first-stage decisions and a **subproblem** for second-stage evaluation.
130
+ On each iteration, the subproblem evaluates the master's candidate solution and `solveBenders()` adds the resulting linear constraints (**cuts**) back to the master:
131
+
132
+ - **Optimality cut (`kind: "optimality"`)**: Tightens the master's estimate (`theta`) of the subproblem objective when the candidate is feasible but its true second-stage cost exceeds the estimate (for minimization; for maximization, tightens the upper bound when the true value is lower).
133
+ - **Feasibility cut (`kind: "feasibility"`)**: Rules out a master candidate when the subproblem is infeasible or violates a lazy structural rule (such as a disconnected TSP subtour).
170
134
 
171
135
  ### Automatic Cut Generation (`sub.link()`)
172
136
 
173
- Return a continuous LP subproblem `Model` from `subproblem` and declare cross-model constraints via `sub.link(...)`. WaSHI automatically manages the auxiliary cost estimator variable $\theta$, substitutes master candidate values, extracts subproblem duals, and adds Benders cuts until convergence:
137
+ Return a continuous LP subproblem `Model` from `subproblem` and connect it to master variables using `sub.link(...)`.
138
+ WaSHI manages the cost estimator `theta`, substitutes current master values, extracts duals from the LP subproblem, and adds optimality cuts until the bound gap falls within `gapTolerance`:
174
139
 
175
140
  ```typescript
176
141
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -180,11 +145,11 @@ const master = new Model("FacilityMaster");
180
145
  const y1 = master.binary("open_F1");
181
146
  const y2 = master.binary("open_F2");
182
147
 
183
- // Fixed opening costs (theta for operational subproblem cost is managed automatically)
148
+ // Fixed opening costs (operational cost estimator theta is added automatically)
184
149
  master.objective(minimize(expr`100 * ${y1} + 120 * ${y2}`));
185
150
  master.constraint(expr`50 * ${y1} + 60 * ${y2} >= 75`, "total_capacity_floor");
186
151
 
187
- // 2. Solve with automatic Benders cut generation
152
+ // 2. Solve with automatic Benders cuts
188
153
  const result = await master.solveBenders({
189
154
  gapTolerance: 1e-4,
190
155
  subproblem: () => {
@@ -216,15 +181,19 @@ const result = await master.solveBenders({
216
181
 
217
182
  console.log("Optimal total cost:", result.objectiveValue); // 390
218
183
  console.log("Cuts added:", result.cutsAdded);
219
- console.log("Open facilities:", result.values);
184
+ console.log("Master values:", result.values);
220
185
  ```
221
186
 
222
- > [!NOTE]
223
- > **`theta` Lower Bound for Negative Subproblem Objectives**: When `sub.link(...)` is used without an explicit `theta` variable, WaSHI injects `__benders_theta` with default `lb: 0` (assuming non-negative subproblem costs). If your subproblem objective can take negative values (e.g., rebate or profit terms), declare `const theta = master.continuous("theta", { lb: -1e6 })`, include `+ ${theta}` in `master.objective(...)`, and pass `{ theta }` in `solveBenders(options)`.
187
+ > [!IMPORTANT]
188
+ > **Preconditions for Automatic `sub.link()` Mode**:
189
+ > - **Optimality cuts only**: Throws if any master candidate makes the LP subproblem infeasible. Add master feasibility guards (like `total_capacity_floor`) or use manual `kind: "feasibility"` cuts.
190
+ > - **Explicit `theta` for `Maximize` or negative costs**: Auto-`theta` assumes a `Minimize` master with `lb: 0`. For `Maximize` or negative subproblem objectives, declare `theta` on `master` with appropriate bounds, include it in `master.objective()`, and pass `{ theta }`.
191
+ > - **LP-dual solver required**: Requires HiGHS or GLPK to solve the continuous LP subproblem.
224
192
 
225
193
  ### Manual Cut Generation (`BendersCut` / Lazy Constraints)
226
194
 
227
- For combinatorial separation (such as lazy subtour elimination) or custom analytical cuts, return one `BendersCut` object, an array `BendersCut[]`, or `null` when converged:
195
+ For custom cuts, feasibility cuts, or lazy constraints (such as TSP subtour elimination), return a `BendersCut`, a `BendersCut[]`, or `null` when converged.
196
+ When returning an optimality cut, pass the **total evaluated objective** (first-stage objective *excluding* `theta`, plus the actual subproblem objective) in `subproblemObjective` so WaSHI can compare it against the master's bound to compute the optimality gap:
228
197
 
229
198
  ```typescript
230
199
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -259,9 +228,70 @@ console.log(result.objectiveValue); // 70 (y = 1, theta = 30)
259
228
 
260
229
  ---
261
230
 
262
- ## Related Examples & Formulation Tips
231
+ ## Low-Level Primitives (Custom Loops)
232
+
233
+ If you want to build your own decomposition loop instead of using the helpers above, WaSHI exposes four building blocks:
234
+
235
+ ### 1. Constraint Duals (`c.dual`)
236
+
237
+ After solving a continuous LP, read each constraint's dual value (shadow price):
238
+
239
+ ```typescript
240
+ import { Model, expr, maximize } from "@ohtaman/washi";
241
+
242
+ const m = new Model();
243
+ const x = m.continuous("x", { lb: 0 });
244
+ const y = m.continuous("y", { lb: 0 });
245
+
246
+ m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
247
+ const c = m.constraint(expr`${x} + ${y} <= 10`, "capacity");
248
+ await m.solve();
249
+
250
+ console.log(c.dual); // Dual value / shadow price
251
+ console.log(m.solution?.duals.capacity); // Lookup by constraint name
252
+ ```
253
+
254
+ ### 2. Continuous LP Relaxation (`m.relax()`)
255
+
256
+ `m.relax()` temporarily relaxes all `Integer` variables to continuous `[lb, ub]` and `Binary` variables to `[0, 1]`, then solves the LP so dual values are available:
257
+
258
+ ```typescript
259
+ const status = await m.relax();
260
+ console.log("LP relaxation bound:", m.objectiveValue);
261
+ ```
262
+
263
+ ### 3. Dynamic Column Injection (`m.column()`)
264
+
265
+ Add a new variable, set its objective coefficient, and attach it to existing named constraints in one call:
266
+
267
+ ```typescript
268
+ const col = m.column({
269
+ name: "pattern_1",
270
+ type: "Integer", // or "Continuous" / "Binary"
271
+ lb: 0,
272
+ cost: 1, // Objective coefficient
273
+ coefficients: {
274
+ capacity: 2,
275
+ },
276
+ });
277
+ ```
278
+
279
+ ### 4. Dynamic Constraint Updates (`c.addTerm()` / `c.setTerm()`)
280
+
281
+ Add to (introducing the variable if not yet present) or overwrite a variable's coefficient in an existing linear constraint:
282
+
283
+ ```typescript
284
+ const extra = m.continuous("extra", { lb: 0 });
285
+ const budget = m.constraint(expr`${x} + ${y} <= 20`, "budget");
286
+
287
+ budget.addTerm(extra, 5); // Adds +5 * extra to the left-hand side
288
+ budget.setTerm(extra, 0); // Setting 0 removes extra from the constraint
289
+ ```
290
+
291
+ ---
292
+
293
+ ## Related Examples & Tips
263
294
 
264
- - **Full Decomposition Walkthroughs**:
265
- - [Vehicle Routing Problem (`solveColumnGeneration`)](../examples/vehicle-routing.md)
266
- - [Traveling Salesperson Problem (`solveBenders` lazy subtour elimination)](../examples/traveling-salesperson.md)
267
- - **Formulation Tips**: See [Formulation Patterns & Optimization Tips](./formulation-tips.md#_5-decomposition-formulation-tips) for Set Covering (`>= 1`) vs. Set Partitioning (`== 1`), Price-and-Branch (`finalizeAsMIP`), and multi-cut separation.
295
+ - [Vehicle Routing Problem (`solveColumnGeneration`)](../examples/vehicle-routing.md)
296
+ - [Traveling Salesperson Problem (`solveBenders` lazy subtour elimination)](../examples/traveling-salesperson.md)
297
+ - [Formulation Patterns & Tips](./formulation-tips.md#_5-decomposition-formulation-tips)
@@ -1,8 +1,8 @@
1
1
  # Expressions (`expr`, `sum`, `dot`)
2
2
 
3
- Mathematical expressions are linear or quadratic combinations of decision variables and numeric coefficients.
4
-
5
- In JavaScript and TypeScript—which do not support operator overloading—WaSHI provides the **unified tagged template literal (`expr`)**, **`sum()`**, and matrix/vector **`dot()`** to construct algebraic expressions with full static type safety.
3
+ Mathematical expressions combine decision variables and numeric coefficients into linear, quadratic, or piecewise-linear formulas.
4
+ Because JavaScript and TypeScript lack operator overloading, WaSHI provides the `expr` tagged template literal together with `sum()` and `dot()`.
5
+ This lets you write readable algebraic formulas while preserving full static type safety.
6
6
 
7
7
  | Approach | Example | Infix readability | Type safety & IDE rename | Indexed variables (`flow[i][j]`) |
8
8
  | :--- | :--- | :--- | :--- | :--- |
@@ -14,9 +14,11 @@ In JavaScript and TypeScript—which do not support operator overloading—WaSHI
14
14
 
15
15
  ## Tagged Template Literal (`expr`)
16
16
 
17
- Similar to parameterized `sql` tagged templates, `expr` receives static operator text (`+`, `-`, `*`, `^2`, `<=`, `>=`, `==`) separately from interpolated `${...}` values (`Var`, `LinExpr`, `QuadExpr`, or finite `number`). Variables are bound by object reference rather than resolved by string name, avoiding naming collisions and preserving TypeScript type checking and IDE refactoring.
17
+ Similar to parameterized SQL templates, `expr` separates operator text (`+`, `-`, `*`, `/`, `^2`, `<=`, `>=`, `==`, and more) from interpolated `${...}` values.
18
+ You can interpolate `Var`, `LinExpr`, `QuadExpr`, or finite `number` values directly, as well as containers (`Array`, `Iterable`, `Record`) and mapping callbacks inside `sum()` or `dot()`.
19
+ Because variables bind by object reference rather than string lookup, you avoid name collisions and keep IDE refactoring intact.
18
20
 
19
- Use `expr` for both arithmetic expressions (`LinExpr | QuadExpr`) and relational constraints (`Constraint`):
21
+ Use `expr` for both arithmetic expressions (`LinExpr | QuadExpr`) and comparison constraints (`Constraint`):
20
22
 
21
23
  ```typescript
22
24
  import { Model, expr } from "@ohtaman/washi";
@@ -31,30 +33,33 @@ const linearExpr = expr`3 * ${x} + 5 * ${y} - 10`;
31
33
  // 2. Quadratic expression: x * y + 2 * x^2
32
34
  const quadExpr = expr`${x} * ${y} + 2 * ${x} * ${x}`;
33
35
 
34
- // 3. Relational constraint:
36
+ // 3. Comparison constraint:
35
37
  const balanceConstraint = expr`${x} + 2 * ${y} <= 40`;
36
38
  ```
37
39
 
38
40
  ### Supported Syntax in `expr`
39
- - **Addition & Subtraction**: `${x} + ${y} - 5`
40
- - **Scalar Multiplication & Division**: `4 * ${x}`, `${x} / 2`
41
- - **Variable Multiplication (Quadratic terms)**: `${x} * ${y}`, `2 * ${x} * ${x}`
42
- - **Powers & Exponentiation**: `${x}^2`, `${x}**2`
43
- - **Unary Plus & Negation**: `-${x} + 10`, `+${x}`
44
- - **Parentheses**: `2 * (${x} + ${y})`
45
- - **Aggregations (`sum` & `dot`)**: `sum(${xVec}) <= 100`, `dot(${costs}, ${xVec})`, `sum(${rows}, ${(r) => grid[r][col]})`
46
- - **Element-Wise Container Arithmetic**: `sum((${price} - ${cost}) * ${qty})`, `sum((${xVec} - ${target})^2)`, `dot(${price} - ${cost}, ${qty})`
47
- - **Nested Expressions**: `expr` interpolates variables, numbers, `Array` / `Record` containers (inside `sum` or `dot`), and nested `LinExpr` / `QuadExpr` objects.
41
+
42
+ - **Addition & subtraction**: `${x} + ${y} - 5`
43
+ - **Scalar multiplication & division**: `4 * ${x}`, `${x} / 2`
44
+ - **Quadratic terms & powers**: `${x} * ${y}`, `2 * ${x} * ${x}`, `${x}^2`, `${x}**2`
45
+ - **Unary signs & parentheses**: `-${x} + 10`, `+${x}`, `2 * (${x} + ${y})`
46
+ - **Aggregations**: `sum(${xVec})`, `dot(${costs}, ${xVec})`, `sum(${rows}, ${(r) => grid[r][col]})`
47
+ - **Piecewise-linear & element lookup**: `max(${xVec}) <= 15`, `sum(abs(${w} - ${target}))`, `at(${costs}, ${idx})` (see [Piecewise-Linear & Element Expressions](#piecewise-linear-element-expressions-max-min-abs-at))
48
+ - **Element-wise container arithmetic**: `sum((${price} - ${cost}) * ${qty})`, `sum((${xVec} - ${target})^2)`, `dot(${price} - ${cost}, ${qty})`
49
+ - **Nested expressions**: Interpolates variables, numbers, nested `LinExpr` or `QuadExpr` objects, and containers inside `sum` or `dot`.
48
50
 
49
51
  > [!NOTE]
50
- > For relational comparisons (`<=`, `>=`, `==`), `expr` (e.g., ``expr`${x} + 2 * ${y} <= 40` ``) returns a first-class `Constraint`.
51
- > For arithmetic expressions without comparison operators, `expr` uniformly handles linear and quadratic expressions (up to degree 2): if quadratic terms are present, `expr` returns a `QuadExpr`; otherwise, it returns a `LinExpr`. Interpolated `Array` or `Record` containers must be reduced to a scalar via `sum(...)` or `dot(..., ...)`. Polynomial terms of degree $> 2$ (e.g., ``${x} * ${y} * ${z}``, ``${x}^3``) and non-linear constraints (e.g., ``${x} * ${y} <= 10``) throw an error because LP/MIP/QP formulations require linear constraints and at most quadratic objectives.
52
+ > - **Comparisons (`<=`, `>=`, `==`, and integer `<`, `>`, `!=`)** return a `Constraint` object.
53
+ > - **Arithmetic expressions** return a `LinExpr` (degree 1) or `QuadExpr` (degree 2). Embedded containers must be reduced to a scalar via `sum(...)`, `dot(..., ...)`, `max(...)`, or `min(...)`.
54
+ > - **Unsupported nonlinearities**: Polynomial terms of degree $> 2$ (such as `${x}^3`) and quadratic constraints (such as `${x} * ${y} <= 10`) throw an error. (Piecewise-linear `max`, `min`, `abs`, and `at` expressions are supported separately below.)
52
55
 
53
56
  ---
54
57
 
55
58
  ## High-Performance Summation (`sum`)
56
59
 
57
- Sum 1D or 2D `Array`, `Iterable`, or `Record` containers directly inside `` expr`sum(...)` `` or via the standalone `sum()` helper:
60
+ Use `sum()` to sum 1D or 2D `Array`, `Iterable`, or `Record` containers directly, either inside `` expr`sum(...)` `` or as a standalone helper.
61
+ `sum()` runs in $O(N)$ linear time without repeated expression copying.
62
+ Summing quadratic (`QuadExpr`) terms is supported inside `` expr`sum(...)` ``, whereas standalone `sum()` accepts linear terms only:
58
63
 
59
64
  ```typescript
60
65
  import { expr, sum } from "@ohtaman/washi";
@@ -76,16 +81,17 @@ const totalWeight = sum(items, (item) => x[item].mul(weights[item]));
76
81
  const count = sum(x);
77
82
  ```
78
83
 
79
- `sum()` runs in $O(N)$ linear time without AST parsing overhead.
80
-
81
84
  > [!TIP]
82
- > **Avoid $O(N^2)$ `expr` Re-Assignment Inside Loops**: Because `LinExpr` and `expr` results are immutable, accumulating terms one by one via ``total = expr`${total} + ${x[i]}` `` inside a loop copies all previously accumulated terms on every iteration ($O(N^2)$ time and memory). Pass arrays or records to `sum(x)` or `dot(coeffs, x)` for $O(N)$ construction.
85
+ > **Avoid $O(N^2)$ `expr` Re-Assignment Inside Loops**: `LinExpr` objects are immutable.
86
+ > Writing ``total = expr`${total} + ${x[i]}` `` inside a loop copies every existing term on each iteration, costing $O(N^2)$ time and memory.
87
+ > Pass containers to `sum()` or `dot()` for $O(N)$ construction instead.
83
88
 
84
89
  ---
85
90
 
86
91
  ## Dot Product (`dot`)
87
92
 
88
- The `dot(a, b)` helper (usable both inside `` expr`dot(${a}, ${b})` `` and as a standalone function `dot(a, b)`) computes linear combinations of numeric coefficients (`number`) and variables or linear expressions (`Var | LinExpr`) in either operand order (`dot(coeffs, vars)` or `dot(vars, coeffs)`).
93
+ `dot(a, b)` computes a weighted linear combination of numeric coefficients (`number`) and variables or linear expressions (`Var | LinExpr`).
94
+ It works both inside `` expr`dot(${a}, ${b})` `` and as a standalone function, in either operand order (`dot(coeffs, vars)` or `dot(vars, coeffs)`).
89
95
 
90
96
  Supported 1D and 2D container shapes:
91
97
  - **1D Arrays**: `number[]` $\times$ `(Var | LinExpr)[]`
@@ -94,21 +100,21 @@ Supported 1D and 2D container shapes:
94
100
  - **2D Records**: `Record<R, Record<C, number>>` $\times$ `Record<R, Record<C, Var | LinExpr>>`
95
101
  - **2D Mixed**: `Array<Record<C, ...>>` or `Record<R, Array<...>>`
96
102
 
97
- Mismatched array lengths, missing dictionary keys, or non-finite/non-linear leaves throw an explicit error indicating the offending path (e.g., `at '[0].StoreB'`).
103
+ Mismatched array lengths, missing keys, or invalid leaves throw an error identifying the exact path (for example, `at '[0].StoreB'`).
98
104
 
99
105
  ### 1D Vector Dot Product
106
+
100
107
  ```typescript
101
108
  import { expr, dot } from "@ohtaman/washi";
102
109
 
103
110
  const profits = { desk: 30, chair: 50 };
104
111
  const vars = m.integer(["desk", "chair"] as const);
105
112
 
106
- // Computes 30 * vars.desk + 50 * vars.chair inside expr (or via standalone dot(profits, vars))
113
+ // Computes 30 * vars.desk + 50 * vars.chair inside expr
107
114
  const totalProfit = expr`dot(${profits}, ${vars})`;
108
115
  ```
109
116
 
110
117
  ### 2D Matrix Inner Product (Frobenius Inner Product)
111
- Works directly with 2D arrays (`m.continuous(rows, cols)`), nested dictionaries (`m.continuous(rowKeys, colKeys)`), or mixed 2D containers:
112
118
 
113
119
  ```typescript
114
120
  const factories = ["Tokyo", "Osaka"] as const;
@@ -121,33 +127,30 @@ const costs = {
121
127
 
122
128
  const ship = m.continuous(factories, stores, { lb: 0 });
123
129
 
124
- // Total shipping cost across all routes (equivalent to expr`sum(${costs} * ${ship})`):
130
+ // Total shipping cost across all routes:
125
131
  const totalShippingCost = expr`dot(${costs}, ${ship})`;
126
132
  ```
127
133
 
128
134
  > [!NOTE]
129
- > **2D `dot(A, B)` is the Frobenius Inner Product**: For 2D matrices or nested records, `dot(A, B)` computes the scalar **Frobenius inner product** $\langle A, B \rangle_F = \sum_{i,j} A_{i,j} B_{i,j}$ (the sum of element-wise products across all rows and columns, equivalent to `` expr`sum(${A} * ${B})` ``), **not** the matrix-matrix product $(AB)_{i,k} = \sum_j A_{i,j} B_{j,k}$.
135
+ > **2D `dot(A, B)` is the Frobenius Inner Product**: For 2D matrices or nested records, `dot(A, B)` returns the scalar sum of element-wise products $\langle A, B \rangle_F = \sum_{i,j} A_{i,j} B_{i,j}$.
136
+ > It does **not** compute matrix multiplication $(AB)_{i,k} = \sum_j A_{i,j} B_{j,k}$.
130
137
 
131
138
  ---
132
139
 
133
140
  ## Composing Aggregations in `expr`
134
141
 
135
- ### Separating Operators and Data
136
-
137
- Write mathematical operators, `sum(...)`, `dot(..., ...)`, and comparison symbols (`<=`, `>=`, `==`) in the template string, and pass variables, scalars, and containers (`Array` / `Record`) via `${...}`:
142
+ Keep `sum(...)`, `dot(..., ...)`, and comparisons inside the `expr` template string rather than pre-evaluating standalone calls or `Object.values()`:
138
143
 
139
144
  ```typescript
140
- // Nested template calls and Object.values() (verbose)
145
+ // Verbose: nested standalone calls and Object.values()
141
146
  const totalProfit1 = expr`${dot(profits, vars)}`;
142
147
  const cap1 = expr`${sum(Object.values(vars))} <= 100`;
143
148
 
144
- // Direct sum() and dot() inside expr (recommended)
149
+ // Recommended: direct sum() and dot() inside expr
145
150
  const totalProfit2 = expr`dot(${profits}, ${vars})`;
146
151
  const cap2 = expr`sum(${vars}) <= 100`;
147
152
  ```
148
153
 
149
- ### Common `expr` Aggregation Syntax
150
-
151
154
  | Operation | Mathematical Formula | WaSHI Expression |
152
155
  | :--- | :--- | :--- |
153
156
  | **Total sum** (1D/2D `Array` or `Record`) | $\sum_i x_i \le C$ | `` m.constraint(expr`sum(${x}) <= ${C}`) `` |
@@ -162,9 +165,11 @@ const cap2 = expr`sum(${vars}) <= 100`;
162
165
 
163
166
  ## Quadratic Expressions (`QuadExpr` & `expr`)
164
167
 
165
- WaSHI supports Convex Quadratic Programming (QP) objectives via the HiGHS solver. Quadratic expressions can be written using the `expr` template literal or constructed programmatically with `QuadExpr` and `.mul()`.
168
+ WaSHI supports Convex Quadratic Programming (QP) objectives via HiGHS.
169
+ You can write quadratic terms with `expr` or assemble them programmatically using `QuadExpr` and `.mul()`.
166
170
 
167
171
  ### 1. Using `expr` (Recommended)
172
+
168
173
  Write quadratic terms with `*`, `^2`, or `**2`:
169
174
 
170
175
  ```typescript
@@ -182,6 +187,7 @@ m.constraint(expr`${x} + ${y} >= 4`);
182
187
  ```
183
188
 
184
189
  ### 2. Method Chaining with `.mul()` or `QuadExpr`
190
+
185
191
  You can also construct quadratic expressions programmatically:
186
192
 
187
193
  ```typescript
@@ -194,7 +200,7 @@ const y = m.continuous("y", { lb: 0 });
194
200
  // 1. Construct quadratic terms with .mul() (x * y + 2 * x^2)
195
201
  const quad = x.mul(y).add(x.mul(x).mul(2));
196
202
 
197
- // 2. Build portfolio variance objective: w^T * Sigma * w
203
+ // 2. Build portfolio variance objective: w^T * Sigma * w (cross term 0.005 combines 2 * cov)
198
204
  const assets = ["Tech", "Bonds"] as const;
199
205
  const w = m.continuous(assets, { lb: 0, ub: 1 });
200
206
 
@@ -207,13 +213,67 @@ m.objective(minimize(risk));
207
213
  ```
208
214
 
209
215
  > [!NOTE]
210
- > **Convexity Requirement ($\mathbf{Q} \succeq 0$)**: QP solvers (including HiGHS) require the quadratic objective matrix $\mathbf{Q}$ to be **positive semi-definite (PSD)** when minimizing (or negative semi-definite when maximizing). Sum-of-squares terms ($\sum_i (x_i - t_i)^2$) and covariance matrices ($\mathbf{w}^\top \boldsymbol{\Sigma} \mathbf{w}$) are guaranteed PSD, whereas indefinite products over continuous variables (such as minimizing $x \cdot y$) are non-convex and rejected by the solver. *(To linearize the product of two binary variables $x_A \cdot x_B$ in MILP, see [Formulation Patterns & Tips](./formulation-tips.md#product-of-two-binary-variables).)*
216
+ > **Convexity Requirement ($\mathbf{Q} \succeq 0$)**: When minimizing a quadratic objective, HiGHS requires the symmetric quadratic matrix $\mathbf{Q}$ to be **positive semi-definite (PSD, $\mathbf{Q} \succeq 0$)**.
217
+ > When maximizing, $\mathbf{Q}$ must be **negative semi-definite ($\mathbf{Q} \preceq 0$)**.
218
+ > Sums of squares ($\sum_i (x_i - t_i)^2$) and variance quadratic forms $\mathbf{w}^\top \boldsymbol{\Sigma} \mathbf{w}$ (with a valid covariance matrix $\boldsymbol{\Sigma}$) are guaranteed convex ($\mathbf{Q} \succeq 0$).
219
+ > Indefinite products of continuous variables (such as minimizing $x \cdot y$) are non-convex and rejected by the solver.
220
+ > To linearize the product of two binary variables $x_A \cdot x_B$ in MILP, see [Formulation Patterns & Tips](./formulation-tips.md#product-of-two-binary-variables).
221
+
222
+ ---
223
+
224
+ ## Piecewise-Linear & Element Expressions (`max`, `min`, `abs`, `at`)
225
+
226
+ WaSHI provides backend-agnostic piecewise-linear functions (`max`, `min`, `abs`) and 0-based variable indexing (`at`).
227
+ They work both inside `` expr`...` `` and as standalone helpers imported from `@ohtaman/washi`:
228
+
229
+ ```typescript
230
+ import { Model, expr, minimize, abs, max, min, at } from "@ohtaman/washi";
231
+
232
+ const m = new Model();
233
+ const w = m.continuous(3, { lb: 0, ub: 20, prefix: "w" });
234
+ const target = [4, 7, 10];
235
+ const route = m.integer("route", { lb: 0, ub: 2 });
236
+ const routeCost = [18, 12, 25];
237
+
238
+ // Convex max/abs terms lower to linear inequalities with zero binary variables (at() uses binary selectors on HiGHS/GLPK):
239
+ m.objective(
240
+ minimize(expr`sum(abs(${w} - ${target})) + at(${routeCost}, ${route})`)
241
+ );
242
+ m.constraint(expr`max(${w}) <= 15`, "peak_cap");
243
+
244
+ // Nested composition and programmatic helpers also work:
245
+ const maxErr = max(expr`abs(${w[0]} - 4)`, abs(expr`${w[1]} - 7`));
246
+ m.constraint(expr`${maxErr} <= 3`);
247
+ ```
248
+
249
+ ### Element-Wise Container Support
250
+
251
+ Inside `expr`, `abs(${arr} - ${target})` expands element-wise over matching 1D or 2D `Array`, `Iterable`, and `Record` containers.
252
+ This lets you write expressions such as `` expr`sum(abs(${w} - ${target}))` `` and `` expr`max(abs(${pred} - ${actual}))` `` directly.
253
+
254
+ ### How Each Solver Handles `max`, `min`, and `abs`
255
+
256
+ In **convex directions**—minimizing or upper-bounding (`<=`) `max` and `abs`, or maximizing or lower-bounding (`>=`) `min`—HiGHS and GLPK use a continuous auxiliary variable with simple linear inequalities.
257
+ This *epigraph* formulation requires **zero binary variables** and works even on unbounded continuous variables.
258
+
259
+ In **non-convex or equality contexts** (`minimize(min(...))`, `maximize(abs(...))`, `max(...) >= rhs`, `abs(...) == rhs`), solvers differ as follows:
260
+
261
+ - **HiGHS & GLPK**: Use an exact discrete MIP encoding, so every participating variable must have finite bounds.
262
+ - **Pumpkin**: Solves these natively over bounded integer variables.
263
+ - **Z3**: Represents them with native conditional (`If`) expressions.
264
+
265
+ ### 0-Based Element Lookup (`at(array, index)`)
266
+
267
+ `at(array, index)` models the classic Constraint Programming `Element` constraint, where the array index itself is a decision variable (`array[index]`).
268
+ The `index` expression must be integer-valued, and all backends automatically enforce `0 <= index < array.length`.
269
+ Pumpkin and Z3 handle `at()` natively, while HiGHS and GLPK encode it with binary selector variables (requiring finite bounds on any variable entries in `array`).
211
270
 
212
271
  ---
213
272
 
214
273
  ## Evaluating Expressions After Solving (`.value`)
215
274
 
216
- Both `LinExpr` and `QuadExpr` expose a `.value` getter (`number | null`). Once a model has been solved and all referenced variables have finite primal values, you can evaluate any sub-expression directly:
275
+ Both `LinExpr` and `QuadExpr` expose a `.value` getter returning `number | null`.
276
+ Once a model has been solved and every referenced variable has a finite value, you can evaluate any sub-expression directly:
217
277
 
218
278
  ```typescript
219
279
  import { Model, expr, maximize } from "@ohtaman/washi";
@@ -235,7 +295,7 @@ console.log("Total Revenue:", revenue.value); // 1100 (x = 20, y = 10)
235
295
  console.log("Labor Used:", laborUsed.value); // 50
236
296
  ```
237
297
 
238
- If the model has not been solved (or any variable in the expression has `value === null`), `.value` returns `null`.
298
+ If the model has not been solved, or if any referenced variable has `value === null`, `.value` returns `null`.
239
299
 
240
300
  ---
241
301
 
@@ -247,9 +307,12 @@ In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent
247
307
  | :--- | :--- | :--- | :--- |
248
308
  | `.add(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Adds a number, `Var`, `LinExpr`, or `QuadExpr`. |
249
309
  | `.sub(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Subtracts a number, `Var`, `LinExpr`, or `QuadExpr`. |
250
- | `.mul(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Multiplies by a scalar `number`, or multiplies two linear terms into a `QuadExpr`. |
310
+ | `.mul(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Multiplies by a scalar `number`, or multiplies two linear expressions into a `QuadExpr` (a `QuadExpr` with quadratic terms only allows scalar multiplication; degree $> 2$ throws). |
251
311
  | `.div(divisor)` | `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Divides by a non-zero finite scalar `number`. |
252
312
  | `.neg()` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Negates all terms ($-e$). |
253
- | `.le(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`). |
254
- | `.ge(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`). |
255
- | `.eq(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs`). |
313
+ | `.le(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`; both sides must have no quadratic terms). |
314
+ | `.ge(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`; both sides must have no quadratic terms). |
315
+ | `.eq(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds an $=$ equality constraint (`lhs == rhs`; both sides must have no quadratic terms). |
316
+ | `.lt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $<$ constraint (`lhs - rhs <= -1`; integer-valued expressions without quadratic terms only). |
317
+ | `.gt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $>$ constraint (`lhs - rhs >= 1`; integer-valued expressions without quadratic terms only). |
318
+ | `.ne(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $\ne$ constraint (`lhs != rhs`; integer-valued expressions without quadratic terms only). |