@ohtaman/washi 0.8.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 (81) hide show
  1. package/README.ja.md +22 -24
  2. package/README.md +20 -22
  3. package/README.zh-CN.md +25 -27
  4. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  5. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  6. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  7. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  8. package/dist/browser/solvers/highs.js +1414 -0
  9. package/dist/browser/washi.js +1090 -1473
  10. package/dist/browser/washi.min.js +4 -4
  11. package/dist/lib/solvers/glpk.js +34 -32
  12. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  13. package/dist/lib/solvers/highs.js +410 -0
  14. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  15. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  16. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  17. package/dist/lib/solvers/pumpkin.js +247 -1146
  18. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  19. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  20. package/dist/lib/solvers/z3.js +125 -123
  21. package/dist/lib/washi.js +2426 -1340
  22. package/dist/types/index.d.ts +1 -2
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/modeler/index.d.ts +0 -1
  25. package/dist/types/modeler/index.d.ts.map +1 -1
  26. package/dist/types/modeler/model.d.ts +6 -7
  27. package/dist/types/modeler/model.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/index.d.ts +2 -1
  29. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  31. package/docs/examples/diet-sensitivity.md +33 -14
  32. package/docs/examples/ecommerce-coupons.md +17 -9
  33. package/docs/examples/index.md +34 -30
  34. package/docs/examples/knapsack.md +11 -5
  35. package/docs/examples/portfolio-qp.md +21 -8
  36. package/docs/examples/production.md +10 -5
  37. package/docs/examples/project-scheduling.md +25 -12
  38. package/docs/examples/shift-scheduling.md +27 -19
  39. package/docs/examples/smt-security.md +27 -12
  40. package/docs/examples/transportation.md +23 -13
  41. package/docs/examples/traveling-salesperson.md +34 -22
  42. package/docs/examples/unsat-core.md +27 -15
  43. package/docs/examples/vehicle-routing.md +74 -28
  44. package/docs/getting-started/ai-agents.md +129 -90
  45. package/docs/getting-started/coding-agents.md +60 -41
  46. package/docs/getting-started/cross-origin.md +27 -14
  47. package/docs/getting-started/index.md +23 -16
  48. package/docs/getting-started/runtimes.md +70 -40
  49. package/docs/guide/constraint-programming.md +74 -44
  50. package/docs/guide/constraints.md +71 -39
  51. package/docs/guide/decomposition.md +72 -42
  52. package/docs/guide/expressions.md +79 -48
  53. package/docs/guide/formulation-tips.md +46 -27
  54. package/docs/guide/objectives.md +55 -31
  55. package/docs/guide/unsat-core.md +56 -53
  56. package/docs/guide/variables.md +61 -28
  57. package/docs/solvers/custom-solver.md +155 -119
  58. package/docs/solvers/glpk.md +58 -17
  59. package/docs/solvers/highs.md +115 -43
  60. package/docs/solvers/index.md +33 -26
  61. package/docs/solvers/pumpkin.md +71 -63
  62. package/docs/solvers/z3.md +63 -25
  63. package/llms-full.txt +1623 -953
  64. package/llms.txt +125 -93
  65. package/package.json +29 -20
  66. package/skills/washi/SKILL.md +43 -22
  67. package/dist/browser/solvers/pumpkin.min.js +0 -1
  68. package/dist/lib/registry-dx7x4e5c.js +0 -1694
  69. /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
  70. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  71. /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
  72. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  73. /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
  74. /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
  75. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  76. /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
  77. /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
  78. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  79. /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
  80. /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
  81. /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
