@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.
Files changed (162) hide show
  1. package/README.ja.md +60 -23
  2. package/README.md +59 -22
  3. package/README.zh-CN.md +62 -25
  4. package/THIRD_PARTY_LICENSES.md +34 -1
  5. package/dist/browser/solvers/glpk.js +289 -238
  6. package/dist/browser/solvers/glpk.min.js +1 -1
  7. package/dist/browser/solvers/highs-__vite-browser-external-Dn-83hnF.js +7 -0
  8. package/dist/browser/solvers/highs-browser-runtime-0Bgq5ksG.js +2021 -0
  9. package/dist/browser/{loader-DewlSho8.js → solvers/highs-loader-BLY3wzDH.js} +190 -149
  10. package/dist/browser/solvers/highs-worker.js +54 -0
  11. package/dist/browser/solvers/highs.js +1414 -0
  12. package/dist/browser/solvers/highs.wasm +0 -0
  13. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  14. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  15. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  16. package/dist/browser/solvers/pumpkin.js +1777 -0
  17. package/dist/browser/solvers/pumpkin.wasm +0 -0
  18. package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
  19. package/dist/browser/solvers/z3.js +1600 -1335
  20. package/dist/browser/solvers/z3.min.js +2 -2
  21. package/dist/browser/washi.js +3313 -1699
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/solvers/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/solvers/glpk.js +174 -132
  25. package/dist/lib/solvers/highs-browser-runtime.js +2413 -0
  26. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  27. package/dist/lib/solvers/highs-runtime.js +16 -0
  28. package/dist/lib/solvers/highs-worker.js +54 -0
  29. package/dist/lib/solvers/highs.js +410 -0
  30. package/dist/lib/solvers/highs.wasm +0 -0
  31. package/dist/lib/{loader-BZUQNvh4.js → solvers/loader-CDpPXN_F.js} +138 -116
  32. package/dist/lib/solvers/loader-Ow74Fa1B.js +311 -0
  33. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  34. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  35. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  36. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  37. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  38. package/dist/lib/solvers/pumpkin.js +868 -0
  39. package/dist/lib/solvers/pumpkin.wasm +0 -0
  40. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  41. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  42. package/dist/lib/solvers/rolldown-runtime-DtPi1Y-2.js +13 -0
  43. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  44. package/dist/lib/solvers/z3.js +489 -307
  45. package/dist/lib/washi.js +3905 -1410
  46. package/dist/types/decomposition/benders.d.ts.map +1 -1
  47. package/dist/types/index.d.ts +4 -5
  48. package/dist/types/index.d.ts.map +1 -1
  49. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  50. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  51. package/dist/types/modeler/constraint.d.ts +40 -4
  52. package/dist/types/modeler/constraint.d.ts.map +1 -1
  53. package/dist/types/modeler/expression.d.ts +129 -2
  54. package/dist/types/modeler/expression.d.ts.map +1 -1
  55. package/dist/types/modeler/index.d.ts +4 -6
  56. package/dist/types/modeler/index.d.ts.map +1 -1
  57. package/dist/types/modeler/linearizer.d.ts +11 -2
  58. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  59. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  60. package/dist/types/modeler/model.d.ts +86 -126
  61. package/dist/types/modeler/model.d.ts.map +1 -1
  62. package/dist/types/modeler/parser.d.ts.map +1 -1
  63. package/dist/types/modeler/quad-expr.d.ts +8 -2
  64. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  65. package/dist/types/modeler/solution-validator.d.ts +12 -12
  66. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  67. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  68. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  69. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  70. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  72. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  73. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  74. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  75. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  76. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  77. package/dist/types/modeler/solvers/index.d.ts +2 -1
  78. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  79. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  80. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  81. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  82. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  83. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  84. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  85. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  86. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  87. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  88. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  89. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  90. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  91. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  92. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  93. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  94. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  95. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  96. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  97. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  98. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  99. package/dist/types/modeler/solvers/types.d.ts +7 -9
  100. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  101. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  102. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  103. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  104. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  105. package/dist/types/modeler/types.d.ts +12 -15
  106. package/dist/types/modeler/types.d.ts.map +1 -1
  107. package/dist/types/modeler/validation.d.ts +26 -2
  108. package/dist/types/modeler/validation.d.ts.map +1 -1
  109. package/dist/types/modeler/variable.d.ts +9 -5
  110. package/dist/types/modeler/variable.d.ts.map +1 -1
  111. package/docs/examples/diet-sensitivity.md +33 -14
  112. package/docs/examples/ecommerce-coupons.md +17 -9
  113. package/docs/examples/index.md +36 -27
  114. package/docs/examples/knapsack.md +11 -5
  115. package/docs/examples/portfolio-qp.md +21 -8
  116. package/docs/examples/production.md +10 -5
  117. package/docs/examples/project-scheduling.md +119 -0
  118. package/docs/examples/shift-scheduling.md +29 -18
  119. package/docs/examples/smt-security.md +27 -11
  120. package/docs/examples/transportation.md +23 -13
  121. package/docs/examples/traveling-salesperson.md +34 -22
  122. package/docs/examples/unsat-core.md +27 -14
  123. package/docs/examples/vehicle-routing.md +74 -28
  124. package/docs/getting-started/ai-agents.md +190 -82
  125. package/docs/getting-started/coding-agents.md +177 -0
  126. package/docs/getting-started/cross-origin.md +27 -14
  127. package/docs/getting-started/index.md +49 -43
  128. package/docs/getting-started/runtimes.md +94 -40
  129. package/docs/guide/constraint-programming.md +171 -0
  130. package/docs/guide/constraints.md +115 -33
  131. package/docs/guide/decomposition.md +118 -88
  132. package/docs/guide/expressions.md +106 -43
  133. package/docs/guide/formulation-tips.md +47 -28
  134. package/docs/guide/objectives.md +102 -75
  135. package/docs/guide/unsat-core.md +62 -50
  136. package/docs/guide/variables.md +81 -35
  137. package/docs/solvers/custom-solver.md +163 -122
  138. package/docs/solvers/glpk.md +58 -17
  139. package/docs/solvers/highs.md +124 -57
  140. package/docs/solvers/index.md +33 -20
  141. package/docs/solvers/pumpkin.md +171 -0
  142. package/docs/solvers/z3.md +63 -25
  143. package/llms-full.txt +2232 -932
  144. package/llms.txt +144 -91
  145. package/package.json +55 -19
  146. package/skills/washi/SKILL.md +107 -34
  147. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  148. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  149. package/dist/browser/highs-worker.js +0 -39
  150. package/dist/browser/highs.wasm +0 -0
  151. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  152. package/dist/lib/highs-browser-runtime.js +0 -2185
  153. package/dist/lib/highs-runtime.js +0 -2
  154. package/dist/lib/highs-worker.js +0 -39
  155. package/dist/lib/highs.wasm +0 -0
  156. package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
  157. package/docs/ja/getting-started/ai-agents.md +0 -280
  158. package/docs/zh/getting-started/ai-agents.md +0 -280
  159. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  160. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  161. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  162. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
