@ohtaman/washi 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.ja.md +139 -418
  2. package/README.md +139 -418
  3. package/README.zh-CN.md +139 -418
  4. package/THIRD_PARTY_LICENSES.md +39 -4
  5. package/dist/browser/__vite-browser-external-rTVKos2U.js +7 -0
  6. package/dist/browser/browser-runtime-AG5QFtKf.js +2021 -0
  7. package/dist/browser/highs-worker.js +26 -11
  8. package/dist/browser/highs.wasm +0 -0
  9. package/dist/browser/{loader-DewlSho8.js → loader-i3FnqMes.js} +183 -149
  10. package/dist/browser/solvers/glpk.js +289 -238
  11. package/dist/browser/solvers/glpk.min.js +1 -1
  12. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  13. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  14. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  15. package/dist/browser/solvers/pumpkin.js +1777 -0
  16. package/dist/browser/solvers/pumpkin.min.js +1 -0
  17. package/dist/browser/solvers/pumpkin.wasm +0 -0
  18. package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
  19. package/dist/browser/solvers/z3.js +1600 -1335
  20. package/dist/browser/solvers/z3.min.js +2 -2
  21. package/dist/browser/washi.js +3828 -1315
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/highs-browser-runtime.js +1846 -1618
  25. package/dist/lib/highs-runtime.js +16 -2
  26. package/dist/lib/highs-worker.js +26 -11
  27. package/dist/lib/highs.wasm +0 -0
  28. package/dist/lib/{loader-BZUQNvh4.js → loader-CDpPXN_F.js} +138 -116
  29. package/dist/lib/registry-dx7x4e5c.js +1694 -0
  30. package/dist/lib/rolldown-runtime-DtPi1Y-2.js +13 -0
  31. package/dist/lib/solvers/glpk.js +161 -121
  32. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  33. package/dist/lib/solvers/pumpkin-loader-Ow74Fa1B.js +311 -0
  34. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  35. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  36. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  37. package/dist/lib/solvers/pumpkin.js +1767 -0
  38. package/dist/lib/solvers/pumpkin.wasm +0 -0
  39. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  40. package/dist/lib/solvers/z3.js +486 -306
  41. package/dist/lib/washi.js +3054 -1202
  42. package/dist/types/decomposition/benders.d.ts.map +1 -1
  43. package/dist/types/index.d.ts +3 -3
  44. package/dist/types/index.d.ts.map +1 -1
  45. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  46. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  47. package/dist/types/modeler/constraint.d.ts +40 -4
  48. package/dist/types/modeler/constraint.d.ts.map +1 -1
  49. package/dist/types/modeler/expression.d.ts +176 -28
  50. package/dist/types/modeler/expression.d.ts.map +1 -1
  51. package/dist/types/modeler/index.d.ts +5 -6
  52. package/dist/types/modeler/index.d.ts.map +1 -1
  53. package/dist/types/modeler/linearizer.d.ts +11 -2
  54. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  55. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  56. package/dist/types/modeler/model.d.ts +97 -130
  57. package/dist/types/modeler/model.d.ts.map +1 -1
  58. package/dist/types/modeler/parser.d.ts +25 -5
  59. package/dist/types/modeler/parser.d.ts.map +1 -1
  60. package/dist/types/modeler/quad-expr.d.ts +8 -2
  61. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  62. package/dist/types/modeler/solution-validator.d.ts +12 -12
  63. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  64. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  65. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  66. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  67. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  68. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  69. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  70. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  72. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  73. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  74. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  75. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  76. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  77. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  78. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  79. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  80. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  81. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  82. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  83. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  84. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  85. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  86. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  87. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  88. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  89. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  90. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  91. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  92. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  93. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  94. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  95. package/dist/types/modeler/solvers/types.d.ts +9 -9
  96. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  97. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  98. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  99. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  100. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  101. package/dist/types/modeler/types.d.ts +12 -15
  102. package/dist/types/modeler/types.d.ts.map +1 -1
  103. package/dist/types/modeler/validation.d.ts +26 -2
  104. package/dist/types/modeler/validation.d.ts.map +1 -1
  105. package/dist/types/modeler/variable.d.ts +9 -5
  106. package/dist/types/modeler/variable.d.ts.map +1 -1
  107. package/docs/examples/diet-sensitivity.md +15 -14
  108. package/docs/examples/ecommerce-coupons.md +15 -22
  109. package/docs/examples/index.md +20 -13
  110. package/docs/examples/knapsack.md +8 -7
  111. package/docs/examples/portfolio-qp.md +11 -4
  112. package/docs/examples/production.md +4 -4
  113. package/docs/examples/project-scheduling.md +106 -0
  114. package/docs/examples/shift-scheduling.md +23 -7
  115. package/docs/examples/smt-security.md +17 -4
  116. package/docs/examples/transportation.md +46 -19
  117. package/docs/examples/traveling-salesperson.md +29 -45
  118. package/docs/examples/unsat-core.md +16 -5
  119. package/docs/examples/vehicle-routing.md +10 -8
  120. package/docs/getting-started/ai-agents.md +114 -34
  121. package/docs/getting-started/coding-agents.md +158 -0
  122. package/docs/getting-started/cross-origin.md +56 -28
  123. package/docs/getting-started/index.md +36 -66
  124. package/docs/getting-started/runtimes.md +98 -69
  125. package/docs/guide/constraint-programming.md +141 -0
  126. package/docs/guide/constraints.md +100 -44
  127. package/docs/guide/decomposition.md +141 -273
  128. package/docs/guide/expressions.md +125 -42
  129. package/docs/guide/formulation-tips.md +212 -0
  130. package/docs/guide/objectives.md +70 -64
  131. package/docs/guide/unsat-core.md +44 -23
  132. package/docs/guide/variables.md +56 -48
  133. package/docs/solvers/custom-solver.md +18 -13
  134. package/docs/solvers/highs.md +41 -25
  135. package/docs/solvers/index.md +13 -7
  136. package/docs/solvers/pumpkin.md +163 -0
  137. package/docs/solvers/z3.md +4 -1
  138. package/llms-full.txt +1732 -860
  139. package/llms.txt +59 -36
  140. package/package.json +40 -13
  141. package/skills/washi/SKILL.md +91 -35
  142. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  143. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  144. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  145. package/dist/lib/registry-C20sxTwm.js +0 -964
  146. package/docs/ja/getting-started/ai-agents.md +0 -270
  147. package/docs/zh/getting-started/ai-agents.md +0 -270