@@ -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,31 +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
- - **Piecewise-Linear & Element Functions (`max`, `min`, `abs`, `at`)**: `max(${xVec}) <= 15`, `sum(abs(${w} - ${target}))`, `at(${costs}, ${idx})` (see [Piecewise-Linear & Element Expressions](#piecewise-linear-element-expressions-max-min-abs-at))
47
- - **Element-Wise Container Arithmetic**: `sum((${price} - ${cost}) * ${qty})`, `sum((${xVec} - ${target})^2)`, `dot(${price} - ${cost}, ${qty})`
48
- - **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`.
49
50
 
50
51
  > [!NOTE]
51
- > For relational comparisons (`<=`, `>=`, `==`), `expr` (e.g., ``expr`${x} + 2 * ${y} <= 40` ``) returns a first-class `Constraint`.
52
- > 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.)
53
55
 
54
56
  ---
55
57
 
56
58
  ## High-Performance Summation (`sum`)
57
59
 
58
- 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:
59
63
 
60
64
  ```typescript
61
65
  import { expr, sum } from "@ohtaman/washi";
@@ -77,16 +81,17 @@ const totalWeight = sum(items, (item) => x[item].mul(weights[item]));
77
81
  const count = sum(x);
78
82
  ```
79
83
 
80
- `sum()` runs in $O(N)$ linear time without AST parsing overhead.
81
-
82
84
  > [!TIP]
83
- > **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.
84
88
 
85
89
  ---
86
90
 
87
91
  ## Dot Product (`dot`)
88
92
 
89
- 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)`).
90
95
 
91
96
  Supported 1D and 2D container shapes:
92
97
  - **1D Arrays**: `number[]` $\times$ `(Var | LinExpr)[]`
@@ -95,21 +100,21 @@ Supported 1D and 2D container shapes:
95
100
  - **2D Records**: `Record<R, Record<C, number>>` $\times$ `Record<R, Record<C, Var | LinExpr>>`
96
101
  - **2D Mixed**: `Array<Record<C, ...>>` or `Record<R, Array<...>>`
97
102
 
98
- 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'`).
99
104
 
100
105
  ### 1D Vector Dot Product
106
+
101
107
  ```typescript
102
108
  import { expr, dot } from "@ohtaman/washi";
103
109
 
104
110
  const profits = { desk: 30, chair: 50 };
105
111
  const vars = m.integer(["desk", "chair"] as const);
106
112
 
107
- // 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
108
114
  const totalProfit = expr`dot(${profits}, ${vars})`;
109
115
  ```
110
116
 
111
117
  ### 2D Matrix Inner Product (Frobenius Inner Product)
112
- Works directly with 2D arrays (`m.continuous(rows, cols)`), nested dictionaries (`m.continuous(rowKeys, colKeys)`), or mixed 2D containers:
113
118
 
114
119
  ```typescript
115
120
  const factories = ["Tokyo", "Osaka"] as const;
@@ -122,18 +127,19 @@ const costs = {
122
127
 
123
128
  const ship = m.continuous(factories, stores, { lb: 0 });
124
129
 
125
- // Total shipping cost across all routes (equivalent to expr`sum(${costs} * ${ship})`):
130
+ // Total shipping cost across all routes:
126
131
  const totalShippingCost = expr`dot(${costs}, ${ship})`;
127
132
  ```
128
133
 
129
134
  > [!NOTE]
130
- > **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}$.
131
137
 
132
138
  ---
133
139
 
134
140
  ## Composing Aggregations in `expr`
135
141
 
136
- Keep operators, `sum(...)`, `dot(..., ...)`, and comparisons (`<=`, `>=`, `==`) in the template string, and interpolate containers directly via `${...}` rather than pre-evaluating standalone `sum()`/`dot()` or `Object.values()`:
142
+ Keep `sum(...)`, `dot(..., ...)`, and comparisons inside the `expr` template string rather than pre-evaluating standalone calls or `Object.values()`:
137
143
 
138
144
  ```typescript
139
145
  // Verbose: nested standalone calls and Object.values()
@@ -159,9 +165,11 @@ const cap2 = expr`sum(${vars}) <= 100`;
159
165
 
160
166
  ## Quadratic Expressions (`QuadExpr` & `expr`)
161
167
 
162
- 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()`.
163
170
 
164
171
  ### 1. Using `expr` (Recommended)
172
+
165
173
  Write quadratic terms with `*`, `^2`, or `**2`:
166
174
 
167
175
  ```typescript
@@ -179,6 +187,7 @@ m.constraint(expr`${x} + ${y} >= 4`);
179
187
  ```
180
188
 
181
189
  ### 2. Method Chaining with `.mul()` or `QuadExpr`
190
+
182
191
  You can also construct quadratic expressions programmatically:
183
192
 
