@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.
@@ -0,0 +1,122 @@
1
+ import { WalkRowError } from "./walkChunk.js";
2
+ // The most bp of own sequence a departure gets its steps attached for
3
+ export const ATTACH_BP = 65536;
4
+ // A position on `refName` with the holes before it removed, so that steps
5
+ // either side of a hole compare as adjacent
6
+ export function squeezer(holes, refName) {
7
+ const spans = holes
8
+ .filter(h => h.refName === refName)
9
+ .sort((a, b) => a.start - b.start);
10
+ return spans.length === 0
11
+ ? (bp) => bp
12
+ : (bp) => {
13
+ let out = bp;
14
+ for (const { start, end } of spans) {
15
+ if (end > bp) {
16
+ break;
17
+ }
18
+ out -= end - start;
19
+ }
20
+ return out;
21
+ };
22
+ }
23
+ // Whether two consecutive steps on S follow S at their passes, and so depart
24
+ // nowhere: no sequence of the path's own between them, the same strand and
25
+ // one's breakpoint the other's, holes removed
26
+ export function adjacentSteps(d, squeeze) {
27
+ return (d.ownBp === 0 &&
28
+ d.leaveReversed === d.rejoinReversed &&
29
+ squeeze(d.leavePos) === squeeze(d.rejoinPos));
30
+ }
31
+ export function departureKind(d, squeeze = bp => bp) {
32
+ if (d.leaveReversed !== d.rejoinReversed) {
33
+ return 'switch';
34
+ }
35
+ const leave = squeeze(d.leavePos);
36
+ const rejoin = squeeze(d.rejoinPos);
37
+ return leave === rejoin
38
+ ? 'adjacent'
39
+ : (d.leaveReversed ? rejoin > leave : rejoin < leave)
40
+ ? 'back'
41
+ : 'forward';
42
+ }
43
+ // The bases of S a departure covers, from the base beside one breakpoint to
44
+ // the base beside the other, [lo, hi), as its record is filed
45
+ export function departureStretch(d) {
46
+ const leaveBase = d.leaveReversed ? d.leavePos : d.leavePos - 1;
47
+ const rejoinBase = d.rejoinReversed ? d.rejoinPos - 1 : d.rejoinPos;
48
+ const lo = Math.max(0, Math.min(leaveBase, rejoinBase));
49
+ return [lo, Math.max(lo, leaveBase, rejoinBase) + 1];
50
+ }
51
+ // Whether a departure leaves or rejoins on `span`: the base of its leave step
52
+ // or of its rejoin step beside the breakpoint lies there
53
+ export function leavesOrRejoinsOn(d, span) {
54
+ const [lo, hi] = departureStretch(d);
55
+ const on = (base) => base >= span.start && base < span.end;
56
+ return on(lo) || on(hi - 1);
57
+ }
58
+ // Whether a cut over `drawn` attaches a departure's own steps
59
+ export const attachesOwnSteps = (d, drawn, attachBp) => d.ownBp <= attachBp && leavesOrRejoinsOn(d, drawn);
60
+ /**
61
+ * Whether a departure's place on the reference is the writer's choice: an
62
+ * end lies on a node the reference passes more than once, so another pass
63
+ * would put it elsewhere or make it none, as where a path follows one copy
64
+ * of a collapsed repeat and the placement hops between copies
65
+ */
66
+ export function placementChoice(d) {
67
+ return d.leavePasses > 1 || d.rejoinPasses > 1;
68
+ }
69
+ const count = (field, row, least = 0) => {
70
+ const n = Number(field);
71
+ if (field === undefined ||
72
+ field === '' ||
73
+ !Number.isInteger(n) ||
74
+ n < least) {
75
+ throw new WalkRowError(`not a departure row: ${row.join('\t')}`);
76
+ }
77
+ return n;
78
+ };
79
+ const strand = (field, row) => {
80
+ if (field !== '+' && field !== '-') {
81
+ throw new WalkRowError(`not a departure row: ${row.join('\t')}`);
82
+ }
83
+ return field === '-';
84
+ };
85
+ // A record row's columns, `departure path hapStart ownBp missingBp leavePos
86
+ // leaveStrand leavePasses rejoinPos rejoinStrand rejoinPasses`, from its kind
87
+ // at `from`; a row that is not one throws
88
+ export function parseDepartureRow(cols, from = 3) {
89
+ const n = (k) => count(cols[from + k], cols);
90
+ const passes = (k) => count(cols[from + k], cols, 1);
91
+ return {
92
+ name: cols[from + 1],
93
+ hapStart: n(2),
94
+ ownBp: n(3),
95
+ missingBp: n(4),
96
+ leavePos: n(5),
97
+ leaveReversed: strand(cols[from + 6], cols),
98
+ leavePasses: passes(7),
99
+ rejoinPos: n(8),
100
+ rejoinReversed: strand(cols[from + 9], cols),
101
+ rejoinPasses: passes(10),
102
+ fromSteps: false,
103
+ };
104
+ }
105
+ // A record row's `ownTiles`, after `rejoinPasses`: the nominal starts of
106
+ // the tiles holding its own steps, `.` for none
107
+ export function departureOwnTiles(cols, from = 3) {
108
+ const field = cols[from + 11];
109
+ const starts = field === '.' || field === undefined ? [] : field.split(',');
110
+ return starts.map(start => {
111
+ const n = Number(start);
112
+ if (start === '' || !Number.isSafeInteger(n) || n < 0) {
113
+ throw new WalkRowError(`a departure record's ownTiles is not a list of tile starts: ${cols.join('\t')}`);
114
+ }
115
+ return n;
116
+ });
117
+ }
118
+ // Every record's rows repeat the same columns after the block, so this keys
119
+ // a row's record
120
+ export function departureRowKey(cols, from = 3) {
121
+ return cols.slice(from).join('\t');
122
+ }
@@ -0,0 +1,80 @@
1
+ import type { WalkDeparture } from './walkDeparture.ts';
2
+ import type { WalkFragment, WalkNode } from './walkRows.ts';
3
+ /**
4
+ * Where a haplotype leaves the reference path R and rejoins it: R's bases
5
+ * `refStart`–`refEnd` against `altLength` of its own. `invertedBp` counts the
6
+ * steps along R against its orientation. A step back along R walks a tandem
7
+ * copy again: the departure is then a point at the junction, `repeatedBp`
8
+ * counts the bp walked again, and `copied` spans them on R.
9
+ */
10
+ export interface Departure {
11
+ refStart: number;
12
+ refEnd: number;
13
+ altLength: number;
14
+ invertedBp: number;
15
+ repeatedBp: number;
16
+ copied?: [number, number];
17
+ }
18
+ /**
19
+ * A `sample#haplotype`'s departures, or a sample's where its paths' names
20
+ * have no haplotype field, by refStart. `covered` spans the R
21
+ * exactly one of its paths reaches, each span within one path.
22
+ */
23
+ export interface HaplotypeDepartures {
24
+ haplotype: string;
25
+ covered: [number, number][];
26
+ departures: Departure[];
27
+ }
28
+ export interface DepartureSource {
29
+ fragments: WalkFragment[];
30
+ departures: WalkDeparture[];
31
+ nodes: Map<number, WalkNode>;
32
+ }
33
+ export type ChainEvent = {
34
+ kind: 'on';
35
+ lo: number;
36
+ hi: number;
37
+ reversed: boolean;
38
+ } | {
39
+ kind: 'own';
40
+ bp: number;
41
+ loaded?: boolean;
42
+ };
43
+ /**
44
+ * Each haplotype's departures from R, `refName`, read off a cut: its
45
+ * departures, every one over the drawn stretch, give where each path leaves
46
+ * R and rejoins it and how much of its own it runs between, and its
47
+ * fragments' first and last steps give where it is on R otherwise. A
48
+ * fragment with the departures at its ends is a chain, as is a departure
49
+ * touching no fragment, such as one jumping over the window; each reads in
50
+ * its own orientation, turned round where it leaves R behind where it
51
+ * entered, and a stretch of R walked against it reads as inverted, a jump
52
+ * back as a tandem copy, and sequence between a contig's W lines as the
53
+ * path's own. R that two chains of a haplotype reach, such as a contig's
54
+ * second visit to the window, has no call. A piece the cut did not load
55
+ * reads as any other, from its steps on R and the bp of its own between
56
+ * them. The walks on R's own haplotype are left out.
57
+ */
58
+ export declare function walkDepartures({ fragments, departures, nodes }: DepartureSource, refName: string): HaplotypeDepartures[];
59
+ /**
60
+ * A chain's crossings in the forward view: its stretches along R in order,
61
+ * turned round where it reads R back to front, and between each two, from
62
+ * where the one leaves R to where the next takes it, a crossing wherever
63
+ * they do not follow on or the path runs bp between them: those of its own
64
+ * and those of the stretches it takes against its way. `first` and `reach`
65
+ * span R from the first stretch along it to the furthest any reaches.
66
+ */
67
+ export declare function chainCrossings(events: ChainEvent[]): {
68
+ flip: boolean;
69
+ crossings: {
70
+ from: number;
71
+ to: number;
72
+ ownBp: number;
73
+ invertedBp: number;
74
+ loaded: boolean;
75
+ }[];
76
+ first: number;
77
+ reach: number;
78
+ };
79
+ export declare function chainDepartures(events: ChainEvent[]): HaplotypeDepartures;
80
+ export declare const FORMS_STEP_BUDGET = 16000000;
@@ -0,0 +1,301 @@
1
+ import { panSNHaplotypeOrSample } from "./util.js";
2
+ const onR = (start) => !Number.isNaN(start);
3
+ /**
4
+ * Each haplotype's departures from R, `refName`, read off a cut: its
5
+ * departures, every one over the drawn stretch, give where each path leaves
6
+ * R and rejoins it and how much of its own it runs between, and its
7
+ * fragments' first and last steps give where it is on R otherwise. A
8
+ * fragment with the departures at its ends is a chain, as is a departure
9
+ * touching no fragment, such as one jumping over the window; each reads in
10
+ * its own orientation, turned round where it leaves R behind where it
11
+ * entered, and a stretch of R walked against it reads as inverted, a jump
12
+ * back as a tandem copy, and sequence between a contig's W lines as the
13
+ * path's own. R that two chains of a haplotype reach, such as a contig's
14
+ * second visit to the window, has no call. A piece the cut did not load
15
+ * reads as any other, from its steps on R and the bp of its own between
16
+ * them. The walks on R's own haplotype are left out.
17
+ */
18
+ export function walkDepartures({ fragments, departures, nodes }, refName) {
19
+ const length = (id) => {
20
+ const node = nodes.get(id);
21
+ return node ? node.end - node.start : 0;
22
+ };
23
+ const reference = panSNHaplotypeOrSample(refName);
24
+ const byPath = new Map();
25
+ const add = (name, item) => {
26
+ const items = byPath.get(name);
27
+ if (items) {
28
+ items.push(item);
29
+ }
30
+ else {
31
+ byPath.set(name, [item]);
32
+ }
33
+ };
34
+ for (const f of fragments) {
35
+ add(f.name, {
36
+ hap: [f.hapStart - f.trimmedBefore, f.hapEnd + f.trimmedAfter],
37
+ fragment: f,
38
+ });
39
+ }
40
+ for (const d of departures) {
41
+ add(d.name, { hap: [d.hapStart, d.hapStart + d.ownBp], departure: d });
42
+ }
43
+ const byHaplotype = new Map();
44
+ for (const [name, items] of byPath) {
45
+ const haplotype = panSNHaplotypeOrSample(name);
46
+ if (haplotype === reference || name === refName) {
47
+ continue;
48
+ }
49
+ let h = byHaplotype.get(haplotype);
50
+ if (!h) {
51
+ h = { haplotype, covered: [], departures: [] };
52
+ byHaplotype.set(haplotype, h);
53
+ }
54
+ for (const chain of pathChains(items, length)) {
55
+ readPath(chain, h);
56
+ }
57
+ }
58
+ const out = [...byHaplotype.values()];
59
+ for (const h of out) {
60
+ h.departures.sort((a, b) => a.refStart - b.refStart || a.refEnd - b.refEnd);
61
+ h.covered = coveredOnce(h.covered);
62
+ }
63
+ return out;
64
+ }
65
+ /**
66
+ * A path's chains, each its events in the path's order: a fragment with the
67
+ * departures leaving its last step, rejoining its first or lying inside it,
68
+ * fragments that abut, and a departure touching no fragment on its own. What
69
+ * the read did not see lies between chains, so each reads on its own, and R
70
+ * that two chains reach has no call.
71
+ */
72
+ function pathChains(items, length) {
73
+ // items chain where one's contig stretch touches another's: a departure's
74
+ // leave at a fragment's last step or inside it, its rejoin at the first,
75
+ // or two fragments abutting. In start order, an item touches the chain so
76
+ // far when it starts no later than the chain's furthest end. A fragment's
77
+ // stretch holds the steps the cut trimmed, so a record's rejoin chains to
78
+ // a piece whose first steps lie outside the drawn stretch
79
+ const all = items
80
+ .map(item => ({ item, edges: item.hap }))
81
+ .sort((a, b) => a.edges[0] - b.edges[0]);
82
+ const chains = [];
83
+ let chainEnd = -Infinity;
84
+ for (const { item, edges: [start, end], } of all) {
85
+ const chain = chains.at(-1);
86
+ if (chain && start <= chainEnd) {
87
+ chain.push(item);
88
+ }
89
+ else {
90
+ chains.push([item]);
91
+ }
92
+ chainEnd = Math.max(chainEnd, end);
93
+ }
94
+ return chains.map(chain => chainEvents(chain, length));
95
+ }
96
+ const on = (from, to, reversed) => ({
97
+ kind: 'on',
98
+ lo: Math.min(from, to),
99
+ hi: Math.max(from, to),
100
+ reversed,
101
+ });
102
+ function chainEvents(items, length) {
103
+ var _a;
104
+ const anchors = [];
105
+ for (const item of items) {
106
+ if ('fragment' in item) {
107
+ const f = item.fragment;
108
+ const n = f.ids.length;
109
+ const sa = f.refStarts[0];
110
+ const sb = f.refStarts[n - 1];
111
+ const ra = f.against[0] === 1;
112
+ const rb = f.against[n - 1] === 1;
113
+ if (onR(sa)) {
114
+ const pos = ra ? sa + length(f.ids[0]) : sa;
115
+ anchors.push({ hap: f.hapStart, order: 1, pos, reversed: ra });
116
+ }
117
+ if (onR(sb)) {
118
+ const pos = rb ? sb : sb + length(f.ids[n - 1]);
119
+ anchors.push({ hap: f.hapEnd, order: 0, pos, reversed: rb, exit: true });
120
+ }
121
+ }
122
+ else {
123
+ const d = item.departure;
124
+ anchors.push({
125
+ hap: d.hapStart,
126
+ order: 0,
127
+ pos: d.leavePos,
128
+ reversed: d.leaveReversed,
129
+ own: d.ownBp,
130
+ }, {
131
+ hap: d.hapStart + d.ownBp,
132
+ order: 1,
133
+ pos: d.rejoinPos,
134
+ reversed: d.rejoinReversed,
135
+ });
136
+ }
137
+ }
138
+ anchors.sort((a, b) => a.hap - b.hap || a.order - b.order);
139
+ const events = [];
140
+ // the open stretch on R: where it began, and the furthest fragment end seen
141
+ // along it
142
+ let cur;
143
+ let end;
144
+ const close = () => {
145
+ if (cur) {
146
+ events.push(on(cur.pos, end !== null && end !== void 0 ? end : cur.pos, cur.reversed));
147
+ }
148
+ cur = undefined;
149
+ end = undefined;
150
+ };
151
+ for (const a of anchors) {
152
+ if (cur && cur.reversed !== a.reversed) {
153
+ close();
154
+ }
155
+ if (a.order === 1) {
156
+ cur !== null && cur !== void 0 ? cur : (cur = { pos: a.pos, reversed: a.reversed });
157
+ }
158
+ else if (a.exit) {
159
+ if (cur) {
160
+ end = a.pos;
161
+ }
162
+ }
163
+ else {
164
+ cur !== null && cur !== void 0 ? cur : (cur = { pos: a.pos, reversed: a.reversed });
165
+ end = a.pos;
166
+ close();
167
+ events.push({ kind: 'own', bp: (_a = a.own) !== null && _a !== void 0 ? _a : 0 });
168
+ }
169
+ }
170
+ close();
171
+ return events;
172
+ }
173
+ /**
174
+ * Whether a chain reads R back to front. One that walks R only along it, or
175
+ * only against it, reads that way. One that does both is forward where it
176
+ * leaves R further along than it entered, so an inversion filling most of
177
+ * the window does not turn round a walk whose flanks run forward; the bp
178
+ * walked each way decide only for a chain that leaves R where it entered.
179
+ */
180
+ function readsBackToFront(events) {
181
+ const stretches = events.filter(e => e.kind === 'on');
182
+ const first = stretches[0];
183
+ const last = stretches.at(-1);
184
+ const bp = (reversed) => stretches
185
+ .filter(e => e.reversed === reversed)
186
+ .reduce((sum, e) => sum + (e.hi - e.lo || 1), 0);
187
+ const along = bp(false);
188
+ const against = bp(true);
189
+ const progress = first && last
190
+ ? (last.reversed ? last.lo : last.hi) -
191
+ (first.reversed ? first.hi : first.lo)
192
+ : 0;
193
+ return along === 0 || against === 0 || progress === 0
194
+ ? against > along
195
+ : progress < 0;
196
+ }
197
+ /**
198
+ * A chain's crossings in the forward view: its stretches along R in order,
199
+ * turned round where it reads R back to front, and between each two, from
200
+ * where the one leaves R to where the next takes it, a crossing wherever
201
+ * they do not follow on or the path runs bp between them: those of its own
202
+ * and those of the stretches it takes against its way. `first` and `reach`
203
+ * span R from the first stretch along it to the furthest any reaches.
204
+ */
205
+ export function chainCrossings(events) {
206
+ const flip = readsBackToFront(events);
207
+ const crossings = [];
208
+ let first = Number.NaN;
209
+ let prevEnd = Number.NaN;
210
+ let reach = -Infinity;
211
+ let own = 0;
212
+ let inverted = 0;
213
+ let loaded = true;
214
+ for (const e of flip ? events.toReversed() : events) {
215
+ if (e.kind === 'own') {
216
+ own += e.bp;
217
+ loaded && (loaded = e.loaded !== false);
218
+ }
219
+ else if (e.reversed !== flip) {
220
+ inverted += e.hi - e.lo;
221
+ }
222
+ else {
223
+ if (Number.isNaN(prevEnd)) {
224
+ first = e.lo;
225
+ }
226
+ else if (e.lo !== prevEnd || own + inverted > 0) {
227
+ crossings.push({
228
+ from: prevEnd,
229
+ to: e.lo,
230
+ ownBp: own,
231
+ invertedBp: inverted,
232
+ loaded,
233
+ });
234
+ }
235
+ prevEnd = e.hi;
236
+ reach = Math.max(reach, e.hi);
237
+ own = 0;
238
+ inverted = 0;
239
+ loaded = true;
240
+ }
241
+ }
242
+ return { flip, crossings, first, reach };
243
+ }
244
+ /**
245
+ * A path's departures in the forward view: its chain's crossings, each a
246
+ * departure from where it leaves R to where it rejoins, a jump back a point
247
+ * at the junction with the bp walked again as `repeatedBp`.
248
+ */
249
+ function readPath(events, h) {
250
+ const { crossings, first, reach } = chainCrossings(events);
251
+ for (const c of crossings) {
252
+ const repeated = c.to < c.from ? c.from - c.to : 0;
253
+ h.departures.push({
254
+ refStart: c.from,
255
+ refEnd: repeated > 0 ? c.from : c.to,
256
+ altLength: c.ownBp + c.invertedBp + repeated,
257
+ invertedBp: c.invertedBp,
258
+ repeatedBp: repeated,
259
+ ...(repeated > 0 ? { copied: [c.to, c.from] } : {}),
260
+ });
261
+ }
262
+ if (!Number.isNaN(first)) {
263
+ h.covered.push([first, reach]);
264
+ }
265
+ }
266
+ // One chain's departures and the R it covers, as walkDepartures reads them
267
+ export function chainDepartures(events) {
268
+ const h = { haplotype: '', covered: [], departures: [] };
269
+ readPath(events, h);
270
+ return h;
271
+ }
272
+ /**
273
+ * The stretches of R that exactly one of a haplotype's paths covers, each
274
+ * within one path. Where two paths overlap, such as a second contig over the
275
+ * same locus, the haplotype holds two copies of that stretch and no call;
276
+ * where one path ends and the next starts, no call crosses the junction.
277
+ */
278
+ function coveredOnce(spans) {
279
+ const points = [...new Set(spans.flat())].sort((a, b) => a - b);
280
+ const out = [];
281
+ let lastPath = -1;
282
+ for (let k = 0; k + 1 < points.length; k++) {
283
+ const a = points[k];
284
+ const b = points[k + 1];
285
+ const paths = spans.flatMap(([s, e], i) => (s <= a && e >= b ? [i] : []));
286
+ const last = out.at(-1);
287
+ if (paths.length !== 1) {
288
+ lastPath = -1;
289
+ }
290
+ else if (last && paths[0] === lastPath && last[1] === a) {
291
+ last[1] = b;
292
+ }
293
+ else {
294
+ out.push([a, b]);
295
+ lastPath = paths[0];
296
+ }
297
+ }
298
+ return out;
299
+ }
300
+ // The most steps a forms cut keeps
301
+ export const FORMS_STEP_BUDGET = 16000000;