@@ -1,8 +1,8 @@
1
1
  # WaSHI Custom Solver Developer Guide
2
2
 
3
- This guide describes how to build, test, and distribute custom solver plugins for **WaSHI** (`@ohtaman/washi`).
3
+ This guide explains how to build, test, and distribute custom solver plugins for **WaSHI** (`@ohtaman/washi`).
4
4
 
5
- WaSHI features a pluggable, decoupled solver architecture. Core `@ohtaman/washi` bundles only the zero-config HiGHS WASM engine and a Mock solver. Any third-party solver—whether implemented in WebAssembly, native C++, a Web Worker, or an external cloud REST/RPC backend—can be registered and used through the unified `Model` API.
5
+ Core `@ohtaman/washi` bundles and auto-registers **HiGHS** (default, `@ohtaman/washi/solvers/highs`), **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`), and `MockSolver`, while optional plugins (`@ohtaman/washi/solvers/glpk`, `@ohtaman/washi/solvers/z3`) register when imported. You can register any other backend—WebAssembly, native C++, Web Worker, or cloud REST/RPC—and use it through the same `Model` API.
6
6
 
7
7
  ---
8
8
 
@@ -11,7 +11,8 @@ WaSHI features a pluggable, decoupled solver architecture. Core `@ohtaman/washi`
11
11
  ```mermaid
12
12
  graph TD
13
13
  A[WaSHI Model] --> B[Solver Registry Map Symbol.for]
14
- B --> C[HiGHS WASM Engine Core]
14
+ B --> C[HiGHS WASM Bundled Default @ohtaman/washi/solvers/highs]
15
+ B --> H[Pumpkin WASM Bundled @ohtaman/washi/solvers/pumpkin]
15
16
  B --> D[Mock Solver Core]
16
17
  B --> E[GLPK Plugin @ohtaman/washi/solvers/glpk]
17
18
  B --> F[Z3 SMT Plugin @ohtaman/washi/solvers/z3]