184
193
  ```typescript
@@ -191,7 +200,7 @@ const y = m.continuous("y", { lb: 0 });
191
200
  // 1. Construct quadratic terms with .mul() (x * y + 2 * x^2)
192
201
  const quad = x.mul(y).add(x.mul(x).mul(2));
193
202
 
194
- // 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)
195
204
  const assets = ["Tech", "Bonds"] as const;
196
205
  const w = m.continuous(assets, { lb: 0, ub: 1 });
197
206
 
@@ -204,13 +213,18 @@ m.objective(minimize(risk));
204
213
  ```
205
214
 
206
215
  > [!NOTE]
207
- > **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).
208
221
 
209
222
  ---
210
223
 
211
224
  ## Piecewise-Linear & Element Expressions (`max`, `min`, `abs`, `at`)
212
225
 
213
- WaSHI provides backend-agnostic scalar piecewise-linear (`max`, `min`, `abs`) and 0-based variable-indexed lookup (`at`) primitives that work directly inside `` expr`...` `` or as standalone helpers imported from `@ohtaman/washi`:
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`:
214
228
 
215
229
  ```typescript
216
230
  import { Model, expr, minimize, abs, max, min, at } from "@ohtaman/washi";
@@ -221,7 +235,7 @@ const target = [4, 7, 10];
221
235
  const route = m.integer("route", { lb: 0, ub: 2 });
222
236
  const routeCost = [18, 12, 25];
223
237
 
224
- // Convex LP epigraph (zero binary variables on HiGHS / GLPK):
238
+ // Convex max/abs terms lower to linear inequalities with zero binary variables (at() uses binary selectors on HiGHS/GLPK):
225
239
  m.objective(
226
240
  minimize(expr`sum(abs(${w} - ${target})) + at(${routeCost}, ${route})`)
227
241
  );
@@ -232,17 +246,34 @@ const maxErr = max(expr`abs(${w[0]} - 4)`, abs(expr`${w[1]} - 7`));
232
246
  m.constraint(expr`${maxErr} <= 3`);
233
247
  ```
234
248
 
235
- - **Element-wise container support**: Inside `expr`, `abs(${arr} - ${target})` evaluates element-wise across matching 1D/2D `Array`, `Iterable`, or `Record` containers so patterns like `` expr`sum(abs(${w} - ${target}))` `` and `` expr`max(abs(${pred} - ${actual}))` `` work naturally.
236
- - **Polarity-aware MIP lowering vs native CP/SMT**:
237
- - In convex directions on HiGHS and GLPK (`minimize` or `<=` on `max`/`abs`, `maximize` or `>=` on `min`), WaSHI emits pure continuous LP epigraph constraints with **zero binary variables** (even on unbounded `Continuous` variables).
238
- - In non-convex or equality contexts (`minimize(min(...))`, `maximize(abs(...))`, `max(...) >= rhs`, `abs(...) == rhs`), HiGHS and GLPK emit bounded MIP formulations (requiring finite variable bounds), Pumpkin lowers via native `maximum`/`minimum`/`absolute` propagators over bounded integers, and Z3 uses native `If` (`ITE`).
239
- - **0-based element lookup (`at(array, index)`)**: Models the classic CP `Element` constraint (`array[index]`). Requires an integer-valued `index` expression and automatically enforces $0 \le \text{index} < \text{array.length}$ across all solvers (native `element` propagator on Pumpkin, nested `If` + bounds guards on Z3, and binary convex-hull linearization on HiGHS/GLPK).
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`).
240
270
 
241
271
  ---
242
272
 
243
273
  ## Evaluating Expressions After Solving (`.value`)
244
274
 
245
- 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:
246
277
 
247
278
  ```typescript
248
279
  import { Model, expr, maximize } from "@ohtaman/washi";
@@ -264,7 +295,7 @@ console.log("Total Revenue:", revenue.value); // 1100 (x = 20, y = 10)
264
295
  console.log("Labor Used:", laborUsed.value); // 50
265
296
  ```
266
297
 
