@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Colin Diesh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # @gmod/gfa-tabix
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The reader for [gfa-to-tabix](https://github.com/GMOD/gfa-to-tabix)'s files, the
4
+ GFA tabix file and the walk file, as [@gmod/bam](https://github.com/GMOD/bam-js)
5
+ is for BAM.
6
+
7
+ ![A stretch of chromosome 6 zooms out into each genome's route through it, as colored lines through shared pieces of DNA, one detouring through extra DNA and one skipping a part](docs/hero.svg)
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @gmod/gfa-tabix
13
+ ```
14
+
15
+ The GFA tabix file also needs `@gmod/tabix`.
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import { WalkFile } from '@gmod/gfa-tabix'
21
+
22
+ const walks = new WalkFile({
23
+ walksUrl:
24
+ 'https://jbrowse.org/demos/hprc/hprc-v2.1-mc-grch38-f8.GRCh38.walks.gz',
25
+ })
26
+ const { tables, refName, sample } = await walks.getGraphForRange(
27
+ 'chr6',
28
+ 160_614_797,
29
+ 160_647_758,
30
+ { haplotypes: ['HG00097', 'HG00133'] },
31
+ )
32
+ ```
33
+
34
+ URLs read by range requests in node and the browser, `walksPath` reads a local
35
+ file, and the directory is the walk file plus `.idx` unless `idxUrl` or
36
+ `idxPath` says otherwise.
37
+
38
+ ## Coordinates
39
+
40
+ Coordinates are 0-based half-open, as in BED, where a samtools-style region is
41
+ 1-based closed: `chr6:160,614,798-160,647,758` is
42
+ `getGraphForRange('chr6', 160_614_797, 160_647_758)`.
43
+
44
+ ## The walk file
45
+
46
+ `gfa-to-tabix --walks` writes `<prefix>.<sample>.walks.gz` and its directory
47
+ `<prefix>.<sample>.walks.gz.idx`. `WalkFile` reads the stretch of it under a
48
+ range: the reference, each haplotype's walk through it, and the nodes and links
49
+ they visit, as typed arrays. `refName` is a contig of the reference sample
50
+ (`chr6`) or the file's full name (`GRCh38#0#chr6`). `getCutForRange`,
51
+ `getCountsForRange` and `getFormsForRange` give the cut itself, per-node
52
+ haplotype counts and structural forms.
53
+
54
+ ## The GFA tabix file
55
+
56
+ `GfaTabixFile` reads gfa-to-tabix's segments and links, Tabix-indexed BED, as
57
+ GFA text:
58
+
59
+ ```ts
60
+ import { GfaTabixFile } from '@gmod/gfa-tabix'
61
+ import { TabixIndexedFile } from '@gmod/tabix'
62
+
63
+ const gfaTabix = new GfaTabixFile({
64
+ graph: new TabixIndexedFile({ url: graphUrl, tbiUrl: `${graphUrl}.tbi` }),
65
+ })
66
+ const gfa = await gfaTabix.getGraphForRange('GRCh38#0#chr6', 0, 100_000)
67
+ ```
68
+
69
+ ## Docs
70
+
71
+ - [Cutting a window](docs/cutting.md): every method and option, fragments,
72
+ departures, the GFA tabix file
73
+ - [Reads, budgets and abridged walks](docs/reads.md): what a cut fetches
74
+ - [Counts](docs/counts.md): haplotypes per node and link
75
+ - [Structural forms](docs/structural-forms.md): grouping haplotypes by change
76
+ - [Migrating to 10](docs/migrating-to-10.md): from @jbrowse/graph-walks
77
+ - [Migrating to graph-walks 8](docs/migrating-to-8.md): changes in 7 and 8
78
+ - [ADR 0001](docs/adr/0001-a-cut-states-what-lies-between-fragments.md): gaps
79
+ between fragments
80
+
81
+ ## License
82
+
83
+ MIT
@@ -0,0 +1,7 @@
1
+ import type { GraphTables } from './util.ts';
2
+ export interface AbridgedWalk {
3
+ name: string;
4
+ bp: number;
5
+ }
6
+ export declare function abridgedWalks({ nodes, walks, departures }: GraphTables): AbridgedWalk[];
7
+ export declare function abridgedText({ name, bp }: AbridgedWalk, label?: string): string;
@@ -0,0 +1,34 @@
1
+ export function abridgedWalks({ nodes, walks, departures }) {
2
+ const byName = new Map();
3
+ const add = (name, steps) => {
4
+ var _a, _b;
5
+ const held = (_a = byName.get(name)) !== null && _a !== void 0 ? _a : new Set();
6
+ for (const i of steps) {
7
+ if (((_b = nodes.placeholders) === null || _b === void 0 ? void 0 : _b[i]) === 1) {
8
+ held.add(i);
9
+ }
10
+ }
11
+ byName.set(name, held);
12
+ };
13
+ walks.names.forEach((name, p) => {
14
+ add(name, walks.steps.subarray(walks.offsets[p], walks.offsets[p + 1]));
15
+ });
16
+ departures.names.forEach((name, k) => {
17
+ add(name, departures.steps.subarray(departures.offsets[k], departures.offsets[k + 1]));
18
+ });
19
+ const found = [];
20
+ for (const [name, held] of byName) {
21
+ let bp = 0;
22
+ for (const i of held) {
23
+ bp += nodes.lengths[i];
24
+ }
25
+ if (bp > 0) {
26
+ found.push({ name, bp });
27
+ }
28
+ }
29
+ return found;
30
+ }
31
+ const readoutBp = (bp) => bp < 1000 ? `${bp} bp` : `${(bp / 1000).toFixed(bp < 10000 ? 1 : 0)} kb`;
32
+ export function abridgedText({ name, bp }, label = name) {
33
+ return `${label}: ${readoutBp(bp)} off the reference not loaded`;
34
+ }
@@ -0,0 +1,50 @@
1
+ import type { StructuralForms } from './structuralForms.ts';
2
+ import type { HaplotypeDepartures } from './walkDepartures.ts';
3
+ /**
4
+ * How a form's statement at a site can contradict a member's own walks:
5
+ * - `call`: the form states a call where the member's walks do not span the
6
+ * site's part inside the window
7
+ * - `hidden`: the form states no call where they do
8
+ * - `rarer`: the form states a rarer change where the member makes none
9
+ * - `count`: at a site wider than SUMMED_SITE_BP, the member makes more or
10
+ * fewer changes there than the form states
11
+ * - `place`: at such a site, as many, but they and the form's marks pair
12
+ * one-to-one on no pairing of changes that cover half of each other: one
13
+ * lies elsewhere in the site
14
+ * - `net`: at a summed site, the member's net change there and the form's
15
+ * disagree; at a wider one, such pairings exist, but none pairs only
16
+ * changes agreeing in net change
17
+ * - `size`: the same for the largest change at a summed site, and for each
18
+ * pair's size at a wider one
19
+ * - `kind`: the member's changes there and the form's agree in size, but not
20
+ * in what they are named: a deletion against a replacement
21
+ * - `unsited`: a change of the member's lies in no site
22
+ */
23
+ export type ContradictionKind = 'call' | 'net' | 'size' | 'kind' | 'rarer' | 'count' | 'place' | 'unsited' | 'hidden';
24
+ export interface Contradiction {
25
+ kind: ContradictionKind;
26
+ haplotype: string;
27
+ site: number;
28
+ stated: number;
29
+ own: number;
30
+ }
31
+ /**
32
+ * Every place a structuralForms result states something of a member that the
33
+ * member's own departures contradict, from the departures and the result's
34
+ * statements alone: at each site that is not `edge`, of each form but
35
+ * `other`, the member's coverage against the form's call, and its changes
36
+ * touching the site against the state's marks there. At a site at most
37
+ * SUMMED_SITE_BP wide its plain pieces there add up to one change where they
38
+ * reach the floor, and its net and largest change and the kinds of its
39
+ * changes agree with the state's; at a wider site its changes pair one-to-one
40
+ * with the state's marks, each pair covering half of each other and agreeing
41
+ * in net change, size and kind.
42
+ * Agreement is structuralForms' `agrees`, the one definition the two share.
43
+ */
44
+ export declare function formContradictions(input: HaplotypeDepartures[], result: StructuralForms, { window, joinBp, }: {
45
+ window: {
46
+ start: number;
47
+ end: number;
48
+ };
49
+ joinBp?: number;
50
+ }): Contradiction[];
@@ -0,0 +1,251 @@
1
+ import { NO_CALL_STATE, OTHER_STATE, RARER_STATE, REFERENCE_STATE, STRUCTURAL_BP, SUMMED_SITE_BP, agrees, changeKind, } from "./structuralForms.js";
2
+ const touches = (m, start, end) => m.refStart <= end && m.refEnd >= start;
3
+ // Whether each of two changes covers at least half of the other on R, a
4
+ // point taking 1 bp
5
+ const halfCover = (a, b) => {
6
+ const aEnd = Math.max(a.refEnd, a.refStart + 1);
7
+ const bEnd = Math.max(b.refEnd, b.refStart + 1);
8
+ const overlap = Math.min(aEnd, bEnd) - Math.max(a.refStart, b.refStart);
9
+ return 2 * overlap >= aEnd - a.refStart && 2 * overlap >= bEnd - b.refStart;
10
+ };
11
+ const sum = (ns) => ns.reduce((s, n) => s + n, 0);
12
+ const kindsOf = (changes) => changes
13
+ .map(c => c.kind)
14
+ .sort()
15
+ .join(' ');
16
+ const largest = (changes) => changes.reduce((most, c) => Math.max(most, c.size), 0);
17
+ function joinedRun(departures, joinBp) {
18
+ const out = [];
19
+ for (const d of departures) {
20
+ const ref = d.refEnd - d.refStart;
21
+ const delta = d.altLength - ref;
22
+ const last = out.at(-1);
23
+ if (last && d.refStart - last.refEnd < joinBp) {
24
+ last.refEnd = Math.max(last.refEnd, d.refEnd);
25
+ last.delta += delta;
26
+ last.refBp += ref;
27
+ last.ownBp += d.altLength;
28
+ last.invertedBp += d.invertedBp;
29
+ last.repeatedBp += d.repeatedBp;
30
+ }
31
+ else {
32
+ out.push({
33
+ refStart: d.refStart,
34
+ refEnd: d.refEnd,
35
+ delta,
36
+ refBp: ref,
37
+ ownBp: d.altLength,
38
+ invertedBp: d.invertedBp,
39
+ repeatedBp: d.repeatedBp,
40
+ });
41
+ }
42
+ }
43
+ return out;
44
+ }
45
+ const isSmall = (d) => d.refEnd - d.refStart < STRUCTURAL_BP && d.altLength < STRUCTURAL_BP;
46
+ // Departures under STRUCTURAL_BP on both sides join only one another, and the
47
+ // rest only one another
48
+ function joined(departures, joinBp) {
49
+ const structural = departures
50
+ .filter(d => d.altLength !== d.refEnd - d.refStart ||
51
+ d.invertedBp > 0 ||
52
+ d.repeatedBp > 0)
53
+ .toSorted((a, b) => a.refStart - b.refStart || a.refEnd - b.refEnd);
54
+ return joinedRun(structural.filter(isSmall), joinBp)
55
+ .concat(joinedRun(structural.filter(d => !isSmall(d)), joinBp))
56
+ .sort((a, b) => a.refStart - b.refStart || a.refEnd - b.refEnd);
57
+ }
58
+ /**
59
+ * A haplotype's changes of at least `floorBp` over the window, from its
60
+ * departures: pieces joined where nearer than joinBp; one changing R's
61
+ * length by floorBp or more changes it, and one that does not but walks
62
+ * floorBp of R against it inverts that span. `plain` lists the pieces a
63
+ * summed site adds up: those making no change other than an insertion,
64
+ * deletion or replacement.
65
+ */
66
+ function haplotypeChanges(departures, floorBp, joinBp, window) {
67
+ const pieces = joined(departures, joinBp).filter(p => touches(p, window.start, window.end));
68
+ const changes = [];
69
+ const plain = [];
70
+ for (const p of pieces) {
71
+ const kind = Math.abs(p.delta) < floorBp
72
+ ? p.invertedBp >= floorBp
73
+ ? 'inversion'
74
+ : undefined
75
+ : p.repeatedBp >= STRUCTURAL_BP && p.delta > 0
76
+ ? 'duplication'
77
+ : changeKind(p.refBp, p.ownBp);
78
+ const isPlain = kind === 'insertion' || kind === 'deletion' || kind === 'replacement';
79
+ if (kind !== undefined) {
80
+ changes.push({
81
+ refStart: p.refStart,
82
+ refEnd: p.refEnd,
83
+ delta: p.delta,
84
+ size: kind === 'inversion' ? p.refEnd - p.refStart : Math.abs(p.delta),
85
+ kind,
86
+ plain: isPlain,
87
+ });
88
+ }
89
+ if (kind === undefined || isPlain) {
90
+ plain.push(p);
91
+ }
92
+ }
93
+ return { changes, plain };
94
+ }
95
+ // A state's marks as changes, sized as a member's are
96
+ const statedChanges = (site, key) => {
97
+ var _a, _b;
98
+ return ((_b = (_a = site.states.find(s => s.key === key)) === null || _a === void 0 ? void 0 : _a.marks) !== null && _b !== void 0 ? _b : []).map(m => ({
99
+ refStart: m.refStart,
100
+ refEnd: m.refEnd,
101
+ delta: m.delta,
102
+ size: m.kind === 'inversion' ? m.refEnd - m.refStart : Math.abs(m.delta),
103
+ kind: m.kind,
104
+ plain: m.kind === 'insertion' ||
105
+ m.kind === 'deletion' ||
106
+ m.kind === 'replacement',
107
+ }));
108
+ };
109
+ // Whether `as` and `bs` pair one-to-one with `pairs` true of every pair
110
+ function pairOneToOne(as, bs, pairs) {
111
+ const holder = bs.map(() => -1);
112
+ const place = (i, seen) => bs.some((b, j) => {
113
+ let placed = false;
114
+ if (!seen.has(j) && pairs(as[i], b)) {
115
+ seen.add(j);
116
+ placed = holder[j] < 0 || place(holder[j], seen);
117
+ if (placed) {
118
+ holder[j] = i;
119
+ }
120
+ }
121
+ return placed;
122
+ });
123
+ return as.length === bs.length && as.every((_, i) => place(i, new Set()));
124
+ }
125
+ // The state key a form states at a site: its key at an informative site, and
126
+ // at a shared one the state of its marks there, R's where it has none; none
127
+ // at an edge site or for `other`
128
+ function statedKey(result, form, site) {
129
+ var _a, _b;
130
+ const k = result.informative.indexOf(site);
131
+ return form.key === OTHER_STATE || result.sites[site].edge
132
+ ? undefined
133
+ : k >= 0
134
+ ? form.states[k]
135
+ : result.sites[site].shared
136
+ ? ((_b = (_a = form.marks.find(m => m.site === site)) === null || _a === void 0 ? void 0 : _a.state) !== null && _b !== void 0 ? _b : REFERENCE_STATE)
137
+ : undefined;
138
+ }
139
+ /**
140
+ * Every place a structuralForms result states something of a member that the
141
+ * member's own departures contradict, from the departures and the result's
142
+ * statements alone: at each site that is not `edge`, of each form but
143
+ * `other`, the member's coverage against the form's call, and its changes
144
+ * touching the site against the state's marks there. At a site at most
145
+ * SUMMED_SITE_BP wide its plain pieces there add up to one change where they
146
+ * reach the floor, and its net and largest change and the kinds of its
147
+ * changes agree with the state's; at a wider site its changes pair one-to-one
148
+ * with the state's marks, each pair covering half of each other and agreeing
149
+ * in net change, size and kind.
150
+ * Agreement is structuralForms' `agrees`, the one definition the two share.
151
+ */
152
+ export function formContradictions(input, result, { window, joinBp = STRUCTURAL_BP, }) {
153
+ var _a;
154
+ const { floorBp, sites } = result;
155
+ const byName = new Map(input.map(h => [h.haplotype, h]));
156
+ const out = [];
157
+ const covers = (h, site) => {
158
+ const start = Math.max(site.refStart, window.start);
159
+ const end = Math.min(site.refEnd, window.end);
160
+ return h.covered.some(([a, b]) => a <= start && b >= end);
161
+ };
162
+ const netAgrees = (a, b) => halfCover(a, b) &&
163
+ agrees(a.delta, b.delta, floorBp, Math.max(a.size, b.size));
164
+ const sizeAgrees = (a, b) => netAgrees(a, b) && agrees(a.size, b.size, floorBp);
165
+ const kindAgrees = (a, b) => sizeAgrees(a, b) && a.kind === b.kind;
166
+ for (const form of result.forms) {
167
+ for (const name of form.members) {
168
+ const h = byName.get(name);
169
+ const { changes, plain } = haplotypeChanges((_a = h === null || h === void 0 ? void 0 : h.departures) !== null && _a !== void 0 ? _a : [], floorBp, joinBp, window);
170
+ const add = (kind, site, stated, own) => {
171
+ out.push({ kind, haplotype: name, site, stated, own });
172
+ };
173
+ for (const c of changes) {
174
+ if (!sites.some(s => touches(c, s.refStart, s.refEnd))) {
175
+ add('unsited', -1, 0, c.delta);
176
+ }
177
+ }
178
+ sites.forEach((site, i) => {
179
+ const key = statedKey(result, form, i);
180
+ if (key !== undefined) {
181
+ const called = h !== undefined && covers(h, site);
182
+ const summed = site.refEnd - site.refStart <= SUMMED_SITE_BP;
183
+ const at = changes.filter(c => touches(c, site.refStart, site.refEnd));
184
+ const plainHere = plain.filter(p => touches(p, site.refStart, site.refEnd));
185
+ const plainNet = sum(plainHere.map(p => p.delta));
186
+ const plainKind = changeKind(sum(plainHere.map(p => p.refBp)), sum(plainHere.map(p => p.ownBp)));
187
+ const own = summed
188
+ ? [
189
+ ...at.filter(c => !c.plain),
190
+ ...(Math.abs(plainNet) >= floorBp
191
+ ? [
192
+ {
193
+ refStart: site.refStart,
194
+ refEnd: site.refEnd,
195
+ delta: plainNet,
196
+ size: Math.abs(plainNet),
197
+ kind: plainKind,
198
+ plain: true,
199
+ },
200
+ ]
201
+ : []),
202
+ ]
203
+ : at;
204
+ const ownNet = sum(own.map(c => c.delta));
205
+ const stated = statedChanges(site, key);
206
+ const statedNet = sum(stated.map(c => c.delta));
207
+ if (key === NO_CALL_STATE) {
208
+ if (called) {
209
+ add('hidden', i, 0, ownNet);
210
+ }
211
+ }
212
+ else if (!called) {
213
+ add('call', i, 0, 0);
214
+ }
215
+ else if (key === RARER_STATE) {
216
+ if (own.length === 0) {
217
+ add('rarer', i, floorBp, ownNet);
218
+ }
219
+ }
220
+ else if (summed) {
221
+ if (!agrees(statedNet, ownNet, floorBp, Math.max(largest(stated), largest(own)))) {
222
+ add('net', i, statedNet, ownNet);
223
+ }
224
+ else if (!agrees(largest(stated), largest(own), floorBp)) {
225
+ add('size', i, largest(stated), largest(own));
226
+ }
227
+ else if (kindsOf(stated) !== kindsOf(own)) {
228
+ add('kind', i, statedNet, ownNet);
229
+ }
230
+ }
231
+ else if (stated.length !== own.length) {
232
+ add('count', i, stated.length, own.length);
233
+ }
234
+ else if (!pairOneToOne(stated, own, halfCover)) {
235
+ add('place', i, statedNet, ownNet);
236
+ }
237
+ else if (!pairOneToOne(stated, own, netAgrees)) {
238
+ add('net', i, statedNet, ownNet);
239
+ }
240
+ else if (!pairOneToOne(stated, own, sizeAgrees)) {
241
+ add('size', i, largest(stated), largest(own));
242
+ }
243
+ else if (!pairOneToOne(stated, own, kindAgrees)) {
244
+ add('kind', i, statedNet, ownNet);
245
+ }
246
+ }
247
+ });
248
+ }
249
+ }
250
+ return out;
251
+ }
@@ -0,0 +1,27 @@
1
+ import type { TabixSource } from './tabixSource.ts';
2
+ export type GfaTabixFileOptions = {
3
+ segments: Pick<TabixSource, 'getLines'>;
4
+ links: Pick<TabixSource, 'getLines'>;
5
+ } | {
6
+ graph: Pick<TabixSource, 'getLines' | 'getHeaderLines'>;
7
+ };
8
+ export interface GfaTabixRangeOptions {
9
+ hops?: number;
10
+ signal?: AbortSignal;
11
+ }
12
+ /**
13
+ * gfa-to-tabix's GFA tabix file, its segments and links Tabix-indexed BED
14
+ * by stable sequence: `{ graph }`, format 2's graph.bed.gz, or `{ segments,
15
+ * links }`, format 1's two files, each a TabixIndexedFile of @gmod/tabix or
16
+ * anything that reads as one
17
+ */
18
+ export declare class GfaTabixFile {
19
+ private readonly files;
20
+ constructor(files: GfaTabixFileOptions);
21
+ /**
22
+ * The graph over the 0-based half-open range of stable sequence `refName`,
23
+ * as GFA text: its segments and links, `hops` rounds of links followed
24
+ * past them, 0 by default
25
+ */
26
+ getGraphForRange(refName: string, start: number, end: number, opts?: GfaTabixRangeOptions): Promise<string>;
27
+ }
@@ -0,0 +1,168 @@
1
+ import { addLink, anchoredCut, closingLinks, closingSpans, formatSubgraph, parseGraphHeader, parseGraphRow, parseLinkLine, parseSegmentRow, } from "./rgfaBed.js";
2
+ import { checkRange } from "./tabixSource.js";
3
+ // What a hop follows: alleles, never the backbone. A rank-0 segment reached
4
+ // through a link is flanking backbone, usually outside the window, so querying
5
+ // its links walks the reference away from the region, brings back more backbone,
6
+ // and closes nothing. Every segment that closes a bubble is an allele interior,
7
+ // and an allele interior is rank > 0 in both index formats (rGFA's SR tag, and
8
+ // pggb's rank 0-or-1 against the anchor path). Reached backbone still becomes a
9
+ // node and its edge still draws; it is only not walked through.
10
+ //
11
+ // This is gfabase's rule, arrived at from the other end. `gfabase sub` expands
12
+ // from a seed either to the whole connected component (`--connected`, which its
13
+ // own README calls overkill) or with `--cutpoints 1`, which takes the biconnected
14
+ // component by *stopping at cutpoints*, the segments every end-to-end walk of
15
+ // the chromosome must traverse. In a reference-anchored pangenome the cutpoints
16
+ // are the backbone, and rank is what the index already states about it, so
17
+ // `rank > 0` is that stopping rule without a connectivity index to build. The
18
+ // third tool is the same shape again: `gfatools view -R` maps the region onto its
19
+ // precomputed bubble decomposition and returns whole overlapping bubbles
20
+ // (gfa_query_by_reg), which is complete for the same reason. Bandage's own
21
+ // `--distance` is a node-step radius, but Bandage holds the entire graph in
22
+ // memory, so its scope is a drawing filter rather than a fetch strategy.
23
+ //
24
+ // Measured with this rule: the E. coli paa window converges at one hop (17
25
+ // segments at 1 and at 2), so the cut closes and stays closed. HPRC's amylase
26
+ // window keeps growing (63 at 0, 78 at 1, 92 at 2) because its alleles have
27
+ // alleles, and wall-clock is flat across all three, since a hop's queries go out
28
+ // together and the remote index dominates.
29
+ //
30
+ // The exact version, when a graph ships a bubble index beside its segments:
31
+ // gfatools' bubble rows carry the member segment ids of every bubble, so the
32
+ // bubbles overlapping the region state which segments a complete cut must
33
+ // contain. That turns the hop count into a termination condition rather than a
34
+ // setting, and MinigraphBubbleAdapter already parses those rows.
35
+ function offReference(segments) {
36
+ return segments.filter(segment => segment.rank > 0);
37
+ }
38
+ const headers = new WeakMap();
39
+ function graphHeader(file, signal) {
40
+ let header = headers.get(file);
41
+ if (!header) {
42
+ header = file.getHeaderLines({ signal }).then(parseGraphHeader);
43
+ header.catch(() => headers.delete(file));
44
+ headers.set(file, header);
45
+ }
46
+ return header;
47
+ }
48
+ function getLines(file, refName, start, end, opts) {
49
+ checkRange(refName, start, end);
50
+ return file.getLines(refName, start, end, opts);
51
+ }
52
+ // The segments and links filed over `span`, and whether the index is
53
+ // anchored. Format 1 reads the segment file only when asked, as a hop needs
54
+ // only links. Format 2's one query returns both kinds, and a link end its row
55
+ // gives no carriers takes the tags of its node row in the same query; an end
56
+ // past the span has none.
57
+ async function readSpan(files, span, withSegments, signal) {
58
+ var _a, _b;
59
+ var _c, _d;
60
+ const segments = [];
61
+ const links = [];
62
+ const read = (file, lineCallback) => getLines(file, span.refName, span.start, span.end, { signal, lineCallback });
63
+ if ('graph' in files) {
64
+ const header = await graphHeader(files.graph, signal);
65
+ await read(files.graph, line => {
66
+ const row = parseGraphRow(line, header);
67
+ if ((row === null || row === void 0 ? void 0 : row.kind) === 'N') {
68
+ segments.push(row.segment);
69
+ }
70
+ else if ((row === null || row === void 0 ? void 0 : row.kind) === 'L') {
71
+ links.push(row.link);
72
+ }
73
+ });
74
+ const tags = new Map(segments.map(s => [s.id, s.tags]));
75
+ for (const link of links) {
76
+ (_c = link.sourceSegment).tags || (_c.tags = (_a = tags.get(link.source)) !== null && _a !== void 0 ? _a : '');
77
+ (_d = link.targetSegment).tags || (_d.tags = (_b = tags.get(link.target)) !== null && _b !== void 0 ? _b : '');
78
+ }
79
+ return {
80
+ segments: withSegments ? segments : [],
81
+ links,
82
+ anchored: header.anchored,
83
+ };
84
+ }
85
+ let anchored = false;
86
+ await Promise.all([
87
+ withSegments &&
88
+ read(files.segments, line => {
89
+ const row = parseSegmentRow(line);
90
+ anchored || (anchored = row.anchored);
91
+ segments.push(row.segment);
92
+ }),
93
+ read(files.links, line => {
94
+ links.push(parseLinkLine(line));
95
+ }),
96
+ ]);
97
+ return { segments, links, anchored };
98
+ }
99
+ /**
100
+ * The graph around a window of one stable sequence, as GFA text. The window's
101
+ * own segments come from the segment file; the link file supplies the edges
102
+ * incident to them *and* the coordinates of the segments on the other end,
103
+ * which typically sit on a different stable sequence (a rank>0 bubble) and so
104
+ * are not reachable by any coordinate query on this window.
105
+ *
106
+ * `hops` is extra rounds of link-following past the window's own segments and
107
+ * their immediate neighbours, each costing one tabix query per off-reference
108
+ * segment newly reached. After the last round, one more read per stretch of
109
+ * stable sequence the cut holds closes it (closingSpans), so an allele reached
110
+ * from both ends draws whole. The view asks for one hop; a hopless cut stays
111
+ * as cheap as it was. `signal` goes to every one of those queries, so a cut
112
+ * the view has replaced stops.
113
+ */
114
+ async function rgfaCut(files, window, { hops = 0, signal } = {}) {
115
+ const segments = new Map();
116
+ const links = new Map();
117
+ // Both layouts read the links over the window, so that read goes out
118
+ // beside the segment read rather than after it.
119
+ const first = await readSpan(files, window, true, signal);
120
+ for (const segment of first.segments) {
121
+ segments.set(segment.id, segment);
122
+ }
123
+ const windowLinks = first.links;
124
+ // An anchored index files every allele and every link under the reference
125
+ // interval its bubble hangs from, so one read of each file holds the whole
126
+ // graph under the window and there is nothing to hop to or close.
127
+ if (first.anchored) {
128
+ const cut = anchoredCut(segments, windowLinks, window);
129
+ return formatSubgraph(cut.segments, cut.links);
130
+ }
131
+ const linksOver = async (span) => (await readSpan(files, span, false, signal)).links;
132
+ const addLinksOver = async (span) => (await linksOver(span)).flatMap(link => addLink(segments, links, link));
133
+ let frontier = offReference(windowLinks.flatMap(link => addLink(segments, links, link)));
134
+ for (let hop = 0; hop < hops; hop++) {
135
+ // One hop's queries are independent of each other, so they go out
136
+ // together rather than one round-trip at a time, and the output is sorted
137
+ // at the end regardless of the order they arrive in.
138
+ const reached = await Promise.all(frontier.map(addLinksOver));
139
+ frontier = offReference(reached.flat());
140
+ }
141
+ if (hops > 0) {
142
+ const spans = closingSpans([...segments.values()], new Set(frontier.map(segment => segment.id)), window);
143
+ const found = await Promise.all(spans.map(span => linksOver(span)));
144
+ for (const link of closingLinks(found.flat(), segments, spans)) {
145
+ addLink(segments, links, link);
146
+ }
147
+ }
148
+ return formatSubgraph(segments, links);
149
+ }
150
+ /**
151
+ * gfa-to-tabix's GFA tabix file, its segments and links Tabix-indexed BED
152
+ * by stable sequence: `{ graph }`, format 2's graph.bed.gz, or `{ segments,
153
+ * links }`, format 1's two files, each a TabixIndexedFile of @gmod/tabix or
154
+ * anything that reads as one
155
+ */
156
+ export class GfaTabixFile {
157
+ constructor(files) {
158
+ this.files = files;
159
+ }
160
+ /**
161
+ * The graph over the 0-based half-open range of stable sequence `refName`,
162
+ * as GFA text: its segments and links, `hops` rounds of links followed
163
+ * past them, 0 by default
164
+ */
165
+ getGraphForRange(refName, start, end, opts = {}) {
166
+ return rgfaCut(this.files, { refName, start, end }, opts);
167
+ }
168
+ }