@ohtaman/washi 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +60 -23
- package/README.md +59 -22
- package/README.zh-CN.md +62 -25
- package/THIRD_PARTY_LICENSES.md +34 -1
- package/dist/browser/solvers/glpk.js +289 -238
- package/dist/browser/solvers/glpk.min.js +1 -1
- package/dist/browser/solvers/highs-__vite-browser-external-Dn-83hnF.js +7 -0
- package/dist/browser/solvers/highs-browser-runtime-0Bgq5ksG.js +2021 -0
- package/dist/browser/{loader-DewlSho8.js → solvers/highs-loader-BLY3wzDH.js} +190 -149
- package/dist/browser/solvers/highs-worker.js +54 -0
- package/dist/browser/solvers/highs.js +1414 -0
- package/dist/browser/solvers/highs.wasm +0 -0
- package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
- package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
- package/dist/browser/solvers/pumpkin-worker.js +45 -0
- package/dist/browser/solvers/pumpkin.js +1777 -0
- package/dist/browser/solvers/pumpkin.wasm +0 -0
- package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/browser/solvers/z3.js +1600 -1335
- package/dist/browser/solvers/z3.min.js +2 -2
- package/dist/browser/washi.js +3313 -1699
- package/dist/browser/washi.min.js +5 -3
- package/dist/lib/solvers/__vite-browser-external-oLchLuMx.js +7 -0
- package/dist/lib/solvers/glpk.js +174 -132
- package/dist/lib/solvers/highs-browser-runtime.js +2413 -0
- package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
- package/dist/lib/solvers/highs-runtime.js +16 -0
- package/dist/lib/solvers/highs-worker.js +54 -0
- package/dist/lib/solvers/highs.js +410 -0
- package/dist/lib/solvers/highs.wasm +0 -0
- package/dist/lib/{loader-BZUQNvh4.js → solvers/loader-CDpPXN_F.js} +138 -116
- package/dist/lib/solvers/loader-Ow74Fa1B.js +311 -0
- package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
- package/dist/lib/solvers/pumpkin-assets.js +1 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
- package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
- package/dist/lib/solvers/pumpkin-worker.js +45 -0
- package/dist/lib/solvers/pumpkin.js +868 -0
- package/dist/lib/solvers/pumpkin.wasm +0 -0
- package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
- package/dist/lib/solvers/rolldown-runtime-DtPi1Y-2.js +13 -0
- package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
- package/dist/lib/solvers/z3.js +489 -307
- package/dist/lib/washi.js +3905 -1410
- package/dist/types/decomposition/benders.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -5
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/boolean-expr.d.ts +137 -29
- package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
- package/dist/types/modeler/constraint.d.ts +40 -4
- package/dist/types/modeler/constraint.d.ts.map +1 -1
- package/dist/types/modeler/expression.d.ts +129 -2
- package/dist/types/modeler/expression.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +4 -6
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/linearizer.d.ts +11 -2
- package/dist/types/modeler/linearizer.d.ts.map +1 -1
- package/dist/types/modeler/lp-writer.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +86 -126
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/parser.d.ts.map +1 -1
- package/dist/types/modeler/quad-expr.d.ts +8 -2
- package/dist/types/modeler/quad-expr.d.ts.map +1 -1
- package/dist/types/modeler/solution-validator.d.ts +12 -12
- package/dist/types/modeler/solution-validator.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
- package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
- package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
- package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
- package/dist/types/modeler/solvers/index.d.ts +2 -1
- package/dist/types/modeler/solvers/index.d.ts.map +1 -1
- package/dist/types/modeler/solvers/mock.d.ts +2 -3
- package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
- package/dist/types/modeler/solvers/types.d.ts +7 -9
- package/dist/types/modeler/solvers/types.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
- package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
- package/dist/types/modeler/types.d.ts +12 -15
- package/dist/types/modeler/types.d.ts.map +1 -1
- package/dist/types/modeler/validation.d.ts +26 -2
- package/dist/types/modeler/validation.d.ts.map +1 -1
- package/dist/types/modeler/variable.d.ts +9 -5
- package/dist/types/modeler/variable.d.ts.map +1 -1
- package/docs/examples/diet-sensitivity.md +33 -14
- package/docs/examples/ecommerce-coupons.md +17 -9
- package/docs/examples/index.md +36 -27
- package/docs/examples/knapsack.md +11 -5
- package/docs/examples/portfolio-qp.md +21 -8
- package/docs/examples/production.md +10 -5
- package/docs/examples/project-scheduling.md +119 -0
- package/docs/examples/shift-scheduling.md +29 -18
- package/docs/examples/smt-security.md +27 -11
- package/docs/examples/transportation.md +23 -13
- package/docs/examples/traveling-salesperson.md +34 -22
- package/docs/examples/unsat-core.md +27 -14
- package/docs/examples/vehicle-routing.md +74 -28
- package/docs/getting-started/ai-agents.md +190 -82
- package/docs/getting-started/coding-agents.md +177 -0
- package/docs/getting-started/cross-origin.md +27 -14
- package/docs/getting-started/index.md +49 -43
- package/docs/getting-started/runtimes.md +94 -40
- package/docs/guide/constraint-programming.md +171 -0
- package/docs/guide/constraints.md +115 -33
- package/docs/guide/decomposition.md +118 -88
- package/docs/guide/expressions.md +106 -43
- package/docs/guide/formulation-tips.md +47 -28
- package/docs/guide/objectives.md +102 -75
- package/docs/guide/unsat-core.md +62 -50
- package/docs/guide/variables.md +81 -35
- package/docs/solvers/custom-solver.md +163 -122
- package/docs/solvers/glpk.md +58 -17
- package/docs/solvers/highs.md +124 -57
- package/docs/solvers/index.md +33 -20
- package/docs/solvers/pumpkin.md +171 -0
- package/docs/solvers/z3.md +63 -25
- package/llms-full.txt +2232 -932
- package/llms.txt +144 -91
- package/package.json +55 -19
- package/skills/washi/SKILL.md +107 -34
- package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
- package/dist/browser/highs-worker.js +0 -39
- package/dist/browser/highs.wasm +0 -0
- package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/lib/highs-browser-runtime.js +0 -2185
- package/dist/lib/highs-runtime.js +0 -2
- package/dist/lib/highs-worker.js +0 -39
- package/dist/lib/highs.wasm +0 -0
- package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
- package/docs/ja/getting-started/ai-agents.md +0 -280
- package/docs/zh/getting-started/ai-agents.md +0 -280
- /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
- /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
- /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Constraint Programming (CP) Modeling
|
|
2
|
+
|
|
3
|
+
WaSHI lets you write both Mathematical Optimization (LP / MIP / QP) and Constraint Programming (CP) models with the same TypeScript API.
|
|
4
|
+
Using the bundled **Pumpkin** solver (`{ solver: "pumpkin" }`, zero extra imports), you can model scheduling, resource limits, all-different rules, and table lookups directly without expanding them into large 0-1 matrices.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. When to Use CP (Pumpkin) vs. MIP (HiGHS / GLPK)
|
|
9
|
+
|
|
10
|
+
The two paradigms differ in how they represent decisions and prune the search space.
|
|
11
|
+
|
|
12
|
+
### Mixed-Integer Programming (`HiGHS` / `GLPK`)
|
|
13
|
+
|
|
14
|
+
MIP represents decisions with continuous and integer (including 0-1) variables, expresses rules as linear inequalities, and solves them with LP relaxation and branch-and-bound.
|
|
15
|
+
This excels at continuous flows, linear budgets, quadratic objectives, and LP dual analysis.
|
|
16
|
+
However, discretizing fine-grained timelines or expanding combinatorial structures into 0-1 variables can make the model grow huge.
|
|
17
|
+
|
|
18
|
+
### Constraint Programming (`Pumpkin`)
|
|
19
|
+
|
|
20
|
+
CP assigns each decision a finite integer domain and connects variables with **global constraints**—high-level predicates that express structured combinatorial rules across groups of variables.
|
|
21
|
+
During search, **domain propagation** automatically prunes impossible values from each variable's domain whenever variable domains or constraints tighten, keeping models compact.
|
|
22
|
+
|
|
23
|
+
The table below shows how common modeling patterns map between MIP and CP:
|
|
24
|
+
|
|
25
|
+
| Task / Pattern | MIP (`HiGHS` / `GLPK`) | CP (`Pumpkin`) |
|
|
26
|
+
| :--- | :--- | :--- |
|
|
27
|
+
| **Start times** | One 0-1 variable per task and time slot | One integer variable `start[i]` per task |
|
|
28
|
+
| **Non-overlapping tasks** | Pairwise ordering binaries + Big-M inequalities | `disjoint(tasks)` |
|
|
29
|
+
| **Shared worker / machine capacity** | One linear sum constraint per time step | `cumulative(tasks, capacity)` |
|
|
30
|
+
| **One-to-one assignment** | 2D 0-1 assignment matrix | `machine[i]` + `distinct(machine)` |
|
|
31
|
+
| **Value / cost lookup by choice** | Weighted sum over 0-1 selector variables | `at(costs, indexVar)` |
|
|
32
|
+
| **Best suited for** | Continuous flows, blending, quadratic objectives, dual analysis | Scheduling, resource limits, permutations, compatibility tables |
|
|
33
|
+
|
|
34
|
+
> [!TIP]
|
|
35
|
+
> Use `HiGHS` when your model requires `Continuous` variables, decimal coefficients, or quadratic objectives, or `Z3` for continuous logical rules.
|
|
36
|
+
> Try `Pumpkin` when your model uses bounded integers and Booleans for scheduling, routing, or combinatorial assignment.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 2. Scheduling Tasks & Shared Resources (`disjoint`, `cumulative`, `max`)
|
|
41
|
+
|
|
42
|
+
Discretizing a long timeline into 0-1 time-slot variables creates tens of thousands of MIP variables.
|
|
43
|
+
WaSHI's MIP converter rejects `cumulative` horizons above 5,000 steps or 25,000 slot variables and recommends `{ solver: "pumpkin" }`.
|
|
44
|
+
|
|
45
|
+
With Pumpkin, each task needs only **one integer variable** (`start[task]`), regardless of horizon granularity.
|
|
46
|
+
Three primitives cover most interval-scheduling models:
|
|
47
|
+
|
|
48
|
+
- **`disjoint(tasks)`**: Takes task objects `{ start, duration }` and forbids any two intervals `[start, start + duration)` from overlapping on a shared single machine.
|
|
49
|
+
- **`cumulative(tasks, capacity)`**: Takes task objects `{ start, duration, demand }` and enforces that total active resource demand never exceeds `capacity` at any moment.
|
|
50
|
+
- **`max(...)`**: Computes the **makespan**—the latest completion time across all tasks, $\max_i (\text{start}_i + \text{duration}_i)$—so you can minimize total schedule length.
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
import { Model, expr, disjoint, cumulative, max, minimize } from "@ohtaman/washi";
|
|
54
|
+
|
|
55
|
+
const m = new Model("IntervalSchedulingCP", { solver: "pumpkin" });
|
|
56
|
+
const tasks = ["prep", "mill", "drill", "coat"] as const;
|
|
57
|
+
const duration = { prep: 3, mill: 4, drill: 3, coat: 2 };
|
|
58
|
+
const workers = { prep: 1, mill: 1, drill: 1, coat: 2 };
|
|
59
|
+
const start = m.integer(tasks, { lb: 0, ub: 20, prefix: "start" });
|
|
60
|
+
|
|
61
|
+
// Precedence rules: prep -> (mill, drill) -> coat
|
|
62
|
+
m.constraint(expr`${start.prep} + ${duration.prep} <= ${start.mill}`, "mill_after_prep");
|
|
63
|
+
m.constraint(expr`${start.prep} + ${duration.prep} <= ${start.drill}`, "drill_after_prep");
|
|
64
|
+
m.constraint(expr`${start.mill} + ${duration.mill} <= ${start.coat}`, "coat_after_mill");
|
|
65
|
+
m.constraint(expr`${start.drill} + ${duration.drill} <= ${start.coat}`, "coat_after_drill");
|
|
66
|
+
|
|
67
|
+
// Single CNC machine shared between mill and drill
|
|
68
|
+
m.constraint(
|
|
69
|
+
disjoint([
|
|
70
|
+
{ start: start.mill, duration: duration.mill },
|
|
71
|
+
{ start: start.drill, duration: duration.drill },
|
|
72
|
+
]),
|
|
73
|
+
"single_cnc"
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
// At most 2 operators working at the same time
|
|
77
|
+
m.constraint(
|
|
78
|
+
cumulative(
|
|
79
|
+
tasks.map((t) => ({ start: start[t], duration: duration[t], demand: workers[t] })),
|
|
80
|
+
2
|
|
81
|
+
),
|
|
82
|
+
"operator_pool"
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
m.objective(minimize(max(tasks.map((t) => expr`${start[t]} + ${duration[t]}`))));
|
|
86
|
+
await m.solve();
|
|
87
|
+
console.log("Makespan:", m.objectiveValue);
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
See the full walkthrough in [Resource-Constrained Project Scheduling (RCPSP)](../examples/project-scheduling.md).
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## 3. Assignment, Compatibility Tables & Cost Lookup (`distinct`, `allowed`, `at`)
|
|
95
|
+
|
|
96
|
+
Instead of an $N \times M$ matrix of 0-1 assignment variables, give each job a single bounded integer variable `machine[job]` ranging from `0` to `M - 1`:
|
|
97
|
+
|
|
98
|
+
- **`distinct(machine)`**: Global all-different constraint forcing every job onto a distinct machine.
|
|
99
|
+
- **`allowed(vars, tuples)` / `not(allowed(vars, tuples))`**: Global table constraint permitting or forbidding explicit value tuples without Big-M inequalities.
|
|
100
|
+
- **`at(costs, indexVar)`**: Variable-indexed lookup returning `costs[indexVar]` directly inside an `expr` or objective.
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
import { Model, expr, distinct, allowed, not, minimize } from "@ohtaman/washi";
|
|
104
|
+
|
|
105
|
+
const m = new Model("MachineAssignmentCP", { solver: "pumpkin" });
|
|
106
|
+
const jobs = ["jobA", "jobB", "jobC"] as const;
|
|
107
|
+
const machine = m.integer(jobs, { lb: 0, ub: 2, prefix: "machine" });
|
|
108
|
+
|
|
109
|
+
const costA = [5, 10, 40];
|
|
110
|
+
const costB = [20, 15, 30];
|
|
111
|
+
const costC = [45, 30, 25];
|
|
112
|
+
|
|
113
|
+
// Each job runs on a separate machine (0, 1, or 2)
|
|
114
|
+
m.constraint(distinct(machine), "one_job_per_machine");
|
|
115
|
+
|
|
116
|
+
// Forbid placing Job A on Machine 0 while Job B is on Machine 1
|
|
117
|
+
m.constraint(not(allowed([machine.jobA, machine.jobB], [[0, 1]])), "interlock_pair");
|
|
118
|
+
|
|
119
|
+
// Look up each job's cost by its assigned machine index
|
|
120
|
+
m.objective(
|
|
121
|
+
minimize(
|
|
122
|
+
expr`at(${costA}, ${machine.jobA}) + at(${costB}, ${machine.jobB}) + at(${costC}, ${machine.jobC})`
|
|
123
|
+
)
|
|
124
|
+
);
|
|
125
|
+
await m.solve();
|
|
126
|
+
console.log("Total cost:", m.objectiveValue);
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## 4. Practical Tips for Pumpkin Models
|
|
132
|
+
|
|
133
|
+
### Keep Integer Bounds Finite and Tight
|
|
134
|
+
|
|
135
|
+
Pumpkin supports only finite integers within $[-(2^{30} - 1),\, 2^{30} - 1]$.
|
|
136
|
+
It rejects `Continuous` variables, non-integer coefficients or constants, and infinite bounds (`-Infinity` / `Infinity`).
|
|
137
|
+
Tighter `[lb, ub]` intervals shrink domains upfront and make domain propagation more effective.
|
|
138
|
+
See [Pumpkin Domain Preconditions](../solvers/pumpkin.md#domain-api-preconditions).
|
|
139
|
+
|
|
140
|
+
### Break Symmetry with Strict Ordering (`<`)
|
|
141
|
+
|
|
142
|
+
When picking $k$ distinct items into $k$ interchangeable slots (`slot[0]`, ..., `slot[k-1]`), every permutation of the same items has the same objective value.
|
|
143
|
+
Without symmetry breaking, the solver wastes time checking $k!$ equivalent orderings.
|
|
144
|
+
Adding `slot[0] < slot[1] < ...` enforces both uniqueness and a single canonical order:
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
148
|
+
|
|
149
|
+
const m = new Model("SymmetryBreakingCP", { solver: "pumpkin" });
|
|
150
|
+
const latencyMs = [600, 380, 420, 470, 550];
|
|
151
|
+
const slot = m.integer(3, { lb: 0, ub: 4, prefix: "slot" });
|
|
152
|
+
|
|
153
|
+
// Strict ascending order enforces uniqueness and removes 3! = 6 duplicate orderings
|
|
154
|
+
m.constraint([
|
|
155
|
+
expr`${slot[0]} < ${slot[1]}`,
|
|
156
|
+
expr`${slot[1]} < ${slot[2]}`,
|
|
157
|
+
]);
|
|
158
|
+
|
|
159
|
+
m.objective(
|
|
160
|
+
minimize(
|
|
161
|
+
expr`at(${latencyMs}, ${slot[0]}) + at(${latencyMs}, ${slot[1]}) + at(${latencyMs}, ${slot[2]})`
|
|
162
|
+
)
|
|
163
|
+
);
|
|
164
|
+
await m.solve();
|
|
165
|
+
console.log("Best 3 latencies total:", m.objectiveValue);
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### Warm Starts & Conflict Diagnosis
|
|
169
|
+
|
|
170
|
+
- **Warm starts (`initialValue`)**: Pass `{ initialValue: val }` to `m.integer()` or `m.binary()` to guide Pumpkin's initial value selection.
|
|
171
|
+
- **Conflict diagnosis (`m.check()`)**: If a CP model returns `"Infeasible"`, call `await m.check({ solver: "pumpkin" })` to pinpoint conflicting named constraints. See [Conflict Diagnosis (`unsatCore`)](./unsat-core.md).
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Constraints (`m.constraint` & `m.indicator`)
|
|
2
2
|
|
|
3
|
-
Constraints
|
|
4
|
-
In WaSHI,
|
|
3
|
+
Constraints define the rules that every valid solution must satisfy.
|
|
4
|
+
In WaSHI, linear arithmetic constraints, logical rules, and CP global constraints are all registered with `m.constraint()`:
|
|
5
5
|
|
|
6
6
|
```typescript
|
|
7
7
|
m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood_limit");
|
|
@@ -11,7 +11,7 @@ m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood_limit");
|
|
|
11
11
|
|
|
12
12
|
## Algebraic Linear Constraints (`expr`)
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
Use the `expr` tagged template literal to write linear equations and inequalities in standard algebraic notation:
|
|
15
15
|
|
|
16
16
|
```typescript
|
|
17
17
|
import { Model, expr } from "@ohtaman/washi";
|
|
@@ -33,12 +33,16 @@ m.constraint(expr`${x} + ${y} == 30`, "exact_quota");
|
|
|
33
33
|
`m.constraint()` returns the registered `Constraint` (or `BoolExpr` for logical formulas), or an array when passed a batch array.
|
|
34
34
|
|
|
35
35
|
### Supported Comparison Operators
|
|
36
|
-
|
|
37
|
-
-
|
|
38
|
-
-
|
|
36
|
+
|
|
37
|
+
- `<=`: Upper-bound inequality.
|
|
38
|
+
- `>=`: Lower-bound inequality.
|
|
39
|
+
- `==` or `=`: Exact equality.
|
|
40
|
+
- `<`, `>`, `!=`: Strict inequality and not-equal constraints for integer-valued expressions only (see [Discrete Comparisons](#discrete-comparisons)).
|
|
39
41
|
|
|
40
42
|
### Batch Registration
|
|
41
|
-
|
|
43
|
+
|
|
44
|
+
Pass an array of constraints to `m.constraint([...])` to register them atomically.
|
|
45
|
+
If any item in the array is invalid, none of them are added:
|
|
42
46
|
|
|
43
47
|
```typescript
|
|
44
48
|
m.constraint([expr`${x} <= 10`, expr`${y} <= 20`]);
|
|
@@ -55,15 +59,16 @@ m.constraint(expr`${x} + ${y} <= 100`, "budget_cap");
|
|
|
55
59
|
```
|
|
56
60
|
|
|
57
61
|
### Why Name Constraints?
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
62
|
+
|
|
63
|
+
1. **Model inspection (`m.toLpString()`)**: Exported CPLEX LP strings retain your constraint names so you can audit the generated formulation.
|
|
64
|
+
2. **Conflict diagnosis (`conflicts` / `unsatCore`)**: When constraints contradict each other, `m.check()` reports the conflicting constraint names.
|
|
65
|
+
3. **Direct lookup (`m.constraints.get()`)**: After solving, fetch any named constraint to read its `dual` or `slack` value.
|
|
61
66
|
|
|
62
67
|
---
|
|
63
68
|
|
|
64
|
-
##
|
|
69
|
+
## Constraints with Sums & Dot Products (`sum` & `dot`)
|
|
65
70
|
|
|
66
|
-
Use `sum(...)` and `dot(..., ...)` directly inside `expr` to express linear aggregations over arrays and dictionaries
|
|
71
|
+
Use `sum(...)` and `dot(..., ...)` directly inside `expr` to express linear aggregations over arrays and dictionaries:
|
|
67
72
|
|
|
68
73
|
```typescript
|
|
69
74
|
import { Model, expr } from "@ohtaman/washi";
|
|
@@ -82,9 +87,36 @@ m.constraint(expr`dot(${weights}, ${selected}) <= 25`, "capacity_limit");
|
|
|
82
87
|
|
|
83
88
|
---
|
|
84
89
|
|
|
90
|
+
## Dual Values, Shadow Prices & Lookups
|
|
91
|
+
|
|
92
|
+
For continuous Linear Programming (LP) models—or LP relaxations solved via `m.relax()`—on HiGHS, each linear constraint exposes two sensitivity properties (GLPK populates `dual` only and leaves `slack` as `null`):
|
|
93
|
+
|
|
94
|
+
- **`dual` (shadow price)**: The marginal signed change in the optimal objective value per unit increase in the constraint's right-hand side (while the optimal basis remains unchanged).
|
|
95
|
+
- **`slack`**: Defined as `rhs - lhs` at the optimal solution (`>= 0` for `<=` constraints, `<= 0` for `>=` constraints, and `0` when the constraint is tight).
|
|
96
|
+
|
|
97
|
+
Both properties have type `number | null`.
|
|
98
|
+
They are `null` before solving, when no optimal LP solution is found, on MIP models solved with `m.solve()`, and on CP, SMT, and logical constraints.
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
const woodConstraint = m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
|
|
102
|
+
|
|
103
|
+
await m.solve();
|
|
104
|
+
|
|
105
|
+
console.log("Shadow price (dual):", woodConstraint.dual);
|
|
106
|
+
console.log("Slack:", woodConstraint.slack);
|
|
107
|
+
console.log("Looked-up dual:", m.constraints.get("wood")?.dual); // number | null
|
|
108
|
+
console.log("Total constraints:", m.constraints.size);
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
85
113
|
## Conditional / Indicator Constraints (`m.indicator`)
|
|
86
114
|
|
|
87
|
-
|
|
115
|
+
Use `m.indicator()` when a linear constraint should only apply if a binary variable (`m.binary()`) equals `activeValue` (`1` by default, or `0`).
|
|
116
|
+
In MIP formulations, this conditional rule is encoded via the **Big-M method**.
|
|
117
|
+
For example, $a^\top x \le b + M(1 - y)$ enforces $a^\top x \le b$ when $y = 1$, and relaxes it with a large constant $M$ when $y = 0$.
|
|
118
|
+
|
|
119
|
+
The target constraint must be linear with `<=`, `>=`, or `==`—discrete `!=`, nonlinear atoms (`max`, `min`, `abs`, `at`), and referencing `binVar` inside the constrained expression are rejected:
|
|
88
120
|
|
|
89
121
|
```typescript
|
|
90
122
|
const useDiscount = m.binary("use_discount");
|
|
@@ -100,12 +132,18 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
|
|
|
100
132
|
|
|
101
133
|
### Safe Automatic Big-M Derivation & Bounds
|
|
102
134
|
|
|
103
|
-
When `options.M` is omitted, WaSHI
|
|
104
|
-
|
|
105
|
-
- For
|
|
106
|
-
- For
|
|
135
|
+
When `options.M` is omitted, WaSHI computes the smallest valid Big-M from finite variable bounds (`lb` and `ub`):
|
|
136
|
+
|
|
137
|
+
- For `<=` constraints, positive coefficients require finite `ub` and negative coefficients require finite `lb`.
|
|
138
|
+
- For `>=` constraints, positive coefficients require finite `lb` and negative coefficients require finite `ub`.
|
|
139
|
+
- For `==` constraints, WaSHI derives bounds for both directions separately, creating `name_le` and `name_ge`.
|
|
107
140
|
|
|
108
|
-
If any referenced variable lacks
|
|
141
|
+
If any referenced variable lacks a required finite bound, `m.indicator()` throws an error asking for finite bounds or an explicit `options.M`.
|
|
142
|
+
|
|
143
|
+
> [!NOTE]
|
|
144
|
+
> **How `m.indicator()` works across MIP, CP, and SMT solvers**: When `options.M` is omitted, `m.indicator()` returns an array of Big-M linear `Constraint` objects (`Constraint[]`) that also carry a native-indicator annotation.
|
|
145
|
+
> HiGHS, GLPK, and `m.toLpString()` use the Big-M inequalities directly, while Pumpkin and Z3 read the annotation to solve the implication natively without Big-M numerical issues or weak relaxations.
|
|
146
|
+
> If you later mutate any returned `Constraint` object, WaSHI clears that annotation so your direct edits take effect across every solver.
|
|
109
147
|
|
|
110
148
|
### Explicit `M` Override
|
|
111
149
|
|
|
@@ -119,13 +157,20 @@ m.indicator(useDiscount, expr`${cartTotal} >= 100`, {
|
|
|
119
157
|
```
|
|
120
158
|
|
|
121
159
|
> [!TIP]
|
|
122
|
-
> **Prefer Finite Variable Bounds Over Arbitrary Large `M`**:
|
|
160
|
+
> **Prefer Finite Variable Bounds Over Arbitrary Large `M`**: Too small an $M$ can cut off valid solutions, while an excessively large $M$ (such as `1e9`) weakens LP relaxations and harms MIP numerical stability.
|
|
161
|
+
> Setting realistic `lb` and `ub` bounds lets WaSHI compute the tightest safe Big-M automatically.
|
|
123
162
|
|
|
124
163
|
---
|
|
125
164
|
|
|
126
165
|
## Propositional Logic & SMT Constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`)
|
|
127
166
|
|
|
128
|
-
WaSHI provides first-class logical operators
|
|
167
|
+
WaSHI provides first-class logical operators that combine `BoolVar` variables from `m.bool()` with linear `Constraint` objects.
|
|
168
|
+
Pumpkin (`{ solver: "pumpkin" }`, bundled with zero extra imports) and Z3 (`import "@ohtaman/washi/solvers/z3"`) solve these formulas natively, while HiGHS and GLPK automatically linearize them into 0-1 MIP constraints.
|
|
169
|
+
|
|
170
|
+
> [!IMPORTANT]
|
|
171
|
+
> **Solver Preconditions**:
|
|
172
|
+
> - **Pumpkin**: Every numeric variable must be `Integer` or `Binary` with finite `lb` and `ub`.
|
|
173
|
+
> - **Z3**: Requires the optional dependency `z3-solver` (`npm install z3-solver`). In browsers, Z3 also requires `COOP`/`COEP` response headers for `SharedArrayBuffer`.
|
|
129
174
|
|
|
130
175
|
```typescript
|
|
131
176
|
import { Model, expr, and, or, not, implies, xor } from "@ohtaman/washi";
|
|
@@ -149,35 +194,72 @@ m.constraint(
|
|
|
149
194
|
m.constraint(and(or(isAdmin, hasMfa), not(xor(isAdmin, hasMfa))), "policy");
|
|
150
195
|
```
|
|
151
196
|
|
|
197
|
+
All registered constraints (including auto-named ones) are stored in `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`) and can be looked up with `m.constraints.get(name)`.
|
|
198
|
+
Logical and CP entries use the shape `{ kind: "logical", name, expr, dual: null, slack: null }`.
|
|
199
|
+
|
|
152
200
|
### Choosing Between `m.indicator()` and `implies()`
|
|
153
201
|
|
|
154
202
|
| Feature | `m.indicator(binVar, constraint, opts)` | `implies(a, b)` / `a.implies(b)` |
|
|
155
203
|
| :--- | :--- | :--- |
|
|
156
204
|
| **Trigger variable** | Numeric `Binary` variable (`m.binary()`) | `BoolVar` (`m.bool()`), `BoolOp`, or `Constraint` |
|
|
157
205
|
| **Consequent** | Linear `Constraint` (`<=`, `>=`, `==`) | `BoolVar`, `BoolOp`, or linear `Constraint` |
|
|
158
|
-
| **Target Solvers** |
|
|
159
|
-
| **Primary Use Case** | MIP optimization models
|
|
206
|
+
| **Target Solvers** | All solvers (Big-M on HiGHS/GLPK; native on Pumpkin/Z3 when `M` is omitted) | All solvers (automatic 0-1 MIP on HiGHS/GLPK; native on Pumpkin/Z3) |
|
|
207
|
+
| **Primary Use Case** | MIP optimization models using numeric binary variables | Logical rule systems and SMT feasibility checks |
|
|
160
208
|
|
|
161
209
|
> [!NOTE]
|
|
162
|
-
> **
|
|
210
|
+
> **Negating Comparison Constraints (arguments of `not` or `xor`, or the condition of `implies`)**:
|
|
211
|
+
> - **Integer expressions**: Negations such as $\neg(x \le 5)$ are converted automatically to $x \ge 6$ on HiGHS and GLPK, and handled natively on Pumpkin and Z3.
|
|
212
|
+
> - **`Continuous` or decimal expressions**: HiGHS and GLPK reject negated continuous comparisons because strict `<` and `>` cannot form closed linear inequalities. Use `{ solver: "z3" }` or model the condition with `m.bool()`.
|
|
163
213
|
|
|
164
214
|
---
|
|
165
215
|
|
|
166
|
-
##
|
|
216
|
+
## Discrete Comparisons (`!=`, `<`, `>`)
|
|
167
217
|
|
|
168
|
-
|
|
218
|
+
WaSHI supports `!=`, `<`, and `>` inside `expr` as well as via `.ne()`, `.lt()`, and `.gt()` on `Var`, `LinExpr`, and `QuadExpr`.
|
|
219
|
+
These operators apply strictly to **integer-valued expressions**—expressions built from `Integer` or `Binary` variables with safe-integer coefficients and constants:
|
|
169
220
|
|
|
170
221
|
```typescript
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
222
|
+
const rankA = m.integer("rankA", { lb: 1, ub: 4 });
|
|
223
|
+
const rankB = m.integer("rankB", { lb: 1, ub: 4 });
|
|
224
|
+
const roomA = m.integer("roomA", { lb: 1, ub: 3 });
|
|
225
|
+
const roomB = m.integer("roomB", { lb: 1, ub: 3 });
|
|
174
226
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
console.log("Total linear constraints:", m.numConstrs);
|
|
227
|
+
m.constraint(expr`${rankA} < ${rankB}`, "strict_order"); // lowered via rankA - rankB <= -1
|
|
228
|
+
m.constraint(expr`${roomA} != ${roomB}`, "diff_room"); // native on Pumpkin/Z3, single-binary MIP on HiGHS/GLPK
|
|
178
229
|
```
|
|
179
230
|
|
|
180
|
-
|
|
231
|
+
Expressions containing `Continuous` variables or decimal constants are rejected immediately for `!=`, `<`, and `>`.
|
|
232
|
+
Over real numbers, strict inequalities define open sets—for example, maximizing $x$ subject to $x < 5$ has no optimal real solution.
|
|
233
|
+
LP and MIP solvers therefore require closed inequalities ($\le$, $\ge$, $=$) so an optimum is well-defined.
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## CP Global Constraints (`distinct`, `disjoint`, `cumulative`, `allowed`)
|
|
238
|
+
|
|
239
|
+
WaSHI provides backend-agnostic Constraint Programming **global constraints**—higher-level predicates over groups of variables that return composable `BoolExpr` objects.
|
|
240
|
+
They combine freely with `and`, `or`, `not`, `implies`, and `xor`.
|
|
241
|
+
For interval scheduling, symmetry breaking, and Pumpkin modeling patterns, see the [Constraint Programming (CP) Modeling Guide](./constraint-programming.md).
|
|
242
|
+
|
|
243
|
+
| Predicate | Meaning | HiGHS / GLPK | Pumpkin | Z3 |
|
|
244
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
245
|
+
| `distinct(...args)` | All values are pairwise different (`!=`) | Pairwise `!=` MIP | Native `all_different` | Native `Distinct` |
|
|
246
|
+
| `disjoint(tasks)` | Tasks `[start, start + duration)` do not overlap | Pairwise ordering + Big-M | Native non-overlap | Pairwise `Or` |
|
|
247
|
+
| `cumulative(tasks, capacity)` | Total demand $\le$ `capacity` at every moment | Time-indexed MIP (errors above 5,000 steps / 25,000 vars) | Native `cumulative` | Event-point load |
|
|
248
|
+
| `allowed(vars, tuples)` | Values match a row in `tuples` (`not(allowed(...))` forbids them) | Tuple selector binaries | Native table | Tuple `Or` / `And` |
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
import { Model, expr, distinct, disjoint, cumulative, allowed, not, minimize } from "@ohtaman/washi";
|
|
252
|
+
|
|
253
|
+
const m = new Model("ScheduleAndAssign");
|
|
254
|
+
const s = m.integer(2, { lb: 0, ub: 10, prefix: "s" });
|
|
255
|
+
const room = m.integer(2, { lb: 1, ub: 2, prefix: "room" });
|
|
256
|
+
|
|
257
|
+
m.constraint(distinct(room), "unique_rooms");
|
|
258
|
+
m.constraint(disjoint([{ start: s[0], duration: 4 }, { start: s[1], duration: 3 }]), "machine_1");
|
|
259
|
+
m.constraint(not(allowed([room[0], room[1]], [[1, 2]])), "forbid_1_2");
|
|
260
|
+
m.constraint(cumulative([{ start: s[0], duration: 4, demand: 1 }, { start: s[1], duration: 3, demand: 1 }], 2), "workers");
|
|
261
|
+
m.objective(minimize(expr`${s[0]} + ${s[1]}`));
|
|
262
|
+
```
|
|
181
263
|
|
|
182
264
|
> [!TIP]
|
|
183
|
-
> For
|
|
265
|
+
> For **soft constraints with slack variables** and **symmetry breaking**, see [Formulation Patterns & Optimization Tips](./formulation-tips.md#_3-constraint-design-numerical-conditioning).
|