@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,12 +1,13 @@
1
1
  # Objectives & Solving (`m.solve` & `m.check`)
2
2
 
3
- The objective function defines the goal of mathematical optimization—whether to maximize profits, minimize costs, or minimize quadratic risk variance. When you only need to verify constraint feasibility or solve pure SMT logic, you can also run `m.check()` without an objective.
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 objective direction and formula declaratively using `m.objective(maximize(...))` or `m.objective(minimize(...))`:
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,21 +24,22 @@ 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`). If you omit setting an objective, the model defaults to minimizing `0`.
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 objective formulation patterns—such as **Min-Max / Max-Min load balancing**, **weighted-sum vs. lexicographic multi-objective optimization**, and **MIP stopping tolerances (`relativeGap` / `absoluteGap`)**—see [Formulation Patterns & Optimization Tips](./formulation-tips.md#_4-multi-objective-mip-stopping-design).
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 entrypoints:
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 constraint satisfiability without an objective. Returns `{ status, values, conflicts?, unsatCore?, runTime? }` where `values: Record<string, number \| boolean>` contains both numeric and Boolean variable assignments. Ideal for CP/SMT/SAT verification and Pumpkin / Z3 `unsatCore` extraction. |
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({
@@ -51,24 +53,26 @@ 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 (e.g. `"highs"`, `"pumpkin"`, `"z3"`, `"glpk"`, or custom) or `Solver` instance for this run. |
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
- | `relativeGap` | `number` | `undefined` | Relative MIP optimality gap tolerance (e.g. `0.01` for 1%). |
58
+ | `relativeGap` | `number` | `undefined` | Relative MIP optimality gap tolerance (for example, `0.01` for 1%). |
57
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
- | `outputFlag` / `verbose` | `boolean` | `false` | Emits internal solver iteration logs (`outputFlag` for HiGHS, `verbose` for GLPK). |
60
- | `useWorker` | `boolean` | `true` (browser) | Offloads **HiGHS** and **Pumpkin** to dedicated Web Workers in browsers. Set `false` for main-thread execution. |
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). |
61
64
  | `wasmUrl` | `string` | Auto-resolved | Custom URL to load `highs.wasm` or `pumpkin.wasm` in browser deployments. |
62
- | `signal` | `AbortSignal` | `undefined` | Cooperative cancellation signal (`AbortController.signal`). |
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).
66
70
 
67
71
  ---
68
72
 
69
73
  ## Reading Results, Bounds & Solver Status
70
74
 
71
- After solving, query the status, optimal values, and MIP optimality bounds on the `Model`:
75
+ After solving, inspect the status, objective value, variable values, and MIP bounds directly on the `Model`:
72
76
 
73
77
  ```typescript
74
78
  const status = await m.solve();
@@ -88,30 +92,36 @@ console.log("x =", x.value, "y =", y.value);
88
92
  console.log("x by name:", m.values.get("x"));
89
93
  ```
90
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
+
91
97
  > [!TIP]
92
- > To independently check that the returned values satisfy all bounds, integrality requirements, and constraints within tolerance, call `m.verify()`—see [Diagnosis, Verification & Debugging](./unsat-core.md#independent-solution-verification-m-verify).
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).
93
100
 
94
101
  ### Understanding `m.status` vs. `m.terminationStatus`
95
102
 
96
- When a MIP solver stops early due to a time limit, iteration limit, or `AbortSignal`, two distinct questions matter:
97
- 1. **Is there a usable solution?** (`m.hasPrimalSolution` / `m.status`)
98
- 2. **Why did the solver stop?** (`m.terminationStatus`)
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`.
99
107
 
100
- 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).
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"`.
101
111
 
102
112
  ### All `SolverStatus` Values
103
113
 
104
114
  | Status | `hasPrimalSolution` | Meaning |
105
115
  | :--- | :--- | :--- |
106
- | `"Optimal"` | `true` | Global optimal solution proven (within tolerances). |
107
- | `"Feasible"` | `true` | Valid primal solution (incumbent) found, but optimality was not proven before stopping (`terminationStatus` indicates why: `"TimeLimit"`, `"IterationLimit"`, `"Interrupted"`, etc.). |
116
+ | `"Optimal"` | `true` | Global optimal solution proven within tolerances. |
117
+ | `"Feasible"` | `true` | Valid solution found, but stopped before proving optimality (see `terminationStatus`). |
108
118
  | `"Sat"` | `true` | Constraints are satisfiable (`m.check()`). |
109
119
  | `"Infeasible"` | `false` | Proven mathematically infeasible; no solution satisfies all constraints. |
110
- | `"Unsat"` | `false` | Logical/arithmetic constraints are unsatisfiable (`m.check()`). |
120
+ | `"Unsat"` | `false` | Logical or arithmetic constraints are unsatisfiable (`m.check()`). |
111
121
  | `"Unbounded"` | `false` | Objective can improve indefinitely without violating constraints. |
112
122
  | `"TimeLimit"` | `false` | Time limit reached before finding any feasible primal solution. |
113
123
  | `"IterationLimit"` | `false` | Iteration limit reached before finding any feasible primal solution. |
114
- | `"Unknown"` | `false` | Solver stopped inconclusively without a valid primal solution (including when cancelled via `AbortSignal` before finding an incumbent, where `terminationStatus === "Interrupted"`). |
124
+ | `"Unknown"` | `false` | Stopped without a solution (for example, cancelled via `AbortSignal` before finding one). |
115
125
  | `"Error"` | `false` | Solver encountered an internal execution error. |