@@ -2,7 +2,7 @@
2
2
 
3
3
  Mathematical expressions are linear or quadratic combinations of decision variables and numeric coefficients.
4
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 without losing static type safety.
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.
6
6
 
7
7
  | Approach | Example | Infix readability | Type safety & IDE rename | Indexed variables (`flow[i][j]`) |
8
8
  | :--- | :--- | :--- | :--- | :--- |
@@ -12,9 +12,9 @@ In JavaScript and TypeScript—which do not support operator overloading—WaSHI
12
12
 
13
13
  ---
14
14
 
15
- ## ✍️ Tagged Template Literal (`expr`)
15
+ ## Tagged Template Literal (`expr`)
16
16
 
17
- Similar to parameterized `sql` tagged templates, `expr` receives the static operator text (`+`, `-`, `*`, `^2`, `<=`, `>=`, `==`) separately from the 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` 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.
18
18
 
19
19
  Use `expr` for both arithmetic expressions (`LinExpr | QuadExpr`) and relational constraints (`Constraint`):
20
20
 
@@ -37,44 +37,56 @@ const balanceConstraint = expr`${x} + 2 * ${y} <= 40`;
37
37
 
38
38
  ### Supported Syntax in `expr`
39
39
  - **Addition & Subtraction**: `${x} + ${y} - 5`
40
- - **Scalar Multiplication**: `4 * ${x}`, `${x} * 4`
40
+ - **Scalar Multiplication & Division**: `4 * ${x}`, `${x} / 2`
41
41
  - **Variable Multiplication (Quadratic terms)**: `${x} * ${y}`, `2 * ${x} * ${x}`
42
42
  - **Powers & Exponentiation**: `${x}^2`, `${x}**2`
43
- - **Unary Negation**: `-${x} + 10`
43
+ - **Unary Plus & Negation**: `-${x} + 10`, `+${x}`
44
44
  - **Parentheses**: `2 * (${x} + ${y})`
45
- - **Nested Expressions**: `expr` seamlessly interpolates variables, numbers, `sum()` results, and nested expressions.
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.
46
49
 
47
50
  > [!NOTE]
48
51
  > For relational comparisons (`<=`, `>=`, `==`), `expr` (e.g., ``expr`${x} + 2 * ${y} <= 40` ``) returns a first-class `Constraint`.
49
- > 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`. Polynomial terms of degree $> 2$ (e.g. ``${x} * ${y} * ${z}``, ``${x}^3``) and non-linear constraints (e.g. ``${x} * ${y} <= 10``) are rejected because standard MILP/LP/QP formulations only support linear constraints and quadratic objectives.
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.
50
53
 
