@ohtaman/washi 0.8.0 → 0.8.2
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.md +32 -34
- package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
- package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
- package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
- package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
- package/dist/browser/solvers/highs.js +1414 -0
- package/dist/browser/washi.js +1090 -1473
- package/dist/browser/washi.min.js +4 -4
- package/dist/lib/solvers/glpk.js +34 -32
- package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
- package/dist/lib/solvers/highs.js +410 -0
- package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
- package/dist/lib/solvers/pumpkin-worker.js +1 -1
- package/dist/lib/solvers/pumpkin.js +247 -1146
- package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
- package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
- package/dist/lib/solvers/z3.js +125 -123
- package/dist/lib/washi.js +2426 -1340
- package/dist/types/index.d.ts +1 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +0 -1
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +6 -7
- package/dist/types/modeler/model.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/registry.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 +34 -30
- 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 +25 -12
- package/docs/examples/shift-scheduling.md +27 -19
- package/docs/examples/smt-security.md +27 -12
- package/docs/examples/transportation.md +23 -13
- package/docs/examples/traveling-salesperson.md +34 -22
- package/docs/examples/unsat-core.md +27 -15
- package/docs/examples/vehicle-routing.md +74 -28
- package/docs/getting-started/ai-agents.md +129 -90
- package/docs/getting-started/coding-agents.md +60 -41
- package/docs/getting-started/cross-origin.md +27 -14
- package/docs/getting-started/index.md +23 -16
- package/docs/getting-started/runtimes.md +70 -40
- package/docs/guide/constraint-programming.md +74 -44
- package/docs/guide/constraints.md +71 -39
- package/docs/guide/decomposition.md +72 -42
- package/docs/guide/expressions.md +79 -48
- package/docs/guide/formulation-tips.md +46 -27
- package/docs/guide/objectives.md +55 -31
- package/docs/guide/unsat-core.md +56 -53
- package/docs/guide/variables.md +61 -28
- package/docs/solvers/custom-solver.md +155 -119
- package/docs/solvers/glpk.md +58 -17
- package/docs/solvers/highs.md +115 -43
- package/docs/solvers/index.md +33 -26
- package/docs/solvers/pumpkin.md +71 -63
- package/docs/solvers/z3.md +63 -25
- package/llms-full.txt +1623 -953
- package/llms.txt +125 -93
- package/package.json +29 -22
- package/skills/washi/SKILL.md +43 -22
- package/README.ja.md +0 -248
- package/README.zh-CN.md +0 -248
- package/dist/browser/solvers/pumpkin.min.js +0 -1
- package/dist/lib/registry-dx7x4e5c.js +0 -1694
- /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
- /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
- /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
- /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
- /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
- /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
- /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
- /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
- /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
- /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
- /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
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,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`).
|
|
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({
|
|
@@ -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 (
|
|
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 (
|
|
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
|
-
| `
|
|
60
|
-
| `
|
|
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` |
|
|
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,
|
|
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
|
|
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
|
|
97
|
-
|
|
98
|
-
|
|
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
|
|
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
|
|
107
|
-
| `"Feasible"` | `true` | Valid
|
|
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
|
|
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` |
|
|
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
|
|
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
|
|
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,
|
|
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`
|
|
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
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
>
|
|
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.
|
package/docs/guide/unsat-core.md
CHANGED
|
@@ -1,29 +1,30 @@
|
|
|
1
1
|
# Conflict Diagnosis (`unsatCore`), Validation & Debugging
|
|
2
2
|
|
|
3
|
-
When
|
|
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
|
-
|
|
6
|
-
- **
|
|
7
|
-
- **
|
|
8
|
-
- **
|
|
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
|
-
##
|
|
12
|
+
## Finding Conflicting Constraints (`m.check()`)
|
|
13
13
|
|
|
14
|
-
When
|
|
15
|
-
|
|
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
|
-
//
|
|
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("
|
|
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
|
-
|
|
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(
|
|
44
|
-
> - **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
|
-
###
|
|
46
|
+
### Choosing a Diagnosis Solver
|
|
47
47
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
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
|
|
66
|
+
// Option 1: Built-in HiGHS (no extra imports; scale-sensitive)
|
|
58
67
|
const diag = await m.check();
|
|
59
|
-
console.error("
|
|
68
|
+
console.error("Constraints to relax:", diag.conflicts);
|
|
60
69
|
|
|
61
|
-
// Option 2: Bundled
|
|
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:
|
|
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
|
-
>
|
|
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
|
-
##
|
|
87
|
+
## Verifying Solutions (`m.verify()`)
|
|
89
88
|
|
|
90
|
-
After solving a model
|
|
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,
|
|
98
|
-
integralityTolerance: 1e-6,
|
|
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`
|
|
113
|
+
### `VerificationReport` Fields
|
|
114
114
|
|
|
115
115
|
| Property | Type | Description |
|
|
116
116
|
| :--- | :--- | :--- |
|
|
117
|
-
| `valid` | `boolean` | `true`
|
|
118
|
-
| `complete` | `boolean` | `true` when
|
|
119
|
-
| `maxViolation` | `number` | Largest numeric violation
|
|
120
|
-
| `violations` | `VerificationViolation[]` |
|
|
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
|
|
124
|
-
| `summary` | `VerificationSummary` | Counts of checked vs. total variables
|
|
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
|
-
|
|
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
|
|
157
|
+
## Unit Testing Without WebAssembly (`MockSolver`)
|
|
155
158
|
|
|
156
|
-
|
|
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";
|
package/docs/guide/variables.md
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
# Variables & Domains
|
|
2
2
|
|
|
3
|
-
Variables represent the
|
|
4
|
-
WaSHI provides domain-specific factory methods
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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, ...)`
|
|
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
|
-
| **
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
| `
|
|
121
|
-
| `
|
|
122
|
-
| `
|
|
123
|
-
| `
|
|
124
|
-
| `
|
|
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
|
-
- **
|
|
129
|
-
- **
|
|
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
|
|
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
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
|
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
|
|
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
|