@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,1389 @@
1
+ import { LocalFile, RemoteFile } from 'generic-filehandle2';
2
+ import { MissingSequenceError, refNameLookup, resolveRefName, } from "./refNames.js";
3
+ import { checkRange } from "./tabixSource.js";
4
+ import { panSNHaplotypeOrSample, panSNMatchesPrefix } from "./util.js";
5
+ import { blockLinks, blocksOver, blocksSteps, bpRow, canonicalLink, chunkRef, decodeChunk, ownRunsRow, ownStretch, tileLinks, parseBlocks, referenceNodes, statedAbridgedSteps, tileNodeIds, tileSteps, unloadedRow, } from "./walkChunk.js";
6
+ import { WalkContainer, WalkFormatError, once, raceAbort, } from "./walkContainer.js";
7
+ import { WalkTally } from "./walkCounts.js";
8
+ import { ATTACH_BP, attachesOwnSteps, departureOwnTiles, parseDepartureRow, squeezer, } from "./walkDeparture.js";
9
+ import { FORMS_STEP_BUDGET, walkDepartures } from "./walkDepartures.js";
10
+ import { WalkGraph, byteBudgetError, countBytesError, countStepsError, edgeKey, isPlaceholder, joinPieces, keptNodesError, keptStepsError, megabytes, readSteps, stepBudgetError, surelyKept, surelyKeptError, unattachedRecords, walkCut, walkHeader, walksKept, } from "./walkRows.js";
11
+ // A window reads whole tiles and keeps the steps on it, so a narrow window
12
+ // reads several times what it keeps: 464 haplotypes across the 1.5 kb ABCA7
13
+ // repeat read 5.0 M steps and keep 1.16 M, and the cut takes 0.4 s from warm
14
+ // files. The step budget bounds what the cut keeps, and rows are read to this
15
+ // multiple of it.
16
+ const READ_STEPS_PER_KEPT = 8;
17
+ // bp of reference a cut keeps past each end of the window
18
+ export const WALK_CONTEXT = 1000;
19
+ // reads of detail records an expanding cut makes at once
20
+ const DETAIL_READS = 16;
21
+ // the most compressed bytes of detail records one of those reads fetches,
22
+ // but for a record larger than that alone
23
+ const DETAIL_READ_BYTES = 2000000;
24
+ // The budgets a cut keeps to unless its caller passes others: what a browser
25
+ // window can hold. Infinity lifts one
26
+ export const WALK_BUDGETS = Object.freeze({
27
+ stepBudget: 4000000,
28
+ byteBudget: 8000000,
29
+ departureByteBudget: 2000000,
30
+ attachBp: ATTACH_BP,
31
+ });
32
+ // The same cut rules in both; a figure has no window to protect
33
+ export const CUT_PRESETS = Object.freeze({
34
+ browser: Object.freeze({
35
+ context: WALK_CONTEXT,
36
+ contained: false,
37
+ attachBp: ATTACH_BP,
38
+ stepBudget: WALK_BUDGETS.stepBudget,
39
+ byteBudget: WALK_BUDGETS.byteBudget,
40
+ departureByteBudget: WALK_BUDGETS.departureByteBudget,
41
+ }),
42
+ figure: Object.freeze({
43
+ context: WALK_CONTEXT,
44
+ contained: false,
45
+ attachBp: ATTACH_BP,
46
+ stepBudget: Infinity,
47
+ byteBudget: Infinity,
48
+ departureByteBudget: Infinity,
49
+ }),
50
+ });
51
+ /**
52
+ * A window whose departure read would fetch more than its budget. Zooming in
53
+ * does not lower the read, since a record is filed over its whole stretch,
54
+ * so this is not a RegionTooLargeError and shows no zoom-in notice.
55
+ */
56
+ export class DepartureReadError extends Error {
57
+ constructor(bytes, limit) {
58
+ super(`Too many departures from the reference over this window to read (${megabytes(bytes)} against a budget of ${megabytes(limit)}). A collapsed repeat usually causes this: haplotypes hop between its copies, and each hop is a departure`);
59
+ this.name = 'DepartureReadError';
60
+ this.bytes = bytes;
61
+ this.limit = limit;
62
+ }
63
+ }
64
+ // Reads `items`, at most `limit` at once and none once `signal` aborts, and
65
+ // hands each to `use` in order
66
+ export async function readInOrder(items, limit, signal, read, use) {
67
+ const reads = [];
68
+ const next = () => {
69
+ if (reads.length < items.length && !signal.aborted) {
70
+ const started = read(items[reads.length]);
71
+ reads.push(started);
72
+ started.then(next, () => { });
73
+ }
74
+ };
75
+ for (let k = 0; k < limit; k++) {
76
+ next();
77
+ }
78
+ for (let i = 0; i < items.length; i++) {
79
+ signal.throwIfAborted();
80
+ use(items[i], await reads[i]);
81
+ }
82
+ }
83
+ // `items` as runs to read at once: those whose units' bytes touch in the
84
+ // file, in file order, up to `maxBytes` a run, the runs in the order of
85
+ // their first item among `items`
86
+ export function touchingRuns(items, maxBytes) {
87
+ var _a;
88
+ const runs = [];
89
+ const place = new Map(items.map((item, k) => [item, k]));
90
+ for (const item of [...items].sort((a, b) => a.unit.offset - b.unit.offset)) {
91
+ const run = runs.at(-1);
92
+ const last = run === null || run === void 0 ? void 0 : run.items.at(-1);
93
+ const at = (_a = place.get(item)) !== null && _a !== void 0 ? _a : 0;
94
+ if (run &&
95
+ last &&
96
+ last.unit.offset + last.unit.length === item.unit.offset &&
97
+ run.bytes + item.unit.length <= maxBytes) {
98
+ run.items.push(item);
99
+ run.bytes += item.unit.length;
100
+ run.first = Math.min(run.first, at);
101
+ }
102
+ else {
103
+ runs.push({ items: [item], bytes: item.unit.length, first: at });
104
+ }
105
+ }
106
+ return runs.sort((a, b) => a.first - b.first).map(run => run.items);
107
+ }
108
+ // The links from each piece's last step to the first of its line's next
109
+ const piecesJoined = (ends) => {
110
+ var _a;
111
+ const lines = new Map();
112
+ for (const piece of ends) {
113
+ const key = `${piece.name}\t${piece.fragStart}`;
114
+ const line = (_a = lines.get(key)) !== null && _a !== void 0 ? _a : new Map();
115
+ lines.set(key, line);
116
+ line.set(piece.piece, piece);
117
+ }
118
+ const pairs = [];
119
+ for (const line of lines.values()) {
120
+ for (const [k, piece] of line) {
121
+ const next = line.get(k + 1);
122
+ if (next && piece.last >= 0 && next.first >= 0) {
123
+ pairs.push(piece.last, next.first);
124
+ }
125
+ }
126
+ }
127
+ return pairs;
128
+ };
129
+ const overlaps = (unit, span) => unit.length > 0 && unit.start < span.end && unit.end > span.start;
130
+ const bytesOf = (units) => units.reduce((sum, unit) => sum + unit.length, 0);
131
+ // The stretch a cut draws: the window and its context
132
+ const drawnSpan = (region, context) => ({
133
+ start: Math.max(0, region.start - context),
134
+ end: region.end + context,
135
+ });
136
+ // The tiles and departure blocks a cut over `drawn` reads first
137
+ const windowUnits = (units, drawn) => ({
138
+ tiles: units.filter(u => u.kind === 'tile' && overlaps(u, drawn)),
139
+ departureBlocks: units.filter(u => u.kind === 'departures' && overlaps(u, drawn)),
140
+ });
141
+ function checkDepartureBytes(departureBlocks, budget) {
142
+ const bytes = bytesOf(departureBlocks);
143
+ if (bytes > budget) {
144
+ throw new DepartureReadError(bytes, budget);
145
+ }
146
+ }
147
+ // The tiles an attach fetch reads for a record: those its `ownTiles` names,
148
+ // in file order
149
+ export function attachTiles(units) {
150
+ const byStart = new Map();
151
+ units.forEach((u, k) => {
152
+ const start = Number(u.name);
153
+ if (u.kind === 'tile' && u.length > 0 && !Number.isNaN(start)) {
154
+ const held = byStart.get(start);
155
+ if (held) {
156
+ held.push(k);
157
+ }
158
+ else {
159
+ byStart.set(start, [k]);
160
+ }
161
+ }
162
+ });
163
+ return (ownTiles) => [...new Set(ownTiles)]
164
+ .flatMap(start => { var _a; return (_a = byStart.get(start)) !== null && _a !== void 0 ? _a : []; })
165
+ .sort((a, b) => a - b)
166
+ .map(k => units[k]);
167
+ }
168
+ const pieceKey = (name, fragStart, piece) => `${name}\t${fragStart}\t${piece}`;
169
+ const keyOf = (row) => pieceKey(row.name, row.fragStart, row.piece);
170
+ // Where each piece of `rows` starts on its contig
171
+ const pieceStarts = (rows) => {
172
+ const starts = new Map();
173
+ for (const row of rows) {
174
+ starts.set(pieceKey(row.name, row.fragStart, row.piece), row.hapOffset);
175
+ }
176
+ return starts;
177
+ };
178
+ // Of each line's pieces, in piece order, by runs of consecutive piece numbers,
179
+ // those from a run's first piece over the drawn stretch to its last, as the
180
+ // items they are read by, each with whether it is that first or that last
181
+ function betweenDrawn(lines) {
182
+ const between = [];
183
+ for (const line of lines) {
184
+ let from = 0;
185
+ for (let i = 1; i <= line.length; i++) {
186
+ if (i === line.length || line[i].piece !== line[i - 1].piece + 1) {
187
+ let first = -1;
188
+ let last = -1;
189
+ for (let j = from; j < i; j++) {
190
+ if (line[j].on) {
191
+ first = first < 0 ? j : first;
192
+ last = j;
193
+ }
194
+ }
195
+ for (let j = Math.max(first, 0); j <= last; j++) {
196
+ const { item } = line[j];
197
+ if (item !== undefined) {
198
+ between.push({ item, first: j === first, last: j === last });
199
+ }
200
+ }
201
+ from = i;
202
+ }
203
+ }
204
+ }
205
+ return between;
206
+ }
207
+ function beforeDrawn(lines) {
208
+ const before = [];
209
+ for (const line of lines) {
210
+ for (let i = 0; i + 1 < line.length; i++) {
211
+ const { item, piece } = line[i];
212
+ const next = line[i + 1];
213
+ if (item !== undefined && next.on && next.piece === piece + 1) {
214
+ before.push(item);
215
+ }
216
+ }
217
+ }
218
+ return before;
219
+ }
220
+ const split = (lines) => lines.map(line => line.split('\t'));
221
+ const keptNodes = (kept) => {
222
+ let count = 0;
223
+ for (const id of kept) {
224
+ count += isPlaceholder(id) ? 0 : 1;
225
+ }
226
+ return count;
227
+ };
228
+ // The records of departure lines over `span`, each line once, of the walks
229
+ // kept, with the tiles holding each one's own steps
230
+ function departureRecords(lines, span, keep) {
231
+ const records = [];
232
+ const ownTiles = new Map();
233
+ for (const line of new Set(lines)) {
234
+ const cols = line.split('\t');
235
+ if (cols[3] === 'departure' &&
236
+ +cols[1] < span.end &&
237
+ +cols[2] > span.start) {
238
+ const record = parseDepartureRow(cols);
239
+ if (keep === undefined || keep(record.name)) {
240
+ records.push(record);
241
+ ownTiles.set(record, departureOwnTiles(cols));
242
+ }
243
+ }
244
+ }
245
+ return { records, ownTiles };
246
+ }
247
+ const directoryOf = (url) => url.replace(/(?=$|[?#])/, '.idx');
248
+ const sourcesGiven = (...values) => values.filter(value => value !== undefined).length;
249
+ function openWalkFile(opts) {
250
+ var _a, _b;
251
+ const idxGiven = sourcesGiven(opts.idxUrl, opts.idxPath, opts.idxFilehandle);
252
+ if (sourcesGiven(opts.walksUrl, opts.walksPath, opts.walksFilehandle) !== 1 ||
253
+ idxGiven > 1 ||
254
+ (idxGiven === 0 && sourcesGiven(opts.walksUrl, opts.walksPath) === 0)) {
255
+ throw new TypeError('A WalkFile takes one of walksUrl, walksPath or walksFilehandle, and at most one of idxUrl, idxPath or idxFilehandle, which a walksFilehandle needs');
256
+ }
257
+ const walks = (_a = opts.walksFilehandle) !== null && _a !== void 0 ? _a : (opts.walksPath !== undefined
258
+ ? new LocalFile(opts.walksPath)
259
+ : new RemoteFile(opts.walksUrl));
260
+ const idx = (_b = opts.idxFilehandle) !== null && _b !== void 0 ? _b : (opts.idxPath !== undefined
261
+ ? new LocalFile(opts.idxPath)
262
+ : opts.idxUrl !== undefined
263
+ ? new RemoteFile(opts.idxUrl)
264
+ : opts.walksPath !== undefined
265
+ ? new LocalFile(`${opts.walksPath}.idx`)
266
+ : new RemoteFile(directoryOf(opts.walksUrl)));
267
+ return new WalkContainer(walks, idx);
268
+ }
269
+ // The abridged walks a cut reads from their detail records: those a
270
+ // function accepts, or those under any of a list's PanSN prefixes
271
+ const expandFilter = (expand) => Array.isArray(expand)
272
+ ? (name) => expand.some(prefix => panSNMatchesPrefix(name, prefix))
273
+ : expand;
274
+ /**
275
+ * A `gfa-to-tabix --walks` file of walk format 8, `<prefix>.<sample>.walks.gz`
276
+ * and its directory `<prefix>.<sample>.walks.gz.idx`, read a window at a
277
+ * time. At open the directory, the header and the sequence's unit table; for
278
+ * a window, the tiles and departure blocks overlapping the window and its
279
+ * context, in one read wherever their bytes touch, each tile decoded once;
280
+ * the `blocks` unit of each of those tiles that abridges a walk kept and not
281
+ * expanded; the detail records of the pieces of the walks `expand` names
282
+ * that the cut builds; then every tile holding own steps the read lacks of
283
+ * a record within `attachBp` that leaves or rejoins on the window or its
284
+ * context, which give those steps alone, from the tile's rows and the
285
+ * records, with no `blocks` unit read. A record that only jumps over them
286
+ * costs no read past its line. The table gives
287
+ * each read's bytes before it is made; a window whose tiles are past the
288
+ * byte budget reads no row, and one whose attach tiles take it past reads
289
+ * none of them. Only the walks `keep` accepts are decoded. The step budget
290
+ * bounds the steps the cut keeps, and rows of the window holding
291
+ * READ_STEPS_PER_KEPT times as many stop the read.
292
+ *
293
+ * Every range method takes 0-based half-open coordinates and a `refName`
294
+ * that is a contig of the reference sample (`chr6`, on `referenceSample`,
295
+ * the file's first reference by default) or the file's own name for it
296
+ * (`GRCh38#0#chr6`), and throws MissingSequenceError for a sequence the
297
+ * file lacks.
298
+ */
299
+ export class WalkFile {
300
+ constructor(opts) {
301
+ this.readHeader = once(async () => {
302
+ const header = walkHeader(await this.container.header());
303
+ const { tile } = header;
304
+ if (tile === undefined) {
305
+ throw new WalkFormatError("The walk file's #walks line states no tile:i:");
306
+ }
307
+ return { ...header, tile };
308
+ });
309
+ this.readLookup = once(async () => refNameLookup(await this.container.sequences()));
310
+ this.container = openWalkFile(opts);
311
+ }
312
+ // The header, read once for every caller: one caller giving up stops only
313
+ // its own wait, and a read that fails is tried again by the next caller
314
+ getHeader(opts = {}) {
315
+ return raceAbort(this.readHeader(), opts.signal);
316
+ }
317
+ // The reference sequences the walk file holds windows on
318
+ getReferenceSequences(opts = {}) {
319
+ return raceAbort(this.container.sequences(), opts.signal);
320
+ }
321
+ /**
322
+ * The walk file's sequence for `contig` on `sample`, or for `contig` as
323
+ * the file spells it: `chr6` on `GRCh38` is `GRCh38#0#chr6`. Undefined when
324
+ * the file holds neither.
325
+ */
326
+ async getSequenceName(sample, contig, opts = {}) {
327
+ const lookup = await raceAbort(this.readLookup(), opts.signal);
328
+ return resolveRefName(lookup, sample, contig);
329
+ }
330
+ // The units the file holds for a reference sequence, by the file's name
331
+ // for it, in file order; none for a sequence the file lacks
332
+ getUnits(refName, opts = {}) {
333
+ return raceAbort(this.container.units(refName), opts.signal);
334
+ }
335
+ // Where the reference's last node on `refName`, the file's name for it,
336
+ // ends, from the extents of its tiles; 0 for a sequence the file lacks
337
+ async getSequenceLength(refName, opts = {}) {
338
+ const units = await this.getUnits(refName, opts);
339
+ return units.reduce((end, u) => (u.kind === 'tile' ? Math.max(end, u.end) : end), 0);
340
+ }
341
+ // The file's name for `refName` and the reference sample it was read on
342
+ async resolve(refName, opts) {
343
+ var _a, _b;
344
+ const { signal } = opts;
345
+ const header = await this.getHeader({ signal });
346
+ const sample = (_b = (_a = opts.referenceSample) !== null && _a !== void 0 ? _a : header.references[0]) !== null && _b !== void 0 ? _b : '';
347
+ const name = await this.getSequenceName(sample, refName, { signal });
348
+ if (name === undefined) {
349
+ throw new MissingSequenceError(refName, sample, await this.getReferenceSequences({ signal }));
350
+ }
351
+ return { refName: name, sample };
352
+ }
353
+ /**
354
+ * The compressed bytes a cut of the range reads when it keeps every walk
355
+ * and expands none: its tiles, their blocks units, its departure blocks,
356
+ * which this reads as the cut does, and the tiles named for their own
357
+ * steps by its records within `attachBp` that leave or rejoin on the
358
+ * window or its context. A cut that keeps fewer walks reads no more, and
359
+ * one that expands walks no more but for their detail units
360
+ */
361
+ async getBytesForRange(refName, start, end, opts = {}) {
362
+ const sequence = await this.resolve(refName, opts);
363
+ return this.bytesFor(sequence.refName, { start, end }, opts);
364
+ }
365
+ async bytesFor(refName, region, opts) {
366
+ const { signal, context = WALK_CONTEXT, attachBp = ATTACH_BP, departureByteBudget = WALK_BUDGETS.departureByteBudget, } = opts;
367
+ checkRange(refName, region.start, region.end);
368
+ const drawn = drawnSpan(region, context);
369
+ const units = await this.getUnits(refName, { signal });
370
+ const { tiles, departureBlocks } = windowUnits(units, drawn);
371
+ checkDepartureBytes(departureBlocks, departureByteBudget);
372
+ const tileNames = new Set(tiles.map(u => u.name));
373
+ const { records, ownTiles } = departureRecords((await this.container.read(departureBlocks, signal)).flat(), drawn, undefined);
374
+ const attachNames = new Set(records
375
+ .filter(d => attachesOwnSteps(d, drawn, attachBp))
376
+ .flatMap(d => { var _a; return (_a = ownTiles.get(d)) !== null && _a !== void 0 ? _a : []; }));
377
+ const blocks = units.filter(u => u.kind === 'blocks' && tileNames.has(u.name));
378
+ const attached = units.filter(u => u.kind === 'tile' &&
379
+ u.length > 0 &&
380
+ attachNames.has(Number(u.name)) &&
381
+ !tileNames.has(u.name));
382
+ return (bytesOf(tiles) +
383
+ bytesOf(blocks) +
384
+ bytesOf(departureBlocks) +
385
+ bytesOf(attached));
386
+ }
387
+ // Every pass of the reference over the range, by start, from the ref rows
388
+ // of the tiles there: a node the reference passes twice there comes twice
389
+ async getReferenceNodes(refName, start, end, opts = {}) {
390
+ const sequence = await this.resolve(refName, opts);
391
+ return this.referenceNodes(sequence.refName, { start, end }, opts);
392
+ }
393
+ async referenceNodes(refName, region, opts) {
394
+ checkRange(refName, region.start, region.end);
395
+ const tiles = (await this.getUnits(refName, opts)).filter(u => u.kind === 'tile' && overlaps(u, region));
396
+ const read = await this.container.read(tiles, opts.signal);
397
+ return referenceNodes(read.flat().map(line => line.split('\t')))
398
+ .filter(node => node.refName === refName &&
399
+ node.end > region.start &&
400
+ node.start < region.end)
401
+ .sort((a, b) => a.start - b.start || a.end - b.end);
402
+ }
403
+ /**
404
+ * The cut of the range: its graph, the nodes it keeps, each walk's
405
+ * fragments and departures over it and the gaps between them, and
406
+ * `tables()`, which makes the graph's tables of all of them
407
+ */
408
+ async getCutForRange(refName, start, end, opts = {}) {
409
+ const sequence = await this.resolve(refName, opts);
410
+ return this.cut(sequence.refName, { start, end }, opts);
411
+ }
412
+ async cut(refName, region, opts) {
413
+ var _a, _b, _c, _d, _e, _f;
414
+ const { signal, keep, context = WALK_CONTEXT, stepBudget = WALK_BUDGETS.stepBudget, byteBudget = WALK_BUDGETS.byteBudget, departureByteBudget = WALK_BUDGETS.departureByteBudget, attachBp = ATTACH_BP, links = 'walked', contained = false, nodeLimit = Infinity, placeholderLimit = Infinity, } = opts;
415
+ const expand = expandFilter(opts.expand);
416
+ checkRange(refName, region.start, region.end);
417
+ const [header, units] = await Promise.all([
418
+ this.getHeader({ signal }),
419
+ this.getUnits(refName, { signal }),
420
+ ]);
421
+ const { tile } = header;
422
+ const drawn = drawnSpan(region, context);
423
+ const { tiles, departureBlocks } = windowUnits(units, drawn);
424
+ const tileBytesTo = (end) => bytesOf(tiles.filter(u => u.start < end + context));
425
+ const checkBytes = (bytesTo, attaching = false) => {
426
+ if (Number.isFinite(byteBudget)) {
427
+ const tooLarge = byteBudgetError(bytesTo, byteBudget, region, tile, opts.budgetNames, attaching);
428
+ if (tooLarge) {
429
+ throw tooLarge;
430
+ }
431
+ }
432
+ };
433
+ checkBytes(tileBytesTo);
434
+ checkDepartureBytes(departureBlocks, departureByteBudget);
435
+ const reads = new AbortController();
436
+ const stop = () => {
437
+ reads.abort(signal === null || signal === void 0 ? void 0 : signal.reason);
438
+ };
439
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
440
+ signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', stop, { once: true });
441
+ const rows = [];
442
+ // the rows of tiles fetched to attach, which give records their own steps
443
+ // and nothing else
444
+ const attachRows = [];
445
+ const graph = new WalkGraph({
446
+ refName,
447
+ start: region.start,
448
+ end: region.end,
449
+ context,
450
+ sequences: opts.sequences,
451
+ }, header.revisited);
452
+ // the name filters each tile was decoded under, by its offset
453
+ const decodedBy = new Map();
454
+ const decodedFor = (unit, name) => { var _a; return ((_a = decodedBy.get(unit.offset)) === null || _a === void 0 ? void 0 : _a.some(took => took(name))) === true; };
455
+ const surely = new Set();
456
+ const surelyPlaceholders = Number.isFinite(placeholderLimit)
457
+ ? new Set()
458
+ : undefined;
459
+ const bounds = {
460
+ contained,
461
+ start: region.start - context,
462
+ end: region.end + context,
463
+ };
464
+ const filtered = keep !== undefined;
465
+ const unitsOf = (kind) => new Map(units.filter(u => u.kind === kind).map(u => [u.name, u]));
466
+ const detailUnits = unitsOf('detail');
467
+ const blocksUnits = unitsOf('blocks');
468
+ // the units read past the window's tiles, each with the base a window
469
+ // must reach to need it
470
+ const extra = [];
471
+ const bytesWith = (more) => (end) => tileBytesTo(end) +
472
+ bytesOf(extra.filter(x => x.from < end + context).map(x => x.unit)) +
473
+ bytesOf(more.filter(x => x.from < end + context).map(x => x.unit));
474
+ // R of each tile decoded, by its name, and the blocks units read
475
+ const tilePaths = new Map();
476
+ const pieceEnds = [];
477
+ const blocksRead = new Map();
478
+ // the id of each run of a contig a placeholder stands for, by the walk's
479
+ // name, the run's start and its end: -1 for the first run, then -2
480
+ const placeholderIds = new Map();
481
+ let minted = 0;
482
+ const placeholderId = (name, start, end) => {
483
+ var _a, _b, _c;
484
+ const byStart = (_a = placeholderIds.get(name)) !== null && _a !== void 0 ? _a : new Map();
485
+ placeholderIds.set(name, byStart);
486
+ const byEnd = (_b = byStart.get(start)) !== null && _b !== void 0 ? _b : new Map();
487
+ byStart.set(start, byEnd);
488
+ const id = (_c = byEnd.get(end)) !== null && _c !== void 0 ? _c : -(minted + 1);
489
+ minted = Math.max(minted, -id);
490
+ byEnd.set(end, id);
491
+ return id;
492
+ };
493
+ // the abridged rows decoded and not yet read from a blocks row or a
494
+ // detail record
495
+ let met = [];
496
+ const refs = new Map();
497
+ // the drawn stretch, as far as the reference's passes over it reach
498
+ const over = { ...drawn };
499
+ const ownRecords = new Map();
500
+ const checkNodes = (chunk, readTo) => {
501
+ var _a, _b, _c;
502
+ if (Number.isFinite(nodeLimit) || Number.isFinite(placeholderLimit)) {
503
+ surelyKept(chunk, graph.nodes, bounds, surely, surelyPlaceholders);
504
+ if (surely.size > nodeLimit ||
505
+ ((_a = surelyPlaceholders === null || surelyPlaceholders === void 0 ? void 0 : surelyPlaceholders.size) !== null && _a !== void 0 ? _a : 0) > placeholderLimit) {
506
+ surely.clear();
507
+ surelyPlaceholders === null || surelyPlaceholders === void 0 ? void 0 : surelyPlaceholders.clear();
508
+ surelyKept({ nodes: graph.nodes, rows }, graph.nodes, bounds, surely, surelyPlaceholders);
509
+ }
510
+ const tooMany = (_b = keptNodesError(surely.size, nodeLimit, region, filtered, readTo)) !== null && _b !== void 0 ? _b : keptNodesError((_c = surelyPlaceholders === null || surelyPlaceholders === void 0 ? void 0 : surelyPlaceholders.size) !== null && _c !== void 0 ? _c : 0, placeholderLimit, region, filtered, readTo);
511
+ if (tooMany) {
512
+ throw tooMany;
513
+ }
514
+ }
515
+ };
516
+ // links as pairs of handles, each written the one way round
517
+ const addLinks = (pairs) => {
518
+ if (links !== 'none') {
519
+ for (let k = 0; k < pairs.length; k += 2) {
520
+ const [a, b] = canonicalLink(pairs[k], pairs[k + 1]);
521
+ graph.addLinkEnds(a, b);
522
+ }
523
+ }
524
+ };
525
+ const placeNodes = (nodes) => {
526
+ for (const [id, node] of nodes) {
527
+ graph.placeNode(id, node);
528
+ }
529
+ };
530
+ const place = (tileCut, readTo) => {
531
+ placeNodes(tileCut.nodes);
532
+ for (const { id, ...node } of tileCut.revisits) {
533
+ graph.placeNode(id, node);
534
+ }
535
+ graph.addSequences(tileCut.sequences);
536
+ checkNodes(tileCut, readTo);
537
+ };
538
+ // a tile is decoded into `into`, with its nodes and the links between
539
+ // pieces, for the names `only` takes that no earlier decode of it took,
540
+ // and a cut over its node limit stops there
541
+ const decode = (unit, lines, into, from, only) => {
542
+ var _a, _b, _c, _d;
543
+ const wanted = (_a = only !== null && only !== void 0 ? only : keep) !== null && _a !== void 0 ? _a : (() => true);
544
+ const earlier = (_b = decodedBy.get(unit.offset)) !== null && _b !== void 0 ? _b : [];
545
+ decodedBy.set(unit.offset, [...earlier, wanted]);
546
+ const tileRows = lines.map(line => line.split('\t'));
547
+ const tileCut = decodeChunk(tileRows, Number(unit.name), name => wanted(name) && !earlier.some(took => took(name)), opts.sequences);
548
+ const { path } = tileCut;
549
+ if (links === 'between' && !tilePaths.has(unit.name)) {
550
+ const taken = tileLinks(tileRows, path);
551
+ tilePaths.set(unit.name, { path, rowStarts: taken.rowStarts });
552
+ addLinks(taken.links);
553
+ for (const ends of taken.ends) {
554
+ pieceEnds.push(ends);
555
+ }
556
+ }
557
+ const hull = into === rows ? path.hull(drawn) : undefined;
558
+ over.start = Math.min(over.start, (_c = hull === null || hull === void 0 ? void 0 : hull.start) !== null && _c !== void 0 ? _c : over.start);
559
+ over.end = Math.max(over.end, (_d = hull === null || hull === void 0 ? void 0 : hull.end) !== null && _d !== void 0 ? _d : over.end);
560
+ for (const row of tileCut.rows) {
561
+ into.push(row);
562
+ }
563
+ for (const piece of tileCut.abridged) {
564
+ met.push({ unit, piece, path, tileRows, into, from });
565
+ }
566
+ place(tileCut, unit.end);
567
+ };
568
+ const readDetails = (run) => this.container.read(run.map(detail => detail.unit), reads.signal);
569
+ const decodeDetail = ({ unit, ref, piece, into, pieces }, held) => {
570
+ const tileCut = decodeChunk(held, piece.chunkStart, name => name === piece.name, opts.sequences, ref);
571
+ const taken = tileCut.rows.filter(row => pieces.has(keyOf(row)));
572
+ if (taken.length !== pieces.size) {
573
+ throw new WalkFormatError(`${refName}'s detail unit ${unit.name} holds walk rows for ${taken.length} of the ${pieces.size} pieces of ${piece.name} that the cut reads from it`);
574
+ }
575
+ for (const row of taken) {
576
+ const { bp } = row.steps;
577
+ const rowBp = bp === null || bp === void 0 ? void 0 : bp.reduce((sum, stepBp) => sum + stepBp, 0);
578
+ const hapBp = pieces.get(keyOf(row));
579
+ if ((bp === null || bp === void 0 ? void 0 : bp.every(stepBp => stepBp >= 0)) === true && rowBp !== hapBp) {
580
+ throw new WalkFormatError(`${refName}'s detail unit ${unit.name} holds ${rowBp} bp of steps for piece ${row.piece} of ${row.name}, and its abridged row states a hapBp of ${hapBp}`);
581
+ }
582
+ into.push(row);
583
+ }
584
+ place({ ...tileCut, rows: taken }, piece.chunkStart + tile);
585
+ };
586
+ const onDrawn = (span) => span.start < over.end && span.end > over.start;
587
+ // the lines `held` names a piece of, each with its pieces among `held`
588
+ // and the rows decoded, in piece order
589
+ const linesOf = (held) => {
590
+ var _a, _b;
591
+ const lines = new Map();
592
+ for (const { name, fragStart, ...piece } of held) {
593
+ const key = `${name}\t${fragStart}`;
594
+ const line = (_a = lines.get(key)) !== null && _a !== void 0 ? _a : [];
595
+ lines.set(key, line);
596
+ line.push(piece);
597
+ }
598
+ for (const row of rows) {
599
+ (_b = lines.get(`${row.name}\t${row.fragStart}`)) === null || _b === void 0 ? void 0 : _b.push({
600
+ piece: row.piece,
601
+ on: row.span === undefined ||
602
+ onDrawn({ start: row.span[0], end: row.span[1] }),
603
+ });
604
+ }
605
+ return [...lines.values()].map(line => line.sort((a, b) => a.piece - b.piece));
606
+ };
607
+ const bySpan = (item) => {
608
+ const { name, fragStart, piece, span } = item.piece;
609
+ return { name, fragStart, piece, on: onDrawn(span), item };
610
+ };
611
+ // each built piece's blocks to build whole: those from the first block
612
+ // over the drawn stretch to the last, of the pieces that join it
613
+ const coresOf = (pieces, others) => {
614
+ const cores = new Map();
615
+ for (const { item, first, last } of betweenDrawn(linesOf([
616
+ ...pieces.map(read => ({ ...bySpan(read), on: read.on.first >= 0 })),
617
+ ...others.map(other => ({ ...bySpan(other), item: undefined })),
618
+ ]))) {
619
+ cores.set(item, [
620
+ first ? item.on.first : 0,
621
+ last ? item.on.last : item.blocks.begins.length - 1,
622
+ ]);
623
+ }
624
+ return cores;
625
+ };
626
+ const expanding = (item) => (expand === null || expand === void 0 ? void 0 : expand(item.piece.name)) === true;
627
+ const ownRunsOf = (piece) => {
628
+ var _a;
629
+ return ((_a = ownRecords.get(piece.name)) !== null && _a !== void 0 ? _a : []).flatMap(d => {
630
+ const stretch = ownStretch(piece, d);
631
+ return stretch
632
+ ? [
633
+ {
634
+ ...stretch,
635
+ attached: attachesOwnSteps(d, drawn, attachBp),
636
+ pos: stretch.trailing ? d.leavePos : d.rejoinPos,
637
+ reversed: stretch.trailing ? d.leaveReversed : d.rejoinReversed,
638
+ key: stretch.trailing
639
+ ? edgeKey(d.name, d.leavePos, d.leaveReversed, d.hapStart)
640
+ : edgeKey(d.name, d.rejoinPos, d.rejoinReversed, d.hapStart + d.ownBp),
641
+ },
642
+ ]
643
+ : [];
644
+ });
645
+ };
646
+ const readBlocks = async (wanted) => {
647
+ const unread = wanted.filter(w => !blocksRead.has(w.unit));
648
+ const fetched = await this.container.read(unread.map(w => w.unit), reads.signal);
649
+ unread.forEach((w, k) => {
650
+ extra.push(w);
651
+ blocksRead.set(w.unit, fetched[k]);
652
+ });
653
+ };
654
+ const blocksOf = async (items, attaching) => {
655
+ var _a, _b, _c, _d;
656
+ const tilesMet = new Map();
657
+ for (const { unit, from } of items) {
658
+ tilesMet.set(unit, Math.min((_a = tilesMet.get(unit)) !== null && _a !== void 0 ? _a : from, from));
659
+ }
660
+ const wanted = [...tilesMet].map(([tileUnit, from]) => {
661
+ const unit = blocksUnits.get(tileUnit.name);
662
+ if (!unit) {
663
+ throw new WalkFormatError(`${refName}'s unit table lists no blocks unit ${tileUnit.name}, which the abridged rows of that tile need`);
664
+ }
665
+ return { unit, from };
666
+ });
667
+ const unread = wanted.filter(w => !blocksRead.has(w.unit));
668
+ if (unread.length > 0) {
669
+ checkBytes(bytesWith(unread), attaching);
670
+ }
671
+ await readBlocks(unread);
672
+ const listed = new Map();
673
+ for (const [k, tileUnit] of [...tilesMet.keys()].entries()) {
674
+ const byPiece = new Map();
675
+ for (const line of blocksRead.get(wanted[k].unit)) {
676
+ const cols = line.split('\t');
677
+ byPiece.set(pieceKey((_b = cols[4]) !== null && _b !== void 0 ? _b : '', (_c = cols[5]) !== null && _c !== void 0 ? _c : '', (_d = cols[6]) !== null && _d !== void 0 ? _d : ''), cols);
678
+ }
679
+ listed.set(tileUnit, byPiece);
680
+ }
681
+ return new Map(items.map(item => {
682
+ var _a;
683
+ const { name, piece, hapBp } = item.piece;
684
+ const cols = (_a = listed.get(item.unit)) === null || _a === void 0 ? void 0 : _a.get(keyOf(item.piece));
685
+ if (!cols) {
686
+ throw new WalkFormatError(`${refName}'s blocks unit ${item.unit.name} holds no row for piece ${piece} of ${name}, which its tile abridges`);
687
+ }
688
+ const blocks = parseBlocks(cols);
689
+ const listBp = blocks.before + blocks.bp + blocks.after;
690
+ if (listBp !== hapBp) {
691
+ throw new WalkFormatError(`${refName}'s blocks row of ${name}, piece ${piece} in tile ${item.unit.name}, adds up to ${listBp} bp, and its abridged row states a hapBp of ${hapBp}`);
692
+ }
693
+ return [item, { ...item, blocks, on: blocksOver(blocks, over) }];
694
+ }));
695
+ };
696
+ const detailOf = (item) => {
697
+ var _a;
698
+ const { name } = item.piece.abridged.detail;
699
+ const unit = detailUnits.get(name);
700
+ if (!unit) {
701
+ throw new WalkFormatError(`${refName}'s unit table lists no detail unit ${name}, which an abridged row of ${item.piece.name} names`);
702
+ }
703
+ const ref = (_a = refs.get(item.unit)) !== null && _a !== void 0 ? _a : chunkRef(item.tileRows);
704
+ refs.set(item.unit, ref);
705
+ return {
706
+ unit,
707
+ ref,
708
+ piece: item.piece,
709
+ into: item.into,
710
+ pieces: new Map(),
711
+ };
712
+ };
713
+ // The cut builds the pieces whose span lies over the drawn stretch, those
714
+ // between two such pieces of a line, those holding the own steps of a
715
+ // record it attaches and, contained with context, those whose own
716
+ // steps the context reaches before a piece over the drawn stretch: an
717
+ // expanded walk's from its detail unit, any other from its tile's blocks
718
+ // unit. Of a tile fetched to attach it builds the pieces holding those
719
+ // own steps, an unexpanded one from its abridged row and the record. Any
720
+ // other piece of a window's tile is its bp
721
+ const resolve = async (attaching) => {
722
+ var _a, _b;
723
+ const batch = met;
724
+ met = [];
725
+ const lines = attaching ? [] : linesOf(batch.map(bySpan));
726
+ const drawnPieces = new Set(betweenDrawn(lines).map(held => held.item));
727
+ const reached = new Set(contained && context > 0 && !attaching ? beforeDrawn(lines) : []);
728
+ const ownRuns = new Map(batch.map(item => [item, ownRunsOf(item.piece)]));
729
+ const built = batch.filter(item => {
730
+ var _a;
731
+ const runs = (_a = ownRuns.get(item)) !== null && _a !== void 0 ? _a : [];
732
+ return (drawnPieces.has(item) ||
733
+ runs.some(run => run.attached) ||
734
+ (reached.has(item) && runs.some(run => run.trailing)));
735
+ });
736
+ const details = new Map();
737
+ for (const item of built.filter(expanding)) {
738
+ const { name } = item.piece.abridged.detail;
739
+ const detail = (_a = details.get(name)) !== null && _a !== void 0 ? _a : detailOf(item);
740
+ details.set(name, detail);
741
+ detail.pieces.set(keyOf(item.piece), item.piece.hapBp);
742
+ }
743
+ const blocks = await blocksOf(attaching ? [] : batch.filter(item => !expanding(item)), attaching);
744
+ const fromBlocks = built.flatMap(item => {
745
+ var _a;
746
+ const read = blocks.get(item);
747
+ return read ? [{ read, runs: (_a = ownRuns.get(item)) !== null && _a !== void 0 ? _a : [] }] : [];
748
+ });
749
+ const cores = coresOf(fromBlocks.map(({ read }) => read), built.filter(expanding));
750
+ const wanted = [...details.values()];
751
+ const held = new Map();
752
+ let decoded = 0;
753
+ await readInOrder(touchingRuns(wanted, DETAIL_READ_BYTES), DETAIL_READS, reads.signal, readDetails, (run, fetched) => {
754
+ var _a;
755
+ run.forEach((detail, k) => { var _a; return held.set(detail, (_a = fetched[k]) !== null && _a !== void 0 ? _a : []); });
756
+ while (decoded < wanted.length && held.has(wanted[decoded])) {
757
+ const detail = wanted[decoded++];
758
+ decodeDetail(detail, split((_a = held.get(detail)) !== null && _a !== void 0 ? _a : []));
759
+ held.delete(detail);
760
+ }
761
+ });
762
+ const starts = attaching ? pieceStarts(attachRows) : pieceStarts(rows);
763
+ for (const { piece } of batch) {
764
+ starts.set(keyOf(piece), piece.hapOffset);
765
+ }
766
+ for (const { piece, unit } of batch) {
767
+ const next = starts.get(pieceKey(piece.name, piece.fragStart, piece.piece + 1));
768
+ const pieceEnd = piece.hapOffset + piece.hapBp;
769
+ if (next !== undefined && next !== pieceEnd) {
770
+ throw new WalkFormatError(`${refName}'s abridged row of ${piece.name}, piece ${piece.piece} in tile ${unit.name}, ends at ${pieceEnd} on its contig, and the line's next piece starts at ${next}`);
771
+ }
772
+ }
773
+ for (const { read, runs } of fromBlocks) {
774
+ const { piece } = read;
775
+ for (const run of runs) {
776
+ const listed = run.trailing ? read.blocks.after : read.blocks.before;
777
+ if (listed !== run.end - run.start) {
778
+ throw new WalkFormatError(`${refName}'s blocks row of ${piece.name}, piece ${piece.piece} in tile ${read.unit.name}, ${run.trailing ? 'ends' : 'starts'} with ${listed} bp off the reference, and a departure record's own steps there are ${run.end - run.start} bp by its abridged row`);
779
+ }
780
+ }
781
+ const made = unloadedRow(piece, read.blocks, read.path, over, cores.get(read), (start, end) => placeholderId(piece.name, start, end));
782
+ read.into.push(made.row);
783
+ placeNodes(made.nodes);
784
+ checkNodes({ nodes: made.nodes, rows: [made.row] }, read.unit.end);
785
+ }
786
+ const unbuilt = new Set(batch);
787
+ for (const item of built) {
788
+ unbuilt.delete(item);
789
+ if (attaching && !expanding(item)) {
790
+ const { piece } = item;
791
+ const made = ownRunsRow(piece, ((_b = ownRuns.get(item)) !== null && _b !== void 0 ? _b : []).filter(run => run.attached), item.path, (start, end) => placeholderId(piece.name, start, end));
792
+ item.into.push(made.row);
793
+ placeNodes(made.nodes);
794
+ }
795
+ }
796
+ for (const item of attaching ? [] : unbuilt) {
797
+ item.into.push(bpRow(item.piece));
798
+ }
799
+ };
800
+ // whether `more` read with the units read so far passes the byte budget
801
+ const overBytes = (more, attach) => Number.isFinite(byteBudget) &&
802
+ byteBudgetError(bytesWith(more), byteBudget, region, tile, opts.budgetNames, attach) !== undefined;
803
+ // Whether none of the refusals a cut makes before keptStepsError can
804
+ // come, from its tiles' lines and records before any is decoded: a row
805
+ // its decode refuses; its node limit, which no more nodes than the
806
+ // tiles' ref rows and routes name can reach where no detail record or
807
+ // attach fetch brings more; its placeholder limit, which nothing reaches
808
+ // where no tile abridges a walk it keeps unexpanded and no attach fetch
809
+ // comes; the byte budget, over the blocks units it reads and every tile
810
+ // it can fetch to attach; and the read budget, over the most its rows
811
+ // and pieces can hold
812
+ const noEarlierRefusal = (read, all, records, ownTiles) => {
813
+ var _a, _b, _c, _d;
814
+ const blocks = tiles
815
+ .filter((_, k) => { var _a; return ((_a = all[k]) === null || _a === void 0 ? void 0 : _a.blocks) === true; })
816
+ .map(unit => ({ unit: blocksUnits.get(unit.name), from: unit.start }));
817
+ const unread = blocks.flatMap(({ unit, from }) => unit && !blocksRead.has(unit) ? [{ unit, from }] : []);
818
+ const attaching = new Map();
819
+ const decoded = new Set(tiles.map(unit => unit.offset));
820
+ const tilesNamed = new Map();
821
+ for (const unit of units) {
822
+ if (unit.kind === 'tile' && unit.length > 0) {
823
+ const start = Number(unit.name);
824
+ tilesNamed.set(start, [...((_a = tilesNamed.get(start)) !== null && _a !== void 0 ? _a : []), unit]);
825
+ }
826
+ }
827
+ for (const d of records) {
828
+ if (attachesOwnSteps(d, bounds, attachBp)) {
829
+ const from = Math.min(d.leavePos, d.rejoinPos, region.end + context - 1);
830
+ for (const start of (_b = ownTiles.get(d)) !== null && _b !== void 0 ? _b : []) {
831
+ for (const unit of (_c = tilesNamed.get(start)) !== null && _c !== void 0 ? _c : []) {
832
+ if (!decoded.has(unit.offset)) {
833
+ attaching.set(unit, Math.min((_d = attaching.get(unit)) !== null && _d !== void 0 ? _d : from, from));
834
+ }
835
+ }
836
+ }
837
+ }
838
+ }
839
+ const fetching = [...attaching].map(([unit, from]) => ({ unit, from }));
840
+ const nodesFit = () => !Number.isFinite(nodeLimit) ||
841
+ (fetching.length === 0 &&
842
+ all.every(t => (t === null || t === void 0 ? void 0 : t.expanded) === false) &&
843
+ read
844
+ .slice(0, tiles.length)
845
+ .reduce((ids, lines) => tileNodeIds(lines, ids), new Set())
846
+ .size <= nodeLimit);
847
+ const placeholdersFit = !Number.isFinite(placeholderLimit) ||
848
+ (fetching.length === 0 && all.every(t => (t === null || t === void 0 ? void 0 : t.blocks) === false));
849
+ const held = all.reduce((sum, t) => {
850
+ var _a, _b;
851
+ return ({
852
+ n: sum.n + ((_a = t === null || t === void 0 ? void 0 : t.n) !== null && _a !== void 0 ? _a : 0),
853
+ interior: sum.interior + ((_b = t === null || t === void 0 ? void 0 : t.interior) !== null && _b !== void 0 ? _b : 0),
854
+ });
855
+ }, { n: 0, interior: 0 });
856
+ return (all.every(t => t !== undefined) &&
857
+ blocks.every(({ unit }) => unit !== undefined) &&
858
+ readSteps(held) <= stepBudget * READ_STEPS_PER_KEPT &&
859
+ !(unread.length > 0 && overBytes(unread, false)) &&
860
+ !(fetching.length > 0 && overBytes([...unread, ...fetching], true)) &&
861
+ placeholdersFit &&
862
+ nodesFit());
863
+ };
864
+ // keptStepsError's notice, given before any tile is decoded where the
865
+ // steps the cut surely keeps pass the step budget and no earlier refusal
866
+ // can come, so the finished cut would throw it. The count is the rows'
867
+ // (tileSteps in walkChunk.ts) of the tiles strictly inside the drawn
868
+ // stretch; where that fits and the steps the tiles' abridged rows state
869
+ // could take it over, the cut reads the blocks units it would read
870
+ // anyway and adds what it builds of each abridged piece on the drawn
871
+ // stretch (blocksSteps), in any tile of the window
872
+ const earlyRefusal = async (read, records, ownTiles) => {
873
+ const counted = tiles.map((unit, k) => unit.start > drawn.start && unit.end < drawn.end
874
+ ? tileSteps(read[k], keep, expand)
875
+ : 'edge');
876
+ const rowSteps = counted.map(tally => tally === 'edge' ? undefined : tally === null || tally === void 0 ? void 0 : tally.kept);
877
+ const kept = rowSteps.reduce((sum, n) => sum + (n !== null && n !== void 0 ? n : 0), 0);
878
+ const all = () => tiles.map((_, k) => {
879
+ const tally = counted[k];
880
+ return tally === 'edge' ? tileSteps(read[k], keep, expand) : tally;
881
+ });
882
+ // an edge tile's `steps` are those of its abridged pieces on the drawn
883
+ // stretch, and `whole` what its rows keep where the cut draws all of it
884
+ const refusal = (steps, whole = []) => surelyKeptError(tiles.map((unit, k) => {
885
+ var _a;
886
+ const start = Math.max(unit.start, drawn.start);
887
+ const end = Math.min(unit.end, drawn.end);
888
+ const drawnShare = unit.end > unit.start
889
+ ? (end - start) / (unit.end - unit.start)
890
+ : 1;
891
+ const count = steps[k];
892
+ return count === undefined
893
+ ? unit
894
+ : counted[k] === 'edge'
895
+ ? {
896
+ start,
897
+ end,
898
+ steps: count,
899
+ likely: count + ((_a = whole[k]) !== null && _a !== void 0 ? _a : 0) * drawnShare,
900
+ }
901
+ : { ...unit, steps: count };
902
+ }), stepBudget, region, context, filtered);
903
+ const fromBlocks = async () => {
904
+ const tallies = all();
905
+ const abridging = tiles.flatMap((windowTile, k) => {
906
+ var _a;
907
+ const unit = blocksUnits.get(windowTile.name);
908
+ return ((_a = tallies[k]) === null || _a === void 0 ? void 0 : _a.blocks) === true && unit
909
+ ? [{ unit, from: windowTile.start, k }]
910
+ : [];
911
+ });
912
+ const builtOf = async () => {
913
+ await readBlocks(abridging);
914
+ return abridging.map(({ unit, k }) => {
915
+ var _a;
916
+ return blocksSteps(read[k], (_a = blocksRead.get(unit)) !== null && _a !== void 0 ? _a : [], bounds, keep, expand);
917
+ });
918
+ };
919
+ const built = noEarlierRefusal(read, tallies, records, ownTiles)
920
+ ? await builtOf()
921
+ : undefined;
922
+ const steps = [...rowSteps];
923
+ abridging.forEach(({ k }, i) => {
924
+ var _a, _b;
925
+ steps[k] = ((_a = steps[k]) !== null && _a !== void 0 ? _a : 0) + ((_b = built === null || built === void 0 ? void 0 : built[i]) !== null && _b !== void 0 ? _b : 0);
926
+ });
927
+ return (built === null || built === void 0 ? void 0 : built.every(n => n !== undefined)) === true
928
+ ? refusal(steps, tallies.map(tally => tally === null || tally === void 0 ? void 0 : tally.kept))
929
+ : undefined;
930
+ };
931
+ return kept > stepBudget
932
+ ? noEarlierRefusal(read, all(), records, ownTiles)
933
+ ? refusal(rowSteps)
934
+ : undefined
935
+ : kept +
936
+ tiles.reduce((sum, _, k) => sum + statedAbridgedSteps(read[k], keep, expand), 0) >
937
+ stepBudget
938
+ ? fromBlocks()
939
+ : undefined;
940
+ };
941
+ let cut;
942
+ try {
943
+ const jumps = links === 'between'
944
+ ? tiles.flatMap(windowTile => {
945
+ const unit = blocksUnits.get(windowTile.name);
946
+ return unit ? [{ unit, from: windowTile.start, windowTile }] : [];
947
+ })
948
+ : [];
949
+ checkBytes(bytesWith(jumps));
950
+ const read = await this.container.read([...tiles, ...departureBlocks, ...jumps.map(x => x.unit)], reads.signal);
951
+ const tilesAndRecords = tiles.length + departureBlocks.length;
952
+ jumps.forEach((x, k) => {
953
+ extra.push(x);
954
+ blocksRead.set(x.unit, read[tilesAndRecords + k]);
955
+ });
956
+ const { records, ownTiles } = departureRecords(read.slice(tiles.length, tilesAndRecords).flat(), drawn, keep);
957
+ for (const d of records) {
958
+ if (d.ownBp > 0) {
959
+ const held = (_a = ownRecords.get(d.name)) !== null && _a !== void 0 ? _a : [];
960
+ ownRecords.set(d.name, held);
961
+ held.push(d);
962
+ }
963
+ }
964
+ const early = Number.isFinite(stepBudget)
965
+ ? await earlyRefusal(read, records, ownTiles)
966
+ : undefined;
967
+ if (early) {
968
+ throw early;
969
+ }
970
+ tiles.forEach((unit, k) => {
971
+ decode(unit, read[k], rows, unit.start);
972
+ });
973
+ for (const { unit, windowTile } of jumps) {
974
+ const { path, rowStarts } = tilePaths.get(windowTile.name);
975
+ for (const line of blocksRead.get(unit)) {
976
+ const piece = blockLinks(line.split('\t'), path, rowStarts);
977
+ addLinks(piece.links);
978
+ pieceEnds.push(piece.ends);
979
+ }
980
+ }
981
+ await resolve(false);
982
+ const tooManyRead = stepBudgetError(rows, stepBudget, READ_STEPS_PER_KEPT, region, tile, filtered, opts.budgetNames);
983
+ if (tooManyRead) {
984
+ throw tooManyRead;
985
+ }
986
+ const joined = joinPieces(rows);
987
+ const cutOptions = {
988
+ contained,
989
+ context,
990
+ attachBp,
991
+ squeeze: squeezer(header.holes, refName),
992
+ drawn: bounds,
993
+ placeholder: placeholderId,
994
+ links: links !== 'none',
995
+ };
996
+ // the tiles holding own steps the read lacks, the walks wanting each,
997
+ // and where on R the first record wanting it starts
998
+ const fetches = new Map();
999
+ const tilesOwning = attachTiles(units);
1000
+ for (const departure of unattachedRecords(joined, graph.nodes, records, cutOptions)) {
1001
+ const { name } = departure;
1002
+ const from = Math.min(departure.leavePos, departure.rejoinPos, region.end + context - 1);
1003
+ for (const unit of tilesOwning((_b = ownTiles.get(departure)) !== null && _b !== void 0 ? _b : [])) {
1004
+ if (!decodedFor(unit, name)) {
1005
+ const wanting = fetches.get(unit);
1006
+ fetches.set(unit, {
1007
+ names: ((_c = wanting === null || wanting === void 0 ? void 0 : wanting.names) !== null && _c !== void 0 ? _c : new Set()).add(name),
1008
+ from: Math.min((_d = wanting === null || wanting === void 0 ? void 0 : wanting.from) !== null && _d !== void 0 ? _d : from, from),
1009
+ });
1010
+ }
1011
+ }
1012
+ }
1013
+ if (fetches.size > 0) {
1014
+ const fetching = [...fetches].map(([unit, { from }]) => ({
1015
+ unit,
1016
+ from,
1017
+ }));
1018
+ checkBytes(bytesWith(fetching), true);
1019
+ const fetched = await this.container.read([...fetches.keys()], reads.signal);
1020
+ for (const [k, [unit, { names, from }]] of [...fetches].entries()) {
1021
+ extra.push(fetching[k]);
1022
+ decode(unit, fetched[k], attachRows, from, name => names.has(name));
1023
+ }
1024
+ await resolve(true);
1025
+ }
1026
+ cut = walkCut(joined, graph.nodes, refName, records, {
1027
+ ...cutOptions,
1028
+ attach: joinPieces(attachRows),
1029
+ });
1030
+ }
1031
+ catch (error) {
1032
+ reads.abort();
1033
+ throw error;
1034
+ }
1035
+ finally {
1036
+ signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', stop);
1037
+ }
1038
+ const nodes = keptNodes(cut.kept);
1039
+ const placeholders = cut.kept.size - nodes;
1040
+ const tooMany = (_f = (_e = keptStepsError(cut.fragments, cut.departures, stepBudget, region, filtered)) !== null && _e !== void 0 ? _e : keptNodesError(nodes, nodeLimit, region, filtered)) !== null && _f !== void 0 ? _f : keptNodesError(placeholders, placeholderLimit, region, filtered);
1041
+ if (tooMany) {
1042
+ throw tooMany;
1043
+ }
1044
+ addLinks(cut.links);
1045
+ addLinks(piecesJoined(pieceEnds));
1046
+ const { kept, fragments, departures } = cut;
1047
+ return {
1048
+ refName,
1049
+ graph,
1050
+ kept,
1051
+ fragments,
1052
+ departures,
1053
+ get gaps() {
1054
+ return cut.gapsOf();
1055
+ },
1056
+ placeholders,
1057
+ tables: () => graph.tables(kept, fragments, departures, cut.gapsOf()),
1058
+ };
1059
+ }
1060
+ /**
1061
+ * How many of the file's haplotypes step each node and link over the range,
1062
+ * and how often, read as a cut that keeps every walk reads, with the same
1063
+ * `context`, `contained`, `attachBp`, budgets and `expand`. It counts each
1064
+ * piece the cut builds whole, and each piece holding the own steps of a
1065
+ * record the cut attaches, while it decodes the rows, keeping no step and
1066
+ * building no graph. Every count states why it may fall short, or that it
1067
+ * is exact (docs/counts.md)
1068
+ */
1069
+ async getCountsForRange(refName, start, end, opts = {}) {
1070
+ const sequence = await this.resolve(refName, opts);
1071
+ return this.counts(sequence.refName, { start, end }, opts);
1072
+ }
1073
+ async counts(refName, region, opts) {
1074
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
1075
+ const { signal, context = WALK_CONTEXT, contained = false, stepBudget = WALK_BUDGETS.stepBudget, byteBudget = WALK_BUDGETS.byteBudget, departureByteBudget = WALK_BUDGETS.departureByteBudget, attachBp = ATTACH_BP, } = opts;
1076
+ const expand = expandFilter(opts.expand);
1077
+ checkRange(refName, region.start, region.end);
1078
+ const [header, units, sequences] = await Promise.all([
1079
+ this.getHeader({ signal }),
1080
+ this.getUnits(refName, { signal }),
1081
+ this.getReferenceSequences({ signal }),
1082
+ ]);
1083
+ const drawn = drawnSpan(region, context);
1084
+ const { tiles, departureBlocks } = windowUnits(units, drawn);
1085
+ const unitsOf = (kind) => new Map(units.filter(u => u.kind === kind).map(u => [u.name, u]));
1086
+ const blocksUnits = unitsOf('blocks');
1087
+ const detailUnits = unitsOf('detail');
1088
+ const extra = [];
1089
+ const checkBytes = (more, attaching = false) => {
1090
+ const bytesTo = (end) => bytesOf(tiles.filter(u => u.start < end + context)) +
1091
+ bytesOf(extra.filter(x => x.from < end + context).map(x => x.unit)) +
1092
+ bytesOf(more.filter(x => x.from < end + context).map(x => x.unit));
1093
+ const tooLarge = Number.isFinite(byteBudget)
1094
+ ? countBytesError(bytesTo, byteBudget, region, header.tile, opts.budgetNames, attaching)
1095
+ : undefined;
1096
+ if (tooLarge) {
1097
+ throw tooLarge;
1098
+ }
1099
+ for (const x of more) {
1100
+ extra.push(x);
1101
+ }
1102
+ };
1103
+ const blocksOf = (tileUnits) => tileUnits.flatMap(tileUnit => {
1104
+ const unit = blocksUnits.get(tileUnit.name);
1105
+ return unit ? [{ unit, from: tileUnit.start }] : [];
1106
+ });
1107
+ const prefetched = expand === undefined ? blocksOf(tiles) : [];
1108
+ checkBytes(prefetched);
1109
+ checkDepartureBytes(departureBlocks, departureByteBudget);
1110
+ const read = await this.container.read([...tiles, ...departureBlocks, ...prefetched.map(x => x.unit)], signal);
1111
+ const { records, ownTiles } = departureRecords(read.slice(tiles.length, tiles.length + departureBlocks.length).flat(), drawn, undefined);
1112
+ const listed = new Map(prefetched.map((x, k) => [
1113
+ x.unit,
1114
+ read[tiles.length + departureBlocks.length + k],
1115
+ ]));
1116
+ const tally = new WalkTally([
1117
+ ...new Set([
1118
+ ...sequences.map(panSNHaplotypeOrSample),
1119
+ ...header.haplotypes,
1120
+ ]),
1121
+ ], header.revisited === 0);
1122
+ const parsed = tiles.map((unit, k) => tally.tile(split(read[k]), Number(unit.name), true));
1123
+ const over = { ...drawn };
1124
+ for (const unit of parsed) {
1125
+ const hull = unit.r.path.hull(drawn);
1126
+ over.start = Math.min(over.start, (_a = hull === null || hull === void 0 ? void 0 : hull.start) !== null && _a !== void 0 ? _a : over.start);
1127
+ over.end = Math.max(over.end, (_b = hull === null || hull === void 0 ? void 0 : hull.end) !== null && _b !== void 0 ? _b : over.end);
1128
+ }
1129
+ for (const unit of parsed) {
1130
+ tally.placeReference(unit, over);
1131
+ }
1132
+ const onOver = (span) => span.start < over.end && span.end > over.start;
1133
+ const attached = records.filter(d => attachesOwnSteps(d, drawn, attachBp));
1134
+ const ownOf = new Map();
1135
+ for (const d of attached) {
1136
+ const held = (_c = ownOf.get(d.name)) !== null && _c !== void 0 ? _c : [];
1137
+ ownOf.set(d.name, held);
1138
+ held.push(d);
1139
+ }
1140
+ const holdsOwn = (name, start, end) => {
1141
+ var _a;
1142
+ return ((_a = ownOf.get(name)) !== null && _a !== void 0 ? _a : []).some(d => start < d.hapStart + d.ownBp && end > d.hapStart);
1143
+ };
1144
+ const pieces = parsed.flatMap((unit, k) => [
1145
+ ...unit.walks.map(walk => ({ unit, tile: tiles[k], walk })),
1146
+ ...unit.abridged.map(moved => ({ unit, tile: tiles[k], moved })),
1147
+ ]);
1148
+ const lines = new Map();
1149
+ for (const item of pieces) {
1150
+ const { name, fragStart, piece, span } = (_d = item.walk) !== null && _d !== void 0 ? _d : item.moved;
1151
+ const key = pieceKey(name, fragStart, '');
1152
+ const line = (_e = lines.get(key)) !== null && _e !== void 0 ? _e : [];
1153
+ lines.set(key, line);
1154
+ line.push({ piece, on: onOver(span), item });
1155
+ }
1156
+ const inOrder = [...lines.values()].map(line => line.sort((a, b) => a.piece - b.piece));
1157
+ const chosen = new Set(betweenDrawn(inOrder).map(held => held.item));
1158
+ for (const item of contained && context > 0 ? beforeDrawn(inOrder) : []) {
1159
+ chosen.add(item);
1160
+ }
1161
+ for (const item of pieces) {
1162
+ const { name, hapOffset } = (_f = item.walk) !== null && _f !== void 0 ? _f : item.moved;
1163
+ if (ownOf.has(name) && !chosen.has(item)) {
1164
+ const bp = item.walk
1165
+ ? tally.walk(item.unit, item.walk, false)
1166
+ : item.moved.hapBp;
1167
+ if (holdsOwn(name, hapOffset, hapOffset + bp)) {
1168
+ chosen.add(item);
1169
+ }
1170
+ }
1171
+ }
1172
+ const rowSteps = parsed.flatMap(unit => unit.walks.map(({ n, interior, name }) => ({
1173
+ n,
1174
+ interior,
1175
+ name,
1176
+ chunkStart: unit.start,
1177
+ })));
1178
+ const tooManyRead = countStepsError(rowSteps, stepBudget, READ_STEPS_PER_KEPT, region, header.tile, opts.budgetNames);
1179
+ if (tooManyRead) {
1180
+ throw tooManyRead;
1181
+ }
1182
+ let stepsRead = rowSteps.reduce((sum, row) => sum + readSteps(row), 0);
1183
+ let stopped = false;
1184
+ // the detail units of the pieces `expand` names that fit the step budget,
1185
+ // each with the pieces it gives; the rest stay unloaded
1186
+ const detailsOf = (wanted) => {
1187
+ var _a;
1188
+ const details = new Map();
1189
+ for (const { unit, moved: abridged } of wanted) {
1190
+ const { name } = abridged.abridged.detail;
1191
+ const detail = detailUnits.get(name);
1192
+ if (!detail) {
1193
+ throw new WalkFormatError(`${refName}'s unit table lists no detail unit ${name}, which an abridged row of ${abridged.name} names`);
1194
+ }
1195
+ const held = (_a = details.get(name)) !== null && _a !== void 0 ? _a : {
1196
+ unit: detail,
1197
+ tile: unit,
1198
+ pieces: new Map(),
1199
+ };
1200
+ details.set(name, held);
1201
+ held.pieces.set(keyOf(abridged), abridged);
1202
+ }
1203
+ return [...details.values()].filter(({ pieces: given }) => {
1204
+ const steps = [...given.values()].reduce((sum, piece) => sum + piece.abridged.steps, 0);
1205
+ stopped || (stopped = stepsRead + steps > stepBudget * READ_STEPS_PER_KEPT);
1206
+ stepsRead += stopped ? 0 : steps;
1207
+ return !stopped;
1208
+ });
1209
+ };
1210
+ const countDetails = (details, unitLines) => {
1211
+ details.forEach(({ unit, tile, pieces: given }, k) => {
1212
+ const held = tally.detail(split(unitLines[k]), tile);
1213
+ const taken = held.walks.filter(walk => given.has(keyOf(walk)));
1214
+ if (taken.length !== given.size) {
1215
+ throw new WalkFormatError(`${refName}'s detail unit ${unit.name} holds walk rows for ${taken.length} of the ${given.size} pieces that the counts read from it`);
1216
+ }
1217
+ for (const walk of taken) {
1218
+ const bp = tally.walk(held, walk, true);
1219
+ const hapBp = given.get(keyOf(walk)).hapBp;
1220
+ if (bp !== hapBp) {
1221
+ throw new WalkFormatError(`${refName}'s detail unit ${unit.name} holds ${bp} bp of steps for piece ${walk.piece} of ${walk.name}, and its abridged row states a hapBp of ${hapBp}`);
1222
+ }
1223
+ }
1224
+ });
1225
+ return new Set(details.flatMap(({ pieces: given }) => [...given.values()]));
1226
+ };
1227
+ const abridgedChosen = pieces.flatMap(item => item.moved && chosen.has(item)
1228
+ ? [{ unit: item.unit, tile: item.tile, moved: item.moved }]
1229
+ : []);
1230
+ const details = detailsOf(abridgedChosen.filter(item => (expand === null || expand === void 0 ? void 0 : expand(item.moved.name)) === true));
1231
+ const expanded = new Set(details.flatMap(({ pieces: given }) => [...given.values()]));
1232
+ const fromBlocks = abridgedChosen.filter(item => !expanded.has(item.moved));
1233
+ const blocksWanted = expand === undefined
1234
+ ? []
1235
+ : blocksOf([...new Set(fromBlocks.map(item => item.tile))]);
1236
+ checkBytes(blocksWanted);
1237
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
1238
+ const more = await this.container.read([...details.map(d => d.unit), ...blocksWanted.map(x => x.unit)], signal);
1239
+ blocksWanted.forEach((x, k) => {
1240
+ listed.set(x.unit, more[details.length + k]);
1241
+ });
1242
+ const starts = new Map();
1243
+ for (const item of pieces) {
1244
+ const held = (_g = item.walk) !== null && _g !== void 0 ? _g : item.moved;
1245
+ starts.set(keyOf(held), held.hapOffset);
1246
+ }
1247
+ for (const { moved: abridged, tile } of pieces.flatMap(item => item.moved ? [{ moved: item.moved, tile: item.tile }] : [])) {
1248
+ const next = starts.get(pieceKey(abridged.name, abridged.fragStart, abridged.piece + 1));
1249
+ const pieceEnd = abridged.hapOffset + abridged.hapBp;
1250
+ if (next !== undefined && next !== pieceEnd) {
1251
+ throw new WalkFormatError(`${refName}'s abridged row of ${abridged.name}, piece ${abridged.piece} in tile ${tile.name}, ends at ${pieceEnd} on its contig, and the line's next piece starts at ${next}`);
1252
+ }
1253
+ }
1254
+ for (const unit of parsed) {
1255
+ for (const reference of unit.references) {
1256
+ if (reference.to > reference.from &&
1257
+ onOver({
1258
+ start: unit.r.path.starts[reference.from],
1259
+ end: unit.r.path.end(reference.to - 1),
1260
+ })) {
1261
+ tally.countReference(unit, reference);
1262
+ }
1263
+ }
1264
+ }
1265
+ for (const item of pieces) {
1266
+ if (item.walk && chosen.has(item)) {
1267
+ tally.walk(item.unit, item.walk, true);
1268
+ }
1269
+ }
1270
+ countDetails(details, more);
1271
+ const blocksRows = new Map();
1272
+ for (const { moved: abridged, tile, unit } of fromBlocks) {
1273
+ const blocksUnit = blocksUnits.get(tile.name);
1274
+ const byPiece = (_h = blocksRows.get(tile)) !== null && _h !== void 0 ? _h : new Map(split(blocksUnit ? ((_j = listed.get(blocksUnit)) !== null && _j !== void 0 ? _j : []) : []).map(cols => {
1275
+ var _a, _b, _c;
1276
+ return [
1277
+ pieceKey((_a = cols[4]) !== null && _a !== void 0 ? _a : '', (_b = cols[5]) !== null && _b !== void 0 ? _b : '', (_c = cols[6]) !== null && _c !== void 0 ? _c : ''),
1278
+ cols,
1279
+ ];
1280
+ }));
1281
+ blocksRows.set(tile, byPiece);
1282
+ const cols = byPiece.get(keyOf(abridged));
1283
+ if (!cols) {
1284
+ throw new WalkFormatError(`${refName}'s blocks unit ${tile.name} holds no row for piece ${abridged.piece} of ${abridged.name}, which its tile abridges`);
1285
+ }
1286
+ const blocks = parseBlocks(cols);
1287
+ const listBp = blocks.before + blocks.bp + blocks.after;
1288
+ if (listBp !== abridged.hapBp) {
1289
+ throw new WalkFormatError(`${refName}'s blocks row of ${abridged.name}, piece ${abridged.piece} in tile ${tile.name}, adds up to ${listBp} bp, and its abridged row states a hapBp of ${abridged.hapBp}`);
1290
+ }
1291
+ tally.blocks(unit, abridged, blocks);
1292
+ }
1293
+ const windowTiles = new Set(tiles.map(u => u.name));
1294
+ const tileUnits = new Map(units
1295
+ .filter(u => u.kind === 'tile' && u.length > 0)
1296
+ .map(u => [Number(u.name), u]));
1297
+ const fetches = new Map();
1298
+ for (const d of attached) {
1299
+ const from = Math.min(d.leavePos, d.rejoinPos, region.end + context - 1);
1300
+ for (const unit of ((_k = ownTiles.get(d)) !== null && _k !== void 0 ? _k : []).flatMap(start => {
1301
+ const held = tileUnits.get(start);
1302
+ return held ? [held] : [];
1303
+ })) {
1304
+ if (!windowTiles.has(unit.name)) {
1305
+ const wanting = fetches.get(unit);
1306
+ fetches.set(unit, {
1307
+ names: ((_l = wanting === null || wanting === void 0 ? void 0 : wanting.names) !== null && _l !== void 0 ? _l : new Set()).add(d.name),
1308
+ from: Math.min((_m = wanting === null || wanting === void 0 ? void 0 : wanting.from) !== null && _m !== void 0 ? _m : from, from),
1309
+ });
1310
+ }
1311
+ }
1312
+ }
1313
+ const fetching = [...fetches].map(([unit, { from }]) => ({ unit, from }));
1314
+ checkBytes(fetching, true);
1315
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
1316
+ const fetched = await this.container.read(fetching.map(x => x.unit), signal);
1317
+ const owned = [...fetches.values()].flatMap(({ names }, k) => {
1318
+ const unit = tally.tile(split(fetched[k]), Number(fetching[k].unit.name), false);
1319
+ for (const walk of unit.walks) {
1320
+ if (names.has(walk.name) &&
1321
+ holdsOwn(walk.name, walk.hapOffset, walk.hapOffset + tally.walk(unit, walk, false))) {
1322
+ tally.walk(unit, walk, true);
1323
+ }
1324
+ }
1325
+ return unit.abridged
1326
+ .filter(abridged => names.has(abridged.name) &&
1327
+ holdsOwn(abridged.name, abridged.hapOffset, abridged.hapOffset + abridged.hapBp))
1328
+ .map(moved => ({ unit, moved }));
1329
+ });
1330
+ const ownDetails = detailsOf(owned.filter(item => (expand === null || expand === void 0 ? void 0 : expand(item.moved.name)) === true));
1331
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
1332
+ const loaded = countDetails(ownDetails, await this.container.read(ownDetails.map(d => d.unit), signal));
1333
+ for (const { moved } of owned) {
1334
+ if (!loaded.has(moved)) {
1335
+ tally.unread(moved);
1336
+ }
1337
+ }
1338
+ tally.departures(records);
1339
+ return tally.result();
1340
+ }
1341
+ /**
1342
+ * The graph under the range as tables: the reference sample's sequence
1343
+ * over it, with `context` bp either side, and the walks of the haplotypes
1344
+ * asked for, every one by default; `refName` names the sequence as the
1345
+ * file does, and `sequences` holds the nodes' bases when asked for.
1346
+ */
1347
+ async getGraphForRange(refName, start, end, opts = {}) {
1348
+ const { haplotypes, ...rest } = opts;
1349
+ const sequence = await this.resolve(refName, opts);
1350
+ const cut = await this.cut(sequence.refName, { start, end }, { ...rest, keep: walksKept(haplotypes, sequence.refName) });
1351
+ return {
1352
+ tables: cut.tables(),
1353
+ refName: sequence.refName,
1354
+ sample: sequence.sample,
1355
+ sequences: opts.sequences === true ? cut.graph.sequences : undefined,
1356
+ };
1357
+ }
1358
+ /**
1359
+ * Every haplotype's departures over the range, for structuralForms, from
1360
+ * one cut without links that expands no walk. A haplotype the header names
1361
+ * with no walk in the cut is listed with nothing covered.
1362
+ */
1363
+ async getFormsForRange(refName, start, end, opts = {}) {
1364
+ const { stepBudget = FORMS_STEP_BUDGET, byteBudget, departureByteBudget, signal, } = opts;
1365
+ const [header, sequence] = await Promise.all([
1366
+ this.getHeader({ signal }),
1367
+ this.resolve(refName, opts),
1368
+ ]);
1369
+ const cut = await this.cut(sequence.refName, { start, end }, {
1370
+ links: 'none',
1371
+ stepBudget: Math.max(stepBudget, FORMS_STEP_BUDGET),
1372
+ byteBudget,
1373
+ departureByteBudget,
1374
+ signal,
1375
+ });
1376
+ const haplotypes = walkDepartures({
1377
+ fragments: cut.fragments,
1378
+ departures: cut.departures,
1379
+ nodes: cut.graph.nodes,
1380
+ }, sequence.refName);
1381
+ const seen = new Set(haplotypes.map(h => h.haplotype));
1382
+ for (const haplotype of header.haplotypes) {
1383
+ if (!seen.has(haplotype)) {
1384
+ haplotypes.push({ haplotype, covered: [], departures: [] });
1385
+ }
1386
+ }
1387
+ return haplotypes;
1388
+ }
1389
+ }