@gmod/gfa-tabix 0.0.0-stage → 10.0.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.
@@ -0,0 +1,1600 @@
1
+ import { RegionTooLargeError, bpString, panSNHaplotypeOrSample, panSNMatchesPrefix, } from "./util.js";
2
+ import { SKIPPED } from "./walkChunk.js";
3
+ import { ATTACH_BP, attachesOwnSteps, departureStretch, } from "./walkDeparture.js";
4
+ import { GAP_KINDS, walkGaps } from "./walkGaps.js";
5
+ // Whether a step's id is a placeholder's: a run of an unloaded piece's
6
+ // steps off R, of known bp and no node identity
7
+ export const isPlaceholder = (id) => id < 0;
8
+ function integerTag(line, tag) {
9
+ const match = new RegExp(`(?:^|\\t)${tag}:i:(\\d+)`).exec(line);
10
+ return match ? +match[1] : undefined;
11
+ }
12
+ const INTEGER_TAGS = [
13
+ 'format',
14
+ 'tile',
15
+ 'revisited',
16
+ 'leftout',
17
+ ];
18
+ function stringTag(line, tag) {
19
+ var _a;
20
+ return (_a = new RegExp(`(?:^|\\t)${tag}:Z:([^\\t]+)`).exec(line)) === null || _a === void 0 ? void 0 : _a[1];
21
+ }
22
+ /**
23
+ * What a walk file's header states: a `#walks` line with the format and the
24
+ * tile size, `format:i:8\ttile:i:65536`, a `#reference\tGRCh38` line naming
25
+ * the reference sample, a `#haplotype\tHG002#1` line per other haplotype with
26
+ * rows and a `#hole` line per stretch of a reference sequence no line of the
27
+ * reference covers
28
+ */
29
+ export function walkHeader(lines) {
30
+ var _a, _b;
31
+ const header = {
32
+ references: [],
33
+ haplotypes: [],
34
+ holes: [],
35
+ };
36
+ for (const line of lines) {
37
+ const [key, value = '', start = '', end = ''] = line.split('\t');
38
+ if (key === '#reference') {
39
+ header.references.push(value);
40
+ }
41
+ else if (key === '#haplotype') {
42
+ header.haplotypes.push(value);
43
+ }
44
+ else if (key === '#hole') {
45
+ header.holes.push({ refName: value, start: +start, end: +end });
46
+ }
47
+ else if (key === '#walks') {
48
+ for (const tag of INTEGER_TAGS) {
49
+ const stated = integerTag(line, tag);
50
+ if (stated !== undefined) {
51
+ (_a = header[tag]) !== null && _a !== void 0 ? _a : (header[tag] = stated);
52
+ }
53
+ }
54
+ const graph = stringTag(line, 'graph');
55
+ if (graph !== undefined) {
56
+ (_b = header.graph) !== null && _b !== void 0 ? _b : (header.graph = graph);
57
+ }
58
+ }
59
+ }
60
+ return header;
61
+ }
62
+ // Which walks a cut decodes: the reference's, and those `wanted` names by
63
+ // PanSN prefix at sample or haplotype depth; undefined decodes every one
64
+ export function walkNameFilter(wanted, referenceHaplotype) {
65
+ return wanted === undefined || wanted.length === 0
66
+ ? undefined
67
+ : (name) => panSNMatchesPrefix(name, referenceHaplotype) ||
68
+ wanted.some(prefix => panSNMatchesPrefix(name, prefix));
69
+ }
70
+ /**
71
+ * The walks a cut on `refName` decodes: its reference's and those `wanted`
72
+ * names. A pggb P-line names a reference with no haplotype field
73
+ * (`chm13#chr1`), whose walks are its sample's.
74
+ */
75
+ export function walksKept(wanted, refName) {
76
+ return walkNameFilter(wanted, panSNHaplotypeOrSample(refName));
77
+ }
78
+ export function joinPieces(rows) {
79
+ const byPath = new Map();
80
+ const runs = [];
81
+ for (const row of rows) {
82
+ const key = `${row.name}\t${row.fragStart}`;
83
+ const list = byPath.get(key);
84
+ if (list) {
85
+ list.push(row);
86
+ }
87
+ else {
88
+ byPath.set(key, [row]);
89
+ }
90
+ }
91
+ for (const pieces of byPath.values()) {
92
+ pieces.sort((a, b) => a.piece - b.piece);
93
+ let from = 0;
94
+ for (let i = 1; i <= pieces.length; i++) {
95
+ if (i === pieces.length ||
96
+ pieces[i].piece !== pieces[i - 1].piece + 1) {
97
+ runs.push(decodeRun(pieces.slice(from, i)));
98
+ from = i;
99
+ }
100
+ }
101
+ }
102
+ return runs;
103
+ }
104
+ function decodeRun(pieces) {
105
+ var _a;
106
+ const n = pieces.reduce((sum, p) => sum + p.n, 0);
107
+ const ids = new Int32Array(n);
108
+ const rev = new Uint8Array(n);
109
+ const refStarts = new Float64Array(n).fill(Number.NaN);
110
+ const against = new Uint8Array(n);
111
+ const pieceStarts = [];
112
+ const pieceChunks = [];
113
+ const bp = pieces.some(p => p.steps.bp)
114
+ ? new Int32Array(n).fill(-1)
115
+ : undefined;
116
+ const unloaded = [];
117
+ const own = [];
118
+ let at = 0;
119
+ for (const p of pieces) {
120
+ for (const steps of (_a = p.own) !== null && _a !== void 0 ? _a : []) {
121
+ own.push({ ...steps, from: at + steps.from, to: at + steps.to });
122
+ }
123
+ if (at > 0) {
124
+ pieceStarts.push(at);
125
+ }
126
+ pieceChunks.push(p.chunkStart);
127
+ if (p.steps.bp) {
128
+ bp === null || bp === void 0 ? void 0 : bp.set(p.steps.bp, at);
129
+ }
130
+ if (p.abridged) {
131
+ unloaded.push({ from: at, to: at + p.n, piece: p.abridged });
132
+ }
133
+ ids.set(p.steps.ids, at);
134
+ rev.set(p.steps.rev, at);
135
+ if (p.steps.refStarts) {
136
+ refStarts.set(p.steps.refStarts, at);
137
+ }
138
+ if (p.steps.against) {
139
+ against.set(p.steps.against, at);
140
+ }
141
+ at += p.n;
142
+ }
143
+ const first = pieces[0];
144
+ return {
145
+ name: first.name,
146
+ fragStart: first.fragStart,
147
+ hapOffset: first.hapOffset,
148
+ firstPiece: first.piece,
149
+ pieceStarts,
150
+ pieceChunks,
151
+ ids,
152
+ rev,
153
+ refStarts,
154
+ against,
155
+ ...(bp ? { bp } : {}),
156
+ ...(unloaded.length > 0 ? { unloaded } : {}),
157
+ ...(own.length > 0 ? { own } : {}),
158
+ };
159
+ }
160
+ // A direct-mapped memo of the last key seen per slot, in front of a Map or
161
+ // Set that most steps would ask the same question of again
162
+ const MEMO_SLOTS = 1 << 16;
163
+ const MEMO_MASK = MEMO_SLOTS - 1;
164
+ const memoKeys = () => new Float64Array(MEMO_SLOTS).fill(Number.NaN);
165
+ // Whether `memo` held the link, which it holds from now on
166
+ function linkHeld(memo, a, b) {
167
+ const slot = a & MEMO_MASK;
168
+ const same = memo.from[slot] === a;
169
+ const held = same && (memo.to[2 * slot] === b || memo.to[2 * slot + 1] === b);
170
+ if (!held) {
171
+ memo.to[2 * slot + 1] = same ? memo.to[2 * slot] : Number.NaN;
172
+ memo.to[2 * slot] = b;
173
+ memo.from[slot] = a;
174
+ }
175
+ return held;
176
+ }
177
+ // A number below 1e12 in absolute value as a key that sorts as its decimal
178
+ // string does: '-' sorts before every digit, and of two digit strings the
179
+ // one with the lower digits, padded right to 12, sorts first, the shorter on
180
+ // a tie
181
+ function stringOrder(x) {
182
+ const m = Math.abs(x);
183
+ let digits = 1;
184
+ let pad = 1e11;
185
+ while (m >= 10 ** digits) {
186
+ digits++;
187
+ pad /= 10;
188
+ }
189
+ return (x < 0 ? 0 : 2 ** 48) + (m * pad * 16 + digits);
190
+ }
191
+ // Each link between two kept nodes once, as its two handles, in the order
192
+ // its L line, source, strand, target and strand joined by tabs, sorts as a
193
+ // string. A tab sorts below every character of the fields, so that is the
194
+ // order of each id as a string, then of its strand, '+' first
195
+ function linkLines(links, kept) {
196
+ const distinct = new PairSet();
197
+ const chosen = [];
198
+ const sources = [];
199
+ const targets = [];
200
+ for (let i = 0; i < links.length; i += 2) {
201
+ const a = links[i];
202
+ const b = links[i + 1];
203
+ const source = Math.floor(a / 2);
204
+ const target = Math.floor(b / 2);
205
+ if (kept.has(source) && kept.has(target) && distinct.add(a, b)) {
206
+ chosen.push(i);
207
+ sources.push(2 * stringOrder(source) + (a & 1));
208
+ targets.push(2 * stringOrder(target) + (b & 1));
209
+ }
210
+ }
211
+ const order = Array.from(chosen.keys()).sort((x, y) => sources[x] - sources[y] || targets[x] - targets[y]);
212
+ const lines = [];
213
+ for (const k of order) {
214
+ lines.push(links[chosen[k]], links[chosen[k] + 1]);
215
+ }
216
+ return lines;
217
+ }
218
+ // Pairs of numbers, each exact as a double, by open addressing, so that a
219
+ // cut's millions of links are no Set apiece
220
+ class PairSet {
221
+ constructor() {
222
+ this.keys = new Float64Array(2048).fill(Number.NaN);
223
+ this.size = 0;
224
+ }
225
+ // whether the pair is new, which the set holds from now on
226
+ add(a, b) {
227
+ if (4 * (this.size + 1) > this.keys.length) {
228
+ const held = this.keys;
229
+ this.keys = new Float64Array(2 * held.length).fill(Number.NaN);
230
+ this.size = 0;
231
+ for (let k = 0; k < held.length; k += 2) {
232
+ if (!Number.isNaN(held[k])) {
233
+ this.add(held[k], held[k + 1]);
234
+ }
235
+ }
236
+ }
237
+ const { keys } = this;
238
+ const mask = keys.length / 2 - 1;
239
+ const mixed = Math.imul(a | 0, 0x9e3779b1) ^ (b | 0);
240
+ let slot = Math.imul(mixed ^ (mixed >>> 16), 0x85ebca6b) & mask;
241
+ while (!Number.isNaN(keys[2 * slot]) &&
242
+ !(keys[2 * slot] === a && keys[2 * slot + 1] === b)) {
243
+ slot = (slot + 1) & mask;
244
+ }
245
+ const fresh = Number.isNaN(keys[2 * slot]);
246
+ if (fresh) {
247
+ keys[2 * slot] = a;
248
+ keys[2 * slot + 1] = b;
249
+ this.size++;
250
+ }
251
+ return fresh;
252
+ }
253
+ }
254
+ // Links each step from `from` to `to` to the one before it, through `add`
255
+ // where `memo` has not held the link
256
+ function linkSteps(ids, rev, from, to, memo, add) {
257
+ const first = Math.max(from, 0);
258
+ const end = Math.min(to, ids.length - 1);
259
+ let before = first <= end ? ids[first] : SKIPPED;
260
+ let a = first <= end ? before * 2 + rev[first] : 0;
261
+ for (let k = first + 1; k <= end; k++) {
262
+ const id = ids[k];
263
+ const b = id * 2 + rev[k];
264
+ if (before !== SKIPPED && id !== SKIPPED && !linkHeld(memo, a, b)) {
265
+ add(a, b);
266
+ }
267
+ before = id;
268
+ a = b;
269
+ }
270
+ }
271
+ // The loops over a run's steps that a cut runs once per walk, each a
272
+ // function of its own so that it is compiled once and stays compiled
273
+ // bp of the steps before each, and after the last
274
+ function bpBefore(ids, stated, length) {
275
+ const out = new Float64Array(ids.length + 1);
276
+ for (let i = 0; i < ids.length; i++) {
277
+ const bp = stated === undefined ? -1 : stated[i];
278
+ out[i + 1] = out[i] + (bp < 0 ? length(ids[i]) : bp);
279
+ }
280
+ return out;
281
+ }
282
+ // The first and last steps whose pass lies over `start`-`end`, and the
283
+ // stretch those passes cover
284
+ function stepsOver(refStarts, bp, start, end) {
285
+ let first = -1;
286
+ let last = -1;
287
+ let lo = Infinity;
288
+ let hi = -Infinity;
289
+ for (let i = 0; i < refStarts.length; i++) {
290
+ const at = refStarts[i];
291
+ const to = at + bp[i + 1] - bp[i];
292
+ if (at < end && to > start) {
293
+ first = first < 0 ? i : first;
294
+ last = i;
295
+ lo = at < lo ? at : lo;
296
+ hi = to > hi ? to : hi;
297
+ }
298
+ }
299
+ return { first, last, lo, hi };
300
+ }
301
+ function keepSteps(ids, first, last, kept, lastKept) {
302
+ for (let i = first; i <= last; i++) {
303
+ const id = ids[i];
304
+ const slot = id & MEMO_MASK;
305
+ if (lastKept[slot] !== id) {
306
+ lastKept[slot] = id;
307
+ kept.add(id);
308
+ }
309
+ }
310
+ }
311
+ // Writes each id's index to `into` from `at`, through `indexOf` where the
312
+ // memo does not hold it
313
+ function indexSteps(ids, into, at, lastId, lastIndex, indexOf) {
314
+ for (let j = 0; j < ids.length; j++) {
315
+ const id = ids[j];
316
+ const slot = id & MEMO_MASK;
317
+ if (lastId[slot] !== id) {
318
+ lastId[slot] = id;
319
+ lastIndex[slot] = indexOf(id);
320
+ }
321
+ into[at + j] = lastIndex[slot];
322
+ }
323
+ }
324
+ function firstOnR(refStarts, from, to) {
325
+ let i = from;
326
+ while (i < to && Number.isNaN(refStarts[i])) {
327
+ i++;
328
+ }
329
+ return i < to ? i : -1;
330
+ }
331
+ function lastOnR(refStarts, from, to) {
332
+ let i = to - 1;
333
+ while (i >= from && Number.isNaN(refStarts[i])) {
334
+ i--;
335
+ }
336
+ return i >= from ? i : -1;
337
+ }
338
+ // Adds to `out` each two consecutive steps on R, from step `from` to `to`,
339
+ // that do not follow R: the one before and the one after
340
+ function departingPairs(refStarts, against, bp, from, to, squeeze, out) {
341
+ let last = -1;
342
+ for (let i = from; i < to; i++) {
343
+ const start = refStarts[i];
344
+ if (!Number.isNaN(start)) {
345
+ if (last >= 0) {
346
+ const leaveReversed = against[last] === 1;
347
+ const rejoinReversed = against[i] === 1;
348
+ const leavePos = leaveReversed
349
+ ? refStarts[last]
350
+ : refStarts[last] + bp[last + 1] - bp[last];
351
+ const rejoinPos = rejoinReversed ? start + bp[i + 1] - bp[i] : start;
352
+ const ownBp = bp[i] - bp[last + 1];
353
+ const adjacent = ownBp === 0 &&
354
+ leaveReversed === rejoinReversed &&
355
+ (leavePos === rejoinPos || squeeze(leavePos) === squeeze(rejoinPos));
356
+ if (!adjacent) {
357
+ out.push(last, i);
358
+ }
359
+ }
360
+ last = i;
361
+ }
362
+ }
363
+ }
364
+ export const edgeKey = (name, pos, reversed, hap) => `${name}\t${pos}\t${reversed ? '-' : '+'}\t${hap}`;
365
+ /**
366
+ * The cut a window draws from its walks: the reference inside the window plus
367
+ * its context, the drawn stretch, and each run from its first step on that
368
+ * stretch to its last. The drawn stretch is the window and its context,
369
+ * widened to the reference nodes over them, whole, and to every pass of a
370
+ * run's step over them. Nothing is followed past the drawn stretch and no fragment runs on
371
+ * through nodes other walks kept, so a haplotype's fragment does not depend on
372
+ * which others are cut.
373
+ *
374
+ * A contained cut splits a run wherever it steps onto the reference off the
375
+ * drawn stretch. Each piece between those steps that steps on the stretch is
376
+ * kept from its first such step to its last, so a detour that comes back is
377
+ * kept whole, and `context` bp of the walk past either end. At AMY1
378
+ * haplotypes go from a 4 kb window to the other copies and back: the cut
379
+ * above keeps 9,928 nodes there, the contained cut 182.
380
+ *
381
+ * Each departure comes back once: those inside one piece are computed from
382
+ * its steps, and kept where their stretch overlaps the drawn stretch; those
383
+ * between pieces, in different tiles or across W lines, are `records`, every
384
+ * one of which comes back, as the reader read them over the window and its
385
+ * context. A computed departure's leave and rejoin passes come from the ref
386
+ * rows the cut read, 0 for a node it places off R. A departure within
387
+ * `attachBp` of own sequence that leaves or rejoins on `drawn`, the base of
388
+ * its leave step or of its rejoin step beside the breakpoint lying there,
389
+ * gets its own steps, a 0 bp step included: a record from the leave and
390
+ * rejoin pieces of `runs` or of `attach`, which give nothing else.
391
+ * `unattached` lists those records lacking either piece, whose tiles the
392
+ * reader fetches into `attach`. Any other departure states its ends and its
393
+ * own bp alone.
394
+ */
395
+ export function walkCut(readRuns, nodes, refName, records, options = {}) {
396
+ var _a, _b;
397
+ const { squeeze = (bp) => bp, attach = [], links: linked = true, } = options;
398
+ const { windowStart, windowEnd, passesOf, before, attaches, breakpoint, runs, spans, } = walkSpans(readRuns, nodes, options);
399
+ // the links the steps returned walk, as pairs of handles, each once
400
+ const links = [];
401
+ const linkedTo = new PairSet();
402
+ const linkMemo = {
403
+ from: memoKeys(),
404
+ to: new Float64Array(2 * MEMO_SLOTS).fill(Number.NaN),
405
+ };
406
+ const link = (a, b) => {
407
+ if (linked && linkedTo.add(a, b)) {
408
+ links.push(a, b);
409
+ }
410
+ };
411
+ // links each step of `run` from `from` to `to` to the one before it
412
+ const walk = (run, from, to) => {
413
+ if (linked) {
414
+ linkSteps(run.ids, run.rev, from, to, linkMemo, link);
415
+ }
416
+ };
417
+ const kept = new Set();
418
+ for (const [id, node] of nodes) {
419
+ if (node.onWindow) {
420
+ kept.add(id);
421
+ }
422
+ }
423
+ const lastKept = memoKeys();
424
+ for (const span of spans) {
425
+ keepSteps(span.run.ids, span.first, span.last, kept, lastKept);
426
+ }
427
+ const runEnd = (run) => run.hapOffset + before(run)[run.ids.length];
428
+ // whether a fragment holds step `i` of `run`; a departure's own steps are
429
+ // linked to its leave step and to its rejoin step where one does
430
+ const spansOf = new Map();
431
+ for (const span of spans) {
432
+ const held = (_a = spansOf.get(span.run)) !== null && _a !== void 0 ? _a : [];
433
+ spansOf.set(span.run, held);
434
+ held.push(span);
435
+ }
436
+ const returned = (run, i) => {
437
+ var _a;
438
+ return ((_a = spansOf.get(run)) === null || _a === void 0 ? void 0 : _a.some(({ first, last }) => first <= i && i <= last)) ===
439
+ true;
440
+ };
441
+ const fragments = [];
442
+ for (const { run, first, last } of spans) {
443
+ const { ids, rev } = run;
444
+ const bp = before(run);
445
+ walk(run, first, last);
446
+ const hapStart = run.hapOffset + bp[first];
447
+ const hapEnd = run.hapOffset + bp[last + 1];
448
+ const held = ((_b = run.unloaded) !== null && _b !== void 0 ? _b : []).filter(({ from, to }) => from <= last && to > first);
449
+ const unloadedSteps = held.reduce((sum, { from, to }) => sum + Math.min(to, last + 1) - Math.max(from, first), 0);
450
+ fragments.push({
451
+ name: run.name,
452
+ fragStart: run.fragStart,
453
+ hapStart,
454
+ hapEnd,
455
+ ids: ids.subarray(first, last + 1),
456
+ rev: rev.subarray(first, last + 1),
457
+ refStarts: run.refStarts.subarray(first, last + 1),
458
+ against: run.against.subarray(first, last + 1),
459
+ trimmedBefore: hapStart - run.hapOffset,
460
+ trimmedAfter: runEnd(run) - hapEnd,
461
+ ...(held.length > 0
462
+ ? { abridged: held.map(u => u.piece), unloadedSteps }
463
+ : {}),
464
+ });
465
+ }
466
+ const departures = [];
467
+ const attached = new Map();
468
+ const markAttached = (run, from, to) => {
469
+ var _a;
470
+ const marks = (_a = attached.get(run)) !== null && _a !== void 0 ? _a : new Set();
471
+ attached.set(run, marks);
472
+ for (let k = from; k < to; k++) {
473
+ marks.add(k);
474
+ const id = run.ids[k];
475
+ const slot = id & MEMO_MASK;
476
+ if (lastKept[slot] !== id) {
477
+ lastKept[slot] = id;
478
+ kept.add(id);
479
+ }
480
+ }
481
+ };
482
+ const unloadedIn = (run, from, to) => {
483
+ var _a;
484
+ return ((_a = run.unloaded) !== null && _a !== void 0 ? _a : [])
485
+ .filter(u => u.from < to && u.to > from)
486
+ .map(u => u.piece);
487
+ };
488
+ const pairs = [];
489
+ for (const run of runs) {
490
+ if (run.name === refName) {
491
+ continue;
492
+ }
493
+ const { ids, rev, refStarts, against } = run;
494
+ const bp = before(run);
495
+ const bounds = pieceBounds(run);
496
+ for (let p = 0; p + 1 < bounds.length; p++) {
497
+ pairs.length = 0;
498
+ departingPairs(refStarts, against, bp, bounds[p], bounds[p + 1], squeeze, pairs);
499
+ for (let q = 0; q < pairs.length; q += 2) {
500
+ const last = pairs[q];
501
+ const i = pairs[q + 1];
502
+ const leaveReversed = against[last] === 1;
503
+ const rejoinReversed = against[i] === 1;
504
+ const ends = {
505
+ ownBp: bp[i] - bp[last + 1],
506
+ leavePos: leaveReversed
507
+ ? refStarts[last]
508
+ : refStarts[last] + bp[last + 1] - bp[last],
509
+ leaveReversed,
510
+ rejoinPos: rejoinReversed
511
+ ? refStarts[i] + bp[i + 1] - bp[i]
512
+ : refStarts[i],
513
+ rejoinReversed,
514
+ };
515
+ const [lo, hi] = departureStretch(ends);
516
+ if (lo < windowEnd && hi > windowStart) {
517
+ const d = {
518
+ name: run.name,
519
+ hapStart: run.hapOffset + bp[last + 1],
520
+ ownBp: ends.ownBp,
521
+ missingBp: 0,
522
+ leavePos: ends.leavePos,
523
+ leaveReversed,
524
+ leavePasses: passesOf(ids[last]),
525
+ rejoinPos: ends.rejoinPos,
526
+ rejoinReversed,
527
+ rejoinPasses: passesOf(ids[i]),
528
+ fromSteps: true,
529
+ };
530
+ if (i > last + 1 && attaches(ends)) {
531
+ d.steps = {
532
+ ids: ids.subarray(last + 1, i),
533
+ rev: rev.subarray(last + 1, i),
534
+ };
535
+ const held = unloadedIn(run, last + 1, i);
536
+ if (held.length > 0) {
537
+ d.abridged = held;
538
+ }
539
+ markAttached(run, last + 1, i);
540
+ walk(run, returned(run, last) ? last : last + 1, returned(run, i) ? i : i - 1);
541
+ }
542
+ departures.push(d);
543
+ }
544
+ }
545
+ }
546
+ }
547
+ const { leaves, rejoins } = recordEnds([...runs, ...attach], before, breakpoint);
548
+ const unattached = [];
549
+ for (const record of records) {
550
+ const d = { ...record };
551
+ if (attaches(d)) {
552
+ const ids = [];
553
+ const rev = [];
554
+ const held = [];
555
+ const leave = leaves.get(edgeKey(d.name, d.leavePos, d.leaveReversed, d.hapStart));
556
+ if (leave) {
557
+ const [run, i, end] = leave;
558
+ for (let k = i + 1; k < end; k++) {
559
+ ids.push(run.ids[k]);
560
+ rev.push(run.rev[k]);
561
+ }
562
+ markAttached(run, i + 1, end);
563
+ walk(run, returned(run, i) ? i : i + 1, end - 1);
564
+ for (const piece of unloadedIn(run, i + 1, end)) {
565
+ held.push(piece);
566
+ }
567
+ }
568
+ const rejoin = rejoins.get(edgeKey(d.name, d.rejoinPos, d.rejoinReversed, d.hapStart + d.ownBp));
569
+ if (rejoin) {
570
+ const [run, i, start] = rejoin;
571
+ for (let k = start; k < i; k++) {
572
+ ids.push(run.ids[k]);
573
+ rev.push(run.rev[k]);
574
+ }
575
+ markAttached(run, start, i);
576
+ walk(run, start, returned(run, i) ? i : i - 1);
577
+ for (const piece of unloadedIn(run, start, i)) {
578
+ held.push(piece);
579
+ }
580
+ }
581
+ const oneRun = leave !== undefined &&
582
+ rejoin !== undefined &&
583
+ leave[0].fragStart === rejoin[0].fragStart &&
584
+ pieceOf(leave[0], leave[1]) + 1 === pieceOf(rejoin[0], rejoin[1]) &&
585
+ (leave[2] - 1 > leave[1] || returned(leave[0], leave[1])) &&
586
+ (rejoin[2] < rejoin[1] || returned(rejoin[0], rejoin[1]));
587
+ if (leave && rejoin && oneRun && ids.length > 0) {
588
+ const [left, , end] = leave;
589
+ const [right, , start] = rejoin;
590
+ const last = left.ids[end - 1];
591
+ const next = right.ids[start];
592
+ if (last !== undefined &&
593
+ next !== undefined &&
594
+ last !== SKIPPED &&
595
+ next !== SKIPPED) {
596
+ link(last * 2 + left.rev[end - 1], next * 2 + right.rev[start]);
597
+ }
598
+ }
599
+ if (ids.length > 0) {
600
+ d.steps = { ids: Int32Array.from(ids), rev: Uint8Array.from(rev) };
601
+ if (!oneRun) {
602
+ d.breakAt = leave ? leave[2] - leave[1] - 1 : 0;
603
+ }
604
+ if (held.length > 0) {
605
+ d.abridged = held;
606
+ }
607
+ }
608
+ if (!leave || !rejoin) {
609
+ unattached.push({ departure: record });
610
+ }
611
+ }
612
+ departures.push(d);
613
+ }
614
+ sortByWalk(departures);
615
+ let gaps;
616
+ const gapsOf = () => {
617
+ gaps !== null && gaps !== void 0 ? gaps : (gaps = walkGaps({
618
+ runs,
619
+ attach,
620
+ fragments,
621
+ departures,
622
+ refName,
623
+ before,
624
+ attached,
625
+ breakpoint,
626
+ spans,
627
+ }));
628
+ return gaps;
629
+ };
630
+ return { kept, fragments, departures, unattached, gapsOf, links };
631
+ }
632
+ // The drawn stretch a cut widens the window and its context to, the runs it
633
+ // keeps, split where a contained span's context ends inside a placeholder,
634
+ // and the spans it keeps of them
635
+ function walkSpans(readRuns, nodes, { contained = false, context = 0, attachBp = ATTACH_BP, drawn, placeholder, }) {
636
+ var _a, _b;
637
+ // the drawn stretch: the window and its context, widened to the reference
638
+ // nodes on it, so a window inside a hole in the reference has one
639
+ let windowStart = (_a = drawn === null || drawn === void 0 ? void 0 : drawn.start) !== null && _a !== void 0 ? _a : Infinity;
640
+ let windowEnd = (_b = drawn === null || drawn === void 0 ? void 0 : drawn.end) !== null && _b !== void 0 ? _b : -Infinity;
641
+ for (const node of nodes.values()) {
642
+ if (node.onWindow) {
643
+ windowStart = Math.min(windowStart, node.start);
644
+ windowEnd = Math.max(windowEnd, node.end);
645
+ }
646
+ }
647
+ const length = (id) => {
648
+ const node = nodes.get(id);
649
+ return node === undefined ? 0 : node.end - node.start;
650
+ };
651
+ const passesSeen = memoKeys();
652
+ const passesHeld = new Float64Array(MEMO_SLOTS);
653
+ // each node's passes, which the cut asks of the same few nodes again and
654
+ // again; it changes no node after it first asks
655
+ const passesOf = (id) => {
656
+ var _a, _b;
657
+ const slot = id & MEMO_MASK;
658
+ if (passesSeen[slot] !== id) {
659
+ passesSeen[slot] = id;
660
+ passesHeld[slot] = (_b = (_a = nodes.get(id)) === null || _a === void 0 ? void 0 : _a.passes) !== null && _b !== void 0 ? _b : 0;
661
+ }
662
+ return passesHeld[slot];
663
+ };
664
+ const onR = (run, i) => !Number.isNaN(run.refStarts[i]);
665
+ // bp of a run's steps before each, and after its last
666
+ const prefixes = new Map();
667
+ const before = (run) => {
668
+ let out = prefixes.get(run);
669
+ if (!out) {
670
+ out = bpBefore(run.ids, run.bp, length);
671
+ prefixes.set(run, out);
672
+ }
673
+ return out;
674
+ };
675
+ // a node the reference passes twice is held at one pass, so the other
676
+ // passes come from the steps placed on them
677
+ if (drawn) {
678
+ for (const run of readRuns) {
679
+ const over = stepsOver(run.refStarts, before(run), drawn.start, drawn.end);
680
+ windowStart = Math.min(windowStart, over.lo);
681
+ windowEnd = Math.max(windowEnd, over.hi);
682
+ }
683
+ }
684
+ const attaches = (d) => attachesOwnSteps(d, drawn !== null && drawn !== void 0 ? drawn : { start: windowStart, end: windowEnd }, attachBp);
685
+ const stepOnWindow = (run, i) => {
686
+ const start = run.refStarts[i];
687
+ const bp = before(run);
688
+ return (!Number.isNaN(start) &&
689
+ start < windowEnd &&
690
+ start + bp[i + 1] - bp[i] > windowStart);
691
+ };
692
+ const spans = [];
693
+ // A contained run's spans: each stretch between steps onto the reference
694
+ // off the window that has steps on it, from its first such step to its
695
+ // last, and `context` bp of the walk past either: whole steps, but of a
696
+ // placeholder only the bp left, which is where to split it
697
+ const containedSpans = (run) => {
698
+ const { ids } = run;
699
+ const bp = before(run);
700
+ const found = [];
701
+ const splits = [];
702
+ const take = (i, left, tail) => {
703
+ const stepBp = bp[i + 1] - bp[i];
704
+ if (stepBp > left && ids[i] < 0 && ids[i] !== SKIPPED) {
705
+ splits.push({ at: i, keep: left, tail });
706
+ }
707
+ return left - stepBp;
708
+ };
709
+ let from = 0;
710
+ let first = -1;
711
+ let last = -1;
712
+ for (let i = 0; i <= ids.length; i++) {
713
+ const on = i < ids.length && stepOnWindow(run, i);
714
+ if (i === ids.length || ids[i] === SKIPPED || (onR(run, i) && !on)) {
715
+ if (first >= 0) {
716
+ for (let left = context; first > from && left > 0;) {
717
+ left = take(--first, left, true);
718
+ }
719
+ for (let left = context; last < i - 1 && left > 0;) {
720
+ left = take(++last, left, false);
721
+ }
722
+ found.push({ run, first, last });
723
+ }
724
+ from = i + 1;
725
+ first = -1;
726
+ }
727
+ else if (on) {
728
+ if (first < 0) {
729
+ first = i;
730
+ }
731
+ last = i;
732
+ }
733
+ }
734
+ return { found, splits };
735
+ };
736
+ // `run` with each split placeholder as two, the part within a span's
737
+ // context and the rest
738
+ const splitRun = (run, splits, mint) => {
739
+ var _a, _b;
740
+ const bp = before(run);
741
+ const n = run.ids.length + splits.length;
742
+ const ids = new Int32Array(n);
743
+ const rev = new Uint8Array(n);
744
+ const refStarts = new Float64Array(n).fill(Number.NaN);
745
+ const against = new Uint8Array(n);
746
+ const stepBp = new Int32Array(n);
747
+ const shifted = new Int32Array(run.ids.length + 1);
748
+ let s = 0;
749
+ let out = 0;
750
+ for (let i = 0; i < run.ids.length; i++) {
751
+ shifted[i] = out;
752
+ const split = splits[s];
753
+ const start = run.hapOffset + bp[i];
754
+ const end = run.hapOffset + bp[i + 1];
755
+ if ((split === null || split === void 0 ? void 0 : split.at) === i) {
756
+ s++;
757
+ const edge = split.tail ? end - split.keep : start + split.keep;
758
+ const part = (a, b) => {
759
+ const id = mint(run.name, a, b);
760
+ nodes.set(id, {
761
+ refName: run.name,
762
+ start: a,
763
+ end: b,
764
+ rank: 1,
765
+ passes: 0,
766
+ onWindow: false,
767
+ placeholder: true,
768
+ });
769
+ ids[out] = id;
770
+ stepBp[out++] = b - a;
771
+ };
772
+ part(start, edge);
773
+ part(edge, end);
774
+ }
775
+ else {
776
+ ids[out] = run.ids[i];
777
+ rev[out] = run.rev[i];
778
+ refStarts[out] = run.refStarts[i];
779
+ against[out] = run.against[i];
780
+ stepBp[out++] = end - start;
781
+ }
782
+ }
783
+ shifted[run.ids.length] = out;
784
+ return {
785
+ ...run,
786
+ ids,
787
+ rev,
788
+ refStarts,
789
+ against,
790
+ bp: stepBp,
791
+ pieceStarts: run.pieceStarts.map(at => shifted[at]),
792
+ unloaded: (_a = run.unloaded) === null || _a === void 0 ? void 0 : _a.map(u => ({
793
+ ...u,
794
+ from: shifted[u.from],
795
+ to: shifted[u.to],
796
+ })),
797
+ own: (_b = run.own) === null || _b === void 0 ? void 0 : _b.map(steps => ({
798
+ ...steps,
799
+ from: shifted[steps.from],
800
+ to: shifted[steps.to],
801
+ })),
802
+ };
803
+ };
804
+ const stretchSpan = (run) => {
805
+ const { first, last } = stepsOver(run.refStarts, before(run), windowStart, windowEnd);
806
+ if (first >= 0) {
807
+ spans.push({ run, first, last });
808
+ }
809
+ };
810
+ const runs = readRuns.map(run => {
811
+ const scan = contained ? containedSpans(run) : undefined;
812
+ const split = scan && placeholder && scan.splits.length > 0
813
+ ? splitRun(run, scan.splits, placeholder)
814
+ : run;
815
+ if (!scan) {
816
+ stretchSpan(run);
817
+ }
818
+ else {
819
+ for (const span of split === run
820
+ ? scan.found
821
+ : containedSpans(split).found) {
822
+ spans.push(span);
823
+ }
824
+ }
825
+ return split;
826
+ });
827
+ // A step's breakpoint on R: where the path's sequence stops following R,
828
+ // the node's end for a step along R and its start for one against it, and
829
+ // the other way round for a rejoin
830
+ const breakpoint = (run, i, leave) => {
831
+ const reversed = run.against[i] === 1;
832
+ const start = run.refStarts[i];
833
+ return {
834
+ pos: reversed === leave
835
+ ? start
836
+ : start + before(run)[i + 1] - before(run)[i],
837
+ reversed,
838
+ };
839
+ };
840
+ return {
841
+ windowStart,
842
+ windowEnd,
843
+ passesOf,
844
+ before,
845
+ attaches,
846
+ breakpoint,
847
+ runs,
848
+ spans,
849
+ };
850
+ }
851
+ // A record's own steps: those after its leave step to the end of that
852
+ // piece, then those before its rejoin step from the start of its piece. A
853
+ // leave step is the last step on R of its piece and a rejoin step the
854
+ // first of its, so the cut indexes by name, breakpoint and contig position
855
+ // each piece's last step on R and where the piece ends, and its first and
856
+ // where the piece starts
857
+ function recordEnds(runs, before, breakpoint) {
858
+ var _a;
859
+ const leaves = new Map();
860
+ const rejoins = new Map();
861
+ for (const run of runs) {
862
+ const bp = before(run);
863
+ const bounds = pieceBounds(run);
864
+ for (let p = 0; p + 1 < bounds.length; p++) {
865
+ const first = firstOnR(run.refStarts, bounds[p], bounds[p + 1]);
866
+ const last = lastOnR(run.refStarts, bounds[p], bounds[p + 1]);
867
+ if (first < 0) {
868
+ continue;
869
+ }
870
+ const leave = breakpoint(run, last, true);
871
+ leaves.set(edgeKey(run.name, leave.pos, leave.reversed, run.hapOffset + bp[last + 1]), [run, last, bounds[p + 1]]);
872
+ const rejoin = breakpoint(run, first, false);
873
+ rejoins.set(edgeKey(run.name, rejoin.pos, rejoin.reversed, run.hapOffset + bp[first]), [run, first, bounds[p]]);
874
+ }
875
+ }
876
+ for (const run of runs) {
877
+ for (const { key, leave, from, to } of (_a = run.own) !== null && _a !== void 0 ? _a : []) {
878
+ if (leave) {
879
+ leaves.set(key, [run, from - 1, to]);
880
+ }
881
+ else {
882
+ rejoins.set(key, [run, to, from]);
883
+ }
884
+ }
885
+ }
886
+ return { leaves, rejoins };
887
+ }
888
+ // The records walkCut lists as unattached, found without cutting: those it
889
+ // attaches own steps for that lack their leave piece or their rejoin piece
890
+ export function unattachedRecords(readRuns, nodes, records, options = {}) {
891
+ const { runs, before, attaches, breakpoint } = walkSpans(readRuns, nodes, options);
892
+ const { leaves, rejoins } = recordEnds(runs, before, breakpoint);
893
+ return records.filter(d => attaches(d) &&
894
+ (!leaves.has(edgeKey(d.name, d.leavePos, d.leaveReversed, d.hapStart)) ||
895
+ !rejoins.has(edgeKey(d.name, d.rejoinPos, d.rejoinReversed, d.hapStart + d.ownBp))));
896
+ }
897
+ // Sorts departures by name, then contig position, then where each leaves R,
898
+ // ties in the order given, comparing numbers: each name by its rank. Names
899
+ // come in long runs, so each is looked up once a run
900
+ function sortByWalk(departures) {
901
+ const n = departures.length;
902
+ const names = new Set();
903
+ let last;
904
+ for (const { name } of departures) {
905
+ if (name !== last) {
906
+ names.add(name);
907
+ last = name;
908
+ }
909
+ }
910
+ const rank = new Map([...names].sort().map((name, k) => [name, k]));
911
+ const ranks = new Float64Array(n);
912
+ const haps = new Float64Array(n);
913
+ const leaves = new Float64Array(n);
914
+ let lastRank = 0;
915
+ last = undefined;
916
+ departures.forEach((d, k) => {
917
+ if (d.name !== last) {
918
+ lastRank = rank.get(d.name);
919
+ last = d.name;
920
+ }
921
+ ranks[k] = lastRank;
922
+ haps[k] = d.hapStart;
923
+ leaves[k] = d.leavePos;
924
+ });
925
+ const order = Array.from(departures.keys()).sort((a, b) => ranks[a] - ranks[b] ||
926
+ haps[a] - haps[b] ||
927
+ leaves[a] - leaves[b] ||
928
+ a - b);
929
+ const sorted = order.map(k => departures[k]);
930
+ sorted.forEach((d, k) => {
931
+ departures[k] = d;
932
+ });
933
+ }
934
+ const pieceOf = (run, step) => run.firstPiece + run.pieceStarts.filter(start => start <= step).length;
935
+ // Where each of a run's pieces starts, and where the last ends
936
+ function pieceBounds(run) {
937
+ const bounds = [0];
938
+ for (const start of run.pieceStarts) {
939
+ bounds.push(start);
940
+ }
941
+ bounds.push(run.ids.length);
942
+ return bounds;
943
+ }
944
+ /**
945
+ * Adds to `into` the nodes of decoded rows that walkCut keeps whatever else
946
+ * the cut reads: those of `chunk.nodes` on the window, and those a row steps
947
+ * on between two of its steps on the window, `start`-`end` with its context,
948
+ * with no step onto the reference off the window between them in a contained
949
+ * cut. A node placed later at a reference position off the window can split a
950
+ * contained walk, so the count holds for the placements at the time. A
951
+ * placeholder is no node, and is counted in `placeholders` where a row steps
952
+ * on it between two such steps.
953
+ */
954
+ export function surelyKept(chunk, nodes, { contained, start, end }, into, placeholders) {
955
+ var _a;
956
+ for (const id of chunk.nodes.keys()) {
957
+ if (((_a = nodes.get(id)) === null || _a === void 0 ? void 0 : _a.onWindow) === true) {
958
+ into.add(id);
959
+ }
960
+ }
961
+ for (const { steps } of chunk.rows) {
962
+ const { ids, refStarts } = steps;
963
+ let last = -1;
964
+ for (let i = 0; i < ids.length; i++) {
965
+ const node = nodes.get(ids[i]);
966
+ const at = refStarts === null || refStarts === void 0 ? void 0 : refStarts[i];
967
+ const onR = at !== undefined && !Number.isNaN(at);
968
+ if ((node === null || node === void 0 ? void 0 : node.onWindow) === true &&
969
+ onR &&
970
+ at < end &&
971
+ at + node.end - node.start > start) {
972
+ if (last >= 0) {
973
+ for (let j = last + 1; j < i; j++) {
974
+ const id = ids[j];
975
+ if (!isPlaceholder(id)) {
976
+ into.add(id);
977
+ }
978
+ else if (id !== SKIPPED) {
979
+ placeholders === null || placeholders === void 0 ? void 0 : placeholders.add(id);
980
+ }
981
+ }
982
+ }
983
+ last = i;
984
+ }
985
+ else if (contained && onR) {
986
+ last = -1;
987
+ }
988
+ }
989
+ }
990
+ }
991
+ // A run of a walk's steps by its walk and its stretch of the contig, which no
992
+ // node's name is
993
+ export const runName = (name, start, end) => `${name}:${start}-${end}`;
994
+ // The places of a fragment's `n` steps it states: none from a host's fragment
995
+ // without `refStarts`, and none past its steps from one whose `refStarts` runs
996
+ // on
997
+ const statedPlaces = (placed, n) => { var _a; return (_a = placed === null || placed === void 0 ? void 0 : placed.subarray(0, n)) !== null && _a !== void 0 ? _a : new Float64Array(); };
998
+ // A node's name in the tables: its id, or for a placeholder its run's name
999
+ const nodeName = (id, node) => (node === null || node === void 0 ? void 0 : node.placeholder) ? runName(node.refName, node.start, node.end) : String(id);
1000
+ // Whether placement `node` beats `held`: a pass of the reference over the
1001
+ // window beats any other, then a reference position beats one off it, and
1002
+ // among equals the path sorting first at its earliest start wins, so the order
1003
+ // a cut reads chunks in does not matter
1004
+ const outranks = (node, held) => node.onWindow !== held.onWindow
1005
+ ? node.onWindow
1006
+ : node.rank === 0 &&
1007
+ (held.rank !== 0 ||
1008
+ node.refName < held.refName ||
1009
+ (node.refName === held.refName && node.start < held.start));
1010
+ /**
1011
+ * The nodes and links of the chunks a cut reads, and the tables of the cut
1012
+ * they make with its walks. A node in two chunks is placed once.
1013
+ */
1014
+ export class WalkGraph {
1015
+ constructor(window, revisited = Number.NaN) {
1016
+ this.nodes = new Map();
1017
+ this.sequences = new Map();
1018
+ this.links = [];
1019
+ this.window = window;
1020
+ this.revisited = revisited;
1021
+ }
1022
+ // A node with its position, unless the cut already holds it at one that
1023
+ // outranks it
1024
+ placeNode(id, node) {
1025
+ const { window } = this;
1026
+ const placed = {
1027
+ ...node,
1028
+ onWindow: node.rank === 0 &&
1029
+ node.refName === window.refName &&
1030
+ node.end > window.start - window.context &&
1031
+ node.start < window.end + window.context,
1032
+ };
1033
+ const held = this.nodes.get(id);
1034
+ if (!held || outranks(placed, held)) {
1035
+ this.nodes.set(id, placed);
1036
+ }
1037
+ }
1038
+ // A link between two endpoints, each id * 2 + 1 when reversed
1039
+ addLinkEnds(source, target) {
1040
+ this.links.push(source, target);
1041
+ }
1042
+ // Bases of nodes a chunk's rows give, for a window that asks for them
1043
+ addSequences(sequences) {
1044
+ if (this.window.sequences === true) {
1045
+ for (const [id, bases] of sequences) {
1046
+ this.sequences.set(id, bases);
1047
+ }
1048
+ }
1049
+ }
1050
+ /**
1051
+ * The cut as typed arrays, which the worker transfers rather than copies:
1052
+ * nodes by reference position, each link once in the order its L line
1053
+ * sorts, then a walk per fragment, the reference's first and the rest by
1054
+ * name, and the departures with their own steps. graphTablesGFA writes
1055
+ * them as the GFA they stand for, the same bytes for the same rows.
1056
+ */
1057
+ tables(kept, fragments, departures, gaps = []) {
1058
+ this.placeOffReference(kept, fragments, departures);
1059
+ const held = [];
1060
+ for (const id of kept) {
1061
+ const node = this.nodes.get(id);
1062
+ if (node) {
1063
+ held.push({ ...node, id });
1064
+ }
1065
+ }
1066
+ held.sort((x, y) => x.refName < y.refName
1067
+ ? -1
1068
+ : x.refName > y.refName
1069
+ ? 1
1070
+ : x.start - y.start || x.id - y.id);
1071
+ const index = new Map();
1072
+ const names = [];
1073
+ const refNames = [];
1074
+ const refIndex = new Map();
1075
+ const lengths = new Int32Array(held.length);
1076
+ const refs = new Int32Array(held.length);
1077
+ const starts = new Float64Array(held.length);
1078
+ const ranks = new Int32Array(held.length);
1079
+ const passes = new Int32Array(held.length);
1080
+ const placeholders = Uint8Array.from(held, node => node.placeholder ? 1 : 0);
1081
+ const reversedOnReference = Uint8Array.from(held, node => node.reversed === true ? 1 : 0);
1082
+ held.forEach((node, i) => {
1083
+ const { id, refName, start, end, rank, passes: n } = node;
1084
+ index.set(id, i);
1085
+ names.push(nodeName(id, node));
1086
+ let ref = refIndex.get(refName);
1087
+ if (ref === undefined) {
1088
+ ref = refNames.length;
1089
+ refIndex.set(refName, ref);
1090
+ refNames.push(refName);
1091
+ }
1092
+ lengths[i] = end - start;
1093
+ refs[i] = ref;
1094
+ starts[i] = start;
1095
+ ranks[i] = rank;
1096
+ passes[i] = n;
1097
+ });
1098
+ // a kept node with no row of its own is named, and not drawn
1099
+ const lastId = memoKeys();
1100
+ const lastIndex = new Int32Array(MEMO_SLOTS);
1101
+ const indexOf = (id) => {
1102
+ let i = index.get(id);
1103
+ if (i === undefined) {
1104
+ i = names.length;
1105
+ index.set(id, i);
1106
+ names.push(nodeName(id, this.nodes.get(id)));
1107
+ }
1108
+ return i;
1109
+ };
1110
+ const nodeIndex = (id) => {
1111
+ const slot = id & MEMO_MASK;
1112
+ if (lastId[slot] !== id) {
1113
+ lastId[slot] = id;
1114
+ lastIndex[slot] = indexOf(id);
1115
+ }
1116
+ return lastIndex[slot];
1117
+ };
1118
+ const lines = linkLines(this.links, kept);
1119
+ const from = new Int32Array(lines.length / 2);
1120
+ const to = new Int32Array(lines.length / 2);
1121
+ const strands = new Uint8Array(lines.length / 2);
1122
+ for (let k = 0; k < lines.length; k += 2) {
1123
+ const a = lines[k];
1124
+ const b = lines[k + 1];
1125
+ from[k / 2] = nodeIndex(Math.floor(a / 2));
1126
+ to[k / 2] = nodeIndex(Math.floor(b / 2));
1127
+ strands[k / 2] = (a & 1) | ((b & 1) << 1);
1128
+ }
1129
+ const walks = this.referenceFirst(fragments);
1130
+ // a piece counts on the first walk holding it, else on the first
1131
+ // departure
1132
+ const counted = new Set();
1133
+ const stepsOf = (pieces) => {
1134
+ let steps = pieces ? 0 : Number.NaN;
1135
+ for (const piece of pieces !== null && pieces !== void 0 ? pieces : []) {
1136
+ if (!counted.has(piece)) {
1137
+ counted.add(piece);
1138
+ steps += piece.steps;
1139
+ }
1140
+ }
1141
+ return steps;
1142
+ };
1143
+ const abridgedSteps = Float64Array.from(walks, f => stepsOf(f.abridged));
1144
+ const offsets = new Int32Array(walks.length + 1);
1145
+ walks.forEach(({ ids }, p) => {
1146
+ offsets[p + 1] = offsets[p] + ids.length;
1147
+ });
1148
+ const steps = new Int32Array(offsets[walks.length]);
1149
+ const reversed = new Uint8Array(steps.length);
1150
+ const refStarts = new Float64Array(steps.length).fill(Number.NaN);
1151
+ walks.forEach(({ ids, rev, refStarts: placed }, p) => {
1152
+ const at = offsets[p];
1153
+ indexSteps(ids, steps, at, lastId, lastIndex, indexOf);
1154
+ reversed.set(rev, at);
1155
+ refStarts.set(statedPlaces(placed, ids.length), at);
1156
+ });
1157
+ return {
1158
+ nodes: {
1159
+ names,
1160
+ lengths,
1161
+ refs,
1162
+ starts,
1163
+ ranks,
1164
+ refNames,
1165
+ passes,
1166
+ reversed: reversedOnReference,
1167
+ placeholders,
1168
+ },
1169
+ links: { from, to, strands },
1170
+ walks: {
1171
+ names: walks.map(f => f.name),
1172
+ starts: Float64Array.from(walks, f => f.hapStart),
1173
+ ends: Float64Array.from(walks, f => f.hapEnd),
1174
+ offsets,
1175
+ steps,
1176
+ reversed,
1177
+ refStarts,
1178
+ trimmedBefore: Float64Array.from(walks, f => f.trimmedBefore),
1179
+ trimmedAfter: Float64Array.from(walks, f => f.trimmedAfter),
1180
+ abridgedSteps,
1181
+ },
1182
+ departures: departureTable(departures, nodeIndex, stepsOf),
1183
+ gaps: gapTable(gaps, new Map(walks.map((f, p) => [f, p])), nodeIndex),
1184
+ revisited: this.revisited,
1185
+ };
1186
+ }
1187
+ placeOffReference(kept, fragments, departures) {
1188
+ var _a;
1189
+ const lengthOf = (id) => {
1190
+ const node = this.nodes.get(id);
1191
+ return node ? node.end - node.start : 0;
1192
+ };
1193
+ const placed = new Map();
1194
+ // the ids no walk places, with their lengths: those on the reference,
1195
+ // placeholders, and those the cut does not keep
1196
+ const passedId = memoKeys();
1197
+ const passedLength = new Float64Array(MEMO_SLOTS);
1198
+ const visit = (name, ids, start) => {
1199
+ let at = start;
1200
+ for (const id of ids) {
1201
+ const slot = id & MEMO_MASK;
1202
+ if (passedId[slot] === id) {
1203
+ at += passedLength[slot];
1204
+ }
1205
+ else {
1206
+ const node = this.nodes.get(id);
1207
+ const length = node ? node.end - node.start : 0;
1208
+ if (node && node.rank !== 0 && !node.placeholder && kept.has(id)) {
1209
+ const held = placed.get(id);
1210
+ if (!held ||
1211
+ name < held.refName ||
1212
+ (name === held.refName && at < held.start)) {
1213
+ placed.set(id, {
1214
+ ...node,
1215
+ refName: name,
1216
+ start: at,
1217
+ end: at + length,
1218
+ });
1219
+ }
1220
+ }
1221
+ else {
1222
+ passedId[slot] = id;
1223
+ passedLength[slot] = length;
1224
+ }
1225
+ at += length;
1226
+ }
1227
+ }
1228
+ };
1229
+ for (const f of fragments) {
1230
+ visit(f.name, f.ids, f.hapStart);
1231
+ }
1232
+ for (const d of departures) {
1233
+ if (d.steps) {
1234
+ const { ids } = d.steps;
1235
+ const leaving = ids.subarray(0, (_a = d.breakAt) !== null && _a !== void 0 ? _a : ids.length);
1236
+ const rejoining = ids.subarray(leaving.length);
1237
+ const rejoiningBp = rejoining.reduce((sum, id) => sum + lengthOf(id), 0);
1238
+ visit(d.name, leaving, d.hapStart);
1239
+ visit(d.name, rejoining, d.hapStart + d.ownBp - rejoiningBp);
1240
+ }
1241
+ }
1242
+ for (const [id, node] of placed) {
1243
+ this.nodes.set(id, node);
1244
+ }
1245
+ }
1246
+ // The view anchors on the first walk when no walk names the assembly, as
1247
+ // gbz-base's cut has it; in file order that was whichever haplotype the
1248
+ // chunk listed first, CHM13 on a GRCh38 window
1249
+ referenceFirst(fragments) {
1250
+ const { refName } = this.window;
1251
+ return [...fragments].sort((a, b) => Number(b.name === refName) - Number(a.name === refName) ||
1252
+ (a.name < b.name ? -1 : a.name > b.name ? 1 : a.hapStart - b.hapStart));
1253
+ }
1254
+ }
1255
+ function gapTable(gaps, walkIndex, nodeIndex) {
1256
+ const segments = gaps.flatMap(g => g.segments);
1257
+ const segmentOffsets = new Int32Array(gaps.length + 1);
1258
+ gaps.forEach((g, k) => {
1259
+ segmentOffsets[k + 1] = segmentOffsets[k] + g.segments.length;
1260
+ });
1261
+ const stepOffsets = new Int32Array(segments.length + 1);
1262
+ segments.forEach((x, k) => {
1263
+ stepOffsets[k + 1] = stepOffsets[k] + x.ids.length;
1264
+ });
1265
+ const steps = new Int32Array(stepOffsets[segments.length]);
1266
+ const reversed = new Uint8Array(steps.length);
1267
+ segments.forEach((x, k) => {
1268
+ const at = stepOffsets[k];
1269
+ x.ids.forEach((id, j) => {
1270
+ steps[at + j] = nodeIndex(id);
1271
+ });
1272
+ reversed.set(x.rev, at);
1273
+ });
1274
+ return {
1275
+ names: gaps.map(g => g.name),
1276
+ walks: Int32Array.from(gaps, g => { var _a; return g.fragment ? ((_a = walkIndex.get(g.fragment)) !== null && _a !== void 0 ? _a : -1) : -1; }),
1277
+ edges: Uint8Array.from(gaps, g => g.edge),
1278
+ starts: Float64Array.from(gaps, g => g.start),
1279
+ ends: Float64Array.from(gaps, g => g.end),
1280
+ segmentOffsets,
1281
+ segments: {
1282
+ kinds: Uint8Array.from(segments, x => GAP_KINDS.indexOf(x.kind)),
1283
+ bp: Float64Array.from(segments, x => x.bp),
1284
+ missingBp: Float64Array.from(segments, x => x.missingBp),
1285
+ before: Float64Array.from(segments, x => x.before),
1286
+ after: Float64Array.from(segments, x => x.after),
1287
+ stepOffsets,
1288
+ steps,
1289
+ reversed,
1290
+ },
1291
+ };
1292
+ }
1293
+ function departureTable(departures, nodeIndex, stepsOf) {
1294
+ var _a;
1295
+ const n = departures.length;
1296
+ const offsets = new Int32Array(n + 1);
1297
+ departures.forEach((d, k) => {
1298
+ var _a, _b;
1299
+ offsets[k + 1] = offsets[k] + ((_b = (_a = d.steps) === null || _a === void 0 ? void 0 : _a.ids.length) !== null && _b !== void 0 ? _b : 0);
1300
+ });
1301
+ const steps = new Int32Array(offsets[n]);
1302
+ const reversed = new Uint8Array(steps.length);
1303
+ departures.forEach((d, k) => {
1304
+ if (d.steps) {
1305
+ const at = offsets[k];
1306
+ for (let j = 0; j < d.steps.ids.length; j++) {
1307
+ steps[at + j] = nodeIndex(d.steps.ids[j]);
1308
+ }
1309
+ reversed.set(d.steps.rev, at);
1310
+ }
1311
+ });
1312
+ const names = new Array(n);
1313
+ const hapStarts = new Float64Array(n);
1314
+ const ownBp = new Float64Array(n);
1315
+ const missingBp = new Float64Array(n);
1316
+ const leavePos = new Float64Array(n);
1317
+ const leaveReversed = new Uint8Array(n);
1318
+ const leavePasses = new Int32Array(n);
1319
+ const rejoinPos = new Float64Array(n);
1320
+ const rejoinReversed = new Uint8Array(n);
1321
+ const rejoinPasses = new Int32Array(n);
1322
+ const fromSteps = new Uint8Array(n);
1323
+ const breakAt = new Int32Array(n);
1324
+ const abridgedSteps = new Float64Array(n);
1325
+ for (let k = 0; k < n; k++) {
1326
+ const d = departures[k];
1327
+ names[k] = d.name;
1328
+ hapStarts[k] = d.hapStart;
1329
+ ownBp[k] = d.ownBp;
1330
+ missingBp[k] = d.missingBp;
1331
+ leavePos[k] = d.leavePos;
1332
+ leaveReversed[k] = d.leaveReversed ? 1 : 0;
1333
+ leavePasses[k] = d.leavePasses;
1334
+ rejoinPos[k] = d.rejoinPos;
1335
+ rejoinReversed[k] = d.rejoinReversed ? 1 : 0;
1336
+ rejoinPasses[k] = d.rejoinPasses;
1337
+ fromSteps[k] = d.fromSteps ? 1 : 0;
1338
+ breakAt[k] = (_a = d.breakAt) !== null && _a !== void 0 ? _a : -1;
1339
+ abridgedSteps[k] = stepsOf(d.abridged);
1340
+ }
1341
+ return {
1342
+ names,
1343
+ hapStarts,
1344
+ ownBp,
1345
+ missingBp,
1346
+ leavePos,
1347
+ leaveReversed,
1348
+ leavePasses,
1349
+ rejoinPos,
1350
+ rejoinReversed,
1351
+ rejoinPasses,
1352
+ fromSteps,
1353
+ breakAt,
1354
+ offsets,
1355
+ steps,
1356
+ reversed,
1357
+ abridgedSteps,
1358
+ };
1359
+ }
1360
+ export const BUDGET_NAMES = {
1361
+ steps: 'the step budget',
1362
+ bytes: 'a byte budget of',
1363
+ };
1364
+ // The reader decodes a step along R several times as fast as one off it, so
1365
+ // the read budget counts it as a quarter
1366
+ const ALONG_R_PER_STEP = 4;
1367
+ export const readSteps = (row) => {
1368
+ var _a;
1369
+ const interior = (_a = row.interior) !== null && _a !== void 0 ? _a : 0;
1370
+ return interior + (row.n - interior) / ALONG_R_PER_STEP;
1371
+ };
1372
+ /**
1373
+ * The zoom-in notice for a cut whose walk rows hold more steps than
1374
+ * `readPerKept` times `stepBudget`, or undefined when they fit. A window reads
1375
+ * whole tiles, so the span that fits is counted in tiles of `tile` bp from
1376
+ * the window's start; when the tiles a window there always reads are over on
1377
+ * their own, no zoom fits and the notice asks for fewer
1378
+ * haplotypes. A cut for every haplotype is also offered fewer where the
1379
+ * reference and one haplotype, at the walks' average steps, would fit the
1380
+ * whole window.
1381
+ */
1382
+ export function stepBudgetError(rows, stepBudget, readPerKept, window, tile, filtered, names = BUDGET_NAMES) {
1383
+ const budget = stepBudget * readPerKept;
1384
+ const over = readStepsOver(rows, budget, window, tile);
1385
+ const fewerFit = over !== undefined &&
1386
+ !filtered &&
1387
+ over.walks > 2 &&
1388
+ (2 * over.total) / over.walks <= budget;
1389
+ return over
1390
+ ? new RegionTooLargeError(over.fitsBp > 0
1391
+ ? `Zoom in to about ${bpString(over.fitsBp)}${fewerFit ? ', or choose fewer haplotypes,' : ''} to see the graph`
1392
+ : `Too many haplotype steps here to draw ${filtered ? 'these haplotypes' : 'every haplotype'} (${Math.round(over.read).toLocaleString()} steps read, a step along the reference counting a quarter, over ${readPerKept} × ${names.steps} of ${stepBudget.toLocaleString()}); choose fewer haplotypes`, budget, window.end - window.start, Math.max(over.fitsBp, 1))
1393
+ : undefined;
1394
+ }
1395
+ export function countStepsError(rows, stepBudget, readPerKept, window, tile, names = BUDGET_NAMES) {
1396
+ const over = readStepsOver(rows, stepBudget * readPerKept, window, tile);
1397
+ return over
1398
+ ? new RegionTooLargeError(`Too many haplotype steps in this window to count: its walk rows hold ${Math.round(over.total).toLocaleString()} steps, a step along the reference counting a quarter, over ${readPerKept} × ${names.steps} of ${stepBudget.toLocaleString()}. ${over.fitsBp > 0 ? `Count a window of about ${bpString(over.fitsBp)} or less, or leave this one uncounted` : `Its first tile alone is over, so leave this window uncounted or raise ${names.steps}`}`, stepBudget * readPerKept, window.end - window.start, Math.max(over.fitsBp, 1))
1399
+ : undefined;
1400
+ }
1401
+ function readStepsOver(rows, budget, window, tile) {
1402
+ var _a;
1403
+ let total = 0;
1404
+ const perChunk = new Map();
1405
+ const walks = new Set();
1406
+ for (const row of rows) {
1407
+ const steps = readSteps(row);
1408
+ total += steps;
1409
+ perChunk.set(row.chunkStart, ((_a = perChunk.get(row.chunkStart)) !== null && _a !== void 0 ? _a : 0) + steps);
1410
+ walks.add(row.name);
1411
+ }
1412
+ let read = 0;
1413
+ let fitsBp = 0;
1414
+ for (const cs of [...perChunk.keys()].sort((a, b) => a - b)) {
1415
+ read += perChunk.get(cs);
1416
+ if (read > budget) {
1417
+ break;
1418
+ }
1419
+ fitsBp = Math.max(fitsBp, cs + tile - window.start);
1420
+ }
1421
+ return total > budget ? { total, read, fitsBp, walks: walks.size } : undefined;
1422
+ }
1423
+ /**
1424
+ * The zoom-in notice for a cut that keeps more steps than `budget`, the
1425
+ * fragments' and the departures' attached steps together, or undefined when
1426
+ * it fits. The span that fits is the window scaled by how far over the cut
1427
+ * is. A step built for a piece the cut did not load counts as any other.
1428
+ */
1429
+ export function keptStepsError(fragments, departures, budget, window, filtered) {
1430
+ const total = fragments.reduce((sum, f) => sum + f.ids.length, 0) +
1431
+ departures.reduce((sum, d) => { var _a, _b; return sum + ((_b = (_a = d.steps) === null || _a === void 0 ? void 0 : _a.ids.length) !== null && _b !== void 0 ? _b : 0); }, 0);
1432
+ return keptOverError(total, budget, window, filtered);
1433
+ }
1434
+ // keptStepsError's notice for a cut that keeps more nodes than `limit`, which
1435
+ // it counted on the window before `readTo` when it stopped reading there
1436
+ export function keptNodesError(nodes, limit, window, filtered, readTo = window.end) {
1437
+ return keptOverError(nodes, limit, window, filtered, readTo);
1438
+ }
1439
+ function keptOverError(kept, limit, window, filtered, readTo = window.end) {
1440
+ const readBp = Math.min(readTo, window.end) - window.start;
1441
+ return kept > limit
1442
+ ? zoomInError(Math.floor((readBp * limit) / kept), limit, window, filtered)
1443
+ : undefined;
1444
+ }
1445
+ function zoomInError(fitsBp, limit, window, filtered) {
1446
+ const fits = Math.max(1, fitsBp);
1447
+ return new RegionTooLargeError(`Zoom in to about ${bpString(fits)}${filtered ? '' : ', or choose fewer haplotypes,'} to see the graph`, limit, window.end - window.start, fits);
1448
+ }
1449
+ /**
1450
+ * keptStepsError's notice given before a cut decodes its tiles, or undefined
1451
+ * where the steps it surely keeps of the tiles it counted (tileSteps in
1452
+ * walkChunk.ts, `steps` here) fit `budget`. `tiles` are the window's tiles in
1453
+ * order, those not counted with no `steps`. The span that fits is worked out
1454
+ * tile by tile from the start of the window's `context`: a counted tile holds
1455
+ * its steps evenly over its extent, a tile not counted holds the counted
1456
+ * tiles' steps per bp, and a stretch no tile covers holds none. Where those
1457
+ * steps reach the budget is where the context of the span that fits ends,
1458
+ * before the last counted tile ends and so before the window's context does:
1459
+ * the span is narrower than the window. A tile's `likely`, no fewer than its
1460
+ * `steps`, is what the cut is expected to keep of it where `steps` counts a
1461
+ * part: the span is worked out from it, and the refusal from `steps` alone.
1462
+ */
1463
+ export function surelyKeptError(tiles, budget, window, context, filtered) {
1464
+ var _a;
1465
+ let steps = 0;
1466
+ let likely = 0;
1467
+ let bp = 0;
1468
+ for (const tile of tiles) {
1469
+ if (tile.steps !== undefined) {
1470
+ steps += tile.steps;
1471
+ likely += Math.max(tile.steps, (_a = tile.likely) !== null && _a !== void 0 ? _a : 0);
1472
+ bp += tile.end - tile.start;
1473
+ }
1474
+ }
1475
+ const drawn = {
1476
+ start: Math.max(0, window.start - context),
1477
+ end: window.end + context,
1478
+ };
1479
+ return steps > budget
1480
+ ? zoomInError(budgetReach(tiles.map(tile => {
1481
+ var _a;
1482
+ return tile.steps === undefined
1483
+ ? tile
1484
+ : { ...tile, steps: Math.max(tile.steps, (_a = tile.likely) !== null && _a !== void 0 ? _a : 0) };
1485
+ }), bp > 0 ? likely / bp : 0, budget, drawn) -
1486
+ context -
1487
+ window.start, budget, window, filtered)
1488
+ : undefined;
1489
+ }
1490
+ // Where on `drawn` the steps of `tiles` from its start reach `budget`, each
1491
+ // tile's spread evenly over its extent, `perBp` a tile's with no steps of its
1492
+ // own; the end of `drawn` where they don't
1493
+ function budgetReach(tiles, perBp, budget, drawn) {
1494
+ let held = 0;
1495
+ let reach;
1496
+ for (const tile of tiles) {
1497
+ const from = Math.max(tile.start, drawn.start);
1498
+ const bp = Math.max(0, Math.min(tile.end, drawn.end) - from);
1499
+ const share = tile.steps === undefined
1500
+ ? perBp * bp
1501
+ : tile.end > tile.start
1502
+ ? (tile.steps * bp) / (tile.end - tile.start)
1503
+ : tile.steps;
1504
+ if (reach === undefined && held + share > budget) {
1505
+ reach = bp > 0 ? from + ((budget - held) * bp) / share : from;
1506
+ }
1507
+ held += share;
1508
+ }
1509
+ return Math.floor(reach !== null && reach !== void 0 ? reach : drawn.end);
1510
+ }
1511
+ /**
1512
+ * The zoom-in notice for a cut whose walk read would fetch more than
1513
+ * `budget` compressed bytes, or undefined when it fits. `bytesTo(end)` is the
1514
+ * bytes of the tiles a read from the window's first base to `end` fetches;
1515
+ * the span that fits grows a tile at a time from the tile holding the
1516
+ * window's start, and when the tiles that reaches are over on their own, no
1517
+ * zoom fits. `attaching` marks bytes the tiles fetched for records' own
1518
+ * steps take past the budget.
1519
+ */
1520
+ export function byteBudgetError(bytesTo, budget, window, tile, names = BUDGET_NAMES, attaching = false) {
1521
+ const over = bytesOver(bytesTo, budget, window, tile);
1522
+ const windowBp = window.end - window.start;
1523
+ return over === undefined
1524
+ ? undefined
1525
+ : over.fitsBp > 0
1526
+ ? new RegionTooLargeError(`Zoom in to about ${bpString(over.fitsBp)} to see the graph`, budget, windowBp, over.fitsBp, { bytes: over.bytes, zoomHelps: true })
1527
+ : new RegionTooLargeError(attaching
1528
+ ? `Too many departures here whose own steps the cut must fetch, even zoomed in (${megabytes(over.least)} against ${names.bytes} ${megabytes(budget)}); choose fewer haplotypes or a smaller attachBp`
1529
+ : `Too much graph here to fetch, even zoomed in (${megabytes(over.least)} against ${names.bytes} ${megabytes(budget)}). A satellite or rDNA array usually causes this: the graph folds the repeat into a few nodes that each haplotype loops through many times`, budget, windowBp, 1, { bytes: over.bytes });
1530
+ }
1531
+ /**
1532
+ * byteBudgetError's refusal for counts, which draw nothing and choose no
1533
+ * haplotypes: what the read would fetch, and a narrower window to count
1534
+ * instead where one fits
1535
+ */
1536
+ export function countBytesError(bytesTo, budget, window, tile, names = BUDGET_NAMES, attaching = false) {
1537
+ const over = bytesOver(bytesTo, budget, window, tile);
1538
+ const windowBp = window.end - window.start;
1539
+ const against = `against ${names.bytes} ${megabytes(budget)}`;
1540
+ const own = attaching
1541
+ ? " with the tiles holding its departures' own steps"
1542
+ : '';
1543
+ const instead = attaching
1544
+ ? '. Count with a smaller attachBp, or leave this window uncounted'
1545
+ : ', so leave this window uncounted';
1546
+ return over === undefined
1547
+ ? undefined
1548
+ : new RegionTooLargeError(`Too many bytes to read to count this window: ${over.fitsBp === 0
1549
+ ? `${megabytes(over.least)} for its first tile alone${own}, ${against}${instead}`
1550
+ : `${megabytes(over.bytes)} ${against}. Count a window of about ${bpString(over.fitsBp)} or less, or leave this one uncounted`}`, budget, windowBp, Math.max(over.fitsBp, 1), over.fitsBp > 0
1551
+ ? { bytes: over.bytes, zoomHelps: true }
1552
+ : { bytes: over.bytes });
1553
+ }
1554
+ // The widest span from the window's start, narrower than the window, whose
1555
+ // read fits `budget`, 0 where none does; `bytesTo` never falls as its end
1556
+ // grows
1557
+ function narrowerFit(bytesTo, budget, window) {
1558
+ let fits = window.start;
1559
+ let over = window.end;
1560
+ while (over - fits > 1) {
1561
+ const middle = Math.floor((fits + over) / 2);
1562
+ if (bytesTo(middle) <= budget) {
1563
+ fits = middle;
1564
+ }
1565
+ else {
1566
+ over = middle;
1567
+ }
1568
+ }
1569
+ return fits - window.start;
1570
+ }
1571
+ // What a read past `budget` would fetch: `bytes` for the window, `least` for
1572
+ // its first tile alone, and `fitsBp`, the span from the window's start whose
1573
+ // read fits, 0 where none does; undefined for a read within the budget. The
1574
+ // span grows a tile at a time, and where every tile fits and the window's
1575
+ // read is still over, as the tiles fetched to attach can make it, it is the
1576
+ // widest narrower one that fits, so it is never the window or more
1577
+ function bytesOver(bytesTo, budget, window, tile) {
1578
+ const bytes = bytesTo(window.end);
1579
+ let fitsBp = 0;
1580
+ let least;
1581
+ let more = bytes > budget;
1582
+ for (let cs = Math.floor(window.start / tile) * tile; more && cs < window.end; cs += tile) {
1583
+ const read = bytesTo(cs + 1);
1584
+ least !== null && least !== void 0 ? least : (least = read);
1585
+ more = read <= budget;
1586
+ fitsBp = more ? cs + tile - window.start : fitsBp;
1587
+ }
1588
+ const reaches = fitsBp >= window.end - window.start;
1589
+ const narrower = reaches ? narrowerFit(bytesTo, budget, window) : fitsBp;
1590
+ return bytes > budget
1591
+ ? {
1592
+ bytes,
1593
+ fitsBp: narrower,
1594
+ least: reaches && narrower === 0
1595
+ ? bytesTo(window.start + 1)
1596
+ : (least !== null && least !== void 0 ? least : bytes),
1597
+ }
1598
+ : undefined;
1599
+ }
1600
+ export const megabytes = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;