267
- 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`.
268
299
 
269
300
  ---
270
301
 
@@ -276,12 +307,12 @@ In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent
276
307
  | :--- | :--- | :--- | :--- |
277
308
  | `.add(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Adds a number, `Var`, `LinExpr`, or `QuadExpr`. |
278
309
  | `.sub(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Subtracts a number, `Var`, `LinExpr`, or `QuadExpr`. |
279
- | `.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). |
280
311
  | `.div(divisor)` | `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Divides by a non-zero finite scalar `number`. |
281
312
  | `.neg()` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Negates all terms ($-e$). |
282
- | `.le(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`; linear LHS required). |
283
- | `.ge(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`; linear LHS required). |
284
- | `.eq(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs`; linear LHS required). |
285
- | `.lt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $<$ constraint (`lhs - rhs <= -1`; integer-valued expressions only). |
286
- | `.gt(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $>$ constraint (`lhs - rhs >= 1`; integer-valued expressions only). |
287
- | `.ne(rhs)` | `Var`, `LinExpr`, `QuadExpr` | `Constraint` | Builds a discrete $\ne$ constraint (`lhs != rhs`; integer-valued expressions only). |
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). |
@@ -1,6 +1,8 @@
1
1
  # Formulation Patterns & Optimization Tips
2
2
 
3
- While the preceding Modeling Guide pages cover WaSHI's APIs (`Model`, `expr`, `m.constraint`, `m.solve`, etc.), this page collects standard mathematical optimization formulation patterns and solver tuning techniques frequently used in linear and mixed-integer programming (LP/MIP). *(For Constraint Programming idioms such as `disjoint`, `cumulative`, `distinct`, `allowed`, and `at` with Pumpkin, see the [Constraint Programming (CP) Modeling Guide](./constraint-programming.md).)*
3
+ The preceding guide pages cover WaSHI's core APIs (`Model`, `expr`, `m.constraint`, `m.solve`).
4
+ This page collects reusable mathematical formulation patterns and solver tuning techniques for Linear Programming (LP) and Mixed-Integer Linear Programming (MILP).
5
+ For Constraint Programming idioms with Pumpkin (`disjoint`, `cumulative`, `distinct`, `allowed`, `at`), see the [Constraint Programming (CP) Modeling Guide](./constraint-programming.md).
4
6
 
5
7
  ---
6
8
 
@@ -8,9 +10,10 @@ While the preceding Modeling Guide pages cover WaSHI's APIs (`Model`, `expr`, `m
8
10
 
9
11
  ### Semi-Continuous Decisions ($\{0\} \cup [L, U]$)
10
12
 
11
- A semi-continuous quantity must be either `0` (inactive) or within a positive interval `[L, U]` (e.g., a production batch with a minimum run size $L = 10$ and capacity $U = 100$).
13
+ A semi-continuous variable must be either `0` when inactive, or lie inside a positive interval $[L, U]$ (`0 < L <= U`) when active.
14
+ For example, a production batch might require a minimum run size $L = 10$ and capacity $U = 100$.
12
15
 
13
- Combine a continuous variable `x` with a binary activation variable `isActive` and linking constraints $L \cdot b \le x \le U \cdot b$:
16
+ Combine a continuous variable $x$ (`batch`) with a binary activation variable $b$ (`isActive`) using linking inequalities $L \cdot b \le x \le U \cdot b$:
14
17
 
15
18
  ```typescript
16
19
  import { Model, expr } from "@ohtaman/washi";
@@ -26,9 +29,10 @@ m.constraint(expr`${batch} <= 100 * ${isActive}`, "max_batch_run");
26
29
 
27
30
  ### Minimal-Perturbation Rescheduling vs. Warm Starting
28
31
 
29
- When re-optimizing an existing schedule after a disruption, passing yesterday's assignment via [`initialValue`](./variables.md#primal-initial-values-warm-start-hints) only gives the MIP solver a starting search point—it does **not** prevent the solver from changing every assignment for a tiny objective gain.
32
+ When re-optimizing a schedule after a disruption, passing the previous plan via [`initialValue`](./variables.md#primal-initial-values-warm-start-hints) only gives the solver a starting hint.
33
+ It does **not** prevent the solver from rewriting the entire schedule for a tiny objective gain.
30
34
 
31
- To keep a revised binary plan $x_i \in \{0, 1\}$ close to a baseline assignment $x_i^{\text{prev}} \in \{0, 1\}$, penalize the **Hamming distance** (number of flipped decisions) in the objective:
35
+ To keep a revised binary plan $x_i \in \{0, 1\}$ close to a baseline $x_i^{\text{prev}} \in \{0, 1\}$, penalize the **Hamming distance** (total number of flipped decisions) in the objective:
32
36
 
33
37
  $$\text{Changes} = \sum_{i:\, x_i^{\text{prev}} = 0} x_i + \sum_{i:\, x_i^{\text{prev}} = 1} (1 - x_i)$$
34
38
 
@@ -44,7 +48,7 @@ const x = prevPlan.map((prev, i) =>
44
48
  // Linear terms counting how many 0/1 decisions differ from prevPlan
45
49
  const flipTerms = x.map((v, i) => (prevPlan[i] === 1 ? expr`1 - ${v}` : v));
46
50
 
47
- // Require at least 3 active slots while penalizing changes from prevPlan
51
+ // Require at least 3 active slots while minimizing changes (in practice, add this weighted penalty to your main cost objective)
48
52
  m.constraint(expr`sum(${x}) >= 3`, "min_active_slots");
49
53
  m.objective(minimize(expr`5 * sum(${flipTerms})`));
50
54
  ```
@@ -55,7 +59,8 @@ m.objective(minimize(expr`5 * sum(${flipTerms})`));
55
59
 
56
60
  ### Product of Two Binary Variables ($x_A \cdot x_B$)
57
61
 
58
- In integer programming, if an interaction cost or synergy bonus applies only when two binary decisions $x_A, x_B \in \{0, 1\}$ are **both** equal to `1`, avoid introducing a quadratic term. Instead, introduce an auxiliary variable $z_{AB} \in [0, 1]$ and add the three standard McCormick / Fortet linear inequalities so the model remains a pure MILP:
62
+ Suppose a synergy bonus or interaction cost applies only when two binary decisions $x_A, x_B \in \{0, 1\}$ are **both** equal to `1`.
63
+ Rather than writing a quadratic product, introduce an auxiliary variable $z_{AB} \in [0, 1]$ with three linear inequalities (standard Fortet / McCormick linearization) so the model remains a pure MILP:
59
64
 
60
65
  $$z_{AB} \le x_A, \quad z_{AB} \le x_B, \quad z_{AB} \ge x_A + x_B - 1$$
61
66
 
@@ -77,9 +82,11 @@ m.objective(maximize(expr`10 * ${xA} + 10 * ${xB} + 5 * ${bothAB}`));
77
82
 
78
83
  ### Min-Max & Max-Min Objectives (Load Balancing)
79
84
 
80
- WaSHI's built-in `max(...)` and `min(...)` primitives (see [Piecewise-Linear & Element Expressions](./expressions.md#piecewise-linear-element-expressions-max-min-abs-at)) already automate convex LP epigraph lowering on HiGHS/GLPK and map directly to native propagators on Pumpkin.
85
+ WaSHI's built-in `max(...)` and `min(...)` helpers already convert convex load-balancing objectives into pure linear inequalities on HiGHS and GLPK, and native constraints on Pumpkin.
86
+ See [Piecewise-Linear & Element Expressions](./expressions.md#piecewise-linear-element-expressions-max-min-abs-at).
81
87
 
82
- When you need explicit access to the auxiliary ceiling/floor variable $z$—for example, to reuse it inside a second-stage constraint for lexicographic optimization (Section 4)—you can write the epigraph reformulation directly by constraining every individual load $\text{load}_i \le z$ and minimizing $z$ (or $\text{u}_i \ge z$ and maximizing $z$ for Max-Min):
88
+ When you need explicit access to the shared ceiling variable $z$—for instance, to reuse it in subsequent constraints or multi-stage formulations (such as constraining peak load after a first-stage solve)—write the **epigraph** reformulation directly.
89
+ Constrain every load $\text{load}_i \le z$ and minimize $z$ (for Max-Min, constrain each score or utility $u_i \ge z$ and maximize $z$):
83
90
 
84
91
  $$\min z \quad \text{subject to} \quad \text{load}_i \le z \quad \forall i$$
85
92
 
@@ -105,7 +112,8 @@ m.objective(minimize(maxHours));
105
112
 
106
113
  ### Hard vs. Soft Constraints (Elastic Slack Variables)
107
114
 
108
- Treating every business target as a strict **hard constraint** makes a model `"Infeasible"` as soon as demand exceeds capacity. Keep physical and legal invariants as hard constraints, and model non-rigid targets as **soft constraints** by adding non-negative slack variables ($s \ge 0$) with penalty weights $W$ in the objective:
115
+ Treating every business target as a strict **hard constraint** makes the model `"Infeasible"` as soon as demand exceeds capacity.
116
+ Keep physical and legal limits as hard constraints, and convert flexible targets into **soft constraints** by adding non-negative slack variables ($s \ge 0$) penalized by weight $W$ in the objective:
109
117
 
110
118
  | Target Type | Hard Constraint | Soft Constraint ($s \ge 0$) | Objective Penalty Term (Minimize) |
111
119
  | :--- | :--- | :--- | :--- |
@@ -131,13 +139,15 @@ await m.solve();
131
139
  ```
132
140
 
133
141
  > [!TIP]
134
- > **Scaling Penalty Weights ($W$)**: Choose $W$ larger than normal operational marginal costs (typically $10\times$ to $1{,}000\times$ unit cost), and avoid extreme constants such as $10^{12}$. Keeping the ratio between the largest and smallest coefficients within $10^5\text{–}10^6$ preserves floating-point numerical stability in LP/MIP solvers.
142
+ > **Scaling Penalty Weights ($W$)**: Set $W$ larger than normal marginal costs (typically 10×–1,000× unit cost), and avoid extreme constants like 10<sup>12</sup>.
143
+ > Keeping the ratio between the largest and smallest non-zero absolute coefficients within 10<sup>5</sup>–10<sup>6</sup> preserves floating-point accuracy in LP and MIP solvers.
135
144
 
136
145
  ### Symmetry Breaking for Identical Resources
137
146
 
138
- When a model contains $K$ interchangeable resources—such as identical trucks, bins, or parallel machines—any feasible assignment has up to $K!$ equivalent permutations with the exact same objective value. Without symmetry breaking, a MIP solver explores redundant mirror-image subtrees before proving optimality.
147
+ When a model contains $K$ interchangeable resources—such as identical trucks, bins, or machines—every feasible assignment has up to $K!$ equivalent permutations with the same objective value.
148
+ Without symmetry breaking, a MIP solver explores redundant isomorphic subtrees before proving optimality.
139
149
 
140
- Impose a canonical ordering ($u_0 \ge u_1 \ge \dots \ge u_{K-1}$) so identical resources are activated in index order:
150
+ Let $u_k \in \{0, 1\}$ indicate whether resource $k$ is used, and impose a canonical ordering ($u_0 \ge u_1 \ge \dots \ge u_{K-1}$) so identical resources activate in index order:
141
151
 
142
152
  ```typescript
143
153
  import { Model, expr } from "@ohtaman/washi";
@@ -161,10 +171,10 @@ for (let k = 0; k < numTrucks - 1; k++) {
161
171
 
162
172
  ### Weighted Sum vs. Lexicographic Two-Stage Optimization
163
173
 
164
- When balancing competing goals—such as minimizing total cost ($f_1$) while also minimizing peak workload ($f_2$)—two approaches are standard:
174
+ When balancing competing goals—such as minimizing total cost $f_1$ and peak workload $f_2$—two strategies are standard:
165
175
 
166
- - **Weighted Sum (Single Solve)**: Combine normalized terms into one objective, e.g., ``minimize(expr`${totalCost} + 50 * ${maxHours}`)``.
167
- - **Lexicographic (Hierarchical) Two-Stage Solve**: When the primary objective has strict priority, solve for $f_1$ first, add a constraint locking $f_1$ within an acceptable tolerance of its optimum $f_1^*$, and re-solve for $f_2$:
176
+ - **Weighted sum (single solve)**: Normalize terms onto a comparable scale and combine them into one objective, such as ``minimize(expr`${totalCost} + 50 * ${maxHours}`)``.
177
+ - **Lexicographic two-stage solve**: Solve for the primary objective $f_1$ first, lock $f_1$ within a tolerance of its optimum $f_1^*$, and then re-solve for $f_2$.
168
178
 
169
179
  ```typescript
170
180
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -192,21 +202,30 @@ await m.solve();
192
202
 
193
203
  ### MIP Tail-Off & Optimality Gap Tolerances
194
204
 
195
- In combinatorial MIP problems, solvers often find a near-optimal feasible solution within seconds, then spend most of the remaining runtime closing the final fraction of a percent in the branch-and-bound tree (**tail-off**).
205
+ In combinatorial MIP problems, solvers often find a strong incumbent solution within seconds, then spend most of their runtime proving the last fraction of a percent (**tail-off**).
196
206
 
197
- In interactive UIs and batch pipelines, combine `timeLimit` with business-meaningful tolerances in [`m.solve(options)`](./objectives.md#solve-options-solveoptions):
198
- - **`relativeGap: 0.01`**: Stop immediately once the incumbent is proven within **1%** of the theoretical dual bound.
199
- - **`absoluteGap: 100`**: Stop immediately once `|objectiveValue - objectiveBound| <= 100` in the objective's native units.
207
+ In interactive apps and batch pipelines, pair `timeLimit` with practical tolerances in [`m.solve(options)`](./objectives.md#solve-options-solveoptions):
208
+
209
+ - **`relativeGap: 0.01`** (HiGHS / GLPK): Stops once the incumbent objective is proven within **1%** of the dual bound.
210
+ - **`absoluteGap: 100`** (HiGHS only): Stops once `|objectiveValue - objectiveBound| <= 100` in objective units.
200
211
 
201
212
  ---
202
213
 
203
214
  ## 5. Decomposition Formulation Tips
204
215
 
205
- When using [`solveColumnGeneration` or `solveBenders`](./decomposition.md):
216
+ When using [`solveColumnGeneration` or `solveBenders`](./decomposition.md), three modeling practices improve convergence and solution quality.
217
+
218
+ ### Set Covering (`>= 1`) vs. Set Partitioning (`== 1`) in Column Generation
219
+
220
+ In minimization problems, writing demand coverage as inequalities (`>= 1`) rather than equalities (`== 1`) restricts dual shadow prices to $\pi_i \ge 0$.
221
+ This reduces dual oscillations and speeds up convergence whenever over-coverage can be removed without increasing cost (such as Euclidean routing under the triangle inequality).
222
+
223
+ ### Price-and-Branch (`finalizeAsMIP: true`) vs. Exact Branch-and-Price
224
+
225
+ Solving one final MIP over the columns generated at the root LP relaxation (`finalizeAsMIP: true`) is called the **Price-and-Branch** heuristic.
226
+ Unlike exact **Branch-and-Price**—which re-runs column generation inside every branch-and-bound node—Price-and-Branch avoids embedding branching constraints into the pricing subproblem while producing strong integer solutions quickly (though exact integer optimality is not guaranteed).
227
+
228
+ ### Returning Multiple Cuts per Iteration (Benders & Lazy Constraints)
206
229
 
207
- 1. **Set Covering (`>= 1`) vs. Set Partitioning (`== 1`) in Column Generation**:
208
- Formulating coverage constraints as inequalities (`>= 1`) rather than equalities (`== 1`) restricts dual shadow prices to $\pi_i \ge 0$, reducing dual oscillations and accelerating convergence whenever over-coverage can be pruned at no extra cost (e.g., Euclidean routing under the triangle inequality).
209
- 2. **Price-and-Branch (`finalizeAsMIP: true`) vs. Exact Branch-and-Price**:
210
- Solving the final Restricted Master Problem as a MIP over columns generated at the root LP relaxation (`finalizeAsMIP: true`) implements the **Price-and-Branch** heuristic—avoiding complex branching inside the pricing subproblem while producing high-quality integer solutions in practice.
211
- 3. **Multi-Cut Separation in Benders / Lazy Constraints**:
212
- When a separation callback detects multiple disconnected subtours or violated components in a candidate solution, returning cuts for **all** violated components in one batch reduces the number of master MIP re-solves (see [Traveling Salesperson (`examples/traveling-salesperson`)](../examples/traveling-salesperson.md)).
230
+ When a `subproblem` callback detects multiple disconnected subtours or violated components in a candidate solution, return cuts for **all** violated components in one batch.
231
+ Adding multiple cuts per iteration significantly reduces the number of master MIP re-solves (see [Traveling Salesperson](../examples/traveling-salesperson.md)).