@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.
- package/README.ja.md +60 -23
- package/README.md +59 -22
- package/README.zh-CN.md +62 -25
- package/THIRD_PARTY_LICENSES.md +34 -1
- package/dist/browser/solvers/glpk.js +289 -238
- package/dist/browser/solvers/glpk.min.js +1 -1
- package/dist/browser/solvers/highs-__vite-browser-external-Dn-83hnF.js +7 -0
- package/dist/browser/solvers/highs-browser-runtime-0Bgq5ksG.js +2021 -0
- package/dist/browser/{loader-DewlSho8.js → solvers/highs-loader-BLY3wzDH.js} +190 -149
- package/dist/browser/solvers/highs-worker.js +54 -0
- package/dist/browser/solvers/highs.js +1414 -0
- package/dist/browser/solvers/highs.wasm +0 -0
- package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
- package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
- package/dist/browser/solvers/pumpkin-worker.js +45 -0
- package/dist/browser/solvers/pumpkin.js +1777 -0
- package/dist/browser/solvers/pumpkin.wasm +0 -0
- package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/browser/solvers/z3.js +1600 -1335
- package/dist/browser/solvers/z3.min.js +2 -2
- package/dist/browser/washi.js +3313 -1699
- package/dist/browser/washi.min.js +5 -3
- package/dist/lib/solvers/__vite-browser-external-oLchLuMx.js +7 -0
- package/dist/lib/solvers/glpk.js +174 -132
- package/dist/lib/solvers/highs-browser-runtime.js +2413 -0
- package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
- package/dist/lib/solvers/highs-runtime.js +16 -0
- package/dist/lib/solvers/highs-worker.js +54 -0
- package/dist/lib/solvers/highs.js +410 -0
- package/dist/lib/solvers/highs.wasm +0 -0
- package/dist/lib/{loader-BZUQNvh4.js → solvers/loader-CDpPXN_F.js} +138 -116
- package/dist/lib/solvers/loader-Ow74Fa1B.js +311 -0
- package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
- package/dist/lib/solvers/pumpkin-assets.js +1 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
- package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
- package/dist/lib/solvers/pumpkin-worker.js +45 -0
- package/dist/lib/solvers/pumpkin.js +868 -0
- package/dist/lib/solvers/pumpkin.wasm +0 -0
- package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
- package/dist/lib/solvers/rolldown-runtime-DtPi1Y-2.js +13 -0
- package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
- package/dist/lib/solvers/z3.js +489 -307
- package/dist/lib/washi.js +3905 -1410
- package/dist/types/decomposition/benders.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -5
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/boolean-expr.d.ts +137 -29
- package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
- package/dist/types/modeler/constraint.d.ts +40 -4
- package/dist/types/modeler/constraint.d.ts.map +1 -1
- package/dist/types/modeler/expression.d.ts +129 -2
- package/dist/types/modeler/expression.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +4 -6
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/linearizer.d.ts +11 -2
- package/dist/types/modeler/linearizer.d.ts.map +1 -1
- package/dist/types/modeler/lp-writer.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +86 -126
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/parser.d.ts.map +1 -1
- package/dist/types/modeler/quad-expr.d.ts +8 -2
- package/dist/types/modeler/quad-expr.d.ts.map +1 -1
- package/dist/types/modeler/solution-validator.d.ts +12 -12
- package/dist/types/modeler/solution-validator.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
- package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
- package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
- package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
- package/dist/types/modeler/solvers/index.d.ts +2 -1
- package/dist/types/modeler/solvers/index.d.ts.map +1 -1
- package/dist/types/modeler/solvers/mock.d.ts +2 -3
- package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
- package/dist/types/modeler/solvers/types.d.ts +7 -9
- package/dist/types/modeler/solvers/types.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
- package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
- package/dist/types/modeler/types.d.ts +12 -15
- package/dist/types/modeler/types.d.ts.map +1 -1
- package/dist/types/modeler/validation.d.ts +26 -2
- package/dist/types/modeler/validation.d.ts.map +1 -1
- package/dist/types/modeler/variable.d.ts +9 -5
- package/dist/types/modeler/variable.d.ts.map +1 -1
- package/docs/examples/diet-sensitivity.md +33 -14
- package/docs/examples/ecommerce-coupons.md +17 -9
- package/docs/examples/index.md +36 -27
- package/docs/examples/knapsack.md +11 -5
- package/docs/examples/portfolio-qp.md +21 -8
- package/docs/examples/production.md +10 -5
- package/docs/examples/project-scheduling.md +119 -0
- package/docs/examples/shift-scheduling.md +29 -18
- package/docs/examples/smt-security.md +27 -11
- package/docs/examples/transportation.md +23 -13
- package/docs/examples/traveling-salesperson.md +34 -22
- package/docs/examples/unsat-core.md +27 -14
- package/docs/examples/vehicle-routing.md +74 -28
- package/docs/getting-started/ai-agents.md +190 -82
- package/docs/getting-started/coding-agents.md +177 -0
- package/docs/getting-started/cross-origin.md +27 -14
- package/docs/getting-started/index.md +49 -43
- package/docs/getting-started/runtimes.md +94 -40
- package/docs/guide/constraint-programming.md +171 -0
- package/docs/guide/constraints.md +115 -33
- package/docs/guide/decomposition.md +118 -88
- package/docs/guide/expressions.md +106 -43
- package/docs/guide/formulation-tips.md +47 -28
- package/docs/guide/objectives.md +102 -75
- package/docs/guide/unsat-core.md +62 -50
- package/docs/guide/variables.md +81 -35
- package/docs/solvers/custom-solver.md +163 -122
- package/docs/solvers/glpk.md +58 -17
- package/docs/solvers/highs.md +124 -57
- package/docs/solvers/index.md +33 -20
- package/docs/solvers/pumpkin.md +171 -0
- package/docs/solvers/z3.md +63 -25
- package/llms-full.txt +2232 -932
- package/llms.txt +144 -91
- package/package.json +55 -19
- package/skills/washi/SKILL.md +107 -34
- package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
- package/dist/browser/highs-worker.js +0 -39
- package/dist/browser/highs.wasm +0 -0
- package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/lib/highs-browser-runtime.js +0 -2185
- package/dist/lib/highs-runtime.js +0 -2
- package/dist/lib/highs-worker.js +0 -39
- package/dist/lib/highs.wasm +0 -0
- package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
- package/docs/ja/getting-started/ai-agents.md +0 -280
- package/docs/zh/getting-started/ai-agents.md +0 -280
- /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
- /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
- /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# Formulation Patterns & Optimization Tips
|
|
2
2
|
|
|
3
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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,7 +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
|
-
|
|
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).
|
|
87
|
+
|
|
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$):
|
|
81
90
|
|
|
82
91
|
$$\min z \quad \text{subject to} \quad \text{load}_i \le z \quad \forall i$$
|
|
83
92
|
|
|
@@ -97,15 +106,14 @@ m.constraint(expr`sum(${hours}) >= 60`, "total_required_work");
|
|
|
97
106
|
m.objective(minimize(maxHours));
|
|
98
107
|
```
|
|
99
108
|
|
|
100
|
-
*(Symmetrically, to **maximize the minimum** level $\max \min_i u_i$, impose $u_i \ge z$ for all $i$ and set `m.objective(maximize(z))`.)*
|
|
101
|
-
|
|
102
109
|
---
|
|
103
110
|
|
|
104
111
|
## 3. Constraint Design & Numerical Conditioning
|
|
105
112
|
|
|
106
113
|
### Hard vs. Soft Constraints (Elastic Slack Variables)
|
|
107
114
|
|
|
108
|
-
Treating every business target as a strict **hard constraint** makes
|
|
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$)**:
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
167
|
-
- **Lexicographic
|
|
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
|
|
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
|
|
198
|
-
|
|
199
|
-
- **`
|
|
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
|
-
|
|
208
|
-
|
|
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)).
|
package/docs/guide/objectives.md
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
# Objectives & Solving (`m.solve` & `m.check`)
|
|
2
2
|
|
|
3
|
-
The objective function defines the goal of mathematical optimization
|
|
3
|
+
The objective function defines the goal of mathematical optimization, such as maximizing profit, minimizing cost, or minimizing quadratic variance.
|
|
4
|
+
If you only need to check feasibility or solve logical rules without an objective, call `m.check()` instead.
|
|
4
5
|
|
|
5
6
|
---
|
|
6
7
|
|
|
7
8
|
## Setting the Objective Function
|
|
8
9
|
|
|
9
|
-
Set the
|
|
10
|
+
Set the optimization direction and formula declaratively with `m.objective(maximize(...))` or `m.objective(minimize(...))`:
|
|
10
11
|
|
|
11
12
|
```typescript
|
|
12
13
|
import { Model, expr, maximize, minimize } from "@ohtaman/washi";
|
|
@@ -23,27 +24,28 @@ m.constraint(expr`2 * ${x} + 3 * ${y} <= 100`, "resource_limit");
|
|
|
23
24
|
// m.objective(minimize(expr`10 * ${x} + 15 * ${y}`));
|
|
24
25
|
```
|
|
25
26
|
|
|
26
|
-
Calling `m.objective()` with no arguments returns the current objective expression (`LinExpr | QuadExpr`).
|
|
27
|
+
Calling `m.objective()` with no arguments returns the current objective expression (`LinExpr | QuadExpr`).
|
|
28
|
+
If you omit setting an objective, the model defaults to minimizing `0`.
|
|
27
29
|
|
|
28
30
|
> [!TIP]
|
|
29
|
-
> For
|
|
31
|
+
> For Min-Max / Max-Min load balancing, see [Min-Max & Max-Min Objectives](./formulation-tips.md#min-max-max-min-objectives-load-balancing); for multi-objective optimization and MIP gap tolerances (`relativeGap` / `absoluteGap`), see [Multi-Objective & MIP Stopping Design](./formulation-tips.md#_4-multi-objective-mip-stopping-design).
|
|
30
32
|
|
|
31
33
|
---
|
|
32
34
|
|
|
33
35
|
## Solving the Model (`m.solve()` vs. `m.check()`)
|
|
34
36
|
|
|
35
|
-
WaSHI provides two asynchronous execution
|
|
37
|
+
WaSHI provides two asynchronous execution methods:
|
|
36
38
|
|
|
37
39
|
| Method | Return Value | Purpose |
|
|
38
40
|
| :--- | :--- | :--- |
|
|
39
41
|
| **`await m.solve(options?)`** | `Promise<SolverStatus>` | Optimizes the objective (`Minimize` or `Maximize`) subject to all constraints. Populates primal values, objective value, MIP bounds/gaps, and LP duals/slacks. |
|
|
40
|
-
| **`await m.check(options?)`** | `Promise<CheckResult>` | Checks
|
|
42
|
+
| **`await m.check(options?)`** | `Promise<CheckResult>` | Checks satisfiability without an objective. Returns `{ status, values, conflicts?, unsatCore?, runTime? }` for CP/SMT checks and conflict diagnosis. |
|
|
41
43
|
|
|
42
44
|
```typescript
|
|
43
45
|
const status = await m.solve({
|
|
44
|
-
timeLimit: 10.0,
|
|
45
|
-
|
|
46
|
-
outputFlag: false,
|
|
46
|
+
timeLimit: 10.0, // Timeout in seconds
|
|
47
|
+
relativeGap: 0.01, // Stop within 1% of global optimum
|
|
48
|
+
outputFlag: false, // Enable/disable solver console logging (HiGHS: outputFlag, GLPK: verbose)
|
|
47
49
|
});
|
|
48
50
|
```
|
|
49
51
|
|
|
@@ -51,24 +53,83 @@ const status = await m.solve({
|
|
|
51
53
|
|
|
52
54
|
| Option | Type | Default | Description |
|
|
53
55
|
| :--- | :--- | :--- | :--- |
|
|
54
|
-
| `solver` | `string` \| `Solver` | Model's solver (`"highs"`) | Registered solver name (
|
|
56
|
+
| `solver` | `string` \| `Solver` | Model's solver (`"highs"`) | Registered solver name (`"highs"`, `"pumpkin"`, `"z3"`, `"glpk"`, or custom) or `Solver` instance for this run. |
|
|
55
57
|
| `timeLimit` | `number` | `undefined` | Maximum solve duration in seconds. |
|
|
56
|
-
| `
|
|
57
|
-
| `
|
|
58
|
+
| `relativeGap` | `number` | `undefined` | Relative MIP optimality gap tolerance (for example, `0.01` for 1%). |
|
|
59
|
+
| `absoluteGap` | `number` | `undefined` | Absolute MIP optimality gap tolerance (HiGHS `mip_abs_gap`). |
|
|
58
60
|
| `presolve` | `"on"` \| `"off"` \| `"choose"` | `"choose"` | Controls solver presolve reduction prior to optimization. |
|
|
59
|
-
| `
|
|
60
|
-
| `
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
61
|
+
| `relax` | `boolean` | `false` | Solves the continuous LP relaxation (equivalent to `m.relax()`); supported on HiGHS and GLPK. |
|
|
62
|
+
| `outputFlag` / `verbose` | `boolean` | `false` | Emits internal solver logs (`outputFlag` for HiGHS, `verbose` for GLPK). |
|
|
63
|
+
| `useWorker` | `boolean` | `true` (browser) / `false` (Node.js) | Runs HiGHS and Pumpkin in a browser Web Worker. Set `false` for main-thread browser runs; omit or set `false` in Node.js (explicit `true` fails). |
|
|
64
|
+
| `wasmUrl` | `string` | Auto-resolved | Custom URL to load `highs.wasm` or `pumpkin.wasm` in browser deployments. |
|
|
65
|
+
| `signal` | `AbortSignal` | `undefined` | Cancellation signal (`AbortController.signal`); see cancellation limitations below. |
|
|
63
66
|
| `onProgress` | `(e: SolveProgressEvent) => void` | `undefined` | Callback receiving live solver progress snapshots. |
|
|
64
67
|
|
|
65
68
|
You can also pass a solver name directly as the first argument: `await m.solve("glpk", { timeLimit: 5 })`.
|
|
69
|
+
Backends throw an error rather than silently ignoring unsupported options; check each backend's support details in [Solvers Overview](../solvers/index.md).
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Reading Results, Bounds & Solver Status
|
|
74
|
+
|
|
75
|
+
After solving, inspect the status, objective value, variable values, and MIP bounds directly on the `Model`:
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
const status = await m.solve();
|
|
79
|
+
|
|
80
|
+
console.log("Status:", m.status); // e.g. "Optimal" or "Feasible"
|
|
81
|
+
console.log("Termination Reason:", m.terminationStatus); // e.g. "Optimal", "TimeLimit", "Interrupted"
|
|
82
|
+
console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value / m.objectiveValue are populated
|
|
83
|
+
|
|
84
|
+
// Objective & MIP Gap Metrics
|
|
85
|
+
console.log("Objective Value:", m.objectiveValue); // Best primal objective (or null)
|
|
86
|
+
console.log("Objective Bound:", m.objectiveBound); // Best dual bound (or undefined)
|
|
87
|
+
console.log("Relative Gap:", m.relativeGap); // Relative MIP gap
|
|
88
|
+
console.log("Absolute Gap:", m.absoluteGap); // |objectiveValue - objectiveBound|
|
|
89
|
+
|
|
90
|
+
// Variable Values (via .value or name-keyed m.values ReadonlyMap)
|
|
91
|
+
console.log("x =", x.value, "y =", y.value);
|
|
92
|
+
console.log("x by name:", m.values.get("x"));
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
When solving without `relax: true`, WaSHI automatically normalizes `Integer` and `Binary` `.value`s within `1e-5` of an integer to exact integers, whereas `m.objectiveValue` preserves the solver's raw floating-point value.
|
|
96
|
+
|
|
97
|
+
> [!TIP]
|
|
98
|
+
> To independently check that returned values satisfy all bounds, integrality rules, and constraints within tolerance, call `m.verify()`.
|
|
99
|
+
> See [Verifying Solutions (`m.verify()`)](./unsat-core.md#verifying-solutions-m-verify).
|
|
100
|
+
|
|
101
|
+
### Understanding `m.status` vs. `m.terminationStatus`
|
|
102
|
+
|
|
103
|
+
When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two separate questions matter:
|
|
104
|
+
|
|
105
|
+
1. **Is there a usable solution?** Check `m.hasPrimalSolution` or `m.status`.
|
|
106
|
+
2. **Why did the solver stop?** Check `m.terminationStatus`.
|
|
107
|
+
|
|
108
|
+
If the solver found a valid solution—called an **incumbent**—before hitting `timeLimit` or `signal.abort()`, WaSHI sets `m.status = "Feasible"`.
|
|
109
|
+
In that case, `x.value` holds the incumbent's variable values and `m.objectiveValue` holds its objective value, while `m.terminationStatus` records `"TimeLimit"`, `"IterationLimit"`, or `"Interrupted"`.
|
|
110
|
+
If no solution was found before stopping, `m.hasPrimalSolution` is `false` and `m.status` is `"TimeLimit"`, `"IterationLimit"`, or `"Unknown"`.
|
|
111
|
+
|
|
112
|
+
### All `SolverStatus` Values
|
|
113
|
+
|
|
114
|
+
| Status | `hasPrimalSolution` | Meaning |
|
|
115
|
+
| :--- | :--- | :--- |
|
|
116
|
+
| `"Optimal"` | `true` | Global optimal solution proven within tolerances. |
|
|
117
|
+
| `"Feasible"` | `true` | Valid solution found, but stopped before proving optimality (see `terminationStatus`). |
|
|
118
|
+
| `"Sat"` | `true` | Constraints are satisfiable (`m.check()`). |
|
|
119
|
+
| `"Infeasible"` | `false` | Proven mathematically infeasible; no solution satisfies all constraints. |
|
|
120
|
+
| `"Unsat"` | `false` | Logical or arithmetic constraints are unsatisfiable (`m.check()`). |
|
|
121
|
+
| `"Unbounded"` | `false` | Objective can improve indefinitely without violating constraints. |
|
|
122
|
+
| `"TimeLimit"` | `false` | Time limit reached before finding any feasible primal solution. |
|
|
123
|
+
| `"IterationLimit"` | `false` | Iteration limit reached before finding any feasible primal solution. |
|
|
124
|
+
| `"Unknown"` | `false` | Stopped without a solution (for example, cancelled via `AbortSignal` before finding one). |
|
|
125
|
+
| `"Error"` | `false` | Solver encountered an internal execution error. |
|
|
126
|
+
| `"NotSolved"` | `false` | Initial state before solving, or after the model has been mutated. |
|
|
66
127
|
|
|
67
128
|
---
|
|
68
129
|
|
|
69
130
|
## Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
|
|
70
131
|
|
|
71
|
-
For long-running MIP
|
|
132
|
+
For long-running MIP solves in interactive apps, you can stream branch-and-bound progress with `onProgress` and cancel runs with `AbortController`:
|
|
72
133
|
|
|
73
134
|
```typescript
|
|
74
135
|
const controller = new AbortController();
|
|
@@ -81,10 +142,10 @@ const status = await m.solve({
|
|
|
81
142
|
`[${event.elapsedTime.toFixed(1)}s] ` +
|
|
82
143
|
`Best: ${event.objectiveValue ?? "—"}, ` +
|
|
83
144
|
`Bound: ${event.objectiveBound ?? "—"}, ` +
|
|
84
|
-
`Gap: ${event.
|
|
145
|
+
`Gap: ${event.relativeGap !== undefined ? (event.relativeGap * 100).toFixed(2) + "%" : "—"}`
|
|
85
146
|
);
|
|
86
147
|
|
|
87
|
-
// Optional: stop early as soon as a good-enough incumbent is found
|
|
148
|
+
// Optional (maximization model): stop early as soon as a good-enough incumbent is found
|
|
88
149
|
if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
|
|
89
150
|
controller.abort();
|
|
90
151
|
}
|
|
@@ -96,6 +157,12 @@ console.log("Termination:", m.terminationStatus); // "Interrupted"
|
|
|
96
157
|
console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
|
|
97
158
|
```
|
|
98
159
|
|
|
160
|
+
> [!NOTE]
|
|
161
|
+
> **`AbortSignal` Behavior Across Backends**:
|
|
162
|
+
> - **Asynchronous preemptive cancellation**: On HiGHS and Pumpkin inside a browser Web Worker (`useWorker: true`), aborting terminates the worker immediately.
|
|
163
|
+
> - **Cooperative mid-solve cancellation**: On HiGHS and Pumpkin in Node.js or on the browser main thread (`useWorker: false`), aborting inside `onProgress` (and during Pumpkin search checkpoints) stops the active solve cleanly.
|
|
164
|
+
> - **Pre-solve cancellation only**: On GLPK and Z3, `AbortSignal` is checked only before starting a solve.
|
|
165
|
+
|
|
99
166
|
### `SolveProgressEvent` Fields
|
|
100
167
|
|
|
101
168
|
| Field | Type | Description |
|
|
@@ -103,71 +170,31 @@ console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was
|
|
|
103
170
|
| `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
|
|
104
171
|
| `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
|
|
105
172
|
| `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
|
|
106
|
-
| `objectiveBound` | `number \| undefined` | Current best proven dual
|
|
107
|
-
| `
|
|
108
|
-
| `
|
|
173
|
+
| `objectiveBound` | `number \| undefined` | Current best proven dual bound (MIP). |
|
|
174
|
+
| `relativeGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
|
|
175
|
+
| `absoluteGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
|
|
109
176
|
| `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
|
|
110
|
-
| `iterations` | `number \| undefined` | Solver iteration count (simplex,
|
|
177
|
+
| `iterations` | `number \| undefined` | Solver iteration count (simplex, interior-point, or MIP LP iterations). |
|
|
111
178
|
| `message` | `string \| undefined` | Raw progress line emitted by the solver. |
|
|
112
179
|
|
|
113
180
|
---
|
|
114
181
|
|
|
115
|
-
##
|
|
116
|
-
|
|
117
|
-
After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
|
|
118
|
-
|
|
119
|
-
```typescript
|
|
120
|
-
const status = await m.solve();
|
|
121
|
-
|
|
122
|
-
console.log("Status:", m.status); // e.g. "Optimal" or "Feasible"
|
|
123
|
-
console.log("Termination Reason:", m.terminationStatus); // e.g. "Optimal", "TimeLimit", "Interrupted"
|
|
124
|
-
console.log("Has Primal Solution:", m.hasPrimalSolution); // true when x.value / m.objectiveValue are populated
|
|
125
|
-
|
|
126
|
-
// Objective & MIP Gap Metrics
|
|
127
|
-
console.log("Objective Value:", m.objectiveValue); // Best primal objective (or null)
|
|
128
|
-
console.log("Objective Bound:", m.objectiveBound); // Best dual bound (or undefined)
|
|
129
|
-
console.log("Relative Gap:", m.relGap); // Relative MIP gap (alias: m.mipGap)
|
|
130
|
-
console.log("Absolute Gap:", m.absGap); // |objectiveValue - objectiveBound|
|
|
131
|
-
|
|
132
|
-
// Individual & Bulk Variable Values
|
|
133
|
-
console.log("x =", x.value, "y =", y.value);
|
|
134
|
-
console.log(m.getValues({ x, y })); // { x: ..., y: ... }
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
### Understanding `m.status` vs. `m.terminationStatus`
|
|
138
|
-
|
|
139
|
-
When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two distinct questions matter:
|
|
140
|
-
1. **Is there a usable solution?** (`m.hasPrimalSolution` / `m.status`)
|
|
141
|
-
2. **Why did the solver stop?** (`m.terminationStatus`)
|
|
142
|
-
|
|
143
|
-
If an integer-feasible incumbent was found before hitting `timeLimit` or `signal.abort()`, WaSHI sets `m.status = "Feasible"` (so you know `x.value` and `m.objectiveValue` hold a valid solution) and sets `m.terminationStatus = "TimeLimit"` (or `"Interrupted"`). If no incumbent was found before stopping, `m.hasPrimalSolution` is `false`, `m.terminationStatus` records why the solver stopped (`"TimeLimit"`, `"IterationLimit"`, or `"Interrupted"`), and `m.status` is `"TimeLimit"`, `"IterationLimit"`, or `"Unknown"` (when aborted via `AbortSignal` without an incumbent).
|
|
144
|
-
|
|
145
|
-
### All `SolverStatus` Values
|
|
182
|
+
## Model Mutations & Execution Validity
|
|
146
183
|
|
|
147
|
-
|
|
148
|
-
| :--- | :--- | :--- |
|
|
149
|
-
| `"Optimal"` | `true` | Global optimal solution proven (within tolerances). |
|
|
150
|
-
| `"Feasible"` | `true` | Valid primal solution (incumbent) found, but optimality was not proven before stopping (`terminationStatus` indicates why: `"TimeLimit"`, `"IterationLimit"`, `"Interrupted"`, etc.). |
|
|
151
|
-
| `"Sat"` | `true` | Constraints are satisfiable (`m.check()`). |
|
|
152
|
-
| `"Infeasible"` | `false` | Proven mathematically infeasible; no solution satisfies all constraints. |
|
|
153
|
-
| `"Unsat"` | `false` | Logical/arithmetic constraints are unsatisfiable (`m.check()`). |
|
|
154
|
-
| `"Unbounded"` | `false` | Objective can improve indefinitely without violating constraints. |
|
|
155
|
-
| `"TimeLimit"` | `false` | Time limit reached before finding any feasible primal solution. |
|
|
156
|
-
| `"IterationLimit"` | `false` | Iteration limit reached before finding any feasible primal solution. |
|
|
157
|
-
| `"Unknown"` | `false` | Solver stopped inconclusively without a valid primal solution (including when cancelled via `AbortSignal` before finding an incumbent, where `terminationStatus === "Interrupted"`). |
|
|
158
|
-
| `"Error"` | `false` | Solver encountered an internal execution error. |
|
|
159
|
-
| `"NotSolved"` | `false` | Initial state before solving, or after the model has been mutated. |
|
|
184
|
+
A `Model` keeps its solution state consistent across edits made through `Model` methods and `Model`, `Var`, and `Constraint` property setters.
|
|
160
185
|
|
|
161
|
-
|
|
186
|
+
### Post-Solve Mutations Reset State
|
|
162
187
|
|
|
163
|
-
|
|
188
|
+
Adding variables or constraints, or updating the objective via `m.objective()` or `m.sense`, immediately resets `m.status` to `"NotSolved"`.
|
|
189
|
+
The same reset applies when modifying variable fields (`v.lb`, `v.ub`, `v.type`, `v.initialValue`) or constraint fields (`c.lhs`, `c.sense`, `c.rhs`).
|
|
190
|
+
This clears `m.solution` and `m.objectiveValue`, resets variable `value` and `reducedCost` to `null`, and resets constraint `dual` and `slack` to `null`.
|
|
164
191
|
|
|
165
|
-
|
|
192
|
+
### Mid-Flight & Overlapping Runs
|
|
166
193
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
4. **Transactional Batch Edits**: If an invalid edit is rejected (including batch array calls like `m.constraint([...])`), the model rolls back the failed edit without leaving partial entities registered or invalidating an existing valid solution.
|
|
194
|
+
- **Mid-flight mutations**: Modifying the model while an async `m.solve()` or `m.check()` is running discards the stale result, keeps `m.status` at `"NotSolved"`, and rejects the in-flight promise.
|
|
195
|
+
- **Overlapping calls**: Starting a new `m.solve()` or `m.check()` supersedes any earlier in-flight call on the same model so late completions cannot overwrite the latest state.
|
|
196
|
+
- **Atomic batch edits**: If a batch call such as `m.constraint([...])` contains an invalid item, WaSHI rolls back the entire call without leaving partial edits or clearing an existing valid solution.
|
|
171
197
|
|
|
172
198
|
> [!NOTE]
|
|
173
|
-
>
|
|
199
|
+
> `Var.name` is read-only, and renaming a registered constraint (`c.name = ...`) is rejected by integrity validation on the next solve, check, or export call.
|
|
200
|
+
> Directly mutating internal maps or AST arrays such as `c.lhs.terms` or `BoolOp.children` bypasses mutation tracking and can leave stale solution state—use `c.addTerm()`, `c.setTerm()`, or property setters instead.
|