@mappedin/route-optimization 6.25.0-beta.0
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/LICENSE.txt +104 -0
- package/README.md +84 -0
- package/THIRD_PARTY_LICENSES.txt +15118 -0
- package/lib/esm/index.d.ts +761 -0
- package/lib/esm/index.js +106 -0
- package/package.json +44 -0
|
@@ -0,0 +1,761 @@
|
|
|
1
|
+
import { Area, Coordinate, MapView, Space, TNavigationTarget } from "@mappedin/mappedin-js";
|
|
2
|
+
|
|
3
|
+
//#region src/optimizer/types.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Core optimizer contracts.
|
|
7
|
+
*
|
|
8
|
+
* Nothing in this folder may import from the Mappedin SDK. The engine only ever
|
|
9
|
+
* sees a cost matrix, which keeps it portable and testable without a map.
|
|
10
|
+
*
|
|
11
|
+
* New algorithms (CPU or WebGPU) plug in by implementing {@link Solver} and
|
|
12
|
+
* calling {@link registerSolver}.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* A routing problem: an NxN cost matrix plus how the route is bounded.
|
|
16
|
+
*
|
|
17
|
+
* Node 0 is always the route start and every solver must keep it in position 0.
|
|
18
|
+
*/
|
|
19
|
+
interface Problem {
|
|
20
|
+
/** matrix[i][j] = walking distance in metres from stop i to stop j. */
|
|
21
|
+
matrix: number[][];
|
|
22
|
+
/** When true the route closes back onto node 0. */
|
|
23
|
+
returnToStart: boolean;
|
|
24
|
+
}
|
|
25
|
+
type SolverParamValue = number | boolean;
|
|
26
|
+
type SolverParams = Record<string, SolverParamValue>;
|
|
27
|
+
/**
|
|
28
|
+
* Self-describing parameter rendered directly into tuning UIs.
|
|
29
|
+
*/
|
|
30
|
+
interface SolverParamDef {
|
|
31
|
+
key: string;
|
|
32
|
+
label: string;
|
|
33
|
+
type: 'number' | 'boolean';
|
|
34
|
+
default: SolverParamValue;
|
|
35
|
+
min?: number;
|
|
36
|
+
max?: number;
|
|
37
|
+
step?: number;
|
|
38
|
+
help?: string;
|
|
39
|
+
}
|
|
40
|
+
interface SolverResult {
|
|
41
|
+
order: number[];
|
|
42
|
+
distance: number;
|
|
43
|
+
}
|
|
44
|
+
interface SolverProgress {
|
|
45
|
+
iteration: number;
|
|
46
|
+
totalIterations: number;
|
|
47
|
+
bestDistance: number;
|
|
48
|
+
bestOrder: number[];
|
|
49
|
+
}
|
|
50
|
+
type ProgressCallback = (progress: SolverProgress) => void;
|
|
51
|
+
/**
|
|
52
|
+
* Checked inside long loops so a run can be cancelled from the UI.
|
|
53
|
+
*/
|
|
54
|
+
interface Cancellation {
|
|
55
|
+
readonly cancelled: boolean;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Qualitative efficiency band for sorting and capability checks.
|
|
59
|
+
* Higher means more efficient (cheaper compute / leaner memory).
|
|
60
|
+
*/
|
|
61
|
+
type EfficiencyBand = 1 | 2 | 3 | 4 | 5;
|
|
62
|
+
/**
|
|
63
|
+
* Where the solver executes. WebGPU solvers run on the GPU when available.
|
|
64
|
+
*/
|
|
65
|
+
type SolverBackend = 'cpu' | 'webgpu';
|
|
66
|
+
/**
|
|
67
|
+
* Whether {@link Solver.run} returns synchronously or via a Promise.
|
|
68
|
+
* WebGPU solvers are always async; CPU solvers may be either.
|
|
69
|
+
*/
|
|
70
|
+
type SolverExecutionMode = 'sync' | 'async';
|
|
71
|
+
/**
|
|
72
|
+
* Asymptotic cost in terms of stop count `n` and solver parameters.
|
|
73
|
+
*/
|
|
74
|
+
interface SolverComplexity {
|
|
75
|
+
/**
|
|
76
|
+
* Big-O style compute cost, e.g. `O(n²)` or `O(ants · iterations · n²)`.
|
|
77
|
+
*/
|
|
78
|
+
time: string;
|
|
79
|
+
/**
|
|
80
|
+
* Big-O style memory cost, e.g. `O(n)` or `O(n²)`.
|
|
81
|
+
*/
|
|
82
|
+
memory: string;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Performance and capability metadata for a solver.
|
|
86
|
+
*
|
|
87
|
+
* Used by UIs to recommend algorithms, and by future schedulers to decide
|
|
88
|
+
* whether a WebGPU path is worth launching for a given problem size.
|
|
89
|
+
*/
|
|
90
|
+
interface SolverCharacteristics {
|
|
91
|
+
/** Execution device / API. */
|
|
92
|
+
backend: SolverBackend;
|
|
93
|
+
/** Whether {@link Solver.run} is sync or async. */
|
|
94
|
+
executionMode: SolverExecutionMode;
|
|
95
|
+
/**
|
|
96
|
+
* Relative computational efficiency (5 = cheapest/fastest per stop).
|
|
97
|
+
* Independent of solution quality — a thorough search can score low here.
|
|
98
|
+
*/
|
|
99
|
+
computeEfficiency: EfficiencyBand;
|
|
100
|
+
/**
|
|
101
|
+
* Relative memory efficiency (5 = leanest working set).
|
|
102
|
+
*/
|
|
103
|
+
memoryEfficiency: EfficiencyBand;
|
|
104
|
+
/** Asymptotic complexity hints for docs and tooling. */
|
|
105
|
+
complexity: SolverComplexity;
|
|
106
|
+
/**
|
|
107
|
+
* Stop counts where this solver is a sensible default.
|
|
108
|
+
* Outside the range, pickers may suggest an alternative.
|
|
109
|
+
*/
|
|
110
|
+
recommendedStopCount: {
|
|
111
|
+
min: number;
|
|
112
|
+
max: number;
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* Whether the algorithm's inner loops are a good fit for data-parallel
|
|
116
|
+
* WebGPU ports (many independent ants, population members, etc.).
|
|
117
|
+
*/
|
|
118
|
+
parallelizable: boolean;
|
|
119
|
+
/** One-line guidance for docs and algorithm pickers. */
|
|
120
|
+
notes: string;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* A pluggable TSP solver.
|
|
124
|
+
*
|
|
125
|
+
* Implement {@link run} (sync or async) and declare {@link characteristics} so
|
|
126
|
+
* callers can choose an algorithm without hard-coding ids. Register extras with
|
|
127
|
+
* {@link registerSolver}.
|
|
128
|
+
*/
|
|
129
|
+
interface Solver {
|
|
130
|
+
id: string;
|
|
131
|
+
name: string;
|
|
132
|
+
description: string;
|
|
133
|
+
paramDefs: SolverParamDef[];
|
|
134
|
+
/** Performance and backend metadata. */
|
|
135
|
+
characteristics: SolverCharacteristics;
|
|
136
|
+
/**
|
|
137
|
+
* Solve the problem. May return a Promise for async backends (WebGPU).
|
|
138
|
+
*
|
|
139
|
+
* Rules every implementation must honour:
|
|
140
|
+
* - Node 0 stays first in the returned order.
|
|
141
|
+
* - `distance` equals {@link tourDistance} of that order.
|
|
142
|
+
* - Check `cancellation.cancelled` inside long loops.
|
|
143
|
+
*/
|
|
144
|
+
run(problem: Problem, params: SolverParams, onProgress?: ProgressCallback, cancellation?: Cancellation): SolverResult | Promise<SolverResult>;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Build a params object populated with each solver's defaults.
|
|
148
|
+
* @param solver - Solver whose paramDefs to use
|
|
149
|
+
* @returns Default parameter map
|
|
150
|
+
*/
|
|
151
|
+
declare function defaultParams(solver: Solver): SolverParams;
|
|
152
|
+
/**
|
|
153
|
+
* Normalize a sync or async solver result to a Promise.
|
|
154
|
+
* @param result - Value returned from {@link Solver.run}
|
|
155
|
+
* @returns Promise resolving to the solver result
|
|
156
|
+
*/
|
|
157
|
+
declare function asSolverPromise(result: SolverResult | Promise<SolverResult>): Promise<SolverResult>;
|
|
158
|
+
/**
|
|
159
|
+
* Whether a solver prefers (or requires) async execution.
|
|
160
|
+
* @param solver - Solver to inspect
|
|
161
|
+
* @returns True when executionMode is async
|
|
162
|
+
*/
|
|
163
|
+
declare function isAsyncSolver(solver: Solver): boolean;
|
|
164
|
+
/**
|
|
165
|
+
* Whether a solver targets WebGPU.
|
|
166
|
+
* @param solver - Solver to inspect
|
|
167
|
+
* @returns True when backend is webgpu
|
|
168
|
+
*/
|
|
169
|
+
declare function isWebGpuSolver(solver: Solver): boolean;
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/types.d.ts
|
|
172
|
+
/**
|
|
173
|
+
* A stop that can be visited by an optimized route.
|
|
174
|
+
*
|
|
175
|
+
* Spaces, areas, and coordinates all work as Mappedin navigation targets.
|
|
176
|
+
*/
|
|
177
|
+
type RouteStop = Coordinate | Space | Area | TNavigationTarget;
|
|
178
|
+
/**
|
|
179
|
+
* Options that control how {@link RouteOptimization.optimize} builds and solves
|
|
180
|
+
* a multi-stop route.
|
|
181
|
+
*/
|
|
182
|
+
type RouteOptimizationOptions = {
|
|
183
|
+
/**
|
|
184
|
+
* When true, the solver returns to the first stop after visiting all others.
|
|
185
|
+
* @default false
|
|
186
|
+
*/
|
|
187
|
+
returnToStart?: boolean;
|
|
188
|
+
/**
|
|
189
|
+
* Solver id from {@link SOLVERS}. Defaults to Ant Colony Optimization.
|
|
190
|
+
* @default "aco"
|
|
191
|
+
*/
|
|
192
|
+
solverId?: string;
|
|
193
|
+
/**
|
|
194
|
+
* Solver-specific parameters. Defaults come from the solver's `paramDefs`.
|
|
195
|
+
*/
|
|
196
|
+
params?: SolverParams;
|
|
197
|
+
/**
|
|
198
|
+
* Called while the walking-distance matrix is being measured.
|
|
199
|
+
*/
|
|
200
|
+
onMatrixProgress?: (progress: {
|
|
201
|
+
measuredPairs: number;
|
|
202
|
+
totalPairs: number;
|
|
203
|
+
}) => void;
|
|
204
|
+
/**
|
|
205
|
+
* Called while the solver is iterating (2-opt passes or ACO iterations).
|
|
206
|
+
*/
|
|
207
|
+
onSolverProgress?: (progress: SolverProgress) => void;
|
|
208
|
+
/**
|
|
209
|
+
* Abort signal that cancels matrix measurement (and cooperative solver loops).
|
|
210
|
+
*/
|
|
211
|
+
signal?: AbortSignal;
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* The result of an optimized multi-stop route.
|
|
215
|
+
*/
|
|
216
|
+
type OptimizedRoute = {
|
|
217
|
+
/**
|
|
218
|
+
* Stops in visit order. Includes the start stop as the first element.
|
|
219
|
+
*/
|
|
220
|
+
orderedStops: RouteStop[];
|
|
221
|
+
/**
|
|
222
|
+
* Indices into the original `stops` array, matching {@link orderedStops}.
|
|
223
|
+
*/
|
|
224
|
+
order: number[];
|
|
225
|
+
/**
|
|
226
|
+
* Measured walk-network distance in metres (penalty legs excluded).
|
|
227
|
+
*/
|
|
228
|
+
totalDistance: number;
|
|
229
|
+
/**
|
|
230
|
+
* Legs the navigation graph could not connect.
|
|
231
|
+
*/
|
|
232
|
+
unreachableLegs: number;
|
|
233
|
+
/**
|
|
234
|
+
* Solver that produced the order.
|
|
235
|
+
*/
|
|
236
|
+
solverId: string;
|
|
237
|
+
/**
|
|
238
|
+
* Wall-clock time spent measuring the distance matrix, in milliseconds.
|
|
239
|
+
*/
|
|
240
|
+
matrixMs: number;
|
|
241
|
+
/**
|
|
242
|
+
* Wall-clock time spent running the solver, in milliseconds.
|
|
243
|
+
*/
|
|
244
|
+
solveMs: number;
|
|
245
|
+
};
|
|
246
|
+
//#endregion
|
|
247
|
+
//#region src/route-optimization.d.ts
|
|
248
|
+
/**
|
|
249
|
+
* Optimizes the visit order of multiple stops on a Mappedin map.
|
|
250
|
+
*
|
|
251
|
+
* Builds a walk-network distance matrix with `getDirections`, then runs a TSP
|
|
252
|
+
* solver (nearest neighbor, 2-opt, or ant colony) that keeps the first stop
|
|
253
|
+
* fixed as the route start.
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```ts
|
|
257
|
+
* import { show3dMap } from '@mappedin/mappedin-js';
|
|
258
|
+
* import { RouteOptimization } from '@mappedin/route-optimization';
|
|
259
|
+
*
|
|
260
|
+
* const mapView = await show3dMap(...);
|
|
261
|
+
* const optimizer = new RouteOptimization(mapView);
|
|
262
|
+
* const spaces = mapView.getMapData().getByType('space').slice(0, 12);
|
|
263
|
+
* const result = await optimizer.optimize(spaces, { solverId: 'two-opt' });
|
|
264
|
+
* console.log(result.order, result.totalDistance, result.solveMs);
|
|
265
|
+
* ```
|
|
266
|
+
*/
|
|
267
|
+
declare class RouteOptimization {
|
|
268
|
+
#private;
|
|
269
|
+
/**
|
|
270
|
+
* Create a new {@link RouteOptimization} instance bound to a {@link MapView}.
|
|
271
|
+
*
|
|
272
|
+
* @param mapView - The map view whose navigation graph will be measured.
|
|
273
|
+
*/
|
|
274
|
+
constructor(mapView: MapView);
|
|
275
|
+
/**
|
|
276
|
+
* Measure walking distances between stops and return an optimized visit order.
|
|
277
|
+
*
|
|
278
|
+
* The first stop in `stops` is always kept as the route start (index 0).
|
|
279
|
+
*
|
|
280
|
+
* @param stops - Stops to visit. Must include at least one stop.
|
|
281
|
+
* @param options - Solver selection, return-to-start, and progress callbacks.
|
|
282
|
+
* @returns Ordered stops, measured distance, and timing metadata.
|
|
283
|
+
*/
|
|
284
|
+
optimize(stops: RouteStop[], options?: RouteOptimizationOptions): Promise<OptimizedRoute>;
|
|
285
|
+
}
|
|
286
|
+
//#endregion
|
|
287
|
+
//#region src/optimizer/tour.d.ts
|
|
288
|
+
/**
|
|
289
|
+
* Total length of a route visiting `order`, closing the loop when required.
|
|
290
|
+
* @param order - Visit order as matrix indices
|
|
291
|
+
* @param problem - Cost matrix and return-to-start flag
|
|
292
|
+
* @returns Total distance in metres
|
|
293
|
+
*/
|
|
294
|
+
declare function tourDistance(order: number[], problem: Problem): number;
|
|
295
|
+
/**
|
|
296
|
+
* The route as given, before any optimization — the baseline order.
|
|
297
|
+
* @param size - Number of stops
|
|
298
|
+
* @returns Identity permutation `[0, 1, …, size-1]`
|
|
299
|
+
*/
|
|
300
|
+
declare function identityOrder(size: number): number[];
|
|
301
|
+
//#endregion
|
|
302
|
+
//#region src/optimizer/nearest-neighbor.d.ts
|
|
303
|
+
/**
|
|
304
|
+
* Greedy construction: repeatedly walk to the closest stop not yet visited.
|
|
305
|
+
*
|
|
306
|
+
* Fast and always produces a valid route, which makes it both a useful baseline
|
|
307
|
+
* and a good starting point for 2-opt to refine.
|
|
308
|
+
*
|
|
309
|
+
* @param problem - Cost matrix problem (node 0 stays first)
|
|
310
|
+
* @returns Visit order as matrix indices
|
|
311
|
+
*/
|
|
312
|
+
declare function nearestNeighbor(problem: Problem): number[];
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region src/optimizer/two-opt.d.ts
|
|
315
|
+
interface TwoOptOptions {
|
|
316
|
+
maxPasses?: number;
|
|
317
|
+
cancellation?: Cancellation;
|
|
318
|
+
onPass?: (pass: number, distance: number) => void;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* 2-opt local search: repeatedly reverse a sub-path when doing so uncrosses the
|
|
322
|
+
* route and shortens it. Runs until a full pass finds no improvement.
|
|
323
|
+
*
|
|
324
|
+
* Position 0 is never moved, so the route keeps starting at the origin stop.
|
|
325
|
+
*
|
|
326
|
+
* @param initialOrder - Seed order (node 0 must already be first)
|
|
327
|
+
* @param problem - Cost matrix problem
|
|
328
|
+
* @param options - Pass limit, cancellation, and progress callback
|
|
329
|
+
* @returns Improved visit order
|
|
330
|
+
*/
|
|
331
|
+
declare function twoOpt(initialOrder: number[], problem: Problem, options?: TwoOptOptions): number[];
|
|
332
|
+
//#endregion
|
|
333
|
+
//#region src/optimizer/aco.d.ts
|
|
334
|
+
interface AcoOptions {
|
|
335
|
+
numAnts: number;
|
|
336
|
+
numIterations: number;
|
|
337
|
+
/** Weight of the pheromone trail — how much ants follow previous success. */
|
|
338
|
+
alpha: number;
|
|
339
|
+
/** Weight of the 1/distance heuristic — how much ants prefer nearby stops. */
|
|
340
|
+
beta: number;
|
|
341
|
+
evaporationRate: number;
|
|
342
|
+
/** Pheromone deposited per unit of route quality. */
|
|
343
|
+
q: number;
|
|
344
|
+
}
|
|
345
|
+
interface AcoRunResult {
|
|
346
|
+
order: number[];
|
|
347
|
+
distance: number;
|
|
348
|
+
}
|
|
349
|
+
type AcoProgress = (iteration: number, bestDistance: number, bestOrder: number[]) => void;
|
|
350
|
+
/**
|
|
351
|
+
* Ant Colony Optimization over a cost matrix.
|
|
352
|
+
*
|
|
353
|
+
* Ants build routes probabilistically, biased by a shared pheromone trail that
|
|
354
|
+
* is reinforced along the best route of each iteration and evaporates
|
|
355
|
+
* elsewhere. Node 0 is pinned as the start.
|
|
356
|
+
*
|
|
357
|
+
* Runs synchronously; progress is reported per iteration.
|
|
358
|
+
*
|
|
359
|
+
* @param problem - Cost matrix problem
|
|
360
|
+
* @param options - Colony size, iterations, and pheromone parameters
|
|
361
|
+
* @param onProgress - Optional per-iteration callback
|
|
362
|
+
* @param cancellation - Optional cancellation token
|
|
363
|
+
* @returns Best order found and its tour distance
|
|
364
|
+
*/
|
|
365
|
+
declare function runAco(problem: Problem, options: AcoOptions, onProgress?: AcoProgress, cancellation?: Cancellation): AcoRunResult;
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/optimizer/solvers/nearest-neighbor-solver.d.ts
|
|
368
|
+
/**
|
|
369
|
+
* Greedy nearest-neighbor construction solver.
|
|
370
|
+
*
|
|
371
|
+
* Extremely cheap compute and memory; quality trails local search and ACO on
|
|
372
|
+
* larger stop sets. A natural CPU baseline and seed for 2-opt.
|
|
373
|
+
*/
|
|
374
|
+
declare const nearestNeighborSolver: Solver;
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/optimizer/solvers/two-opt-solver.d.ts
|
|
377
|
+
/**
|
|
378
|
+
* Nearest-neighbor seed refined with 2-opt local search.
|
|
379
|
+
*
|
|
380
|
+
* Strong quality-per-second on CPU for typical venue sizes. The pass loop is
|
|
381
|
+
* sequential, so it is a weaker WebGPU candidate than population methods.
|
|
382
|
+
*/
|
|
383
|
+
declare const twoOptSolver: Solver;
|
|
384
|
+
//#endregion
|
|
385
|
+
//#region src/optimizer/solvers/aco-solver.d.ts
|
|
386
|
+
/**
|
|
387
|
+
* Ant Colony Optimization with optional 2-opt polish.
|
|
388
|
+
*
|
|
389
|
+
* Higher compute and O(n²) pheromone memory, but ants are independent within an
|
|
390
|
+
* iteration — a natural shape for a future WebGPU parallel port.
|
|
391
|
+
*/
|
|
392
|
+
declare const acoSolver: Solver;
|
|
393
|
+
//#endregion
|
|
394
|
+
//#region src/optimizer/solvers/aco-webgpu-solver.d.ts
|
|
395
|
+
/**
|
|
396
|
+
* Data-parallel Ant Colony Optimization on WebGPU (TensorACO-style).
|
|
397
|
+
*
|
|
398
|
+
* Rebuilds the probability matrix on-device once per iteration, then runs
|
|
399
|
+
* `n - 1` AdaIR (Adaptive Independent Roulette) selection steps in parallel
|
|
400
|
+
* across ants. Falls back to the CPU `aco` solver when WebGPU is unavailable —
|
|
401
|
+
* headless / Node environments therefore still get a valid result via the same
|
|
402
|
+
* solver id.
|
|
403
|
+
*/
|
|
404
|
+
declare const acoWebGpuSolver: Solver;
|
|
405
|
+
//#endregion
|
|
406
|
+
//#region src/optimizer/solvers/registry.d.ts
|
|
407
|
+
/** Built-in solvers, ordered fastest → most thorough. */
|
|
408
|
+
declare const BUILTIN_SOLVERS: readonly Solver[];
|
|
409
|
+
/**
|
|
410
|
+
* @deprecated Prefer {@link listSolvers} so registered (e.g. WebGPU) solvers are included.
|
|
411
|
+
* Frozen snapshot of the built-in CPU solvers only.
|
|
412
|
+
*/
|
|
413
|
+
declare const SOLVERS: readonly Solver[];
|
|
414
|
+
/** ACO with a 2-opt polish gives the strongest default result. */
|
|
415
|
+
declare const DEFAULT_SOLVER_ID: string;
|
|
416
|
+
/**
|
|
417
|
+
* Register a solver (e.g. a WebGPU implementation) at runtime.
|
|
418
|
+
*
|
|
419
|
+
* Built-in ids may be overridden so a GPU port can replace its CPU twin while
|
|
420
|
+
* keeping the same public id.
|
|
421
|
+
*
|
|
422
|
+
* @param solver - Solver to add
|
|
423
|
+
* @returns The registered solver
|
|
424
|
+
*/
|
|
425
|
+
declare function registerSolver(solver: Solver): Solver;
|
|
426
|
+
/**
|
|
427
|
+
* Remove a previously registered custom solver.
|
|
428
|
+
* Built-ins cannot be unregistered; override them with {@link registerSolver} instead.
|
|
429
|
+
*
|
|
430
|
+
* @param id - Solver id
|
|
431
|
+
* @returns True when a custom solver was removed
|
|
432
|
+
*/
|
|
433
|
+
declare function unregisterSolver(id: string): boolean;
|
|
434
|
+
/**
|
|
435
|
+
* List all available solvers: customs override built-ins with the same id.
|
|
436
|
+
* @returns Solvers in stable order (built-in order, then extra customs)
|
|
437
|
+
*/
|
|
438
|
+
declare function listSolvers(): Solver[];
|
|
439
|
+
/**
|
|
440
|
+
* Look up a solver by id, falling back to the default when unknown.
|
|
441
|
+
* @param id - Solver id
|
|
442
|
+
* @returns Matching or default solver
|
|
443
|
+
*/
|
|
444
|
+
declare function getSolver(id: string): Solver;
|
|
445
|
+
/**
|
|
446
|
+
* Suggest solvers whose recommended stop-count range includes `n`.
|
|
447
|
+
* Results are sorted by descending compute efficiency, then memory efficiency.
|
|
448
|
+
*
|
|
449
|
+
* @param stopCount - Number of stops in the problem
|
|
450
|
+
* @returns Matching solvers, best efficiency first
|
|
451
|
+
*/
|
|
452
|
+
declare function recommendSolvers(stopCount: number): Solver[];
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region src/optimizer/webgpu/adair.d.ts
|
|
455
|
+
/**
|
|
456
|
+
* Cosine anneal `gamma` from `gammaStart` (iteration 0) to `gammaEnd`
|
|
457
|
+
* (iteration `totalIterations - 1`).
|
|
458
|
+
*
|
|
459
|
+
* Matches the AdaIR schedule described by TensorACO: exploration → exploitation
|
|
460
|
+
* as the pheromone trail stabilises. Larger `gamma` puts more weight on random
|
|
461
|
+
* roulette noise, smaller `gamma` collapses toward greedy argmax on the
|
|
462
|
+
* probability matrix.
|
|
463
|
+
*
|
|
464
|
+
* @param iteration - Current iteration index (0-based)
|
|
465
|
+
* @param totalIterations - Total number of iterations (>= 1)
|
|
466
|
+
* @param gammaStart - Starting gamma (typically high for exploration)
|
|
467
|
+
* @param gammaEnd - Ending gamma (typically low for exploitation)
|
|
468
|
+
* @returns Interpolated gamma for the current iteration
|
|
469
|
+
*/
|
|
470
|
+
declare function cosineGamma(iteration: number, totalIterations: number, gammaStart: number, gammaEnd: number): number;
|
|
471
|
+
/**
|
|
472
|
+
* Rebuild the row-normalized ACO probability matrix `M_p`.
|
|
473
|
+
*
|
|
474
|
+
* `M_p[i, j] ∝ pheromone[i, j]^alpha · attractiveness[i, j]^beta`, row-summed to
|
|
475
|
+
* one so an ant at node `i` can sample directly from `M_p[i]`.
|
|
476
|
+
*
|
|
477
|
+
* @param pheromone - Flat `size²` pheromone matrix
|
|
478
|
+
* @param attractiveness - Flat `size²` heuristic matrix (typically `1 / distance`)
|
|
479
|
+
* @param size - Row/column count
|
|
480
|
+
* @param alpha - Pheromone weight
|
|
481
|
+
* @param beta - Heuristic weight
|
|
482
|
+
* @param out - Optional pre-allocated `size²` target buffer
|
|
483
|
+
* @returns Row-normalized probability matrix
|
|
484
|
+
*/
|
|
485
|
+
declare function buildProbabilityMatrix(pheromone: Float32Array | Float64Array | number[], attractiveness: Float32Array | Float64Array | number[], size: number, alpha: number, beta: number, out?: Float32Array): Float32Array;
|
|
486
|
+
/**
|
|
487
|
+
* CPU reference implementation of the AdaIR next-city selection.
|
|
488
|
+
*
|
|
489
|
+
* Picks `argmax(r^gamma · M_p[current, j])` over unvisited `j`, matching the
|
|
490
|
+
* WGSL kernel. Callers pass a `random` function to keep tests deterministic.
|
|
491
|
+
*
|
|
492
|
+
* @param current - Current node index
|
|
493
|
+
* @param mp - Flat `size²` probability matrix (row-normalized)
|
|
494
|
+
* @param size - Node count
|
|
495
|
+
* @param visited - `size`-length flag array (`0`/`1`); mutated to mark the pick
|
|
496
|
+
* @param gamma - AdaIR annealing parameter
|
|
497
|
+
* @param random - RNG returning values in `[0, 1)`
|
|
498
|
+
* @returns Chosen next node index (`-1` when no unvisited candidate scored positively)
|
|
499
|
+
*/
|
|
500
|
+
declare function pickNextAdaIR(current: number, mp: Float32Array | number[], size: number, visited: Uint8Array | Uint32Array | number[], gamma: number, random: () => number): number;
|
|
501
|
+
/**
|
|
502
|
+
* CPU reference: build a single tour by AdaIR selection, pinned at node 0.
|
|
503
|
+
*
|
|
504
|
+
* Useful for testing the algorithm without a GPU device and for the fallback
|
|
505
|
+
* path when WebGPU is unavailable.
|
|
506
|
+
*
|
|
507
|
+
* @param mp - Flat `size²` probability matrix
|
|
508
|
+
* @param size - Node count
|
|
509
|
+
* @param gamma - AdaIR gamma
|
|
510
|
+
* @param random - RNG returning values in `[0, 1)`
|
|
511
|
+
* @param scratch - Optional pre-allocated `size`-length visited buffer
|
|
512
|
+
* @returns Tour as an array of node indices starting with `0`
|
|
513
|
+
*/
|
|
514
|
+
declare function buildTourAdaIR(mp: Float32Array | number[], size: number, gamma: number, random: () => number, scratch?: Uint8Array): number[];
|
|
515
|
+
/**
|
|
516
|
+
* Evaporate the whole pheromone matrix and reinforce a single tour.
|
|
517
|
+
*
|
|
518
|
+
* Mirrors the CPU ACO update: `pheromone *= 1 - evaporationRate`, then deposit
|
|
519
|
+
* `q / distance` on every edge of the given tour (both directions). Closes the
|
|
520
|
+
* loop when `returnToStart` is set.
|
|
521
|
+
*
|
|
522
|
+
* @param pheromone - Flat `size²` pheromone matrix (mutated in place)
|
|
523
|
+
* @param size - Row/column count
|
|
524
|
+
* @param evaporationRate - Fraction of pheromone lost each iteration
|
|
525
|
+
* @param order - Tour order to reinforce
|
|
526
|
+
* @param distance - Tour distance (`q / distance` becomes the deposit)
|
|
527
|
+
* @param q - Deposit constant
|
|
528
|
+
* @param returnToStart - Whether the tour closes the loop
|
|
529
|
+
*/
|
|
530
|
+
declare function evaporateAndDeposit(pheromone: Float64Array | Float32Array, size: number, evaporationRate: number, order: number[], distance: number, q: number, returnToStart: boolean): void;
|
|
531
|
+
/**
|
|
532
|
+
* Build a `size²` attractiveness matrix from a distance matrix (`1/d`).
|
|
533
|
+
*
|
|
534
|
+
* Non-finite or non-positive distances become 0 so an ant never favours an
|
|
535
|
+
* unreachable edge.
|
|
536
|
+
*
|
|
537
|
+
* @param problem - Problem holding the cost matrix
|
|
538
|
+
* @returns Flat `size²` attractiveness values
|
|
539
|
+
*/
|
|
540
|
+
declare function attractivenessMatrix(problem: Problem): Float32Array;
|
|
541
|
+
//#endregion
|
|
542
|
+
//#region src/optimizer/webgpu/types.d.ts
|
|
543
|
+
interface GpuBuffer {
|
|
544
|
+
readonly size: number;
|
|
545
|
+
destroy(): void;
|
|
546
|
+
mapAsync(mode: number, offset?: number, size?: number): Promise<undefined>;
|
|
547
|
+
getMappedRange(offset?: number, size?: number): ArrayBuffer;
|
|
548
|
+
unmap(): void;
|
|
549
|
+
}
|
|
550
|
+
interface GpuBindGroup {
|
|
551
|
+
readonly label?: string;
|
|
552
|
+
}
|
|
553
|
+
interface GpuComputePipeline {
|
|
554
|
+
getBindGroupLayout(index: number): GpuBindGroupLayout;
|
|
555
|
+
}
|
|
556
|
+
interface GpuBindGroupLayout {
|
|
557
|
+
readonly label?: string;
|
|
558
|
+
}
|
|
559
|
+
interface GpuCommandEncoder {
|
|
560
|
+
beginComputePass(): GpuComputePassEncoder;
|
|
561
|
+
copyBufferToBuffer(source: GpuBuffer, sourceOffset: number, destination: GpuBuffer, destinationOffset: number, size: number): void;
|
|
562
|
+
finish(): GpuCommandBuffer;
|
|
563
|
+
}
|
|
564
|
+
interface GpuComputePassEncoder {
|
|
565
|
+
setPipeline(pipeline: GpuComputePipeline): void;
|
|
566
|
+
setBindGroup(index: number, bindGroup: GpuBindGroup): void;
|
|
567
|
+
dispatchWorkgroups(x: number, y?: number, z?: number): void;
|
|
568
|
+
end(): void;
|
|
569
|
+
}
|
|
570
|
+
interface GpuCommandBuffer {
|
|
571
|
+
readonly label?: string;
|
|
572
|
+
}
|
|
573
|
+
interface GpuQueue {
|
|
574
|
+
submit(buffers: GpuCommandBuffer[]): void;
|
|
575
|
+
writeBuffer(buffer: GpuBuffer, bufferOffset: number, data: ArrayBufferView | ArrayBufferLike, dataOffset?: number, size?: number): void;
|
|
576
|
+
onSubmittedWorkDone(): Promise<undefined>;
|
|
577
|
+
}
|
|
578
|
+
interface GpuShaderModule {
|
|
579
|
+
readonly label?: string;
|
|
580
|
+
}
|
|
581
|
+
interface GpuDeviceLostInfo {
|
|
582
|
+
readonly reason: 'destroyed' | 'unknown';
|
|
583
|
+
readonly message: string;
|
|
584
|
+
}
|
|
585
|
+
interface GpuDevice {
|
|
586
|
+
readonly lost: Promise<GpuDeviceLostInfo>;
|
|
587
|
+
readonly queue: GpuQueue;
|
|
588
|
+
createBuffer(descriptor: {
|
|
589
|
+
size: number;
|
|
590
|
+
usage: number;
|
|
591
|
+
mappedAtCreation?: boolean;
|
|
592
|
+
label?: string;
|
|
593
|
+
}): GpuBuffer;
|
|
594
|
+
createShaderModule(descriptor: {
|
|
595
|
+
code: string;
|
|
596
|
+
label?: string;
|
|
597
|
+
}): GpuShaderModule;
|
|
598
|
+
createComputePipeline(descriptor: {
|
|
599
|
+
layout: 'auto' | unknown;
|
|
600
|
+
compute: {
|
|
601
|
+
module: GpuShaderModule;
|
|
602
|
+
entryPoint: string;
|
|
603
|
+
};
|
|
604
|
+
label?: string;
|
|
605
|
+
}): GpuComputePipeline;
|
|
606
|
+
createBindGroup(descriptor: {
|
|
607
|
+
layout: GpuBindGroupLayout;
|
|
608
|
+
entries: {
|
|
609
|
+
binding: number;
|
|
610
|
+
resource: {
|
|
611
|
+
buffer: GpuBuffer;
|
|
612
|
+
};
|
|
613
|
+
}[];
|
|
614
|
+
label?: string;
|
|
615
|
+
}): GpuBindGroup;
|
|
616
|
+
createCommandEncoder(descriptor?: {
|
|
617
|
+
label?: string;
|
|
618
|
+
}): GpuCommandEncoder;
|
|
619
|
+
destroy(): void;
|
|
620
|
+
}
|
|
621
|
+
//#endregion
|
|
622
|
+
//#region src/optimizer/webgpu/device.d.ts
|
|
623
|
+
/**
|
|
624
|
+
* Whether the current environment exposes a WebGPU entry point.
|
|
625
|
+
*
|
|
626
|
+
* Does not request an adapter — that would spin one up unconditionally and can
|
|
627
|
+
* flash a permissions prompt on some browsers. Use this before deciding to try
|
|
628
|
+
* `requestWebGpuDevice`.
|
|
629
|
+
*
|
|
630
|
+
* @returns True when `navigator.gpu` is defined
|
|
631
|
+
*/
|
|
632
|
+
declare function hasWebGpuSupport(): boolean;
|
|
633
|
+
/**
|
|
634
|
+
* Request a WebGPU device, returning `null` when the environment or hardware
|
|
635
|
+
* does not support one.
|
|
636
|
+
*
|
|
637
|
+
* All failures are swallowed and reported as `null` so callers can fall back to
|
|
638
|
+
* a CPU path without try/catching.
|
|
639
|
+
*
|
|
640
|
+
* @param options - Optional adapter power preference
|
|
641
|
+
* @returns A device, or `null` when unavailable
|
|
642
|
+
*/
|
|
643
|
+
declare function requestWebGpuDevice(options?: {
|
|
644
|
+
powerPreference?: 'low-power' | 'high-performance';
|
|
645
|
+
}): Promise<GpuDevice | null>;
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/optimizer/webgpu/aco-webgpu.d.ts
|
|
648
|
+
/**
|
|
649
|
+
* Options for {@link runAcoWebGpu}. Extends the CPU ACO parameter set with the
|
|
650
|
+
* AdaIR annealing schedule and a fallback toggle.
|
|
651
|
+
*/
|
|
652
|
+
interface AcoWebGpuOptions extends AcoOptions {
|
|
653
|
+
/**
|
|
654
|
+
* Starting AdaIR gamma (iteration 0). Higher values push wider exploration.
|
|
655
|
+
* @default 3.0
|
|
656
|
+
*/
|
|
657
|
+
gammaStart?: number;
|
|
658
|
+
/**
|
|
659
|
+
* Ending AdaIR gamma (final iteration). Lower values collapse toward greedy
|
|
660
|
+
* argmax on the probability matrix.
|
|
661
|
+
* @default 0.5
|
|
662
|
+
*/
|
|
663
|
+
gammaEnd?: number;
|
|
664
|
+
/**
|
|
665
|
+
* Deterministic seed for the per-ant xorshift RNG. Falls back to
|
|
666
|
+
* `Math.random()` when omitted so repeated runs vary.
|
|
667
|
+
*/
|
|
668
|
+
seed?: number;
|
|
669
|
+
/**
|
|
670
|
+
* Fall back to the CPU {@link runAco} when WebGPU is not available.
|
|
671
|
+
* @default true
|
|
672
|
+
*/
|
|
673
|
+
fallbackToCpu?: boolean;
|
|
674
|
+
}
|
|
675
|
+
/** Extra metadata reported alongside the tour and distance. */
|
|
676
|
+
interface AcoWebGpuRunResult extends AcoRunResult {
|
|
677
|
+
/** Whether the run executed on the GPU (`true`) or fell back to CPU (`false`). */
|
|
678
|
+
usedWebGpu: boolean;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* WebGPU ACO with AdaIR next-city selection.
|
|
682
|
+
*
|
|
683
|
+
* Follows the TensorACO pattern: rebuild the row-normalized probability matrix
|
|
684
|
+
* once per iteration on-device, then dispatch `n - 1` AdaIR steps where each
|
|
685
|
+
* ant thread picks its next city in parallel via
|
|
686
|
+
* `argmax(pow(r, gamma) * M_p[current, j])` over unvisited candidates.
|
|
687
|
+
* Pheromone evaporation + iteration-best deposit stay on the CPU because
|
|
688
|
+
* matrices are venue-scale small and float atomics in WGSL would only add
|
|
689
|
+
* complexity without a win.
|
|
690
|
+
*
|
|
691
|
+
* Node 0 is pinned as the start of every tour, matching the package contract.
|
|
692
|
+
*
|
|
693
|
+
* Falls back to the CPU {@link runAco} when WebGPU is not available and
|
|
694
|
+
* `fallbackToCpu` is not explicitly `false`.
|
|
695
|
+
*
|
|
696
|
+
* @param problem - Cost matrix problem
|
|
697
|
+
* @param options - Colony size, iterations, ACO weights, AdaIR gammas, seed
|
|
698
|
+
* @param onProgress - Optional per-iteration callback
|
|
699
|
+
* @param cancellation - Optional cooperative cancellation token
|
|
700
|
+
* @returns Best tour, distance, and whether WebGPU actually ran
|
|
701
|
+
*/
|
|
702
|
+
declare function runAcoWebGpu(problem: Problem, options: AcoWebGpuOptions, onProgress?: AcoProgress, cancellation?: Cancellation): Promise<AcoWebGpuRunResult>;
|
|
703
|
+
//#endregion
|
|
704
|
+
//#region src/distance-matrix.d.ts
|
|
705
|
+
/** A navigation target plus a human-readable name, so failures can be traced. */
|
|
706
|
+
interface RoutingPoint {
|
|
707
|
+
name: string;
|
|
708
|
+
target: TNavigationTarget;
|
|
709
|
+
}
|
|
710
|
+
interface MatrixProgress {
|
|
711
|
+
measuredPairs: number;
|
|
712
|
+
totalPairs: number;
|
|
713
|
+
}
|
|
714
|
+
interface DistanceMatrixResult {
|
|
715
|
+
/** Symmetric NxN walking distances in metres, straight from the SDK. */
|
|
716
|
+
matrix: number[][];
|
|
717
|
+
/** Pairs with no walkable path, which carry `penaltyCost` instead. */
|
|
718
|
+
unreachablePairs: number;
|
|
719
|
+
/** Any matrix entry at or above this is a penalty, not a measured distance. */
|
|
720
|
+
penaltyCost: number;
|
|
721
|
+
}
|
|
722
|
+
interface BuildMatrixOptions {
|
|
723
|
+
onProgress?: (progress: MatrixProgress) => void;
|
|
724
|
+
signal?: AbortSignal;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Builds a symmetric walking-distance matrix between navigation targets.
|
|
728
|
+
*
|
|
729
|
+
* Every value is `Directions.distance` from the Mappedin SDK, in metres.
|
|
730
|
+
*
|
|
731
|
+
* Each unordered pair is measured once with `getDirections` and mirrored.
|
|
732
|
+
* Do **not** use `getDirectionsMultiDestination` here — it chains destinations
|
|
733
|
+
* into one multi-stop trip rather than measuring origin→each destination.
|
|
734
|
+
*
|
|
735
|
+
* @param mapView - Active map view
|
|
736
|
+
* @param points - Stops to measure between (node 0 is the route start)
|
|
737
|
+
* @param options - Progress and abort options
|
|
738
|
+
* @returns Finalized matrix with penalties for unreachable pairs
|
|
739
|
+
*/
|
|
740
|
+
declare function buildDistanceMatrix(mapView: MapView, points: RoutingPoint[], options?: BuildMatrixOptions): Promise<DistanceMatrixResult>;
|
|
741
|
+
interface MeasuredRoute {
|
|
742
|
+
/** Metres actually reported by the SDK, with penalties left out. */
|
|
743
|
+
distance: number;
|
|
744
|
+
/** Legs the navigation graph could not connect. */
|
|
745
|
+
unreachableLegs: number;
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Sums a route using only distances the SDK actually measured.
|
|
749
|
+
*
|
|
750
|
+
* Penalty edges are counted rather than added, so an unroutable pair can never
|
|
751
|
+
* inflate the number shown to the user.
|
|
752
|
+
*
|
|
753
|
+
* @param matrix - Distance matrix
|
|
754
|
+
* @param order - Visit order
|
|
755
|
+
* @param returnToStart - Whether to include the closing leg
|
|
756
|
+
* @param penaltyCost - Threshold at/above which a cost is a penalty
|
|
757
|
+
* @returns Measured distance and unreachable leg count
|
|
758
|
+
*/
|
|
759
|
+
declare function measureRoute(matrix: number[][], order: number[], returnToStart: boolean, penaltyCost: number): MeasuredRoute;
|
|
760
|
+
//#endregion
|
|
761
|
+
export { type AcoOptions, type AcoWebGpuOptions, type AcoWebGpuRunResult, BUILTIN_SOLVERS, DEFAULT_SOLVER_ID, type DistanceMatrixResult, type EfficiencyBand, type MatrixProgress, type MeasuredRoute, type OptimizedRoute, type Problem, RouteOptimization, type RouteOptimizationOptions, type RouteStop, type RoutingPoint, SOLVERS, type Solver, type SolverBackend, type SolverCharacteristics, type SolverComplexity, type SolverExecutionMode, type SolverParamDef, type SolverParams, type SolverProgress, type SolverResult, type TwoOptOptions, acoSolver, acoWebGpuSolver, asSolverPromise, attractivenessMatrix, buildDistanceMatrix, buildProbabilityMatrix, buildTourAdaIR, cosineGamma, defaultParams, evaporateAndDeposit, getSolver, hasWebGpuSupport, identityOrder, isAsyncSolver, isWebGpuSolver, listSolvers, measureRoute, nearestNeighbor, nearestNeighborSolver, pickNextAdaIR, recommendSolvers, registerSolver, requestWebGpuDevice, runAco, runAcoWebGpu, tourDistance, twoOpt, twoOptSolver, unregisterSolver };
|