51
54
  ---
52
55
 
53
- ## ⚡ High-Performance Summation (`sum`)
56
+ ## High-Performance Summation (`sum`)
54
57
 
55
- For iterating over large collections of variables or indices:
58
+ Sum 1D or 2D `Array`, `Iterable`, or `Record` containers directly inside `` expr`sum(...)` `` or via the standalone `sum()` helper:
56
59
 
57
60
  ```typescript
58
- import { sum } from "@ohtaman/washi";
61
+ import { expr, sum } from "@ohtaman/washi";
59
62
 
60
- const items = ["A", "B", "C"];
63
+ const items = ["A", "B", "C"] as const;
61
64
  const weights = { A: 10, B: 20, C: 30 };
62
65
  const x = m.binary(items);
63
66
 
64
- // 1. Transform elements with a mapping callback:
67
+ // 1. Direct Record or Array summation inside expr (no Object.values() needed):
68
+ m.constraint(expr`sum(${x}) <= 2`, "max_selected");
69
+
70
+ // 2. Element-wise arithmetic inside expr`sum(...)`:
71
+ const weightedExpr = expr`sum(${weights} * ${x})`;
72
+
73
+ // 3. Transform elements with a mapping callback (standalone or inside expr):
65
74
  const totalWeight = sum(items, (item) => x[item].mul(weights[item]));
66
75
 
67
- // 2. Direct array summation:
68
- const count = sum(Object.values(x));
76
+ // 4. Standalone 1D/2D Record or Array summation:
77
+ const count = sum(x);
69
78
  ```
70
79
 
71
- `sum()` runs in $O(N)$ linear time without AST overhead.
80
+ `sum()` runs in $O(N)$ linear time without AST parsing overhead.
81
+
82
+ > [!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.
72
84
 
73
85
  ---
74
86
 
75
- ## 🎯 Dot Product (`dot`)
87
+ ## Dot Product (`dot`)
76
88
 
77
- The `dot(a, b)` helper 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)`).
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)`).
78
90
 
79
91
  Supported 1D and 2D container shapes:
80
92
  - **1D Arrays**: `number[]` $\times$ `(Var | LinExpr)[]`
@@ -87,41 +99,70 @@ Mismatched array lengths, missing dictionary keys, or non-finite/non-linear leav
87
99
 
88
100
  ### 1D Vector Dot Product
89
101
  ```typescript
90
- import { dot } from "@ohtaman/washi";
102
+ import { expr, dot } from "@ohtaman/washi";
91
103
 
92
104
  const profits = { desk: 30, chair: 50 };
93
- const vars = m.integer(["desk", "chair"]);
105
+ const vars = m.integer(["desk", "chair"] as const);
94
106
 
95
- // Computes 30 * vars.desk + 50 * vars.chair
96
- const totalProfit = dot(profits, vars);
107
+ // Computes 30 * vars.desk + 50 * vars.chair inside expr (or via standalone dot(profits, vars))
108
+ const totalProfit = expr`dot(${profits}, ${vars})`;
97
109
  ```
98
110
 
99
- ### 2D Matrix Dot Product
111
+ ### 2D Matrix Inner Product (Frobenius Inner Product)
100
112
  Works directly with 2D arrays (`m.continuous(rows, cols)`), nested dictionaries (`m.continuous(rowKeys, colKeys)`), or mixed 2D containers:
101
113
 
102
114
  ```typescript
103
- const factories = ["Tokyo", "Osaka"];
104
- const stores = ["StoreA", "StoreB"];
115
+ const factories = ["Tokyo", "Osaka"] as const;
116
+ const stores = ["StoreA", "StoreB"] as const;
105
117
 
106
118
  const costs = {
107
119
  Tokyo: { StoreA: 4, StoreB: 7 },
108
120
  Osaka: { StoreA: 8, StoreB: 3 },
109
121
  };
110
122
 
111
- const ship = m.continuous(factories, stores);
123
+ const ship = m.continuous(factories, stores, { lb: 0 });
112
124
 
113
- // Total shipping cost in one line:
114
- m.objective(minimize(dot(costs, ship)));
125
+ // Total shipping cost across all routes (equivalent to expr`sum(${costs} * ${ship})`):
126
+ const totalShippingCost = expr`dot(${costs}, ${ship})`;
115
127
  ```