116
126
  | `"NotSolved"` | `false` | Initial state before solving, or after the model has been mutated. |
117
127
 
@@ -119,7 +129,7 @@ If an integer-feasible incumbent was found before hitting `timeLimit` or `signal
119
129
 
120
130
  ## Real-Time Progress (`onProgress`) & Cancellation (`AbortSignal`)
121
131
 
122
- For long-running MIP optimizations in interactive UIs, you can stream live branch-and-bound progress (`SolveProgressEvent`) and allow users to cancel the solve cleanly with `AbortController`:
132
+ For long-running MIP solves in interactive apps, you can stream branch-and-bound progress with `onProgress` and cancel runs with `AbortController`:
123
133
 
124
134
  ```typescript
125
135
  const controller = new AbortController();
@@ -135,7 +145,7 @@ const status = await m.solve({
135
145
  `Gap: ${event.relativeGap !== undefined ? (event.relativeGap * 100).toFixed(2) + "%" : "—"}`
136
146
  );
137
147
 
138
- // 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
139
149
  if (event.objectiveValue !== undefined && event.objectiveValue >= 1000) {
140
150
  controller.abort();
141
151
  }
@@ -147,6 +157,12 @@ console.log("Termination:", m.terminationStatus); // "Interrupted"
147
157
  console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was available
148
158
  ```
149
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
+
150
166
  ### `SolveProgressEvent` Fields
151
167
 
152
168
  | Field | Type | Description |
@@ -154,23 +170,31 @@ console.log("Has incumbent:", m.hasPrimalSolution); // true if an incumbent was
154
170
  | `elapsedTime` | `number` | Elapsed solver time in seconds (optional alias: `elapsedSeconds`). |
155
171
  | `phase` | `"simplex" \| "ipm" \| "mip" \| undefined` | Current solver phase when known. |
156
172
  | `objectiveValue` | `number \| undefined` | Current best feasible incumbent objective value (MIP). |
157
- | `objectiveBound` | `number \| undefined` | Current best proven dual / objective bound (MIP). |
173
+ | `objectiveBound` | `number \| undefined` | Current best proven dual bound (MIP). |
158
174
  | `relativeGap` | `number \| undefined` | Current relative MIP optimality gap (`0.05` = 5%). |
159
175
  | `absoluteGap` | `number \| undefined` | Current absolute MIP optimality gap `\|objectiveValue - objectiveBound\|`. |
160
176
  | `nodes` | `number \| undefined` | Branch-and-bound nodes explored so far. |
161
- | `iterations` | `number \| undefined` | Solver iteration count (simplex, IPM, or MIP LP iterations). |
177
+ | `iterations` | `number \| undefined` | Solver iteration count (simplex, interior-point, or MIP LP iterations). |
162
178
  | `message` | `string \| undefined` | Raw progress line emitted by the solver. |
163
179
 
164
180
  ---
165
181
 
166
182
  ## Model Mutations & Execution Validity
167
183
 
168
- A `Model` instance keeps its solution state synchronized across mutations made through `Model` methods and `Model` / `Var` / `Constraint` property setters:
184
+ A `Model` keeps its solution state consistent across edits made through `Model` methods and `Model`, `Var`, and `Constraint` property setters.
185
+
186
+ ### Post-Solve Mutations Reset State
187
+
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`.
191
+
192
+ ### Mid-Flight & Overlapping Runs
169
193
 
170
- 1. **Post-Solve Mutations Reset Solution State**: Adding variables or constraints, updating the objective (`m.objective(...)`, `m.sense = ...`), or modifying variable bounds/types (`v.lb`, `v.ub`, `v.type`) or constraint properties (`c.lhs`, `c.sense`, `c.rhs`) immediately resets `m.status` to `"NotSolved"`, clears `m.solution` and `m.objectiveValue`, and resets variable/constraint primal and dual values to `null`.
171
- 2. **Mid-Flight Mutations Discard Stale Runs**: If the model is modified via these APIs while an asynchronous `m.solve()` or `m.check()` call is in progress, the stale solver result is discarded, the model remains in `"NotSolved"`, and the in-flight promise rejects with an explicit error.
172
- 3. **Overlapping Executions**: Starting a new `m.solve()` or `m.check()` call supersedes any earlier in-flight call on the same model so out-of-order completions can never overwrite the latest run's state.
173
- 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.
174
197
 
175
198
  > [!NOTE]
176
- > Renaming already-registered variables or constraints (e.g., reassigning `c.name` after registration) or mutating internal backing maps and ASTs directly (such as `c.lhs.terms` or `BoolOp.children`) is unsupported and will be rejected by internal model integrity validation on the next solve/check/export call.
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.
@@ -1,29 +1,30 @@
1
1
  # Conflict Diagnosis (`unsatCore`), Validation & Debugging
2
2
 
3
- When building real-world optimization and rule systems, you need to diagnose infeasible models, verify returned solutions, and inspect or unit-test formulations cleanly.
3
+ When a model has no feasible solution (`"Infeasible"`), or when you want to verify solver output before using it in production, WaSHI provides four diagnostic and debugging tools:
4
4
 
5
- WaSHI provides a unified verification and debugging toolkit for all three:
6
- - **Conflict diagnosis (`m.check()`)**: Pinpoint contradictory constraints via built-in HiGHS elastic relaxation, bundled Pumpkin Unsat Core, or Z3 Unsat Core.
7
- - **Solution verification & LP inspection (`m.verify()`, `m.toLpString()`)**: Independently verify variable bounds, integrality, and constraints, and export CPLEX `.lp` text to inspect generated equations.
8
- - **Fast unit testing (`MockSolver`)**: Test application model-building and post-processing logic in CI without loading WebAssembly.
5
+ - **Conflict diagnosis (`m.check()`)**: Pinpoints which named constraints cause infeasibility.
6
+ - **Solution verification (`m.verify()`)**: Independently checks variable bounds, integrality, and all constraints.
7
+ - **Formulation inspection (`m.toLpString()`)**: Exports CPLEX `.lp` text to inspect signs, coefficients, and names.
8
+ - **Deterministic testing (`MockSolver`)**: Returns fixed results in unit tests without loading WebAssembly.
9
9
 
10
10
  ---
11
11
 
12
- ## Conflict Diagnosis (`unsatCore` / `conflicts`)
12
+ ## Finding Conflicting Constraints (`m.check()`)
13
13
 
14
- When an optimization run (`m.solve()`) returns **`"Infeasible"`**, the status alone tells you that no solution satisfies every constraint—not *which* rules conflict with each other.
15
- By calling **`await m.check({ solver: "pumpkin" })`** (for bounded integer and boolean models without `COOP`/`COEP` headers or external peer dependencies) or **`await m.check({ solver: "z3" })`** (for models including `Continuous` variables or fractional arithmetic), WaSHI computes an **Unsatisfiable Core (`unsatCore`)**—a conflicting subset of named constraints that cannot be satisfied simultaneously:
14
+ When `m.solve()` returns `"Infeasible"`, it proves that no solution satisfies every rule, but does not tell you *which* rules clash.
15
+ To diagnose the cause, call `m.check()`.
16
+ A logical **Unsat Core** is a subset of named constraints that cannot hold simultaneously—even if every other named constraint in the model were removed (keeping variable bounds), those rules would still conflict.
17
+
18
+ Pass `{ solver: "pumpkin" }` for models with only bounded integer and Boolean variables, or `{ solver: "z3" }` for models with `Continuous` variables or non-integer coefficients/constants:
16
19
 
17
20
  ```typescript
18
21
  import { Model, expr } from "@ohtaman/washi";
19
- // Register the Z3 solver plugin (for Continuous / real-valued SMT models)
20
22
  import "@ohtaman/washi/solvers/z3";
21
23
 
22
24
  const m = new Model();
23
-
24
25
  const x = m.continuous("reserve", { lb: 0 });
25
26
 
26
- // Add named business requirements
27
+ // Register named constraints
27
28
  m.constraint(expr`${x} >= 100`, "minimum_regulatory_reserve");
28
29
  m.constraint(expr`${x} <= 50`, "budget_ceiling");
29
30
  m.constraint(expr`${x} >= 10`, "routine_operating_cost");
@@ -31,71 +32,70 @@ m.constraint(expr`${x} >= 10`, "routine_operating_cost");
31
32
  const result = await m.check({ solver: "z3" });
32
33
 
33
34
  if (result.status === "Unsat") {
34
- console.log("Contradictory constraints identified:");
35
- console.log(m.conflicts); // or result.conflicts / result.unsatCore / m.unsatCore
35
+ console.log("Conflicting constraints:", result.unsatCore); // also available via m.conflicts
36
36
  // Output: ["minimum_regulatory_reserve", "budget_ceiling"]
37
37
  }
38
38
  ```
39
39
 
40
- Notice that `routine_operating_cost` is **not** in the core, because only `minimum_regulatory_reserve` ($x \ge 100$) and `budget_ceiling` ($x \le 50$) directly contradict each other.
40
+ In this example, `routine_operating_cost` is excluded because only `minimum_regulatory_reserve` and `budget_ceiling` directly contradict each other.
41
41
 
42
42
  > [!IMPORTANT]
43
- > - **Use `m.check({ solver: "pumpkin" })` or `m.check({ solver: "z3" })` for Unsat Core extraction**: `m.solve()` runs optimization, whereas `m.check()` runs assumption-tracked satisfiability checking (Pumpkin assumption core or `Z3.Solver.assertAndTrack`) and populates `result.conflicts` / `m.conflicts` (and alias `m.unsatCore`).
44
- > - **Name your constraints**: Variable bounds (`lb`, `ub`) act as background domain declarations. To include a bound or business rule in the reported `unsatCore` list, register it as a named constraint via `m.constraint(expr`...`, "rule_name")`.
43
+ > - **Use `m.check()` for diagnosis**: When a model is infeasible, `m.solve()` only returns `"Infeasible"` without identifying the conflicting rules. When `m.check()` returns `"Unsat"`, it populates `conflicts` on all solvers, plus `unsatCore` on Pumpkin and Z3 (`undefined` on HiGHS/GLPK).
44
+ > - **Name every rule you want diagnosed**: Variable `lb`/`ub` bounds are unnamed and never appear in `conflicts`. Register any bound you want diagnosed with ``m.constraint(expr`...`, "rule_name")``.
45
45
 
46
- ### Workflow: Infeasibility Diagnosis with HiGHS, Pumpkin, or Z3
46
+ ### Choosing a Diagnosis Solver
47
47
 
48
- Because WaSHI models are solver-independent, you can choose from three diagnosis strategies:
49
- 1. **Built-in HiGHS & GLPK (default)**: `await m.check()` uses a single-solve elastic slack formulation ($\min \sum s_i$) to identify which constraints required relaxation (`diag.conflicts`), requiring no extra imports.
50
- 2. **Bundled Pumpkin CP/LCG Solver**: `await m.check({ solver: "pumpkin" })` (after `import "@ohtaman/washi/solvers/pumpkin"`) extracts a scale-invariant `unsatCore` / `conflicts` over bounded integer and boolean models with **zero external dependencies** and **zero browser `COOP` / `COEP` headers**.
51
- 3. **Z3 SMT Solver**: `await m.check({ solver: "z3" })` uses SMT tracking to extract an exact unsatisfiable core (`diag.unsatCore` / `diag.conflicts`), including models with `Continuous` variables or fractional arithmetic.
48
+ After `m.solve()` returns `"Infeasible"`, choose among three backends based on your variable types and scale sensitivity:
49
+
50
+ | Criterion | Pumpkin (`m.check({ solver: "pumpkin" })`) | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()` / `{ solver: "glpk" }`) |
51
+ | :--- | :--- | :--- | :--- |
52
+ | **Best for** | Bounded integer & Boolean models | Models with `Continuous` or non-integer values | General LP / MIP models (HiGHS needs zero extra imports) |
53
+ | **Setup** | Bundled (no extra import) | Optional (`z3-solver` + `@ohtaman/washi/solvers/z3`) | Bundled (HiGHS, default) / optional (`glpk.js`) |
54
+ | **Browser headers** | None | Requires `COOP` / `COEP` headers | None |
55
+ | **Result fields** | `unsatCore` and `conflicts` | `unsatCore` and `conflicts` | `conflicts` only (`unsatCore` is `undefined`) |
56
+ | **What it returns** | Unsat Core (mutually incompatible rules) | Unsat Core (mutually incompatible rules) | Elastic-relaxation set (rules to relax to restore feasibility) |
57
+ | **Unit-scale sensitivity** | Scale-invariant | Scale-invariant | Scale-sensitive (prefers relaxing smaller-scale constraints) |
52
58
 
53
59
  ```typescript
54
- const status = await m.solve(); // Fast MIP solve with default HiGHS
60
+ // Import Z3 at the top of your file if needed (HiGHS and Pumpkin require no extra import):
61
+ // import "@ohtaman/washi/solvers/z3";
62
+
63
+ const status = await m.solve();
55
64
 
56
65
  if (status === "Infeasible") {
57
- // Option 1: Built-in single-solve elastic diagnosis with HiGHS
66
+ // Option 1: Built-in HiGHS (no extra imports; scale-sensitive)
58
67
  const diag = await m.check();
59
- console.error("Model is infeasible due to conflicting rules:", diag.conflicts);
68
+ console.error("Constraints to relax:", diag.conflicts);
60
69
 
61
- // Option 2: Bundled zero-COOP/COEP unsat core with Pumpkin (bounded int/bool models; requires import "@ohtaman/washi/solvers/pumpkin")
70
+ // Option 2: Bundled Pumpkin (bounded int/bool; scale-invariant Unsat Core)
62
71
  // const pumpkinDiag = await m.check({ solver: "pumpkin" });
63
72
  // console.error("Pumpkin Unsat Core:", pumpkinDiag.unsatCore);
64
73
 
65
- // Option 3: Exact SMT unsat core diagnosis with Z3 (supports Continuous/real vars; requires import "@ohtaman/washi/solvers/z3")
74
+ // Option 3: Z3 (supports Continuous/decimal variables; requires z3-solver)
66
75
  // const z3Diag = await m.check({ solver: "z3" });
67
76
  // console.error("Z3 Unsat Core:", z3Diag.unsatCore);
68
77
  }
69
78
  ```
70
79
 
71
- ### Comparing Pumpkin `unsatCore`, Z3 `unsatCore`, and HiGHS Elastic Slack `conflicts`
72
-
73
- | Property | Pumpkin (`m.check({ solver: "pumpkin" })`) | Z3 (`m.check({ solver: "z3" })`) | HiGHS / GLPK (`m.check()`) |
74
- | :--- | :--- | :--- | :--- |
75
- | **Setup & Dependencies** | **Bundled** (`@ohtaman/washi/solvers/pumpkin`, zero peer deps) | Optional peer dependency (`z3-solver`) | **Built-in** (HiGHS) / optional `glpk.js` |
76
- | **Browser Headers** | **None** (`COOP` / `COEP` not required) | Requires `COOP` / `COEP` (`SharedArrayBuffer`) | **None** |
77
- | **Supported Variables** | Bounded `Integer`, `Binary`, `BoolVar` | `Continuous`, `Integer`, `Binary`, `BoolVar` | `Continuous`, `Integer`, `Binary`, `BoolVar` |
78
- | **Algorithm** | LCG conflict analysis under constraint assumptions | SMT assumption tracking (`assertAndTrack`) | Single-solve $L_1$ elastic slack relaxation ($\min \sum s_i$) |
79
- | **Populated Fields** | Both `result.unsatCore` and `result.conflicts` | Both `result.unsatCore` and `result.conflicts` | `result.conflicts` (`unsatCore` is `undefined`) |
80
- | **Semantic Meaning** | A **contradictory subset** of rules that cannot all hold together | A **contradictory subset** of rules that cannot all hold together | A **minimum-violation repair set** of constraints whose relaxation restores feasibility |
81
- | **Unit-Scaling Sensitivity** | **Scale-invariant** (pure logical/integer contradiction) | **Scale-invariant** (pure logical/algebraic contradiction) | **Scale-sensitive** (minimizing unweighted $\sum s_i$ prefers relaxing a headcount constraint by `2` units over a budget constraint by `10,000` dollars) |
82
-
83
80
  > [!TIP]
84
- > When diagnosing models that mix constraints of vastly different magnitudes (e.g., headcount $\le 8$ alongside budget $\le 50{,}000$), use **`m.check({ solver: "pumpkin" })`** (for bounded integer/boolean models without `COOP`/`COEP`) or **`m.check({ solver: "z3" })`** (when `Continuous` variables or fractional thresholds are present) if you want a scale-invariant set of mutually contradictory rules, or normalize constraint scales when relying on unweighted $L_1$ slack relaxation.
81
+ > **Why HiGHS / GLPK are scale-sensitive**: In HiGHS and GLPK, `m.check()` introduces non-negative relaxation slacks to each constraint (including auto-named ones)—subtracting on `<=`, adding on `>=`, and both on `==`—and minimizes their **unweighted sum**.
82
+ > When constraints mix very different numeric scales—such as headcount $\le 8$ alongside budget $\le 50{,}000$—relaxing the smaller-scale constraint adds far less to the total slack, so HiGHS/GLPK tends to flag it first.
83
+ > Normalize your constraint units to reduce scale bias in elastic relaxation, or use `pumpkin` or `z3` when you need a scale-invariant Unsat Core.
85
84
 
86
85
  ---
87
86
 
88
- ## Independent Solution Verification (`m.verify()`)
87
+ ## Verifying Solutions (`m.verify()`)
89
88
 
90
- After solving a model (or supplying a custom candidate map via `values`), you can independently verify that all variable bounds, integer/binary domains, linear constraints, and logical SMT formulas hold against the original model definitions:
89
+ After solving a model, call `m.verify()` to check that every bound, integrality rule, linear constraint, and logical constraint holds within tolerance.
90
+ You can also pass a plain object via `values` (not a `Map`), such as `m.verify({ values: { x: 1, y: 2 } })`, to validate an externally produced assignment:
91
91
 
92
92
  ```typescript
93
93
  const status = await m.solve();
94
94
 
95
95
  if (m.hasPrimalSolution) {
96
96
  const report = m.verify({
97
- feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
98
- integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
97
+ feasibilityTolerance: 1e-6, // Max allowed violation for bounds and linear constraints
98
+ integralityTolerance: 1e-6, // Max distance from nearest integer for Integer/Binary vars
99
99
  evaluateLogicalConstraints: true,
100
100
  });
101
101
 
@@ -110,26 +110,29 @@ if (m.hasPrimalSolution) {
110
110
  }
111
111
  ```
112
112
 
113
- ### `VerificationReport` Summary
113
+ ### `VerificationReport` Fields
114
114
 
115
115
  | Property | Type | Description |
116
116
  | :--- | :--- | :--- |
117
- | `valid` | `boolean` | `true` iff `complete === true`, `uncheckedConstraints.length === 0`, and `violations.length === 0`. |
118
- | `complete` | `boolean` | `true` when all variables, Boolean variables, linear constraints, and logical constraints were evaluated. |
119
- | `maxViolation` | `number` | Largest numeric violation magnitude across all evaluated bounds, integrality checks, and constraints. |
120
- | `violations` | `VerificationViolation[]` | Flat list of violations (`"missing_value"`, `"non_finite_value"`, `"invalid_boolean_value"`, `"lower_bound"`, `"upper_bound"`, `"integrality"`, `"linear_constraint"`, `"logical_constraint"`, `"unchecked_constraint"`). |
117
+ | `valid` | `boolean` | `true` when `complete === true`, `uncheckedConstraints` is empty, and `violations` is empty. |
118
+ | `complete` | `boolean` | `true` when every variable and constraint in the model was evaluated. |
119
+ | `maxViolation` | `number` | Largest numeric violation across all checked bounds, integrality rules, and constraints. |
120
+ | `violations` | `VerificationViolation[]` | List of detected violations (bounds, integrality, linear/logical constraints, or missing/invalid values). |
121
121
  | `violationsByName` | `Record<string, VerificationViolation[]>` | Violations grouped by variable or constraint name. |
122
122
  | `uncheckedConstraints` | `string[]` | Names of constraints that could not be evaluated. |
123
- | `missingVariables` | `string[]` | Names of numeric or Boolean variables whose values were `null` or `undefined`. |
124
- | `summary` | `VerificationSummary` | Counts of checked vs. total variables, Boolean variables, linear constraints, and logical constraints. |
123
+ | `missingVariables` | `string[]` | Names of variables whose values were `null` or `undefined`. |
124
+ | `summary` | `VerificationSummary` | Counts of checked vs. total variables and constraints. |
125
125
 
126
126
  ---
127
127
 
128
128
  ## Inspecting the LP Formulation (`m.toLpString()`)
129
129
 
130
- When debugging coefficients, signs, or Big-M indicator expansions, call `m.toLpString()` to export the model in standard CPLEX/HiGHS `.lp` format:
130
+ To inspect coefficients, signs, or constraint names, call `m.toLpString()` to export the model in standard CPLEX `.lp` format.
131
+ It exports numeric variables, linear/quadratic objectives, linear constraints, and lowered `max`/`min`/`abs`/`at`/`!=` expressions, while omitting propositional `BoolVar`s and logical constraints:
131
132
 
132
133
  ```typescript
134
+ import { Model, expr, maximize } from "@ohtaman/washi";
135
+
133
136
  const m = new Model("DebugModel");
134
137
  const x = m.integer("x", { lb: 0, ub: 10 });
135
138
  m.objective(maximize(expr`5 * ${x}`));
@@ -151,9 +154,9 @@ End
151
154
 
152
155
  ---
153
156
 
154
- ## Unit Testing Application Logic with `MockSolver`
157
+ ## Unit Testing Without WebAssembly (`MockSolver`)
155
158
 
156
- When running unit tests for application code that builds or consumes a WaSHI `Model`, you can use the built-in `MockSolver` (`solver: "mock"`) to return deterministic results instantaneously without loading WebAssembly:
159
+ In unit tests for application code that builds or reads a `Model`, pass `MockSolver` to return fixed results immediately without loading WebAssembly:
157
160
 
158
161
  ```typescript
159
162
  import { Model, MockSolver, expr, maximize } from "@ohtaman/washi";
@@ -1,14 +1,16 @@
1
1
  # Variables & Domains
2
2
 
3
- Variables represent the mathematical decision variables in your optimization or logical model.
4
- WaSHI provides domain-specific factory methods on the `Model` instance: `m.continuous()`, `m.integer()`, `m.binary()`, and `m.bool()`.
3
+ Variables represent the unknown decision quantities in an optimization or logical model.
4
+ On a `Model` instance, WaSHI provides four domain-specific factory methods: `m.continuous()`, `m.integer()`, `m.binary()`, and `m.bool()`.
5
5
 
6
6
  ---
7
7
 
8
8
  ## Decision Variable Types
9
9
 
10
10
  ### 1. Continuous Variables (`m.continuous`)
11
- Can take any real number value within `[lb, ub]`. Used for continuous quantities such as flow rates, weights, budgets, and portfolio allocations:
11
+
12
+ Continuous variables take any real number bounded by `lb` and `ub` (default: `lb = 0`, `ub = Infinity`).
13
+ Use them for divisible quantities such as flow rates, weights, budgets, and portfolio weights:
12
14
 
13
15
  ```typescript
14
16
  import { Model } from "@ohtaman/washi";
@@ -20,7 +22,9 @@ const fuel = m.continuous("fuel", { lb: 0, ub: 1000 });
20
22
  ```
21
23
 
22
24
  ### 2. Integer Variables (`m.integer`)
23
- Restricted to integer values within `[lb, ub]`. Used for discrete counts such as machines, vehicles, or headcount:
25
+
26
+ Integer variables take whole numbers bounded by `lb` and `ub` (default: `lb = 0`, `ub = Infinity`).
27
+ Use them for indivisible counts such as vehicles, machines, or staff headcount:
24
28
 
25
29
  ```typescript
26
30
  // Single integer variable bounded in [0, 15]
@@ -28,7 +32,9 @@ const trucks = m.integer("trucks", { lb: 0, ub: 15 });
28
32
  ```
29
33
 
30
34
  ### 3. Binary Variables (`m.binary`)
31
- Restricted to $\{0, 1\}$ as numeric values (`lb = 0`, `ub = 1`). Used for 0-1 MIP selection and yes/no decisions that appear in linear sums or objective costs:
35
+
36
+ Binary variables take numeric values in $\{0, 1\}$ with `lb = 0` and `ub = 1` set automatically.
37
+ Use them for yes/no decisions in Mixed-Integer Programming (MIP) that appear in linear sums or objective costs:
32
38
 
33
39
  ```typescript
34
40
  // Single binary variable (lb = 0, ub = 1 automatically)
@@ -36,7 +42,8 @@ const openWarehouse = m.binary("open_warehouse");
36
42
  ```
37
43
 
38
44
  ### 4. Propositional Boolean Variables (`m.bool`)
39
- Pure boolean propositions (`true` / `false`) for logical and SMT constraints:
45
+
46
+ Propositional Boolean variables take pure truth values (`true` or `false`) for logical and Satisfiability Modulo Theories (SMT) rules:
40
47
 
41
48
  ```typescript
42
49
  // Single propositional boolean variables
@@ -53,20 +60,19 @@ m.constraint(isAdmin.implies(hasMfa), "admin_requires_mfa");
53
60
  | :--- | :--- | :--- |
54
61
  | **Solved `.value` type** | `number \| null` (`0` or `1`) | `boolean \| null` (`true` or `false`) |
55
62
  | **Linear arithmetic (`expr`, `sum`, `dot`, objective costs)** | ✅ Native (`` expr`30 * ${b}` ``) | ❌ Cannot be multiplied by numbers or summed directly |
56
- | **Indicator constraints (`m.indicator(b, ...)` )** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
63
+ | **Indicator constraints (`m.indicator(b, ...)`)** | ✅ Supported as trigger variable | ❌ Use `` implies(flag, expr`...`) `` instead |
57
64
  | **Propositional logic (`and`, `or`, `not`, `implies`, `xor`)** | Via comparison (`` expr`${b} == 1` ``) | ✅ Native first-class methods (`.implies()`, `.and()`) |
58
- | **Solver execution** | Native 0-1 MIP on HiGHS/GLPK; bounded `{0, 1}` integer on Pumpkin/Z3 | Native boolean proposition on Pumpkin/Z3; auto-linearized to 0-1 MIP on HiGHS/GLPK |
59
-
60
- > [!TIP]
61
- > Use **`m.binary()`** when a decision participates in arithmetic expressions—such as linear sums ($\sum x_i \ge 3$), objective cost terms ($c_i x_i$), or `m.indicator()`. Use **`m.bool()`** when expressing logical conditions with `implies()`, `and()`, and `or()` without numeric coefficients.
65
+ | **Best used for** | Arithmetic sums, objective costs, `m.indicator()` | Pure logical rules without numeric coefficients |
62
66
 
63
67
  ---
64
68
 
65
69
  ## Multi-Dimensional & Array Creation
66
70
 
67
- The domain factory methods (`continuous`, `integer`, `binary`, `bool`) accept a numeric count or an array of string keys to create 1D arrays, typed dictionaries, and 2D matrices in a single call.
71
+ All four factory methods (`continuous`, `integer`, `binary`, `bool`) accept counts or string-key arrays.
72
+ This lets you create 1D arrays, typed dictionaries, and 2D matrices in a single call.
68
73
 
69
74
  ### By Count
75
+
70
76
  Pass a number to create an array of variables:
71
77
 
72
78
  ```typescript
@@ -75,7 +81,8 @@ const flags = m.bool(3); // BoolVar[] (p_0, p_1, p_2)
75
81
  ```
76
82
 
77
83
  ### 1D Variable Dictionaries
78
- Pass an array of keys to get a typed dictionary `Record<K, Var>` or `Record<K, BoolVar>`:
84
+
85
+ Pass an array of string keys to create a typed dictionary (`Record<K, Var>` or `Record<K, BoolVar>`):
79
86
 
80
87
  ```typescript
81
88
  const items = ["laptop", "phone", "tablet"] as const;
@@ -88,7 +95,9 @@ const perms = m.bool(["read", "write", "execute"] as const);
88
95
  ```
89
96
 
90
97
  ### 2D Variable Matrices & Grids
91
- Each dimension follows a consistent rule: passing a numeric count (`number`) produces an `Array`, and passing a collection of keys produces a `Record`:
98
+
99
+ Each dimension follows one rule: a numeric count produces an `Array`, and a key list produces a `Record`.
100
+
92
101
  - `(rowsCount, colsCount)` $\rightarrow$ `Var[][]` (or `BoolVar[][]`)
93
102
  - `(rowKeys, colKeys)` $\rightarrow$ `Record<R, Record<C, Var>>` (or `Record<R, Record<C, BoolVar>>`)
94
103
  - `(rowsCount, colKeys)` $\rightarrow$ `Array<Record<C, Var>>`
@@ -115,24 +124,30 @@ const schedule = m.binary(factories, 7, { prefix: "open_day" });
115
124
 
116
125
  ## Variable Options
117
126
 
127
+ Each factory method accepts options matching its variable kind.
128
+ `m.continuous()` and `m.integer()` accept all factory options below, `m.binary()` omits `lb` and `ub`, and `m.bool()` accepts `name` and `prefix` only.
129
+
118
130
  | Option | Type | Default | Description |
119
131
  | :--- | :--- | :--- | :--- |
120
- | `lb` | `number` | `0` | Lower bound. Defaults to `0` (non-negative). Pass `-Infinity` for free lower bounds. |
121
- | `ub` | `number` | `Infinity` (or `1` for binary) | Upper bound. |
122
- | `prefix` | `string` | `"x"` (`"p"` for `m.bool()`) | Name prefix for unnamed scalar variables and indexed arrays/matrices (e.g., `queen_0_0`). |
123
- | `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Underlying variable domain category. |
124
- | `initialValue` | `number` | `undefined` | Optional primal solution hint (MIP warm start), kept distinct from solved `variable.value`. |
132
+ | `name` | `string` | Auto-generated | Explicit name for a scalar variable (alternative to passing the name as the first argument). |
133
+ | `lb` | `number` | `0` | Lower bound (`m.continuous()`, `m.integer()`). Pass a negative finite number or `-Infinity` to allow negative values. |
134
+ | `ub` | `number` | `Infinity` (`1` for binary) | Upper bound (`m.continuous()`, `m.integer()`). Fixed to `1` for `m.binary()`. |
135
+ | `prefix` | `string` | `"x"` (`"p"` for `m.bool()`) | Name prefix for unnamed scalars, arrays, dictionaries, and 2D containers (e.g., `queen_0_0`). |
136
+ | `type` | `"Continuous"` \| `"Integer"` \| `"Binary"` | Inferred from method | Numeric variable domain (applies to direct `new Var()` construction only). |
137
+ | `initialValue` | `number` | `undefined` | Warm-start hint for numeric variables (`m.continuous()`, `m.integer()`, `m.binary()`), stored separately from solved `variable.value`. |
125
138
 
126
139
  ### Designing Bounds (`lb` & `ub`)
127
140
 
128
- - **Default non-negativity**: Numeric variables default to `lb: 0, ub: Infinity`. If a variable can take negative values (such as net inventory change or deviation), explicitly pass `{ lb: -Infinity }`.
129
- - **Prefer realistic finite bounds**: Specifying finite `lb` and `ub` values strengthens MIP presolve, allows `m.indicator()` to derive tight Big-M constants automatically, and is required by bounded-integer CP solvers such as **Pumpkin**.
141
+ - **Allowing negative values**: Numeric variables are non-negative by default. For signed quantities such as net inventory change or deviation, explicitly pass a negative finite bound or `{ lb: -Infinity }`.
142
+ - **Strengthening MIP formulations**: Realistic finite `lb` and `ub` bounds improve MIP presolve and let `m.indicator()` compute tight Big-M constants automatically.
143
+ - **CP solver requirement**: Bounded-integer Constraint Programming (CP) solvers such as Pumpkin require finite integer bounds on every numeric variable.
130
144
 
131
145
  ---
132
146
 
133
147
  ## Primal Initial Values (Warm-Start Hints)
134
148
 
135
- When rebuilding a model across iterations, you can supply optional primal initial values (`initialValue`) on a subset or all numeric variables (`m.continuous`, `m.integer`, `m.binary`, or `v.initialValue = ...`):
149
+ When re-solving a modified model, you can supply a warm-start hint (`initialValue`) on some or all numeric variables.
150
+ Pass `initialValue` in the factory options or assign `v.initialValue = ...` directly:
136
151
 
137
152
  ```typescript
138
153
  const prevValues: Record<string, number | null> = { trucks: 8, open_warehouse: 1 };
@@ -149,15 +164,33 @@ const openWarehouse2 = m2.binary("open_warehouse", {
149
164
  const extraCapacity = m2.continuous("extra_capacity", { lb: 0 }); // Partial start: no initialValue needed
150
165
  ```
151
166
 
152
- - **Hint vs. Hard Constraint**: `initialValue` is an optional solver hint (passed to HiGHS via `setSolution`, or to Pumpkin's `WarmStart` branching strategy). It does **not** fix the variable or add a constraint, and `variable.value` remains `null` until solved. *(To penalize deviations from a previous plan, see [Formulation Patterns & Tips](./formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).)*
153
- - **Validation & Tolerance (`1e-6`)**: Supplied values must be finite numbers within `[lb - 1e-6, ub + 1e-6]` (and within `1e-6` of an integer for `"Integer"` and `"Binary"` variables). Partial starts are accepted without needing to satisfy every model constraint, though supplying a complete constraint-feasible assignment gives MIP solvers an immediate incumbent bound.
154
- - **Solver Support**: Supported by **HiGHS** and **Pumpkin** (`capabilities.supportsWarmStart === true`; Pumpkin supports `initialValue` on bounded `Integer` and `Binary` variables in both `solve()` and `check()`). Solvers without warm-start support (**GLPK**, **Z3**, or custom adapters without `supportsWarmStart: true`) reject `solve()` and `check()` with a descriptive error rather than silently ignoring `initialValue`.
167
+ ### Hint vs. Hard Constraint
168
+
169
+ `initialValue` is an optional starting hint for the solver, not a constraint or variable fixation.
170
+ Before solving, `variable.value` remains `null`.
171
+ To penalize changes from an existing schedule in the objective instead, see [Formulation Patterns & Tips](./formulation-tips.md#minimal-perturbation-rescheduling-vs-warm-starting).
172
+
173
+ ### Validation & Tolerance (`1e-6`)
174
+
175
+ Every supplied `initialValue` must be a finite number within `[lb - 1e-6, ub + 1e-6]`.
176
+ For `"Integer"` and `"Binary"` variables, the value must also lie within `1e-6` of an integer.
177
+ Partial starts are allowed; providing a complete feasible assignment gives MIP solvers an immediate incumbent solution (a valid baseline objective value used to prune search branches).
178
+
179
+ ### Solver Support
180
+
181
+ - **Supported**: HiGHS supports warm starts on all numeric variables. Pumpkin supports them on bounded `Integer` and `Binary` variables in both `solve()` and `check()`.
182
+ - **Unsupported**: GLPK, Z3, and custom adapters without warm-start support reject `solve()` and `check()` with an explicit error instead of silently ignoring `initialValue`.
155
183
 
156
184
  ---
157
185
 
158
186
  ## Accessing Solution Values & Reduced Costs
159
187
 
160
- After calling `await m.solve()` or `await m.check()`, assigned variable values are accessible directly via `variable.value` (returns `number | null` for `Var`, or `boolean | null` for `BoolVar`), or by variable name via `m.values`:
188
+ After calling `await m.solve()` or `await m.check()`, read assigned values directly from `variable.value` or look them up by name in `m.values`.
189
+ `variable.value` returns `number | null` for `Var` and `boolean | null` for `BoolVar`.
190
+
191
+ For continuous Linear Programming (LP) models—or LP relaxations solved via `m.relax()`—on HiGHS, `variable.reducedCost` exposes the variable's reduced cost as `number | null`.
192
+ The **reduced cost** indicates how much a non-basic variable's objective coefficient must improve before moving it away from its active bound (`lb` or `ub`) becomes worthwhile.
193
+ `reducedCost` is `null` before solving, when no optimal LP solution is found, on GLPK (which populates constraint `dual` only), on MIP models solved with `m.solve()`, and on CP and SMT models.
161
194
 
162
195
  ```typescript
163
196
  await m.solve();
@@ -173,7 +206,7 @@ console.log(`Tokyo -> StoreA: ${ship.Tokyo.StoreA.value}`);
173
206
  // Name-keyed ReadonlyMap lookup (ReadonlyMap<string, number | boolean>)
174
207
  console.log(`trucks by name: ${m.values.get("trucks")}`);
175
208
 
176
- // Reduced cost (LP sensitivity analysis)
209
+ // Reduced cost (LP sensitivity analysis; number | null)
177
210
  console.log(`fuel reduced cost: ${fuel.reducedCost}`);
178
211
  ```
179
212
 
@@ -181,7 +214,7 @@ console.log(`fuel reduced cost: ${fuel.reducedCost}`);
181
214
 
182
215
  ## Looking Up Variables by Name
183
216
 
184
- All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are exposed through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
217
+ All registered numeric (`Var`) and propositional Boolean (`BoolVar`) variables are accessible through `m.variables` (`ReadonlyMap<string, Var | BoolVar>`):
185
218
 
186
219
  ```typescript
187
220
  const v = m.variables.get("trucks"); // Var | BoolVar | undefined