@gmod/gfa-tabix 0.0.0-stage → 10.1.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/esm/index.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ export { CUT_PRESETS, DepartureReadError, WALK_BUDGETS, WALK_CONTEXT, WalkFile, } from './walkFile.ts';
2
+ export type { BytesForRangeOptions, CountsForRangeOptions, CutForRange, CutForRangeOptions, FormsForRangeOptions, GraphForRange, GraphForRangeOptions, RunsForRangeOptions, WalkCountOptions, WalkCutOptions, WalkFileHeader, WalkFileOptions, } from './walkFile.ts';
3
+ export { GfaTabixFile } from './gfaTabixFile.ts';
4
+ export type { GfaTabixFileOptions, GfaTabixRangeOptions, } from './gfaTabixFile.ts';
5
+ export { WALK_FORMAT, WalkFormatError } from './walkContainer.ts';
6
+ export type { WalkFilehandle, WalkUnit } from './walkContainer.ts';
7
+ export { WalkRowError } from './walkChunk.ts';
8
+ export { AmbiguousSequenceError, MissingSequenceError, refNameLookup, resolveRefName, } from './refNames.ts';
9
+ export { RegionTooLargeError, bpString, panSNContig, panSNHaplotype, panSNMatchesPrefix, panSNSample, } from './util.ts';
10
+ export type { DepartureTable, GapTable, GraphTables } from './util.ts';
11
+ export { BUDGET_NAMES, isPlaceholder, keptStepsError, walksKept, } from './walkRows.ts';
12
+ export type { Abridged, BudgetNames, WalkFragment, WalkNode, } from './walkRows.ts';
13
+ export { ATTACH_BP, departureKind, placementChoice } from './walkDeparture.ts';
14
+ export type { DepartureKind, WalkDeparture } from './walkDeparture.ts';
15
+ export { GAP_KINDS } from './walkGaps.ts';
16
+ export type { GapKind, GapSegment, WalkGap } from './walkGaps.ts';
17
+ export { END_KINDS, RunsRefusedError, fragmentRuns } from './walkRuns.ts';
18
+ export type { EndKind, WalkEnds, WalkRuns } from './walkRuns.ts';
19
+ export { COUNT_REASONS, countReasons } from './walkCounts.ts';
20
+ export type { CountColumns, CountReason, WalkCounts } from './walkCounts.ts';
21
+ export { FORMS_STEP_BUDGET, walkDepartures } from './walkDepartures.ts';
22
+ export type { Departure, DepartureSource, HaplotypeDepartures, } from './walkDepartures.ts';
23
+ export { FLOOR_PRESETS, NO_CALL_STATE, OTHER_STATE, RARER_STATE, REFERENCE_STATE, STRUCTURAL_BP, changeKind, describeForm, formStateAt, formTag, markTag, sizeTag, stateKey, structuralForms, } from './structuralForms.ts';
24
+ export type { Form, FormsOptions, Mark, MarkKind, Site, SiteMark, SiteState, StructuralForms, } from './structuralForms.ts';
25
+ export { abridgedText, abridgedWalks } from './abridgedWalks.ts';
26
+ export type { AbridgedWalk } from './abridgedWalks.ts';
27
+ export { checkRange } from './tabixSource.ts';
28
+ export type { TabixSource } from './tabixSource.ts';
29
+ export { formatSubgraph, linkKey, parseGraphHeader, parseGraphRow, parseLinkLine, parseSegmentLine, parseSegmentRow, segmentSamples, } from './rgfaBed.ts';
30
+ export type { RgfaSegment } from './rgfaBed.ts';
package/esm/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export { CUT_PRESETS, DepartureReadError, WALK_BUDGETS, WALK_CONTEXT, WalkFile, } from "./walkFile.js";
2
+ export { GfaTabixFile } from "./gfaTabixFile.js";
3
+ export { WALK_FORMAT, WalkFormatError } from "./walkContainer.js";
4
+ export { WalkRowError } from "./walkChunk.js";
5
+ export { AmbiguousSequenceError, MissingSequenceError, refNameLookup, resolveRefName, } from "./refNames.js";
6
+ export { RegionTooLargeError, bpString, panSNContig, panSNHaplotype, panSNMatchesPrefix, panSNSample, } from "./util.js";
7
+ export { BUDGET_NAMES, isPlaceholder, keptStepsError, walksKept, } from "./walkRows.js";
8
+ export { ATTACH_BP, departureKind, placementChoice } from "./walkDeparture.js";
9
+ export { GAP_KINDS } from "./walkGaps.js";
10
+ export { END_KINDS, RunsRefusedError, fragmentRuns } from "./walkRuns.js";
11
+ export { COUNT_REASONS, countReasons } from "./walkCounts.js";
12
+ export { FORMS_STEP_BUDGET, walkDepartures } from "./walkDepartures.js";
13
+ export { FLOOR_PRESETS, NO_CALL_STATE, OTHER_STATE, RARER_STATE, REFERENCE_STATE, STRUCTURAL_BP, changeKind, describeForm, formStateAt, formTag, markTag, sizeTag, stateKey, structuralForms, } from "./structuralForms.js";
14
+ export { abridgedText, abridgedWalks } from "./abridgedWalks.js";
15
+ export { checkRange } from "./tabixSource.js";
16
+ export { formatSubgraph, linkKey, parseGraphHeader, parseGraphRow, parseLinkLine, parseSegmentLine, parseSegmentRow, segmentSamples, } from "./rgfaBed.js";
@@ -0,0 +1,25 @@
1
+ export declare class AmbiguousSequenceError extends Error {
2
+ name: string;
3
+ readonly sequences: string[];
4
+ constructor(assemblyName: string, refName: string, sequences: string[]);
5
+ }
6
+ export declare class MissingSequenceError extends Error {
7
+ name: string;
8
+ readonly sequences: string[];
9
+ constructor(refName: string, assemblyName: string, sequences: string[]);
10
+ }
11
+ /**
12
+ * A file's sequence names under each spelling a caller may ask by: the file's
13
+ * own (`GRCh38#0#chr6`), and a PanSN name's contig under its sample (`chr6`
14
+ * on `GRCh38`) and under its haplotype (`chr6` on `GRCh38#0`). A pggb name
15
+ * with no haplotype field, `chm13#chr1`, is `chr1` on `chm13`. A spelling
16
+ * two names share, `chr1` on `HG002` where the file holds `HG002#1#chr1` and
17
+ * `HG002#2#chr1`, keeps both.
18
+ */
19
+ export declare function refNameLookup(names: string[]): Map<string, string[]>;
20
+ /**
21
+ * The file's name for `refName` on `assemblyName`, a sample or a haplotype,
22
+ * else for `refName` as the file spells it; undefined when it holds neither.
23
+ * Throws AmbiguousSequenceError where the spelling names more than one.
24
+ */
25
+ export declare function resolveRefName(lookup: Map<string, string[]>, assemblyName: string, refName: string): string | undefined;
@@ -0,0 +1,65 @@
1
+ import { panSNContig, panSNHaplotype, panSNSample } from "./util.js";
2
+ // A tab can occur in neither half: both come out of BED columns
3
+ function qualifiedKey(assemblyName, refName) {
4
+ return `${assemblyName}\t${refName}`;
5
+ }
6
+ export class AmbiguousSequenceError extends Error {
7
+ constructor(assemblyName, refName, sequences) {
8
+ super(`${refName} on ${assemblyName} is ${sequences.length} sequences of the file, ${sequences.join(', ')}; name one of them, or its haplotype: ${sequences.map(name => panSNHaplotype(name)).join(', ')}`);
9
+ this.name = 'AmbiguousSequenceError';
10
+ this.sequences = sequences;
11
+ }
12
+ }
13
+ export class MissingSequenceError extends Error {
14
+ constructor(refName, assemblyName, sequences) {
15
+ super(`The walk file has no sequence ${refName} on ${assemblyName}; it holds ${sequences.slice(0, 5).join(', ')}${sequences.length > 5 ? ', …' : ''}`);
16
+ this.name = 'MissingSequenceError';
17
+ this.sequences = sequences;
18
+ }
19
+ }
20
+ /**
21
+ * A file's sequence names under each spelling a caller may ask by: the file's
22
+ * own (`GRCh38#0#chr6`), and a PanSN name's contig under its sample (`chr6`
23
+ * on `GRCh38`) and under its haplotype (`chr6` on `GRCh38#0`). A pggb name
24
+ * with no haplotype field, `chm13#chr1`, is `chr1` on `chm13`. A spelling
25
+ * two names share, `chr1` on `HG002` where the file holds `HG002#1#chr1` and
26
+ * `HG002#2#chr1`, keeps both.
27
+ */
28
+ export function refNameLookup(names) {
29
+ const lookup = new Map();
30
+ const file = (key, name) => {
31
+ const held = lookup.get(key);
32
+ if (held === undefined) {
33
+ lookup.set(key, [name]);
34
+ }
35
+ else if (!held.includes(name)) {
36
+ held.push(name);
37
+ }
38
+ };
39
+ for (const name of names) {
40
+ file(name, name);
41
+ const sample = panSNSample(name);
42
+ if (sample !== name) {
43
+ const contig = panSNContig(name);
44
+ file(qualifiedKey(sample, contig), name);
45
+ const haplotype = panSNHaplotype(name);
46
+ if (haplotype !== undefined) {
47
+ file(qualifiedKey(haplotype, contig), name);
48
+ }
49
+ }
50
+ }
51
+ return lookup;
52
+ }
53
+ /**
54
+ * The file's name for `refName` on `assemblyName`, a sample or a haplotype,
55
+ * else for `refName` as the file spells it; undefined when it holds neither.
56
+ * Throws AmbiguousSequenceError where the spelling names more than one.
57
+ */
58
+ export function resolveRefName(lookup, assemblyName, refName) {
59
+ var _a;
60
+ const held = (_a = lookup.get(qualifiedKey(assemblyName, refName))) !== null && _a !== void 0 ? _a : lookup.get(refName);
61
+ if (held !== undefined && held.length > 1) {
62
+ throw new AmbiguousSequenceError(assemblyName, refName, held);
63
+ }
64
+ return held === null || held === void 0 ? void 0 : held[0];
65
+ }
@@ -0,0 +1,67 @@
1
+ export interface RgfaSegment {
2
+ refName: string;
3
+ start: number;
4
+ end: number;
5
+ id: string;
6
+ rank: number;
7
+ tags: string;
8
+ }
9
+ export interface RgfaLink {
10
+ source: string;
11
+ sourceStrand: string;
12
+ target: string;
13
+ targetStrand: string;
14
+ sourceSegment: RgfaSegment;
15
+ targetSegment: RgfaSegment;
16
+ }
17
+ export declare function parseSegmentLine(line: string): RgfaSegment;
18
+ export declare function parseSegmentRow(line: string): {
19
+ anchored: boolean;
20
+ segment: {
21
+ refName: string;
22
+ start: number;
23
+ end: number;
24
+ id: string;
25
+ rank: number;
26
+ tags: string;
27
+ };
28
+ };
29
+ export declare function segmentSamples(segment: RgfaSegment): string[] | undefined;
30
+ export declare function parseLinkLine(line: string): RgfaLink;
31
+ export interface GraphHeader {
32
+ anchored: boolean;
33
+ samples: string[];
34
+ }
35
+ export declare function parseGraphHeader(lines: string[]): GraphHeader;
36
+ export declare function carrierNames(hex: string, samples: string[]): string[];
37
+ export declare function parseGraphRow(line: string, header: GraphHeader): {
38
+ kind: "N";
39
+ segment: {
40
+ refName: string;
41
+ start: number;
42
+ end: number;
43
+ id: string;
44
+ rank: number;
45
+ tags: string;
46
+ };
47
+ link?: undefined;
48
+ } | {
49
+ kind: "L";
50
+ link: RgfaLink;
51
+ segment?: undefined;
52
+ } | undefined;
53
+ export declare function linkKey(link: RgfaLink): string;
54
+ export declare function addLink(segments: Map<string, RgfaSegment>, links: Map<string, RgfaLink>, link: RgfaLink): RgfaSegment[];
55
+ export declare function anchoredCut(under: Map<string, RgfaSegment>, found: RgfaLink[], window: StableSpan): {
56
+ segments: Map<string, RgfaSegment>;
57
+ links: Map<string, RgfaLink>;
58
+ };
59
+ export declare const MOVED_TAG = "mv:i:1";
60
+ export interface StableSpan {
61
+ refName: string;
62
+ start: number;
63
+ end: number;
64
+ }
65
+ export declare function closingSpans(held: RgfaSegment[], unread: Set<string>, window: StableSpan): StableSpan[];
66
+ export declare function closingLinks(found: RgfaLink[], held: Map<string, RgfaSegment>, spans: StableSpan[]): RgfaLink[];
67
+ export declare function formatSubgraph(segments: Map<string, RgfaSegment>, links: Map<string, RgfaLink>): string;
package/esm/rgfaBed.js ADDED
@@ -0,0 +1,301 @@
1
+ export function parseSegmentLine(line) {
2
+ return parseSegmentRow(line).segment;
3
+ }
4
+ // gfa-to-tabix's anchored layout files a segment under the reference interval
5
+ // its bubble hangs from and states the segment's own coordinate after the rank:
6
+ // `anchorName anchorStart anchorEnd segmentId rank stableName start end [tags]`.
7
+ // One query over a region then returns every segment of every bubble under it,
8
+ // and `anchored` tells a cut it has nothing left to follow.
9
+ export function parseSegmentRow(line) {
10
+ const cols = line.split('\t');
11
+ return segmentFromColumns(cols, cols.length >= 8);
12
+ }
13
+ function segmentFromColumns(cols, anchored) {
14
+ var _a;
15
+ const own = anchored ? 5 : 0;
16
+ return {
17
+ anchored,
18
+ segment: {
19
+ refName: cols[own],
20
+ start: +cols[own + 1],
21
+ end: +cols[own + 2],
22
+ id: cols[3],
23
+ rank: +cols[4],
24
+ tags: (_a = cols[anchored ? 8 : 5]) !== null && _a !== void 0 ? _a : '',
25
+ },
26
+ };
27
+ }
28
+ // Carriage as an ordinary feature attribute, for the linear track rather than
29
+ // the graph. The tag column reaches the graph view through the synthesized
30
+ // S-line (formatSegment below, then gfaConverter reads SM into
31
+ // `GraphNode.samples`), and that route ends at the graph: `getFeatures` builds
32
+ // its own features and had no way to say who carries a segment, so a lane
33
+ // colored by carriage was not expressible.
34
+ //
35
+ // `SM:Z:` is its own grammar check here. build_pggb_tabix.sh wrote a bare
36
+ // comma-separated list in this column before the tag column existed, and those
37
+ // files are still hosted; a bare list has no prefix to match, so it is dropped
38
+ // rather than read as one sample named `K12,Sakai,CFT073`.
39
+ //
40
+ // Undefined rather than [] when the tag is absent, matching gfaConverter: an
41
+ // rGFA has no sixth column at all, so a segment that says nothing about
42
+ // carriage stays distinguishable from one carried by nobody.
43
+ export function segmentSamples(segment) {
44
+ const tag = segment.tags.split(' ').find(t => t.startsWith('SM:Z:'));
45
+ if (tag === undefined) {
46
+ return undefined;
47
+ }
48
+ const samples = tag
49
+ .slice('SM:Z:'.length)
50
+ .split(',')
51
+ .map(s => s.trim())
52
+ .filter(Boolean);
53
+ return samples.length > 0 ? samples : undefined;
54
+ }
55
+ // `s322+` — the L-line's segment id with its orientation appended, mirroring
56
+ // the GFA record it came from.
57
+ function parseEndpoint(field) {
58
+ return { id: field.slice(0, -1), strand: field.slice(-1) };
59
+ }
60
+ export function parseLinkLine(line) {
61
+ return linkFromColumns(line.split('\t'));
62
+ }
63
+ function linkFromColumns(cols) {
64
+ var _a, _b;
65
+ const source = parseEndpoint(cols[3]);
66
+ const target = parseEndpoint(cols[4]);
67
+ return {
68
+ source: source.id,
69
+ sourceStrand: source.strand,
70
+ target: target.id,
71
+ targetStrand: target.strand,
72
+ sourceSegment: {
73
+ id: source.id,
74
+ refName: cols[5],
75
+ start: +cols[6],
76
+ end: +cols[7],
77
+ rank: +cols[8],
78
+ tags: (_a = cols[13]) !== null && _a !== void 0 ? _a : '',
79
+ },
80
+ targetSegment: {
81
+ id: target.id,
82
+ refName: cols[9],
83
+ start: +cols[10],
84
+ end: +cols[11],
85
+ rank: +cols[12],
86
+ tags: (_b = cols[14]) !== null && _b !== void 0 ? _b : '',
87
+ },
88
+ };
89
+ }
90
+ export function parseGraphHeader(lines) {
91
+ const first = lines.find(l => l.startsWith('#gfa-to-tabix\t'));
92
+ if (first === undefined) {
93
+ throw new Error('not a gfa-to-tabix graph file: no #gfa-to-tabix header');
94
+ }
95
+ const tags = new Map(first
96
+ .split('\t')
97
+ .slice(1)
98
+ .map(tag => [
99
+ tag.slice(0, tag.indexOf(':')),
100
+ tag.slice(tag.indexOf(':') + 3),
101
+ ]));
102
+ const format = tags.get('format');
103
+ if (format !== '2') {
104
+ throw new Error(`gfa-to-tabix format ${format}: this @gmod/gfa-tabix reads format 2`);
105
+ }
106
+ const samples = lines.find(l => l.startsWith('#samples\t'));
107
+ return {
108
+ anchored: tags.get('layout') === 'anchored',
109
+ samples: samples !== undefined
110
+ ? samples.slice('#samples\t'.length).split(',')
111
+ : [],
112
+ };
113
+ }
114
+ // `SB:H:` hex digit i / 4, counted from the left, holds sample i as bit i % 4
115
+ export function carrierNames(hex, samples) {
116
+ const names = [];
117
+ for (let digit = 0; digit < hex.length; digit++) {
118
+ const bits = Number.parseInt(hex[digit], 16);
119
+ for (let bit = 0; bit < 4; bit++) {
120
+ if (bits & (1 << bit)) {
121
+ names.push(samples[digit * 4 + bit]);
122
+ }
123
+ }
124
+ }
125
+ return names;
126
+ }
127
+ // A format-2 row as format 1 states it: `SB:H:` becomes the `SM:Z:` list of
128
+ // names that segmentSamples and bandage-core read, in `#samples` order, on a
129
+ // node row and on either end of a link row that states one. Undefined for a
130
+ // row kind this reader doesn't know.
131
+ export function parseGraphRow(line, header) {
132
+ const cols = line.split('\t');
133
+ const [kind] = cols.splice(3, 1);
134
+ const named = (i) => {
135
+ var _a;
136
+ if (((_a = cols[i]) === null || _a === void 0 ? void 0 : _a.startsWith('SB:H:')) === true) {
137
+ cols[i] =
138
+ `SM:Z:${carrierNames(cols[i].slice(5), header.samples).join(',')}`;
139
+ }
140
+ };
141
+ if (kind === 'N') {
142
+ named(header.anchored ? 8 : 5);
143
+ return {
144
+ kind: 'N',
145
+ segment: segmentFromColumns(cols, header.anchored).segment,
146
+ };
147
+ }
148
+ if (kind === 'L') {
149
+ named(13);
150
+ named(14);
151
+ return { kind: 'L', link: linkFromColumns(cols) };
152
+ }
153
+ return undefined;
154
+ }
155
+ export function linkKey(link) {
156
+ return `${link.source}${link.sourceStrand}${link.target}${link.targetStrand}`;
157
+ }
158
+ // gfa-to-tabix writes both endpoints of a link into every row and files the
159
+ // link under each endpoint's stable sequence, so a read covering both returns
160
+ // it twice; linkKey dedupes it. Returns the endpoints the cut lacked.
161
+ export function addLink(segments, links, link) {
162
+ links.set(linkKey(link), link);
163
+ const added = [];
164
+ for (const segment of [link.sourceSegment, link.targetSegment]) {
165
+ if (!segments.has(segment.id)) {
166
+ segments.set(segment.id, segment);
167
+ added.push(segment);
168
+ }
169
+ }
170
+ return added;
171
+ }
172
+ // The cut an anchored index gives: `under` is what the segment file returned
173
+ // for the window, every segment of every bubble under it, and `found` is what
174
+ // the link file returned. gfa-to-tabix files a link widely enough that `found`
175
+ // holds every link touching a segment in `under` and every link between the
176
+ // segments those lead to, plus links of neither kind, which are dropped here.
177
+ // A backbone link that jumps the whole window, as a deletion or inversion
178
+ // spanning it does, touches nothing in `under` and is kept by its own rule.
179
+ export function anchoredCut(under, found, window) {
180
+ const side = (segment) => segment.rank !== 0 || segment.refName !== window.refName
181
+ ? 0
182
+ : segment.end <= window.start
183
+ ? -1
184
+ : segment.start >= window.end
185
+ ? 1
186
+ : 0;
187
+ const segments = new Map(under);
188
+ const links = new Map();
189
+ for (const link of found) {
190
+ if (under.has(link.source) ||
191
+ under.has(link.target) ||
192
+ side(link.sourceSegment) * side(link.targetSegment) === -1) {
193
+ addLink(segments, links, link);
194
+ }
195
+ }
196
+ for (const link of found) {
197
+ if (segments.has(link.source) && segments.has(link.target)) {
198
+ links.set(linkKey(link), link);
199
+ }
200
+ }
201
+ // Every segment of a bubble under the window comes back from the segment
202
+ // file, so one of rank 1 or more that only a link brought belongs to a
203
+ // component gfa-to-tabix's --max-component left on its own coordinates
204
+ for (const [id, segment] of segments) {
205
+ if (!under.has(id) && segment.rank > 0) {
206
+ segments.set(id, {
207
+ ...segment,
208
+ tags: segment.tags ? `${segment.tags} ${MOVED_TAG}` : MOVED_TAG,
209
+ });
210
+ }
211
+ }
212
+ return { segments, links };
213
+ }
214
+ // The tag anchoredCut puts on a segment of a moved component, whose other
215
+ // segments the cut lacks, so a viewer can draw it as a stub
216
+ export const MOVED_TAG = 'mv:i:1';
217
+ // Where a cut reads links once more to close itself. A hop reads the links of
218
+ // the segments the round before it reached, so a link between two segments of
219
+ // the last round is never read and an allele reached from both ends draws as
220
+ // two stubs. rGFA lays an allele out as one stretch of the stable sequence that
221
+ // introduced it, so pieces of one sequence within the window's length of each
222
+ // other merge into a span, and reading it brings the pieces between too.
223
+ // Backbone reached past the window is unread for the same reason; its spans
224
+ // join only abutting pieces, since the reference past the window is not the
225
+ // cut's to fill. A span whose segments were all read and abut is skipped.
226
+ export function closingSpans(held, unread, window) {
227
+ const outside = (segment) => segment.refName !== window.refName ||
228
+ segment.end <= window.start ||
229
+ segment.start >= window.end;
230
+ return [
231
+ ...mergedSpans(held.filter(segment => segment.rank > 0), segment => unread.has(segment.id), window.end - window.start),
232
+ ...mergedSpans(held.filter(segment => segment.rank === 0 && outside(segment)), () => true, 0),
233
+ ];
234
+ }
235
+ function mergedSpans(segments, isUnread, maxGap) {
236
+ const sorted = [...segments].sort((a, b) => compare(a.refName, b.refName) || a.start - b.start);
237
+ const spans = [];
238
+ for (const segment of sorted) {
239
+ const span = spans.at(-1);
240
+ if ((span === null || span === void 0 ? void 0 : span.refName) === segment.refName &&
241
+ segment.start - span.end <= maxGap) {
242
+ span.needed || (span.needed = segment.start > span.end || isUnread(segment));
243
+ span.end = Math.max(span.end, segment.end);
244
+ }
245
+ else {
246
+ spans.push({
247
+ refName: segment.refName,
248
+ start: segment.start,
249
+ end: segment.end,
250
+ needed: isUnread(segment),
251
+ });
252
+ }
253
+ }
254
+ return spans
255
+ .filter(span => span.needed)
256
+ .map(({ refName, start, end }) => ({ refName, start, end }));
257
+ }
258
+ // The links a closing read keeps: each end is a segment the cut holds or one
259
+ // lying inside a span. Following anything else is what another hop is for.
260
+ export function closingLinks(found, held, spans) {
261
+ const inside = (segment) => held.has(segment.id) ||
262
+ spans.some(span => span.refName === segment.refName &&
263
+ segment.start >= span.start &&
264
+ segment.end <= span.end);
265
+ return found.filter(link => inside(link.sourceSegment) && inside(link.targetSegment));
266
+ }
267
+ // Segments carry no sequence here — the BED records only their span — so every
268
+ // S-line is written with `*` and an LN tag, which is what the GFA spec asks for
269
+ // and what @jbrowse/bandage-core's GFA parser reads back as the node length.
270
+ // `NM:i:0`, `SM:Z:HG002.1,HG002.2` — the GFA tag grammar, checked rather than
271
+ // trusted. Files built before the tag column existed put a bare comma-separated
272
+ // sample list here, and passing that through would put a field that is not a
273
+ // tag on an S-line, which is a malformed GFA rather than a missing annotation.
274
+ // Dropping it degrades to the pre-tag behaviour instead.
275
+ const GFA_TAG = /^[A-Za-z][A-Za-z0-9]:[AifZJHB]:/;
276
+ function formatSegment(segment) {
277
+ const { id, refName, start, end, rank, tags } = segment;
278
+ const valid = tags.split(' ').filter(t => GFA_TAG.test(t));
279
+ const extra = valid.length === 0 ? '' : `\t${valid.join('\t')}`;
280
+ return `S\t${id}\t*\tLN:i:${end - start}\tSN:Z:${refName}\tSO:i:${start}\tSR:i:${rank}${extra}`;
281
+ }
282
+ function formatLink(link) {
283
+ const { source, sourceStrand, target, targetStrand } = link;
284
+ return `L\t${source}\t${sourceStrand}\t${target}\t${targetStrand}\t0M`;
285
+ }
286
+ // Codepoint order, not localeCompare: the byte-identical-output guarantee below
287
+ // has to hold across locales.
288
+ function compare(a, b) {
289
+ return a < b ? -1 : a > b ? 1 : 0;
290
+ }
291
+ // Deterministic ordering: the same region always produces byte-identical GFA,
292
+ // so a layout computed from it is reproducible.
293
+ export function formatSubgraph(segments, links) {
294
+ const sortedSegments = [...segments.values()].sort((a, b) => compare(a.refName, b.refName) || a.start - b.start || compare(a.id, b.id));
295
+ const sortedLinks = [...links.keys()].sort((a, b) => compare(a, b));
296
+ return [
297
+ 'H\tVN:Z:1.0',
298
+ ...sortedSegments.map(s => formatSegment(s)),
299
+ ...sortedLinks.map(k => formatLink(links.get(k))),
300
+ ].join('\n');
301
+ }