116
128
 
129
+ > [!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}$.
131
+
117
132
  ---
118
133
 
119
- ## 🧮 Quadratic Expressions (`QuadExpr` & `expr`)
134
+ ## Composing Aggregations in `expr`
135
+
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()`:
120
137
 
121
- WaSHI natively supports Convex Quadratic Programming (QP) with the HiGHS solver. Quadratic objectives can be written uniformly using the `expr` template literal, or algebraically using `QuadExpr` and `.mul()`:
138
+ ```typescript
139
+ // Verbose: nested standalone calls and Object.values()
140
+ const totalProfit1 = expr`${dot(profits, vars)}`;
141
+ const cap1 = expr`${sum(Object.values(vars))} <= 100`;
142
+
143
+ // Recommended: direct sum() and dot() inside expr
144
+ const totalProfit2 = expr`dot(${profits}, ${vars})`;
145
+ const cap2 = expr`sum(${vars}) <= 100`;
146
+ ```
147
+
148
+ | Operation | Mathematical Formula | WaSHI Expression |
149
+ | :--- | :--- | :--- |
150
+ | **Total sum** (1D/2D `Array` or `Record`) | $\sum_i x_i \le C$ | `` m.constraint(expr`sum(${x}) <= ${C}`) `` |
151
+ | **Inner product** (1D vector or 2D Frobenius) | $\sum_i c_i x_i \le B$ | `` m.constraint(expr`dot(${c}, ${x}) <= ${B}`) `` |
152
+ | **Element-wise difference & product** | $\sum_i (p_i - c_i) \cdot x_i$ | `` expr`sum((${price} - ${cost}) * ${x})` `` |
153
+ | **Sum of squared deviations (QP)** | $\sum_i (x_i - t_i)^2$ | `` expr`sum((${x} - ${target})^2)` `` |
154
+ | **Element-wise constraints** ($\forall i \in I$) | $a_i x_i \le b_i \quad (\forall i)$ | `` m.constraint(items.map((i) => expr`${a[i]} * ${x[i]} <= ${b[i]}`)) `` |
155
+ | **2D row sums** (for each row $f$) | $\sum_s X_{f,s} \le S_f \quad (\forall f)$ | `` m.constraint(factories.map((f) => expr`sum(${ship[f]}) <= ${supply[f]}`)) `` |
156
+ | **2D column sums** (for each column $s$) | $\sum_f X_{f,s} \ge D_s \quad (\forall s)$ | `` m.constraint(stores.map((s) => expr`sum(${factories}, ${(f) => ship[f][s]}) >= ${demand[s]}`)) `` |
157
+
158
+ ---
159
+
160
+ ## Quadratic Expressions (`QuadExpr` & `expr`)
161
+
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()`.
122
163
 
123
164
  ### 1. Using `expr` (Recommended)
124
- You can write quadratic formulas naturally with `*`, `^2`, or `**2`:
165
+ Write quadratic terms with `*`, `^2`, or `**2`:
125
166
 
126
167
  ```typescript
127
168
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -138,7 +179,7 @@ m.constraint(expr`${x} + ${y} >= 4`);
138
179
  ```
139
180
 
140
181
  ### 2. Method Chaining with `.mul()` or `QuadExpr`
141
- Alternatively, you can construct quadratic expressions programmatically:
182
+ You can also construct quadratic expressions programmatically:
142
183
 
143
184
  ```typescript
144
185
  import { Model, QuadExpr, minimize } from "@ohtaman/washi";
@@ -147,12 +188,11 @@ const m = new Model();
147
188
  const x = m.continuous("x", { lb: 0 });
148
189
  const y = m.continuous("y", { lb: 0 });
149
190
 
150
- // 1. Construct quadratic terms with .mul()
151
- // Represents x * y + 2 * x^2
191
+ // 1. Construct quadratic terms with .mul() (x * y + 2 * x^2)
152
192
  const quad = x.mul(y).add(x.mul(x).mul(2));
153
193
 
154
- // 2. Build portfolio risk objective: w^T * Sigma * w
155
- const assets = ["Tech", "Bonds"];
194
+ // 2. Build portfolio variance objective: w^T * Sigma * w
195
+ const assets = ["Tech", "Bonds"] as const;
156
196
  const w = m.continuous(assets, { lb: 0, ub: 1 });
157
197
 
158
198
  let risk = new QuadExpr();
@@ -163,13 +203,54 @@ risk = risk.add(w.Bonds.mul(w.Bonds).mul(0.01));
163
203
  m.objective(minimize(risk));
164
204
  ```
