@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,813 @@
1
+ import { panSNMatchesPrefix } from "./util.js";
2
+ // The smallest change detected
3
+ export const STRUCTURAL_BP = 50;
4
+ export const FLOOR_PRESETS = [50, 1000, 10000];
5
+ // A form's state at a site where it keeps R's structure, where its walks have
6
+ // no call, where it makes a change too rare to stand alone that agrees with no
7
+ // common state, and the `other` form's, which states nothing
8
+ export const REFERENCE_STATE = '0';
9
+ export const NO_CALL_STATE = '.';
10
+ export const RARER_STATE = '~';
11
+ export const OTHER_STATE = '*';
12
+ /**
13
+ * The floor for a window `widthBp` wide: about 10 px at 1,000 px, snapped to a
14
+ * preset, so 50 bp under 25 kb, 1 kb to 300 kb and 10 kb past it
15
+ */
16
+ export function autoFloor(widthBp) {
17
+ const px = widthBp / 100;
18
+ const [fine, medium, coarse] = FLOOR_PRESETS;
19
+ return px < 250 ? fine : px < 3000 ? medium : coarse;
20
+ }
21
+ export const minCarriersFor = (haplotypes) => Math.max(1, Math.round(haplotypes / 100));
22
+ export function changeKind(refLength, altLength) {
23
+ return altLength === 0
24
+ ? 'deletion'
25
+ : refLength === 0
26
+ ? 'insertion'
27
+ : 'replacement';
28
+ }
29
+ const PLAIN_KINDS = new Set(['insertion', 'deletion', 'replacement']);
30
+ // The second significant figure's place value: 1,000 for 10-99 kb
31
+ const figureUnit = (n) => 10 ** (Math.floor(Math.log10(n)) - 1);
32
+ const twoFigures = (n) => {
33
+ const unit = figureUnit(n);
34
+ return Math.round(Math.round(n / unit) * unit);
35
+ };
36
+ /**
37
+ * A mark's state, its kind and its size change to two significant figures:
38
+ * one repeat unit is one state wherever the walk's boundaries fall (22,201 and
39
+ * 22,204 bp are both `+22000`), and two units another. A deletion keys as `-`
40
+ * and an insertion as `+`, a replacement as `r-` or `r+` and a duplication as
41
+ * `d`. An inversion keys on its span.
42
+ */
43
+ export function stateKey(m) {
44
+ const sign = m.delta > 0 ? '+' : '-';
45
+ switch (m.kind) {
46
+ case 'inversion':
47
+ return `v${twoFigures(Math.max(Math.abs(m.delta), m.refEnd - m.refStart, 1))}`;
48
+ case 'replacement':
49
+ return `r${sign}${twoFigures(Math.abs(m.delta))}`;
50
+ case 'duplication':
51
+ return `d${twoFigures(m.delta)}`;
52
+ default:
53
+ return `${sign}${twoFigures(Math.abs(m.delta))}`;
54
+ }
55
+ }
56
+ const refOf = (d) => d.refEnd - d.refStart;
57
+ const deltaOf = (d) => d.altLength - refOf(d);
58
+ // A departure that changes R's length, walks R against it or walks it again;
59
+ // one that runs as many bp of its own as it leaves out of R and does neither
60
+ // says nothing a mark states
61
+ const isStructural = (d) => deltaOf(d) !== 0 || d.invertedBp > 0 || d.repeatedBp > 0;
62
+ // A departure under STRUCTURAL_BP on both sides, which no mark states alone
63
+ const isSmall = (d) => refOf(d) < STRUCTURAL_BP && d.altLength < STRUCTURAL_BP;
64
+ function joinRun(departures, joinBp) {
65
+ const out = [];
66
+ for (const d of departures) {
67
+ const last = out.at(-1);
68
+ if (last && d.refStart - last.refEnd < joinBp) {
69
+ last.refEnd = Math.max(last.refEnd, d.refEnd);
70
+ last.delta += deltaOf(d);
71
+ last.refBp += refOf(d);
72
+ last.ownBp += d.altLength;
73
+ last.invertedBp += d.invertedBp;
74
+ last.repeatedBp += d.repeatedBp;
75
+ if (d.copied) {
76
+ last.copied = last.copied
77
+ ? [
78
+ Math.min(last.copied[0], d.copied[0]),
79
+ Math.max(last.copied[1], d.copied[1]),
80
+ ]
81
+ : d.copied;
82
+ }
83
+ }
84
+ else {
85
+ out.push({
86
+ refStart: d.refStart,
87
+ refEnd: d.refEnd,
88
+ delta: deltaOf(d),
89
+ refBp: refOf(d),
90
+ ownBp: d.altLength,
91
+ invertedBp: d.invertedBp,
92
+ repeatedBp: d.repeatedBp,
93
+ ...(d.copied ? { copied: d.copied } : {}),
94
+ });
95
+ }
96
+ }
97
+ return out;
98
+ }
99
+ // The structural departures nearer than `joinBp` on R joined, summing their
100
+ // sides. A small one joins only another small one, so an indel no mark states
101
+ // alone neither names a change beside it nor widens it, while a repeat's
102
+ // change that walks split into small pieces still adds up
103
+ export function joinDepartures(departures, joinBp) {
104
+ const structural = departures.filter(isStructural);
105
+ return joinRun(structural.filter(isSmall), joinBp)
106
+ .concat(joinRun(structural.filter(d => !isSmall(d)), joinBp))
107
+ .sort((a, b) => a.refStart - b.refStart || a.refEnd - b.refEnd);
108
+ }
109
+ function markOf(d, floorBp) {
110
+ const size = Math.abs(d.delta);
111
+ const kind = size < floorBp
112
+ ? d.invertedBp >= floorBp
113
+ ? 'inversion'
114
+ : undefined
115
+ : d.repeatedBp >= STRUCTURAL_BP && d.delta > 0
116
+ ? 'duplication'
117
+ : changeKind(d.refBp, d.ownBp);
118
+ return (kind && {
119
+ kind,
120
+ refStart: d.refStart,
121
+ refEnd: d.refEnd,
122
+ refLength: d.refBp,
123
+ altLength: d.ownBp,
124
+ delta: d.delta,
125
+ ...(kind === 'duplication' ? { repeatedBp: d.repeatedBp } : {}),
126
+ ...(kind === 'duplication' && d.copied ? { copied: d.copied } : {}),
127
+ });
128
+ }
129
+ // The widest site whose plain changes sum into one per haplotype. The gate
130
+ // windows' repeats that walks split run up to 600 bp, and the next wider
131
+ // informative sites, 3.8 kb and up, hold separate changes
132
+ export const SUMMED_SITE_BP = 1000;
133
+ /**
134
+ * A haplotype's departures joined and kept where they touch the window, its
135
+ * marks, and its plain pieces: the joined departures that make no mark of
136
+ * their own kind, an inversion or duplication
137
+ */
138
+ function haplotypePieces(departures, floorBp, joinBp, window) {
139
+ const pieces = joinDepartures(departures, joinBp).filter(d => !window || (d.refEnd >= window.start && d.refStart <= window.end));
140
+ const marked = pieces.map(d => ({ d, mark: markOf(d, floorBp) }));
141
+ return {
142
+ marks: marked.flatMap(({ mark }) => (mark ? [mark] : [])),
143
+ plain: marked.flatMap(({ d, mark }) => mark && !PLAIN_KINDS.has(mark.kind) ? [] : [d]),
144
+ };
145
+ }
146
+ /**
147
+ * A haplotype's marks of at least `floorBp`: its departures nearer than
148
+ * `joinBp` on R joined, and those touching the window kept.
149
+ * structuralForms then sums the plain changes at each site, so these are the
150
+ * marks the sites come from, not each haplotype's state.
151
+ */
152
+ export function haplotypeMarks(departures, { floorBp = STRUCTURAL_BP, joinBp = STRUCTURAL_BP, window, }) {
153
+ return haplotypePieces(departures, floorBp, joinBp, window).marks;
154
+ }
155
+ /**
156
+ * The plain pieces at one site as one mark, where their net change reaches
157
+ * `floorBp`. It spans the pieces that reach it alone, or all those that
158
+ * change length where none does.
159
+ */
160
+ function siteChange(pieces, floorBp) {
161
+ const delta = pieces.reduce((s, d) => s + d.delta, 0);
162
+ if (Math.abs(delta) < floorBp) {
163
+ return undefined;
164
+ }
165
+ const large = pieces.filter(d => Math.abs(d.delta) >= floorBp);
166
+ const spanned = large.length > 0 ? large : pieces.filter(d => d.delta !== 0);
167
+ let refStart = Infinity;
168
+ let refEnd = -Infinity;
169
+ for (const d of spanned) {
170
+ refStart = Math.min(refStart, d.refStart);
171
+ refEnd = Math.max(refEnd, d.refEnd);
172
+ }
173
+ const refLength = pieces.reduce((s, d) => s + d.refBp, 0);
174
+ const altLength = pieces.reduce((s, d) => s + d.ownBp, 0);
175
+ return {
176
+ kind: changeKind(refLength, altLength),
177
+ refStart,
178
+ refEnd,
179
+ refLength,
180
+ altLength,
181
+ delta,
182
+ };
183
+ }
184
+ const sumDelta = (marks) => marks.reduce((s, m) => s + m.delta, 0);
185
+ /**
186
+ * Two net changes agree where both are under `floorBp`, or they differ by
187
+ * under `floorBp`, under a tenth of the larger, or under the last figure a
188
+ * state key gives a change of `size`
189
+ */
190
+ export const agrees = (a, b, floorBp, size = 0) => Math.max(Math.abs(a), Math.abs(b)) < floorBp ||
191
+ Math.abs(a - b) <
192
+ Math.max(floorBp, 0.1 * Math.max(Math.abs(a), Math.abs(b)), size > 0 ? figureUnit(size) : 0);
193
+ const sizeOf = (m) => m.kind === 'inversion' ? m.refEnd - m.refStart : Math.abs(m.delta);
194
+ export const largestChange = (marks) => marks.reduce((most, m) => Math.max(most, sizeOf(m)), 0);
195
+ const kindsOf = (marks) => marks
196
+ .map(m => m.kind)
197
+ .sort()
198
+ .join(' ');
199
+ // Two sets of marks at one site make the same kinds of change and agree in net
200
+ // change and in largest change
201
+ export const statesAgree = (a, b, floorBp) => kindsOf(a) === kindsOf(b) &&
202
+ agrees(sumDelta(a), sumDelta(b), floorBp, Math.max(largestChange(a), largestChange(b))) &&
203
+ agrees(largestChange(a), largestChange(b), floorBp);
204
+ const covers = (h, start, end) => h.covered.some(([a, b]) => a <= start && b >= end);
205
+ const overlaps = (h, start, end) => h.covered.some(([a, b]) => a <= end && b >= start);
206
+ // Whether each of two spans on R covers at least half of the other, a point
207
+ // taking 1 bp
208
+ const halfCover = (a, b) => {
209
+ const overlap = Math.min(a.end, b.end) - Math.max(a.start, b.start);
210
+ return 2 * overlap >= a.end - a.start && 2 * overlap >= b.end - b.start;
211
+ };
212
+ const spanOf = (m) => ({
213
+ start: m.refStart,
214
+ end: Math.max(m.refEnd, m.refStart + 1),
215
+ });
216
+ // Whether `as` and `bs` pair one-to-one with `pairs` true of every pair
217
+ function pairOneToOne(as, bs, pairs) {
218
+ const holder = bs.map(() => -1);
219
+ const place = (i, seen) => bs.some((b, j) => {
220
+ let placed = false;
221
+ if (!seen.has(j) && pairs(as[i], b)) {
222
+ seen.add(j);
223
+ placed = holder[j] < 0 || place(holder[j], seen);
224
+ if (placed) {
225
+ holder[j] = i;
226
+ }
227
+ }
228
+ return placed;
229
+ });
230
+ return as.length === bs.length && as.every((_, i) => place(i, new Set()));
231
+ }
232
+ // The first of `spans`, sorted by start, starting at or after `from`
233
+ const firstFrom = (spans, from) => {
234
+ let lo = 0;
235
+ let hi = spans.length;
236
+ while (lo < hi) {
237
+ const mid = (lo + hi) >> 1;
238
+ if (spans[mid].start < from) {
239
+ lo = mid + 1;
240
+ }
241
+ else {
242
+ hi = mid;
243
+ }
244
+ }
245
+ return lo;
246
+ };
247
+ // Spans by start, then end
248
+ const byStartEnd = (a, b) => a.start - b.start || a.end - b.end;
249
+ // Marks of at least `minCarriers` haplotypes, two marks shared where they
250
+ // half-cover each other, and each mark's place: spans every two of which
251
+ // half-cover each other, named by the first. The common spans take places
252
+ // most carried first, then by start and end, each joining the place whose
253
+ // spans it all half-covers with the most carriers, then the earliest start
254
+ // and end, or starting its own, and a rarer mark's place is its own span.
255
+ // Each span is one place's first at most, so these orders are total and the
256
+ // places do not depend on the order of the haplotypes. Marks of one span
257
+ // compare once, and a mark stops gathering sharers at minCarriers
258
+ function commonMarks(marksBy, minCarriers) {
259
+ const bySpan = new Map();
260
+ marksBy.forEach((marks, hap) => {
261
+ var _a;
262
+ for (const m of marks) {
263
+ const span = spanOf(m);
264
+ const key = `${span.start} ${span.end}`;
265
+ const group = (_a = bySpan.get(key)) !== null && _a !== void 0 ? _a : { ...span, marks: [], haps: new Set() };
266
+ group.marks.push(m);
267
+ group.haps.add(hap);
268
+ bySpan.set(key, group);
269
+ }
270
+ });
271
+ const all = [...bySpan.values()].sort(byStartEnd);
272
+ const sharers = all.map(g => new Set(g.haps));
273
+ const gather = (into, from) => {
274
+ for (const hap of from) {
275
+ if (into.size >= minCarriers) {
276
+ return;
277
+ }
278
+ into.add(hap);
279
+ }
280
+ };
281
+ all.forEach((a, i) => {
282
+ const half = (a.end - a.start) / 2;
283
+ for (let j = i + 1; j < all.length && all[j].start <= a.start + half; j++) {
284
+ const b = all[j];
285
+ if (halfCover(a, b)) {
286
+ gather(sharers[i], b.haps);
287
+ gather(sharers[j], a.haps);
288
+ }
289
+ }
290
+ });
291
+ const common = all.filter((_, i) => sharers[i].size >= minCarriers);
292
+ // a span that half-covers another is at most twice as long, so a place
293
+ // whose first span it half-covers starts no earlier than twice its length
294
+ // before it
295
+ const places = [];
296
+ const placeOf = new Map();
297
+ for (const g of common.toSorted((a, b) => b.haps.size - a.haps.size || byStartEnd(a, b))) {
298
+ let best;
299
+ for (let k = firstFrom(places, g.start - 2 * (g.end - g.start)); k < places.length && places[k].start <= g.end; k++) {
300
+ const p = places[k];
301
+ if ((!best || (p.carriers - best.carriers || byStartEnd(best, p)) > 0) &&
302
+ p.spans.every(span => halfCover(span, g))) {
303
+ best = p;
304
+ }
305
+ }
306
+ if (best) {
307
+ best.spans.push(g);
308
+ best.carriers += g.haps.size;
309
+ placeOf.set(g, best);
310
+ }
311
+ else {
312
+ const place = {
313
+ start: g.start,
314
+ end: g.end,
315
+ spans: [g],
316
+ carriers: g.haps.size,
317
+ };
318
+ places.splice(firstFrom(places, g.start), 0, place);
319
+ placeOf.set(g, place);
320
+ }
321
+ }
322
+ return {
323
+ common: new Set(common.flatMap(g => g.marks)),
324
+ place: new Map(all.flatMap(g => g.marks.map(m => { var _a; return [m, (_a = placeOf.get(g)) !== null && _a !== void 0 ? _a : g]; }))),
325
+ };
326
+ }
327
+ function unionSpans(marks) {
328
+ const spans = marks
329
+ .map(m => [m.refStart, m.refEnd])
330
+ .sort((a, b) => a[0] - b[0]);
331
+ const sites = [];
332
+ for (const [start, end] of spans) {
333
+ const last = sites.at(-1);
334
+ if (last && start <= last[1]) {
335
+ last[1] = Math.max(last[1], end);
336
+ }
337
+ else {
338
+ sites.push([start, end]);
339
+ }
340
+ }
341
+ return sites;
342
+ }
343
+ // The spans of overlapping common marks, then of overlapping rarer marks that
344
+ // overlap none of those
345
+ const isPlainState = (s) => s !== NO_CALL_STATE && s !== RARER_STATE;
346
+ function siteSpans(marks, common) {
347
+ const commonSpans = unionSpans(marks.filter(m => common.has(m)));
348
+ const apart = marks.filter(m => !common.has(m) && sitesOver(commonSpans, m).length === 0);
349
+ return [...commonSpans, ...unionSpans(apart)].sort((a, b) => a[0] - b[0]);
350
+ }
351
+ // The indices of the sites `m` overlaps
352
+ function sitesOver(sites, m) {
353
+ let lo = 0;
354
+ let hi = sites.length;
355
+ while (lo < hi) {
356
+ const mid = (lo + hi) >> 1;
357
+ if (sites[mid][1] < m.refStart) {
358
+ lo = mid + 1;
359
+ }
360
+ else {
361
+ hi = mid;
362
+ }
363
+ }
364
+ const over = [];
365
+ for (let i = lo; i < sites.length && sites[i][0] <= m.refEnd; i++) {
366
+ over.push(i);
367
+ }
368
+ return over;
369
+ }
370
+ /**
371
+ * Groups haplotypes by the structural changes their walks make over a
372
+ * window. Each haplotype's own marks make its state at a site, so a change
373
+ * nested in another counts once. A state with fewer than minCarriers folds
374
+ * only into a common state its change agrees with (`agrees`; where the site
375
+ * keys on place, change by change, each pair covering half of each other),
376
+ * and is `~` where none does; a no call stays
377
+ * one. A haplotype whose form has fewer than minCarriers joins the largest
378
+ * common form whose every state fits it, or `other`.
379
+ */
380
+ export function structuralForms(input, opts = {}) {
381
+ var _a, _b, _c, _d, _e;
382
+ const exclude = (_a = opts.exclude) !== null && _a !== void 0 ? _a : [];
383
+ const haplotypes = input.filter(h => !exclude.some(prefix => panSNMatchesPrefix(h.haplotype, prefix)));
384
+ const minCarriers = (_b = opts.minCarriers) !== null && _b !== void 0 ? _b : minCarriersFor(haplotypes.length);
385
+ const window = (_c = opts.window) !== null && _c !== void 0 ? _c : extent(haplotypes);
386
+ const floorBp = opts.floorBp === undefined || opts.floorBp === 'auto'
387
+ ? autoFloor(window.end - window.start)
388
+ : Math.max(STRUCTURAL_BP, opts.floorBp);
389
+ const joinBp = (_d = opts.joinBp) !== null && _d !== void 0 ? _d : STRUCTURAL_BP;
390
+ const keepRare = opts.foldRareForms === false;
391
+ const piecesBy = haplotypes.map(h => haplotypePieces(h.departures, floorBp, joinBp, opts.window));
392
+ const marksBy = piecesBy.map(p => p.marks);
393
+ const { common: sharedMarks, place } = commonMarks(marksBy, minCarriers);
394
+ const spans = siteSpans(marksBy.flat(), sharedMarks);
395
+ const summed = spans.map(([a, b]) => b - a <= SUMMED_SITE_BP);
396
+ const rawAt = piecesBy.map(({ marks, plain }) => {
397
+ var _a;
398
+ const at = new Map();
399
+ const add = (i, m) => {
400
+ var _a;
401
+ at.set(i, [...((_a = at.get(i)) !== null && _a !== void 0 ? _a : []), m]);
402
+ };
403
+ for (const m of marks) {
404
+ for (const i of sitesOver(spans, m)) {
405
+ if (!PLAIN_KINDS.has(m.kind) || !summed[i]) {
406
+ add(i, m);
407
+ }
408
+ }
409
+ }
410
+ const plainAt = new Map();
411
+ for (const d of plain) {
412
+ for (const i of sitesOver(spans, d)) {
413
+ if (summed[i]) {
414
+ plainAt.set(i, [...((_a = plainAt.get(i)) !== null && _a !== void 0 ? _a : []), d]);
415
+ }
416
+ }
417
+ }
418
+ for (const [i, pieces] of plainAt) {
419
+ const m = siteChange(pieces, floorBp);
420
+ if (m) {
421
+ add(i, m);
422
+ }
423
+ }
424
+ return at;
425
+ });
426
+ // a mark's state at a site keyed on place: its size at its place's start,
427
+ // or at its place's span where the same size has another place starting
428
+ // there
429
+ const placeEnds = new Map();
430
+ for (const m of marksBy.flat()) {
431
+ const p = place.get(m);
432
+ const key = `${stateKey(m)}@${p.start}`;
433
+ placeEnds.set(key, ((_e = placeEnds.get(key)) !== null && _e !== void 0 ? _e : new Set()).add(p.end));
434
+ }
435
+ const placedKey = (m) => {
436
+ const p = place.get(m);
437
+ const key = `${stateKey(m)}@${p.start}`;
438
+ return placeEnds.get(key).size > 1 ? `${key}-${p.end}` : key;
439
+ };
440
+ const marksAt = rawAt.map(at => new Map([...at].map(([site, ms]) => {
441
+ ms.sort((a, b) => a.refStart - b.refStart || a.refEnd - b.refEnd);
442
+ const state = ms
443
+ .map(m => (summed[site] ? stateKey(m) : placedKey(m)))
444
+ .join(';');
445
+ return [site, ms.map((m) => ({ ...m, site, state }))];
446
+ })));
447
+ const raw = spans.map(([start, end], i) => haplotypes.map((h, j) => {
448
+ var _a, _b;
449
+ return covers(h, Math.max(start, window.start), Math.min(end, window.end))
450
+ ? ((_b = (_a = marksAt[j].get(i)) === null || _a === void 0 ? void 0 : _a[0].state) !== null && _b !== void 0 ? _b : REFERENCE_STATE)
451
+ : NO_CALL_STATE;
452
+ }));
453
+ const inWindow = haplotypes.map(h => overlaps(h, window.start, window.end));
454
+ const windowCount = inWindow.filter(Boolean).length;
455
+ const edge = raw.map(states => 2 * states.filter((s, j) => inWindow[j] && s !== NO_CALL_STATE).length <
456
+ windowCount);
457
+ const isPlaced = haplotypes.map((_, j) => inWindow[j] &&
458
+ (edge.every(Boolean) ||
459
+ raw.some((states, i) => !edge[i] && states[j] !== NO_CALL_STATE)));
460
+ const placed = haplotypes.flatMap((_, j) => (isPlaced[j] ? [j] : []));
461
+ const fits = (j, i, state) => {
462
+ var _a;
463
+ const own = (_a = marksAt[j].get(i)) !== null && _a !== void 0 ? _a : [];
464
+ return summed[i]
465
+ ? statesAgree(state.marks, own, floorBp)
466
+ : pairOneToOne(state.marks, own, (a, b) => halfCover(spanOf(a), spanOf(b)) && statesAgree([a], [b], floorBp));
467
+ };
468
+ const rare = new Set();
469
+ const sites = [];
470
+ const keyed = [];
471
+ const folded = [];
472
+ spans.forEach(([refStart, refEnd], i) => {
473
+ var _a, _b;
474
+ const states = raw[i];
475
+ const carriers = new Map();
476
+ for (const j of placed) {
477
+ const list = carriers.get(states[j]);
478
+ if (list) {
479
+ list.push(j);
480
+ }
481
+ else {
482
+ carriers.set(states[j], [j]);
483
+ }
484
+ }
485
+ const ranked = [...carriers].sort((a, b) => b[1].length - a[1].length || (a[0] < b[0] ? -1 : 1));
486
+ const siteStates = ranked.flatMap(([key, js]) => {
487
+ if (key === NO_CALL_STATE) {
488
+ return [];
489
+ }
490
+ const byDelta = js
491
+ .map(j => { var _a; return ({ j, marks: (_a = marksAt[j].get(i)) !== null && _a !== void 0 ? _a : [] }); })
492
+ .map(c => ({ ...c, delta: sumDelta(c.marks) }))
493
+ .sort((a, b) => a.delta - b.delta ||
494
+ (haplotypes[a.j].haplotype < haplotypes[b.j].haplotype ? -1 : 1));
495
+ const median = byDelta[Math.floor(byDelta.length / 2)];
496
+ return [
497
+ {
498
+ key,
499
+ delta: median.delta,
500
+ marks: median.marks,
501
+ carriers: js.map(j => haplotypes[j].haplotype),
502
+ },
503
+ ];
504
+ });
505
+ sites.push({
506
+ refStart,
507
+ refEnd,
508
+ edge: edge[i],
509
+ shared: false,
510
+ covered: placed.length - ((_b = (_a = carriers.get(NO_CALL_STATE)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0),
511
+ states: siteStates,
512
+ });
513
+ if (!edge[i]) {
514
+ const common = siteStates.filter(s => s.carriers.length >= minCarriers);
515
+ keyed.push(i);
516
+ folded.push(states.map((state, j) => {
517
+ var _a, _b, _c;
518
+ const stays = keepRare ||
519
+ !isPlaced[j] ||
520
+ state === NO_CALL_STATE ||
521
+ state === REFERENCE_STATE ||
522
+ ((_b = (_a = carriers.get(state)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) >= minCarriers;
523
+ if (!stays) {
524
+ rare.add(haplotypes[j].haplotype);
525
+ }
526
+ const into = stays ? [] : common.filter(s => fits(j, i, s));
527
+ return stays
528
+ ? state
529
+ : into.length > 0
530
+ ? nearest(into, s => s.delta, sumDelta((_c = marksAt[j].get(i)) !== null && _c !== void 0 ? _c : []))
531
+ .key
532
+ : RARER_STATE;
533
+ }));
534
+ }
535
+ });
536
+ const byKey = new Map();
537
+ for (const j of placed) {
538
+ const states = folded.map(fold => fold[j]);
539
+ const key = states.join('|');
540
+ const form = byKey.get(key);
541
+ if (form) {
542
+ form.members.push(haplotypes[j].haplotype);
543
+ }
544
+ else {
545
+ byKey.set(key, { states, members: [haplotypes[j].haplotype] });
546
+ }
547
+ }
548
+ const grouped = [...byKey.values()];
549
+ const common = keepRare
550
+ ? grouped
551
+ : grouped.filter(f => f.members.length >= minCarriers);
552
+ const kept = common.length > 0 ? common : grouped;
553
+ const matches = (j, k, key) => {
554
+ const own = folded[k][j];
555
+ const state = sites[keyed[k]].states.find(s => s.key === key);
556
+ return (key === own ||
557
+ (isPlainState(key) &&
558
+ isPlainState(own) &&
559
+ !!state &&
560
+ fits(j, keyed[k], state)));
561
+ };
562
+ const largestFirst = kept.toSorted((a, b) => b.members.length - a.members.length ||
563
+ (a.states.join('|') < b.states.join('|') ? -1 : 1));
564
+ const keptMembers = new Set(kept.flatMap(f => f.members));
565
+ const other = [];
566
+ for (const j of placed) {
567
+ const name = haplotypes[j].haplotype;
568
+ if (!keptMembers.has(name)) {
569
+ const into = largestFirst.find(f => f.states.every((key, k) => matches(j, k, key)));
570
+ (into ? into.members : other).push(name);
571
+ rare.add(name);
572
+ }
573
+ }
574
+ const told = keyed.map((_, k) => {
575
+ var _a;
576
+ const first = (_a = kept[0]) === null || _a === void 0 ? void 0 : _a.states[k];
577
+ return (first === NO_CALL_STATE ||
578
+ first === RARER_STATE ||
579
+ kept.some(f => f.states[k] !== first));
580
+ });
581
+ keyed.forEach((i, k) => {
582
+ sites[i].shared = !told[k];
583
+ });
584
+ const informative = keyed.filter((_, k) => told[k]);
585
+ const stateAt = (i, key) => { var _a, _b; return (_b = (_a = sites[i].states.find(s => s.key === key)) === null || _a === void 0 ? void 0 : _a.marks) !== null && _b !== void 0 ? _b : []; };
586
+ const forms = kept.map(({ states, members }) => {
587
+ const marks = onceEach(spans, keyed.flatMap((i, k) => stateAt(i, states[k]))).sort((a, b) => a.refStart - b.refStart);
588
+ const formStates = states.filter((_, k) => told[k]);
589
+ return {
590
+ members,
591
+ key: formStates.join('|'),
592
+ states: formStates,
593
+ marks,
594
+ net: sumDelta(marks),
595
+ };
596
+ });
597
+ const otherForm = other.length > 0
598
+ ? [
599
+ {
600
+ members: other,
601
+ key: OTHER_STATE,
602
+ states: informative.map(() => OTHER_STATE),
603
+ marks: [],
604
+ net: 0,
605
+ },
606
+ ]
607
+ : [];
608
+ return {
609
+ sites,
610
+ informative,
611
+ forms: [...sortForms(forms), ...otherForm],
612
+ placed: placed.length,
613
+ unplaced: haplotypes.flatMap((h, j) => (isPlaced[j] ? [] : [h.haplotype])),
614
+ rareCarriers: haplotypes
615
+ .filter(h => rare.has(h.haplotype))
616
+ .map(h => h.haplotype),
617
+ minCarriers,
618
+ floorBp,
619
+ };
620
+ }
621
+ // A rarer mark over several sites states itself at each, and counts once
622
+ function onceEach(spans, marks) {
623
+ const seen = new Set();
624
+ return marks.filter(m => {
625
+ const over = sitesOver(spans, m);
626
+ const key = over.length > 1
627
+ ? `${stateKey(m)} ${over.join(',')}`
628
+ : `${m.kind} ${m.refStart} ${m.refEnd} ${m.delta}`;
629
+ const fresh = !seen.has(key);
630
+ seen.add(key);
631
+ return fresh;
632
+ });
633
+ }
634
+ function extent(haplotypes) {
635
+ let start = Infinity;
636
+ let end = -Infinity;
637
+ for (const h of haplotypes) {
638
+ for (const [a, b] of h.covered) {
639
+ start = Math.min(start, a);
640
+ end = Math.max(end, b);
641
+ }
642
+ }
643
+ return start <= end ? { start, end } : { start: 0, end: 0 };
644
+ }
645
+ // The first of `items` whose value is nearest `target`
646
+ function nearest(items, value, target) {
647
+ let best = items[0];
648
+ for (const item of items) {
649
+ if (Math.abs(value(item) - target) < Math.abs(value(best) - target)) {
650
+ best = item;
651
+ }
652
+ }
653
+ return best;
654
+ }
655
+ const sortForms = (forms) => forms.toSorted((a, b) => b.members.length - a.members.length ||
656
+ Math.abs(a.net) - Math.abs(b.net) ||
657
+ (a.key < b.key ? -1 : 1));
658
+ /**
659
+ * A length to three significant figures with its unit attached: "94bp",
660
+ * "6.46kb", "1.2Mb"
661
+ */
662
+ export function sizeTag(n) {
663
+ const r = Number(n.toPrecision(3));
664
+ return r >= 1000000
665
+ ? `${Number((r / 1000000).toPrecision(3))}Mb`
666
+ : r >= 1000
667
+ ? `${Number((r / 1000).toPrecision(3))}kb`
668
+ : `${r}bp`;
669
+ }
670
+ // A mark's two sides, R's first, or the one that has bp where the other has
671
+ // none
672
+ const sides = (m) => m.refLength === 0
673
+ ? sizeTag(m.altLength)
674
+ : m.altLength === 0
675
+ ? sizeTag(m.refLength)
676
+ : `${sizeTag(m.refLength)}->${sizeTag(m.altLength)}`;
677
+ /**
678
+ * A mark as a short token: "del 18.4kb", "ins 22kb", "repl 32.7kb->58.7kb",
679
+ * "dup 94.1kb", "inv 12kb". A deletion gives the bp of R it leaves out, an
680
+ * insertion and a duplication at a point the bp they run, and a replacement,
681
+ * or a duplication that also leaves R out, both, R's first, at any ratio:
682
+ * "repl 2.65kb->1bp", "dup 113kb->207kb". An inversion gives its span
683
+ */
684
+ export function markTag(m) {
685
+ switch (m.kind) {
686
+ case 'insertion':
687
+ return `ins ${sides(m)}`;
688
+ case 'deletion':
689
+ return `del ${sides(m)}`;
690
+ case 'duplication':
691
+ return `dup ${sides(m)}`;
692
+ case 'inversion':
693
+ return `inv ${sizeTag(m.refEnd - m.refStart)}`;
694
+ case 'replacement':
695
+ return `repl ${sides(m)}`;
696
+ }
697
+ }
698
+ // markTag under its earlier name
699
+ export const changeName = markTag;
700
+ // The size a row draws a change at: a mark's larger side, an inversion's span
701
+ const drawnSize = (m) => m.kind === 'inversion'
702
+ ? m.refEnd - m.refStart
703
+ : Math.max(m.refLength, m.altLength);
704
+ // That size as a label prints it, to three significant figures
705
+ const printedSize = (m) => Number(drawnSize(m).toPrecision(3));
706
+ const drawnOverSpan = (m) => m.copied ? m.copied[1] > m.copied[0] : m.refEnd > m.refStart;
707
+ // Marks as a label names them: largest as printed first, then a change drawn
708
+ // over a span of R before one at a point, then larger first
709
+ const byDrawnSize = (a, b) => printedSize(b) - printedSize(a) ||
710
+ Number(drawnOverSpan(b)) - Number(drawnOverSpan(a)) ||
711
+ drawnSize(b) - drawnSize(a);
712
+ const counted = (token, n) => n === 0 ? [] : [n === 1 ? token : `${token} x${n}`];
713
+ /**
714
+ * How a form differs from R: each mark's markTag, largest first, then
715
+ * "rarer" and "no call" with their site counts, comma-separated:
716
+ * "ins 6.4kb, del 1.7kb", "del 2kb, no call". "ref" where it makes no change,
717
+ * and "other" for the `other` form.
718
+ */
719
+ export function describeForm(form) {
720
+ const tokens = [
721
+ ...form.marks.toSorted(byDrawnSize).map(markTag),
722
+ ...counted('rarer', form.states.filter(s => s === RARER_STATE).length),
723
+ ...counted('no call', form.states.filter(s => s === NO_CALL_STATE).length),
724
+ ];
725
+ return form.key === OTHER_STATE
726
+ ? 'other'
727
+ : tokens.length > 0
728
+ ? tokens.join(', ')
729
+ : 'ref';
730
+ }
731
+ /**
732
+ * The state key `form` has at `site`, an index into `result.sites`: its key
733
+ * there at an informative site, the state every form carries at a shared one,
734
+ * `*` for the `other` form, and undefined at an edge site, which no form key
735
+ * holds
736
+ */
737
+ export function formStateAt(result, form, site) {
738
+ var _a, _b, _c;
739
+ const k = result.informative.indexOf(site);
740
+ return k >= 0
741
+ ? form.states[k]
742
+ : ((_a = result.sites[site]) === null || _a === void 0 ? void 0 : _a.shared) !== true
743
+ ? undefined
744
+ : form.key === OTHER_STATE
745
+ ? OTHER_STATE
746
+ : ((_c = (_b = form.marks.find(m => m.site === site)) === null || _b === void 0 ? void 0 : _b.state) !== null && _c !== void 0 ? _c : REFERENCE_STATE);
747
+ }
748
+ // A form's tokens outside the shared sites, as a label names its marks, then
749
+ // "rarer" and "no call" once per site, and how many lead at the largest size
750
+ // as printed
751
+ function ownTokens(form, result) {
752
+ const own = form.marks
753
+ .filter(m => { var _a; return !('site' in m && ((_a = result === null || result === void 0 ? void 0 : result.sites[m.site]) === null || _a === void 0 ? void 0 : _a.shared) === true); })
754
+ .toSorted(byDrawnSize);
755
+ const each = (token, state) => form.states.filter(s => s === state).map(() => token);
756
+ const tokens = own
757
+ .map(markTag)
758
+ .concat(each('rarer', RARER_STATE), each('no call', NO_CALL_STATE));
759
+ const [largest] = own;
760
+ return {
761
+ tokens,
762
+ largest: largest
763
+ ? own.filter(m => printedSize(m) === printedSize(largest)).length
764
+ : Math.min(tokens.length, 1),
765
+ shared: own.length < form.marks.length,
766
+ };
767
+ }
768
+ /**
769
+ * A form for a row label of about 20 characters: its largest change as
770
+ * markTag gives it, then " +N" counting the rest describeForm names, as in
771
+ * "del 18.4kb" or "ins 78kb +1"; "ref" where it makes no change. Every change
772
+ * as large as the largest, as printed, is named, one drawn over R before one
773
+ * at a point: "del 32.7kb, ins 32.7kb". A replacement's size is its larger
774
+ * side. Given the
775
+ * form's result, the tag leaves out the marks every form shares, so a form
776
+ * with no other change is "shared": naming the change there would read as if
777
+ * the other rows lacked it. Where other forms of the result would read the
778
+ * same, it names the changes that tell it from them, each the largest of those
779
+ * that the most of them lack: at C4, "del 32.7kb, del 6.37kb" and "del 32.7kb,
780
+ * repl 6.32kb->32.7kb" where both had read "del 32.7kb +1".
781
+ */
782
+ export function formTag(form, result) {
783
+ var _a;
784
+ const { tokens, largest, shared } = ownTokens(form, result);
785
+ const named = tokens.slice(0, largest);
786
+ const readAlike = (other) => other.tokens.length === tokens.length &&
787
+ other.tokens.slice(0, other.largest).join('\n') === named.join('\n');
788
+ let alike = ((_a = result === null || result === void 0 ? void 0 : result.forms) !== null && _a !== void 0 ? _a : [])
789
+ .filter(f => f !== form && f.key !== OTHER_STATE)
790
+ .map(f => ownTokens(f, result))
791
+ .filter(readAlike)
792
+ .map(other => other.tokens);
793
+ const lacking = (t) => alike.filter(other => !other.includes(t));
794
+ const telling = (candidates) => candidates.reduce((best, t) => lacking(t).length > (best === undefined ? 0 : lacking(best).length)
795
+ ? t
796
+ : best, undefined);
797
+ const shown = named.length > 0 ? named : [shared ? 'shared' : 'ref'];
798
+ let unshown = tokens.slice(largest);
799
+ let told = telling(unshown);
800
+ while (told !== undefined) {
801
+ const t = told;
802
+ const at = unshown.indexOf(t);
803
+ shown.push(t);
804
+ unshown = unshown.filter((_, i) => i !== at);
805
+ alike = alike.filter(other => other.includes(t));
806
+ told = telling(unshown);
807
+ }
808
+ return form.key === OTHER_STATE
809
+ ? 'other'
810
+ : unshown.length > 0
811
+ ? `${shown.join(', ')} +${unshown.length}`
812
+ : shown.join(', ');
813
+ }