@@ -19,15 +20,16 @@ graph TD
19
20
  ```
20
21
 
21
22
  ### Key Architectural Characteristics
22
- 1. **Unified Global Registry**: The solver registry is backed by `Symbol.for("washi.solverRegistry")` on `globalThis`. This ensures that even across different ESM chunks, dynamic imports, or `<script>` tags, every bundle accesses the identical solver map.
23
- 2. **Behavioral Symmetry**: Node.js and browser environments share identical error messages, solver naming, and capability handling.
24
- 3. **Decoupled Bundling**: Core WaSHI does not import optional or custom plugins. A plugin only registers itself when explicitly imported.
23
+
24
+ - **Unified global registry**: Stored under `Symbol.for("washi.solverRegistry")` on `globalThis`, so separate ESM chunks, dynamic imports, and `<script>` tags share one solver map.
25
+ - **Cross-runtime symmetry**: Node.js and browser builds share identical solver naming, capability checks, and error messages.
26
+ - **Decoupled bundling**: Core WaSHI never imports optional or custom plugins; each plugin registers itself only when imported.
25
27
 
26
28
  ---
27
29
 
28
30
  ## 2. API Contracts & TypeScript Interfaces
29
31
 
30
- All custom solvers must implement the `Solver` interface defined in `@ohtaman/washi`:
32
+ Every custom solver implements the `Solver` interface exported from `@ohtaman/washi`:
31
33
 
32
34
  ```typescript