165
205
 
206
+ > [!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).)*
208
+
209
+ ---
210
+
211
+ ## Piecewise-Linear & Element Expressions (`max`, `min`, `abs`, `at`)
212
+
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`:
214
+
215
+ ```typescript
216
+ import { Model, expr, minimize, abs, max, min, at } from "@ohtaman/washi";
217
+
218
+ const m = new Model();
219
+ const w = m.continuous(3, { lb: 0, ub: 20, prefix: "w" });
220
+ const target = [4, 7, 10];
221
+ const route = m.integer("route", { lb: 0, ub: 2 });
222
+ const routeCost = [18, 12, 25];
223
+
224
+ // Convex LP epigraph (zero binary variables on HiGHS / GLPK):
225
+ m.objective(
226
+ minimize(expr`sum(abs(${w} - ${target})) + at(${routeCost}, ${route})`)
227
+ );
228
+ m.constraint(expr`max(${w}) <= 15`, "peak_cap");
229
+
230
+ // Nested composition and programmatic helpers also work:
231
+ const maxErr = max(expr`abs(${w[0]} - 4)`, abs(expr`${w[1]} - 7`));
232
+ m.constraint(expr`${maxErr} <= 3`);
233
+ ```
234
+
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).
240
+
166
241
  ---
167
242
 
168
- ## 📊 Evaluating Expressions After Solving (`.value`)
243
+ ## Evaluating Expressions After Solving (`.value`)
169
244
 
170
- 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—such as total department cost, portfolio return, or resource utilization—directly without manual arithmetic:
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:
171
246
 
172
247
  ```typescript
248
+ import { Model, expr, maximize } from "@ohtaman/washi";
249
+
250
+ const m = new Model();
251
+ const x = m.integer("x", { lb: 0 });
252
+ const y = m.integer("y", { lb: 0 });
253
+
173
254
  const revenue = expr`30 * ${x} + 50 * ${y}`;
174
255
  const laborUsed = expr`2 * ${x} + ${y}`;
175
256
 
