/
suggestAStar.ts
523 lines (468 loc) · 15.6 KB
/
suggestAStar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import { TrieRoot, TrieNode } from './TrieNode';
import { CompoundWordsMethod, JOIN_SEPARATOR, WORD_SEPARATOR } from './walker';
import { SuggestionGenerator, suggestionCollector, SuggestionResult } from './suggestCollector';
import { PairingHeap } from './PairingHeap';
import { visualLetterMaskMap } from './orthography';
import { createSuggestionOptions, GenSuggestionOptionsStrict, SuggestionOptions } from './genSuggestionsOptions';
export function* genCompoundableSuggestions(
root: TrieRoot,
word: string,
options: GenSuggestionOptionsStrict
): SuggestionGenerator {
const { compoundMethod, ignoreCase, changeLimit } = options;
const len = word.length;
const nodes = determineInitialNodes(root, ignoreCase);
const noFollow = determineNoFollow(root);
function compare(a: Candidate, b: Candidate): number {
const deltaCost = a.g - b.g;
if (deltaCost) return deltaCost;
// The costs are the some return the one with the most progress.
return b.i - a.i;
}
const opCosts = {
baseCost: 100,
swapCost: 75,
duplicateLetterCost: 25,
visuallySimilar: 1,
firstLetterBias: 25,
wordBreak: 99,
} as const;
const bc = opCosts.baseCost;
const maxCostScale = 1.03 / 2;
const mapSugCost = opCosts.visuallySimilar;
const wordSeparator = compoundMethod === CompoundWordsMethod.JOIN_WORDS ? JOIN_SEPARATOR : WORD_SEPARATOR;
const compoundIndicator = root.compoundCharacter;
let costLimit = bc * Math.min(len * maxCostScale, changeLimit);
let stopNow = false;
const candidates = new PairingHeap(compare);
const locationCache: LocationCache = new Map();
const wordsToEmit: EmitWord[] = [];
const pathToLocation: Map<Path, LocationNode> = new Map();
const edgesToResolve: EdgeToResolve[] = [];
const emittedWords = new Map<string, number>();
function updateCostLimit(maxCost: number | symbol | undefined) {
switch (typeof maxCost) {
case 'number':
costLimit = Math.min(maxCost, costLimit);
break;
case 'symbol':
stopNow = true;
break;
}
}
function getLocationNode(path: Path): LocationNode {
const index = path.i;
const node = path.n;
const foundByIndex = locationCache.get(index);
const byTrie: LocationByTriNode = foundByIndex || new Map<TrieNode, LocationNode>();
if (!foundByIndex) locationCache.set(index, byTrie);
const f = byTrie.get(node);
const n: LocationNode = f || { in: new Map(), er: [], bc: 0, p: path, sbc: -1, sfx: [] };
if (!f) byTrie.set(node, n);
return n;
}
function* emitWord(word: string, cost: number): SuggestionGenerator {
if (cost <= costLimit) {
// console.log(`e: ${word} ${cost}`);
const f = emittedWords.get(word);
if (f !== undefined && f <= cost) return undefined;
emittedWords.set(word, cost);
const lastChar = word[word.length - 1];
if (!noFollow[lastChar]) {
updateCostLimit(yield { word: word, cost: cost });
}
}
return undefined;
}
function* emitWords(): SuggestionGenerator {
for (const w of wordsToEmit) {
yield* emitWord(w.word, w.cost);
}
wordsToEmit.length = 0;
return undefined;
}
function addEdgeToBeResolved(path: Path, edge: Edge) {
path.r = path.r || new Set();
path.r.add(edge);
}
function addEdge(path: Path, edge: Edge): Edge | undefined {
const g = path.g + edge.c;
const i = edge.i;
if (g > costLimit) return undefined;
const { n } = edge;
const w = path.w + edge.s;
const can: Path = { e: edge, n, i, w, g, r: undefined, a: true };
const location = getLocationNode(can);
location.er.push(edge);
// Is Location Resolved
if (location.sbc >= 0 && location.sbc <= can.g) {
// No need to go further, this node has been resolved.
// Return the edge to be resolved
addEdgeToBeResolved(path, edge);
edgesToResolve.push({ edge, suffixes: location.sfx });
return undefined;
}
const found = location.in.get(can.w);
if (found) {
// If the existing path is cheaper or the same keep it.
// Do not add the edge.
if (found.g <= can.g) return undefined;
// Otherwise mark it as inactive and
const e = found.e;
if (e) {
edgesToResolve.push({ edge: e, suffixes: [] });
}
found.a = false;
}
addEdgeToBeResolved(path, edge);
location.in.set(can.w, can);
if (location.p.g > can.g) {
pathToLocation.delete(location.p);
location.sbc = -1;
location.sfx.length = 0;
location.p = can;
}
if (location.p === can) {
// Make this path the representation of this location.
pathToLocation.set(can, location);
candidates.add(can);
}
return edge;
}
function opWordFound(best: Candidate): void {
if (!best.n.f) return;
const i = best.i;
const toDelete = len - i;
const edge: Edge = { p: best, n: best.n, i, s: '', c: bc * toDelete, a: Action.Delete };
addEdgeToBeResolved(best, edge);
edgesToResolve.push({ edge, suffixes: [{ s: '', c: 0 }] });
if (compoundMethod && best.g + opCosts.wordBreak <= costLimit) {
const s = wordSeparator;
nodes.forEach((node) => {
const e: Edge = { p: best, n: node, i, s, c: opCosts.wordBreak, a: Action.WordBreak };
addEdge(best, e);
});
}
}
function opCompoundWord(best: Candidate): void {
if (!best.n.c?.get(compoundIndicator)) return;
const i = best.i;
const s = '';
nodes.forEach((node) => {
const n = node.c?.get(compoundIndicator);
if (!n) return;
const e: Edge = { p: best, n, i, s, c: opCosts.wordBreak, a: Action.CompoundWord };
addEdge(best, e);
});
}
function opInsert(best: Candidate): void {
const children = best.n.c;
if (!children) return;
const i = best.i;
const c = bc;
for (const [s, n] of children) {
const e: Edge = { p: best, n, i, s, c, a: Action.Insert };
addEdge(best, e);
}
}
function opDelete(best: Candidate, num = 1): Edge | undefined {
const i = best.i;
const e: Edge = {
p: best,
n: best.n,
i: i + num,
s: '',
c: bc * num,
a: Action.Delete,
// t: word.slice(i, i + num),
};
return addEdge(best, e);
}
function opIdentity(best: Candidate): void {
const s = word[best.i];
const n = best.n.c?.get(s);
if (!n) return;
const i = best.i + 1;
const e: Edge = { p: best, n, i, s, c: 0, a: Action.Identity };
addEdge(best, e);
}
function opReplace(best: Candidate): void {
const children = best.n.c;
if (!children) return;
const wc = word[best.i];
const wg = visualLetterMaskMap[wc] || 0;
const i = best.i + 1;
const cost = bc + (best.i ? 0 : opCosts.firstLetterBias);
for (const [s, n] of children) {
if (s == wc) continue;
const sg = visualLetterMaskMap[s] || 0;
const c = wg & sg ? mapSugCost : cost;
const e: Edge = { p: best, n, i, s, c, a: Action.Replace /* , t: wc */ };
addEdge(best, e);
}
}
function opSwap(best: Candidate): void {
const children = best.n.c;
const i = best.i;
const i2 = i + 1;
if (!children || len <= i2) return;
const wc1 = word[i];
const wc2 = word[i2];
if (wc1 === wc2) return;
const n = best.n.c?.get(wc2);
const n2 = n?.c?.get(wc1);
if (!n || !n2) return;
const e: Edge = {
p: best,
n: n2,
i: i2 + 1,
s: wc2 + wc1,
c: opCosts.swapCost,
a: Action.Swap,
// , t: wc1 + wc2,
};
addEdge(best, e);
}
function opDuplicate(best: Candidate): void {
const children = best.n.c;
const i = best.i;
const i2 = i + 1;
if (!children || len <= i2) return;
const wc1 = word[i];
const wc2 = word[i2];
const n = best.n.c?.get(wc1);
if (!n) return;
if (wc1 === wc2) {
// convert double letter to single
const e: Edge = { p: best, n, i: i + 2, s: wc1, c: opCosts.duplicateLetterCost, a: Action.Delete };
addEdge(best, e);
return;
}
const n2 = n?.c?.get(wc1);
if (!n2) return;
// convert single to double letter
const e: Edge = { p: best, n: n2, i: i2, s: wc1 + wc1, c: opCosts.duplicateLetterCost, a: Action.Insert };
addEdge(best, e);
}
function resolveEdges() {
let e: EdgeToResolve | undefined;
while ((e = edgesToResolve.shift())) {
resolveEdge(e);
}
}
function resolveLocationEdges(location: LocationNode, suffixes: Suffix[]) {
for (const edge of location.er) {
edgesToResolve.push({ edge, suffixes });
}
}
function resolveEdge({ edge, suffixes }: EdgeToResolve) {
const { p, s: es, c: ec } = edge;
if (!p.r?.has(edge)) return;
const edgeSuffixes = suffixes.map((sfx) => ({ s: es + sfx.s, c: ec + sfx.c }));
for (const { s, c } of edgeSuffixes) {
const cost = p.g + c;
if (cost <= costLimit) {
const word = p.w + s;
wordsToEmit.push({ word, cost });
}
}
p.r.delete(edge);
const location = pathToLocation.get(p);
if (location?.p === p) {
location.sfx = location.sfx.concat(edgeSuffixes);
if (!p.r.size) {
location.sbc = p.g;
resolveLocationEdges(location, edgeSuffixes);
}
} else if (!p.r.size) {
if (p.e) {
// Keep rolling up.
edgesToResolve.push({ edge: p.e, suffixes: edgeSuffixes });
}
}
}
function cancelEdges(path: Path) {
if (!path.r) return;
const suffixes: Suffix[] = [];
for (const edge of path.r) {
edgesToResolve.push({ edge, suffixes });
}
}
/************
* Below is the core of the A* algorithm
*/
updateCostLimit(yield undefined);
nodes.forEach((node, idx) => {
const g = idx ? 1 : 0;
candidates.add({ e: undefined, n: node, i: 0, w: '', g, r: undefined, a: true });
});
const iterationsBeforePolling = 100;
let i = iterationsBeforePolling;
let maxSize = 0;
let best: Candidate | undefined;
// const bc2 = 2 * bc;
while (!stopNow && (best = candidates.dequeue())) {
if (--i < 0) {
i = iterationsBeforePolling;
updateCostLimit(yield undefined);
}
maxSize = Math.max(maxSize, candidates.length);
if (!best.a) {
// best's edges are already part of a location node.
continue;
}
if (best.g > costLimit) {
cancelEdges(best);
continue;
}
const bi = best.i;
opWordFound(best);
const children = best.n.c;
if (!children) continue;
if (bi === len) {
opInsert(best);
} else {
opIdentity(best);
opReplace(best);
opDelete(best);
opInsert(best);
opSwap(best);
opCompoundWord(best);
opDuplicate(best);
}
resolveEdges();
yield* emitWords();
}
resolveEdges();
yield* emitWords();
// console.log(`
// word: ${word}
// maxSize: ${maxSize}
// length: ${candidates.length}
// `);
return undefined;
}
enum Action {
Identity,
Replace,
Delete,
Insert,
Swap,
CompoundWord,
WordBreak,
}
interface Edge {
/** from */
p: Path;
/** to Node */
n: TrieNode;
/** index into the original word */
i: number;
/** suffix character to add to Path p. */
s: string;
/** edge cost */
c: number;
/** Action */
a: Action;
/** Optional Transform */
// t?: string | undefined;
}
interface Path {
/** Edge taken to get here */
e: Edge | undefined;
/** to Node */
n: TrieNode;
/** index into the original word */
i: number;
/** Suggested word so far */
w: string;
/** cost so far */
g: number;
/** active */
a: boolean;
/** Edges to be resolved. */
r: Set<Edge> | undefined;
}
interface Suffix {
/** suffix */
s: string;
/** Cost of using suffix */
c: number;
}
interface LocationNode {
/** Incoming Paths */
in: Map<string, Path>;
/** Edges to Resolve when Location is Resolved */
er: Edge[];
/** Best Possible cost - only non-zero when location has been resolved. */
bc: number;
/** Pending Path to be resolved */
p: Path;
/**
* Suffix Base Cost
* The base cost used when calculating the suffixes.
* If a new path comes in with a lower base cost,
* then the suffixes need to be recalculated.
*/
sbc: number;
/** Set of suffixes, calculated when location has been resolved. */
sfx: Suffix[];
}
type LocationByTriNode = Map<TrieNode, LocationNode>;
type LocationCache = Map<number, LocationByTriNode>;
type Candidate = Path;
type NoFollow = Record<string, true | undefined>;
interface EmitWord {
word: string;
cost: number;
}
interface EdgeToResolve {
edge: Edge;
suffixes: Suffix[];
}
export function suggest(root: TrieRoot | TrieRoot[], word: string, options: SuggestionOptions): SuggestionResult[] {
const opts = createSuggestionOptions(options);
const collector = suggestionCollector(word, {
numSuggestions: opts.numSuggestions,
changeLimit: opts.changeLimit,
includeTies: opts.includeTies,
ignoreCase: opts.ignoreCase,
timeout: opts.timeout,
});
collector.collect(genSuggestions(root, word, opts));
return collector.suggestions;
}
export function* genSuggestions(
root: TrieRoot | TrieRoot[],
word: string,
options: GenSuggestionOptionsStrict
): SuggestionGenerator {
const roots = Array.isArray(root) ? root : [root];
for (const r of roots) {
yield* genCompoundableSuggestions(r, word, options);
}
return undefined;
}
function determineNoFollow(root: TrieRoot): NoFollow {
const noFollow: NoFollow = Object.assign(Object.create(null), {
[root.compoundCharacter]: true,
[root.forbiddenWordPrefix]: true,
[root.stripCaseAndAccentsPrefix]: true,
});
return noFollow;
}
function determineInitialNodes(root: TrieRoot | TrieRoot[], ignoreCase: boolean): TrieNode[] {
const roots = Array.isArray(root) ? root : [root];
const rootNodes: TrieNode[] = roots;
const noCaseNodes = ignoreCase
? roots
.filter((r) => r.stripCaseAndAccentsPrefix)
.map((n) => n.c?.get(n.stripCaseAndAccentsPrefix))
.filter(isDefined)
: [];
const nodes: TrieNode[] = rootNodes.concat(noCaseNodes);
return nodes;
}
function isDefined<T>(v: T | undefined): v is T {
return v !== undefined;
}