33
35
  import {
@@ -56,20 +58,20 @@ import {
56
58
 
57
59
  ```typescript
58
60
  export interface Solver {
59
- /** Unique human-readable name of the solver (e.g. "GLPK", "AcmeCloudSolver") */
61
+ /** Identifier name of the solver engine (e.g. "GLPK", "AcmeCloudSolver") */
60
62
  readonly name: string;
61
63
 
62
- /** Solver version string (e.g. "1.2.0") */
64
+ /** Version string of the solver (e.g. "1.2.0") */
63
65
  readonly version?: string;
64
66
 
65
- /** Capability flags declaring which problem classes the solver supports */
67
+ /** Feature capabilities of this solver */
66
68
  readonly capabilities?: SolverCapabilities;
67
69
 
70
+ /** Default options configured on this solver instance */
71
+ readonly options?: SolverOptions;
72
+
68
73
  /**
69
- * Main solve method for LP, MIP, QP, and SMT optimization models.
70
- *
71
- * @param modelData Typed in-memory model structure (variables, constraints, objective, sense, boolVars, logicalConstraints)
72
- * @param options Runtime execution options (timeLimit, mipGap, verbose, signal, onProgress, etc.)
74
+ * Solve a mathematical programming model (LP, MIP, QP, CP, or SMT).
73
75
  */
74
76
  solve(
75
77
  modelData: SolveModelData,
@@ -77,10 +79,7 @@ export interface Solver {
77
79
  ): Promise<SolverResult>;
78
80
 
79
81
  /**
80
- * Optional check method for Pure SAT / SMT or feasibility checking without an objective.
81
- *
82
- * @param modelData Objective-free in-memory model structure (variables, boolVars, constraints, logicalConstraints)
83
- * @param options Runtime execution options
82
+ * Optional objective-free satisfiability / feasibility check (SAT / SMT / CP).
84
83
  */
85
84
  check?(
86
85
  modelData: CheckModelData,
@@ -91,173 +90,189 @@ export interface Solver {
91
90
 
92
91
  ### `CheckModelData` & `SolveModelData`
93
92
 
94
- `Model.solve()` and `Model.check()` pass the structured model directly to your adapter without serializing an LP string upfront:
93
+ `Model.solve()` and `Model.check()` pass structured model snapshots directly to your adapter without serializing a CPLEX LP format string upfront:
95
94
 
96
95
  ```typescript
97
96
  export interface CheckModelData {
98
- /** Model name */
99
97
  name?: string;
100
- /** Decision variables registered in the model */
101
98
  variables: Var[];
102
- /** Propositional Boolean variables registered in the model */
103
99
  boolVars?: BoolVar[];
104
- /** Linear arithmetic constraints registered in the model */
105
100
  constraints: Constraint[];
106
- /** Logical / SMT constraints registered in the model */
107
101
  logicalConstraints?: LogicalConstraintItem[];
108
102
  }
109
103
 
110
104
  export interface SolveModelData extends CheckModelData {
111
- /** Optimization direction ("Minimize" | "Maximize") */
112
105
  sense: OptimizationSense;
113
- /** Linear or quadratic objective expression */
114
106
  objective: LinExpr | QuadExpr;
115
107
  }
116
108
  ```
117
109
 
118
110
  ### `SolverCapabilities`
119
111
 
120
- Custom solvers declare their supported features using `capabilities`. Before dispatching `solve()` or `check()`, `Model` validates:
121
- - `supportsQP === false` when the objective contains quadratic terms (`QuadExpr`),
122
- - when the model contains logical constraints (`m.logicalConstraints`) and the solver does not support SMT (`supportsSMT !== true`), `Model` automatically linearizes them into equivalent 0-1 MIP binary variables and linear constraints via `linearizeModelForMip`, and
123
- - `supportsWarmStart !== true` when any variable has a primal `initialValue` set.
112
+ Declare supported features on `capabilities`. Before calling `solve()` or `check()`, `Model` checks these flags:
113
+
114
+ - **Quadratic objectives (`QuadExpr`)**: Rejected when the model has a quadratic objective and `supportsQP === false`.
115
+ - **Warm starts (`initialValue`)**: Rejected when any variable sets `initialValue` and `supportsWarmStart !== true`.
116
+ - **Logical constraints**: Passed natively in `modelData.logicalConstraints` when `supportsLogicalConstraints === true` or `supportsSMT === true`.
117
+ - **Automatic MIP linearization on `solve()`**: When neither logical flag is `true`, `Model` linearizes `logicalConstraints`, `boolVars`, and nonlinear/CP expressions into equivalent binary variables and linear constraints before calling `solve()`.
118
+ - **`check()` fallback**: When a solver omits `check()`, `Model.check()` falls back to solving an elastic-slack feasibility problem via `solve()` (returning violated constraint names in `conflicts`, with `unsatCore: undefined`).
124
119
 
125
120
  ```typescript
126
121
  export interface SolverCapabilities {
127
- /** Supports mixed-integer programming (integer/binary variables) */
122
+ /** Supports Mixed-Integer Programming (integer and binary variables) */
128
123
  supportsMIP?: boolean;
129
124
 
130
- /** Supports quadratic objectives (QP: x^T Q x + c^T x) */
125
+ /** Supports Quadratic Programming objectives (QP) */
131
126
  supportsQP?: boolean;
132
127
 
133
- /** Supports second-order cone or quadratic constraints */
128
+ /** Supports quadratic constraints (QCQP / SOCP) */
134
129
  supportsQCQP?: boolean;
135
130
 
136
- /** Supports satisfiability modulo theories / boolean logic constraints */
131
+ /** Supports Satisfiability Modulo Theories (SMT) and logical constraints */
137
132
  supportsSMT?: boolean;
138
133
 
139
- /** Supports extracting an unsatisfiable core (conflicting constraint subset) */
134
+ /** Supports native boolean/propositional logical constraints without SMT continuous theories */
135
+ supportsLogicalConstraints?: boolean;
136
+
137
+ /** Supports extracting an unsatisfiable core (conflicting constraint subset; minimality is not guaranteed) */
140
138
  supportsUnsatCore?: boolean;
141
139
 
142
- /** Supports primal initial values / MIP warm starts (Var.initialValue) */
140
+ /** Supports primal initial values / warm-start hints (Var.initialValue) */
143
141
  supportsWarmStart?: boolean;
144
142
  }
145
143
  ```
146
144
 
147
145
  ### `SolverOptions` & `SolveProgressEvent`
148
146
 
149
- Runtime options passed to `solve` and `check` include cancellation and progress hooks (note that the routing `solver` field from `SolveOptions` is stripped before options are passed to your adapter):
147
+ Runtime options passed to `solve()` and `check()` follow `SolverOptions`. Note that `Model` strips the routing `solver` field before forwarding options to your adapter.
150
148
 
151
149
  ```typescript
152
150
  export interface SolverOptions {
153
- /** Time limit in seconds */
151
+ /** Maximum solve time limit in seconds */
154
152
  timeLimit?: number;
155
153
 
156
- /** Relative MIP optimality gap tolerance */
157
- mipGap?: number;
154
+ /** Presolve mode */
155
+ presolve?: "on" | "off" | "choose";
156
+
157
+ /** Relative MIP gap tolerance (e.g. 0.01 for 1%) */
158
+ relativeGap?: number;
159
+
160
+ /** Absolute MIP gap tolerance */
161
+ absoluteGap?: number;
158
162
 
159
- /** Enable solver console logging */
163
+ /** Number of parallel threads */
164
+ threads?: number;
165
+
166
+ /** Enable verbose solver logging */
160
167
  verbose?: boolean;
161
168
 
162
- /** Cooperative cancellation signal; when aborted, return terminationStatus: "Interrupted" */
169
+ /** Solve the continuous LP relaxation by relaxing integer and binary variables */
170
+ relax?: boolean;
171
+
172
+ /** Use Web Worker for non-blocking browser execution */
173
+ useWorker?: boolean;
174
+
175
+ /** AbortSignal to cancel an in-flight solve */
163
176
  signal?: AbortSignal;
164
177
 
165
- /** Progress callback invoked with normalized SolveProgressEvent snapshots */
178
+ /** Callback invoked with normalized SolveProgressEvent metrics */
166
179
  onProgress?: (progress: SolveProgressEvent) => void;
167
180
 
168
181
  /** Additional solver-specific options */
169
182
  [key: string]: any;
170
183
  }
184
+
185
+ export interface SolveProgressEvent {
186
+ /** Elapsed solver time in seconds */
187
+ elapsedTime: number;
188
+ /** Alias for elapsedTime: elapsed solver time in seconds */
189
+ elapsedSeconds?: number;
190
+ /** Current solver phase when known */
191
+ phase?: "simplex" | "ipm" | "mip";
192
+ /** Best feasible incumbent objective value when available */
193
+ objectiveValue?: number;
194
+ /** Best proven dual / objective bound when available */
195
+ objectiveBound?: number;
196
+ /** Relative MIP optimality gap when available */
197
+ relativeGap?: number;
198
+ /** Absolute MIP optimality gap |objectiveValue - objectiveBound| when available */
199
+ absoluteGap?: number;
200
+ /** Explored MIP branch-and-bound node count when available */
201
+ nodes?: number;
202
+ /** Solver iteration count (simplex, IPM, or MIP LP iterations) when available */
203
+ iterations?: number;
204
+ /** Optional raw progress message from the solver */
205
+ message?: string;
206
+ }
171
207
  ```
172
208
 
173
- ### Optional LP Serialization & Symbol-Mapping Helpers
209
+ ### Direct Model Data vs. LP Helpers
210
+
211
+ Choose how your adapter reads `modelData` based on your backend's input format:
174
212
 
175
- Solvers that consume structured JS/WASM data (such as `GLPKSolver` and `Z3Solver`) work directly with `SolveModelData` / `CheckModelData`.
176
- If your adapter targets a backend that requires CPLEX/HiGHS LP text or restricted identifier syntax, WaSHI exports opt-in helpers:
213
+ - **Use `SolveModelData` / `CheckModelData` directly** when your backend accepts structured JS or WebAssembly objects (as `PumpkinSolver`, `GLPKSolver`, and `Z3Solver` do).
214
+ - **Use WaSHI's opt-in LP helpers** when your backend expects CPLEX/HiGHS LP text or restricted ASCII identifiers:
177
215
 
178
- - `generateLpString(modelData): LpExportResult` — serializes `modelData` into a CPLEX LP format string (`lpString`) along with collision-safe symbol lookup maps (`nameToVar`, `nameToConstraint`).
179
- - `buildLpSymbolMaps(modelData): LpSymbolMaps` — builds collision-safe sanitized symbol maps (`nameToVar`, `varToName`, `nameToConstraint`, `constraintToName`) without serializing an LP string.
180
- - `isLpExportResult(value): value is LpExportResult` — runtime type guard for `LpExportResult` (useful when supporting legacy 3-argument `solve(modelData, lpResult, options)` overloads).
181
- - `sanitizeIdentifier(raw, fallbackPrefix = "x", id = 0)` — sanitizes an arbitrary display name into a valid LP identifier.
216
+ | Helper | Purpose |
217
+ | :--- | :--- |
218
+ | `generateLpString(modelData, { relax }?)` | Serializes `modelData` into a CPLEX LP string (`lpString`) with collision-safe `nameToVar` and `nameToConstraint` maps; pass `{ relax: true }` for a continuous LP relaxation. Omits `modelData.objective.constant`, so adapters must add it back to `objectiveValue` and `objectiveBound`. |
219
+ | `buildLpSymbolMaps(modelData)` | Builds collision-safe sanitized symbol maps (`nameToVar`, `varToName`, `nameToConstraint`, `constraintToName`) without serializing an LP string. |
220
+ | `isLpExportResult(value)` | Runtime type guard for `LpExportResult` (useful for legacy 3-argument `solve(modelData, lpResult, options)` overloads). |
221
+ | `sanitizeIdentifier(raw, fallbackPrefix = "x", id = 0)` | Converts an arbitrary variable or constraint name into a valid LP identifier. |
182
222
 
183
223
  ```typescript
184
224
  export interface LpExportResult {
185
- /** Standard CPLEX/HiGHS LP formatted string */
186
225
  lpString: string;
187
-
188
- /** Map translating sanitized LP variable identifiers back to WaSHI Var objects */
189
226
  nameToVar: Map<string, Var>;
190
-
191
- /** Map translating sanitized LP constraint identifiers back to WaSHI Constraint objects */
192
227
  nameToConstraint: Map<string, Constraint>;
193
228
  }
194
229
  ```
195
230
 
196
- ### `SolverResult` Normalization & Identity Decoding
231
+ ### `SolverResult` & `SolverCheckResult` Normalization
197
232
 
198
- The `solve` method must return normalized results keyed by the model's canonical variable/constraint names (`v.name`, `bv.name`, `c.name`). Adapters that use `generateLpString(modelData)` or `buildLpSymbolMaps(modelData)` for an LP backend must translate sanitized LP identifiers back to canonical model names using `nameToVar` and `nameToConstraint`:
233
+ `solve()` must key returned `values`, `boolValues`, `reducedCosts`, `duals`, and `slacks` by the model's canonical names (`v.name`, `bv.name`, `c.name`). Likewise, `check()` keys `values`, `unsatCore`, and `conflicts` by canonical names (`v.name`, `bv.name`, `c.name`, `lc.name`). When using LP helpers, decode sanitized LP identifiers back via `nameToVar` and `nameToConstraint`.
199
234
 
200
235
  ```typescript
201
236
  export interface SolverResult {
202
- /** Standardized status string */
203
237
  status: SolverStatus;
204
-
205
- /** Exact termination reason independent of whether a feasible incumbent is available (defaults to status) */
206
238
  terminationStatus?: TerminationStatus;
207
-
208
- /** Whether a feasible primal solution / incumbent is available (inferred from status/values if omitted) */
209
239
  hasPrimalSolution?: boolean;
210
-
211
- /** Optimal or best objective value (null if no primal solution is available) */
212
240
  objectiveValue: number | null;
213
-
214
- /** Best proven dual/objective bound when provided by the solver */
215
241
  objectiveBound?: number;
216
-
217
- /** Relative MIP optimality gap when provided by the solver */
218
- relGap?: number;
219
-
220
- /** Alias for relGap: relative MIP optimality gap when provided by the solver */
221
- mipGap?: number;
222
-
223
- /** Absolute MIP optimality gap |objectiveValue - objectiveBound| (computed automatically when both are finite) */
224
- absGap?: number;
225
-
226
- /** Variable primal values keyed by canonical variable name (non-finite values are ignored) */
242
+ relativeGap?: number;
243
+ absoluteGap?: number;
227
244
  values: Record<string, number>;
228
-
229
- /** Propositional Boolean variable assignments keyed by BoolVar name (optional, SMT/SAT) */
230
245
  boolValues?: Record<string, boolean>;
231
-
232
- /** Variable reduced costs (optional, LP only) */
233
246
  reducedCosts?: Record<string, number>;
234
-
235
- /** Constraint dual values / shadow prices (optional, LP only) */
236
247
  duals?: Record<string, number>;
237
-
238
- /** Constraint slack values (optional) */
239
248
  slacks?: Record<string, number>;
240
-
241
- /** Solve execution duration in seconds */
242
249
  runTime?: number;
243
-
244
- /** Diagnostic solver logs / text outputs */
245
250
  logs?: string[];
251
+ raw?: any;
252
+ }
246
253
 
247
- /** Raw solver response object for inspection */
254
+ export interface SolverCheckResult {
255
+ status: "Sat" | "Unsat" | "Unknown";
256
+ values: Record<string, number | boolean>;
257
+ unsatCore?: readonly string[];
258
+ /** Alias for unsatCore: subset of conflicting constraints causing infeasibility */
259
+ conflicts?: readonly string[];
260
+ runTime?: number;
261
+ logs?: string[];
248
262
  raw?: any;
249
263
  }
250
264
  ```
251
265
 
252
266
  #### Standardized `SolverStatus` Values
253
- - `"Optimal"`: Global optimal solution found (for MIP within tolerance, for LP proven optimal).
254
- - `"Feasible"`: Feasible solution found, but optimality not yet proven (e.g., hit time limit with an incumbent).
255
- - `"Infeasible"`: Model is proven mathematically infeasible.
267
+
268
+ - `"Optimal"`: Optimal solution found (within MIP tolerance, or proven optimal for LP).
269
+ - `"Feasible"`: Feasible incumbent found, but optimality is not yet proven.
270
+ - `"Infeasible"`: Model is proven infeasible.
256
271
  - `"Unbounded"`: Model objective is unbounded.
257
- - `"TimeLimit"`: Solver terminated due to `timeLimit` without proof of optimality.
258
- - `"IterationLimit"`: Solver terminated due to iteration limit.
259
- - `"Sat"` / `"Unsat"`: Satisfiable / unsatisfiable status returned by `check()` or SMT solvers.
260
- - `"Error"` / `"NotSolved"` / `"Unknown"`: Error, not yet solved, or unrecognized status. **Never convert Unknown/Error to Optimal.**
272
+ - `"TimeLimit"`: Stopped by `timeLimit` without finding a feasible incumbent.
273
+ - `"IterationLimit"`: Stopped by an iteration limit without finding a feasible incumbent.
274
+ - `"Sat"` / `"Unsat"`: Satisfiable / unsatisfiable status from `check()` or SMT solvers.
275
+ - `"Error"` / `"NotSolved"` / `"Unknown"`: Failure, unsolved, or unrecognized status. Never map `"Unknown"` or `"Error"` to `"Optimal"`.
261
276
 
262
277
  ---
263
278
 
@@ -265,7 +280,7 @@ export interface SolverResult {
265
280
 
266
281
  ### Tutorial A: In-House Cloud REST Solver Adapter
267
282
 
268
- Here is a complete, production-ready custom solver connecting to an HTTP microservice that accepts LP format strings on demand via `generateLpString(modelData)`:
283
+ This example builds a custom solver that calls an HTTP microservice accepting CPLEX LP strings generated on demand with `generateLpString`:
269
284
 
270
285
  ```typescript
271
286
  import {
@@ -290,21 +305,27 @@ export class CloudSolver implements Solver {
290
305
  supportsMIP: true,
291
306
  supportsQP: false,
292
307
  };
308
+ public readonly options: SolverOptions;
293
309
 
294
310
  private endpoint: string;
295
311
  private apiKey: string;
296
312
 
297
313
  constructor(config: CloudSolverConfig = {}) {
298
- this.endpoint = config.endpoint || "https://solver.mycompany.internal/v1/solve";
299
- this.apiKey = config.apiKey || "";
314
+ const { endpoint, apiKey, ...defaultOptions } = config;
315
+ this.endpoint = endpoint || "https://solver.mycompany.internal/v1/solve";
316
+ this.apiKey = apiKey || "";
317
+ this.options = defaultOptions;
300
318
  }
301
319
 
302
320
  async solve(
303
321
  modelData: SolveModelData,
304
322
  options: SolverOptions = {}
305
323
  ): Promise<SolverResult> {
324
+ const mergedOptions: SolverOptions = { ...this.options, ...options };
306
325
  const startTime = performance.now();
307
- const { lpString, nameToVar, nameToConstraint } = generateLpString(modelData);
326
+ const { lpString, nameToVar, nameToConstraint } = generateLpString(modelData, {
327
+ relax: mergedOptions.relax,
328
+ });
308
329
 
309
330
  let payload: any;
310
331
  try {
@@ -316,10 +337,11 @@ export class CloudSolver implements Solver {
316
337
  },
317
338
  body: JSON.stringify({
318
339
  lp: lpString,
319
- timeLimit: options.timeLimit,
320
- mipGap: options.mipGap,
340
+ timeLimit: mergedOptions.timeLimit,
341
+ relativeGap: mergedOptions.relativeGap,
342
+ absoluteGap: mergedOptions.absoluteGap,
321
343
  }),
322
- signal: options.signal,
344
+ signal: mergedOptions.signal,
323
345
  });
324
346
 
325
347
  if (!response.ok) {
@@ -328,10 +350,11 @@ export class CloudSolver implements Solver {
328
350
 
329
351
  payload = await response.json();
330
352
  } catch (err: any) {
331
- if (options.signal?.aborted || err?.name === "AbortError") {
353
+ if (mergedOptions.signal?.aborted || err?.name === "AbortError") {
332
354
  return {
333
355
  status: "Unknown",
334
356
  terminationStatus: "Interrupted",
357
+ hasPrimalSolution: false,
335
358
  objectiveValue: null,
336
359
  values: {},
337
360
  runTime: (performance.now() - startTime) / 1000,
@@ -369,19 +392,25 @@ export class CloudSolver implements Solver {
369
392
  UNSAT: "Unsat",
370
393
  };
371
394
  const rawStatus: SolverStatus = statusMap[String(payload.status).toUpperCase()] ?? "Unknown";
395
+ const offset = modelData.objective?.constant ?? 0;
396
+ const hasFiniteObj =
397
+ typeof payload.objectiveValue === "number" && Number.isFinite(payload.objectiveValue);
372
398
  const hasIncumbent =
373
- (typeof payload.objectiveValue === "number" && Number.isFinite(payload.objectiveValue)) ||
399
+ hasFiniteObj ||
374
400
  Object.values(values).some((val) => typeof val === "number" && Number.isFinite(val));
375
401
  const isLimitStop = rawStatus === "TimeLimit" || rawStatus === "IterationLimit";
376
402
  const status: SolverStatus = isLimitStop && hasIncumbent ? "Feasible" : rawStatus;
403
+ const hasPrimalSolution =
404
+ (status === "Optimal" || status === "Feasible") && hasIncumbent;
377
405
 
378
406
  return {
379
407
  status,
380
408
  terminationStatus: rawStatus,
381
- objectiveValue: payload.objectiveValue ?? null,
382
- values,
383
- duals,
384
- slacks,
409
+ hasPrimalSolution,
410
+ objectiveValue: hasPrimalSolution && hasFiniteObj ? payload.objectiveValue + offset : null,
411
+ values: hasPrimalSolution ? values : {},
412
+ duals: hasPrimalSolution ? duals : {},
413
+ slacks: hasPrimalSolution ? slacks : {},
385
414
  runTime: payload.solveDuration || runTime,
386
415
  logs: payload.logs || [],
387
416
  raw: payload,
@@ -400,18 +429,26 @@ registerCloudSolver();
400
429
 
401
430
  ### Tutorial B: Registering and Using the Custom Solver
402
431
 
403
- Once implemented, the custom solver can be selected in three different ways:
432
+ Choose how to attach your solver based on whether configuration is shared globally or varies per call or per model:
433
+
434
+ | Method | Best For |
435
+ | :--- | :--- |
436
+ | **Registered name string** | Reusable plugins with default settings (`solver: "cloud"`). |
437
+ | **Solver instance** | Per-call or per-model credentials, endpoints, or custom option presets. |
438
+ | **Global default (`setDefaultSolver`)** | Replacing HiGHS across an entire application without updating every `new Model()`. |
404
439
 
405
440
  #### Option 1: By Registered Name String
441
+
406
442
  ```typescript
407
443
  import { Model } from "@ohtaman/washi";
408
444
  import "./cloud-solver.js"; // Auto-registers "cloud"
409
445
 
410
446
  const model = new Model({ name: "SupplyChain", solver: "cloud" });
411
- // Or model.solve("cloud")
447
+ // Or await model.solve({ solver: "cloud" })
412
448
  ```
413
449
 
414
450
  #### Option 2: By Passing the Solver Instance Directly
451
+
415
452
  ```typescript
416
453
  import { Model } from "@ohtaman/washi";
417
454
  import { CloudSolver } from "./cloud-solver.js";
@@ -426,13 +463,14 @@ const status = await model.solve();
426
463
  ```
427
464
 
428
465
  #### Option 3: Setting Global Default Solver
466
+
429
467
  ```typescript
430
468
  import { setDefaultSolver, Model } from "@ohtaman/washi";
431
469
  import { CloudSolver } from "./cloud-solver.js";
432
470
 
433
471
  setDefaultSolver(() => new CloudSolver());
434
472
 
435
- // All subsequent models use CloudSolver by default
473
+ // Models without an explicit solver use CloudSolver by default
436
474
  const model = new Model("DefaultedModel");
437
475
  ```
438
476
 
@@ -440,9 +478,10 @@ const model = new Model("DefaultedModel");
440
478
 
441
479
  ## 4. Distribution: Packaging as a Plugin
442
480
 
443
- To publish your solver as an independent npm package (e.g. `@my-org/washi-solver-cplex`):
481
+ To publish your solver as an independent npm package (such as `@my-org/washi-solver-cplex`), declare Node ESM and browser entry points in `package.json`:
444
482
 
445
483
  ### 1. `package.json` Exports Structure
484
+
446
485
  ```json
447
486
  {
448
487
  "name": "@my-org/washi-solver-cplex",
@@ -464,22 +503,24 @@ To publish your solver as an independent npm package (e.g. `@my-org/washi-solver
464
503
  "./browser/index.min.js": "./dist/browser/index.min.js"
465
504
  },
466
505
  "peerDependencies": {
467
- "@ohtaman/washi": ">=0.1.0"
506
+ "@ohtaman/washi": ">=0.8.0"
468
507
  }
469
508
  }
470
509
  ```
471
510
 
472
- ### 2. Browser IIFE Build
473
- When building the browser standalone script (`.min.js`), configure your bundler (Vite or Rollup) to:
474
- - Output format: `iife`
475
- - Global name: `WashiCplex`
476
- - Rely on `Symbol.for("washi.solverRegistry")` so that `<script src="washi.min.js"></script><script src="washi-cplex.min.js"></script>` automatically connects.
511
+ ### 2. Browser Standalone Build (IIFE)
512
+
513
+ When building a browser `.min.js` bundle, configure Vite or Rollup for Immediately Invoked Function Expression (`iife`) output:
514
+
515
+ - **Output format**: `iife`
516
+ - **Global name**: `WashiCplex`
517
+ - **Registry linking**: Because registration uses `Symbol.for("washi.solverRegistry")`, loading `<script src="washi.min.js"></script>` followed by `<script src="washi-cplex.min.js"></script>` connects automatically.
477
518
 
478
519
  ---
479
520
 
480
521
  ## 5. Testing Your Custom Solver
481
522
 
482
- You can test your solver using Vitest or Jest without bundling:
523
+ You can test your adapter directly in Vitest or Jest without bundling by mocking network calls:
483
524
 
484
525
  ```typescript
485
526
  import { describe, it, expect, vi } from "vitest";
@@ -515,7 +556,7 @@ describe("Custom Solver Integration", () => {
515
556
  const status = await model.solve();
516
557
  expect(status).toBe("Optimal");
517
558
  expect(x.value).toBe(2);
518
- const c1 = model.getConstraintByName("budget");
559
+ const c1 = model.constraints.get("budget");
519
560
  expect(c1?.dual).toBe(2);
520
561
  } finally {
521
562
  fetchSpy.mockRestore();