@@ -187,7 +268,7 @@ If the model has not been solved (or any variable in the expression has `value =
187
268
 
188
269
  ---
189
270
 
190
- ## 🔗 Fluent Arithmetic & Relational Methods
271
+ ## Fluent Arithmetic & Relational Methods
191
272
 
192
273
  In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent methods for programmatic expression building:
193
274
 
@@ -198,7 +279,9 @@ In addition to `expr`, `Var`, `LinExpr`, and `QuadExpr` provide immutable fluent
198
279
  | `.mul(other)` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Multiplies by a scalar `number`, or multiplies two linear terms into a `QuadExpr`. |
199
280
  | `.div(divisor)` | `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Divides by a non-zero finite scalar `number`. |
200
281
  | `.neg()` | `Var`, `LinExpr`, `QuadExpr` | `LinExpr` or `QuadExpr` | Negates all terms ($-e$). |
201
- | `.le(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\le$ constraint (`lhs <= rhs`). |
202
- | `.ge(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds a $\ge$ constraint (`lhs >= rhs`). |
203
- | `.eq(rhs)` | `Var`, `LinExpr` | `Constraint` | Builds an $==$ equality constraint (`lhs == rhs`). |
204
-
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). |
@@ -0,0 +1,212 @@
1
+ # Formulation Patterns & Optimization Tips
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).)*
4
+
5
+ ---
6
+
7
+ ## 1. Variables & Domain Modeling
8
+
9
+ ### Semi-Continuous Decisions ($\{0\} \cup [L, U]$)
10
+
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$).
12
+
13
+ Combine a continuous variable `x` with a binary activation variable `isActive` and linking constraints $L \cdot b \le x \le U \cdot b$:
14
+
15
+ ```typescript
16
+ import { Model, expr } from "@ohtaman/washi";
17
+
18
+ const m = new Model("SemiContinuousBatch");
19
+ const batch = m.continuous("batch", { lb: 0, ub: 100 });
20
+ const isActive = m.binary("is_active");
21
+
22
+ // If isActive === 0, batch is forced to 0; if isActive === 1, batch lies in [10, 100]
23
+ m.constraint(expr`${batch} >= 10 * ${isActive}`, "min_batch_run");
24
+ m.constraint(expr`${batch} <= 100 * ${isActive}`, "max_batch_run");
25
+ ```
26
+
27
+ ### Minimal-Perturbation Rescheduling vs. Warm Starting
28
+
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.
30
+
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:
32
+
33
+ $$\text{Changes} = \sum_{i:\, x_i^{\text{prev}} = 0} x_i + \sum_{i:\, x_i^{\text{prev}} = 1} (1 - x_i)$$
34
+
35
+ ```typescript
36
+ import { Model, expr, minimize } from "@ohtaman/washi";
37
+
38
+ const m = new Model("StableReschedule");
39
+ const prevPlan = [1, 0, 1, 0];
40
+ const x = prevPlan.map((prev, i) =>
41
+ m.binary(`slot_${i}`, { initialValue: prev })
42
+ );
43
+
44
+ // Linear terms counting how many 0/1 decisions differ from prevPlan
45
+ const flipTerms = x.map((v, i) => (prevPlan[i] === 1 ? expr`1 - ${v}` : v));
46
+
47
+ // Require at least 3 active slots while penalizing changes from prevPlan
48
+ m.constraint(expr`sum(${x}) >= 3`, "min_active_slots");
49
+ m.objective(minimize(expr`5 * sum(${flipTerms})`));
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 2. Linearizing Non-Linear Expressions
55
+
56
+ ### Product of Two Binary Variables ($x_A \cdot x_B$)
57
+
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:
59
+
60
+ $$z_{AB} \le x_A, \quad z_{AB} \le x_B, \quad z_{AB} \ge x_A + x_B - 1$$
61
+
62
+ ```typescript
63
+ import { Model, expr, maximize } from "@ohtaman/washi";
64
+
65
+ const m = new Model("BinaryProductLinearization");
66
+ const xA = m.binary("xA");
67
+ const xB = m.binary("xB");
68
+ // When xA and xB are binary, continuous [0, 1] bounds suffice to force bothAB into {0, 1}
69
+ const bothAB = m.continuous("both_AB", { lb: 0, ub: 1 });
70
+
71
+ m.constraint(expr`${bothAB} <= ${xA}`, "and_upper_A");
72
+ m.constraint(expr`${bothAB} <= ${xB}`, "and_upper_B");
73
+ m.constraint(expr`${bothAB} >= ${xA} + ${xB} - 1`, "and_lower_AB");
74
+
75
+ m.objective(maximize(expr`10 * ${xA} + 10 * ${xB} + 5 * ${bothAB}`));
76
+ ```
77
+
78
+ ### Min-Max & Max-Min Objectives (Load Balancing)
79
+
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.
81
+
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):
83
+
84
+ $$\min z \quad \text{subject to} \quad \text{load}_i \le z \quad \forall i$$
85
+
86
+ ```typescript
87
+ import { Model, expr, minimize } from "@ohtaman/washi";
88
+
89
+ const m = new Model("MinMaxLoadBalancing");
90
+ const workers = ["Alice", "Bob", "Carol"] as const;
91
+ const hours = m.continuous(workers, { lb: 0, ub: 40 });
92
+ const maxHours = m.continuous("max_hours", { lb: 0, ub: 40 });
93
+
94
+ // Bound every worker's hours by the shared ceiling maxHours
95
+ m.constraint(workers.map((w) => expr`${hours[w]} <= ${maxHours}`));
96
+ m.constraint(expr`sum(${hours}) >= 60`, "total_required_work");
97
+
98
+ // Minimizing maxHours distributes the 60 hours evenly (20 hours each)
99
+ m.objective(minimize(maxHours));
100
+ ```
101
+
102
+ ---
103
+
104
+ ## 3. Constraint Design & Numerical Conditioning
105
+
106
+ ### Hard vs. Soft Constraints (Elastic Slack Variables)
107
+
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:
109
+
110
+ | Target Type | Hard Constraint | Soft Constraint ($s \ge 0$) | Objective Penalty Term (Minimize) |
111
+ | :--- | :--- | :--- | :--- |
112
+ | **Lower bound** | $\text{lhs} \ge b$ | $\text{lhs} + s_{\text{short}} \ge b$ | $+ W \cdot s_{\text{short}}$ |
113
+ | **Upper bound** | $\text{lhs} \le b$ | $\text{lhs} - s_{\text{excess}} \le b$ | $+ W \cdot s_{\text{excess}}$ |
114
+ | **Target equality** | $\text{lhs} = b$ | $\text{lhs} + s_{\text{short}} - s_{\text{excess}} = b$ | $+ W_1 \cdot s_{\text{short}} + W_2 \cdot s_{\text{excess}}$ |
115
+
116
+ ```typescript
117
+ import { Model, expr, minimize } from "@ohtaman/washi";
118
+
119
+ const m = new Model("SoftConstraintCoverage");
120
+ const assignedStaff = m.integer("assigned_staff", { lb: 0, ub: 4 }); // Max 4 staff available
121
+ const shortage = m.continuous("shortage", { lb: 0 }); // Non-negative slack (s >= 0)
122
+
123
+ // Soft target: aim for 5 staff, allowing shortage > 0 if unavailable
124
+ m.constraint(expr`${assignedStaff} + ${shortage} >= 5`, "target_5_staff");
125
+
126
+ // Penalize unmet shortage ($1,000) above regular wage ($100)
127
+ m.objective(minimize(expr`100 * ${assignedStaff} + 1000 * ${shortage}`));
128
+
129
+ await m.solve();
130
+ // assignedStaff.value === 4, shortage.value === 1 (returns best compromise instead of Infeasible)
131
+ ```
132
+
133
+ > [!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.
135
+
136
+ ### Symmetry Breaking for Identical Resources
137
+
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.
139
+
140
+ Impose a canonical ordering ($u_0 \ge u_1 \ge \dots \ge u_{K-1}$) so identical resources are activated in index order:
141
+
142
+ ```typescript
143
+ import { Model, expr } from "@ohtaman/washi";
144
+
145
+ const m = new Model("SymmetryBreaking");
146
+ const numTrucks = 4;
147
+ const truckUsed = m.binary(numTrucks, { prefix: "truck_used" });
148
+
149
+ // Only allow activating truck k+1 when truck k is also active
150
+ for (let k = 0; k < numTrucks - 1; k++) {
151
+ m.constraint(
152
+ expr`${truckUsed[k]} >= ${truckUsed[k + 1]}`,
153
+ `order_truck_${k}`
154
+ );
155
+ }
156
+ ```
157
+
158
+ ---
159
+
160
+ ## 4. Multi-Objective & MIP Stopping Design
161
+
162
+ ### Weighted Sum vs. Lexicographic Two-Stage Optimization
163
+
164
+ When balancing competing goals—such as minimizing total cost ($f_1$) while also minimizing peak workload ($f_2$)—two approaches are standard:
165
+
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$:
168
+
169
+ ```typescript
170
+ import { Model, expr, minimize } from "@ohtaman/washi";
171
+
172
+ const m = new Model("LexicographicTwoStage");
173
+ const workers = ["Alice", "Bob"] as const;
174
+ const wage = { Alice: 20, Bob: 20 };
175
+ const hours = m.continuous(workers, { lb: 0, ub: 40 });
176
+ const maxHours = m.continuous("max_hours", { lb: 0, ub: 40 });
177
+
178
+ const totalCost = expr`dot(${wage}, ${hours})`;
179
+ m.constraint(expr`sum(${hours}) >= 40`, "required_hours");
180
+ m.constraint(workers.map((w) => expr`${hours[w]} <= ${maxHours}`));
181
+
182
+ // Stage 1: Minimize primary objective (total wage cost)
183
+ m.objective(minimize(totalCost));
184
+ await m.solve();
185
+ const minCost = m.objectiveValue!;
186
+
187
+ // Stage 2: Keep cost within 1% of minCost and balance workload (minimize maxHours)
188
+ m.constraint(expr`${totalCost} <= ${minCost * 1.01}`, "near_optimal_cost");
189
+ m.objective(minimize(maxHours));
190
+ await m.solve();
191
+ ```
192
+
193
+ ### MIP Tail-Off & Optimality Gap Tolerances
194
+
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**).
196
+
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.
200
+
201
+ ---
202
+
203
+ ## 5. Decomposition Formulation Tips
204
+
205
+ When using [`solveColumnGeneration` or `solveBenders`](./decomposition.md):
206
+
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)).