jbrowse-plugin-tview 2.2.0 → 2.2.1

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/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "2.2.0";
1
+ export declare const version = "2.2.1";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.2.0';
1
+ export const version = '2.2.1';
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.2.0",
2
+ "version": "2.2.1",
3
3
  "license": "MIT",
4
4
  "name": "jbrowse-plugin-tview",
5
5
  "repository": {
@@ -23,6 +23,7 @@
23
23
  "format": "pnpm prettier --write .",
24
24
  "prebuild": "pnpm clean",
25
25
  "build": "tsc && NODE_ENV=production node esbuild.mjs && cp distconfig.json dist/config.json",
26
+ "typecheck": "tsc --noEmit",
26
27
  "lint": "eslint --report-unused-disable-directives --max-warnings 0",
27
28
  "test": "vitest run",
28
29
  "test:watch": "vitest",
@@ -36,7 +37,6 @@
36
37
  "postversion": "git push --follow-tags",
37
38
  "figures:repeats": "node scripts/repeat-figures.mjs",
38
39
  "prefigures:repeats": "pnpm pretest:e2e",
39
- "qc:repeats": "tsx test/liveRepeats.qc.ts",
40
40
  "report:repeats": "tsx scripts/repeat-report.mjs",
41
41
  "readme:repeats": "tsx scripts/repeat-readme.mjs"
42
42
  },
@@ -45,31 +45,32 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@emotion/styled": "^11.14.1",
48
- "swr": "^2.4.2"
48
+ "swr": "^2.5.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@emotion/react": "^11.14.0",
52
52
  "@eslint/js": "^10.0.1",
53
53
  "@fal-works/esbuild-plugin-global-externals": "^2.1.2",
54
- "@gmod/bam": "^7.3.4",
54
+ "@gmod/bam": "^8.3.0",
55
+ "@gmod/indexedfasta": "^5.0.9",
55
56
  "@jbrowse/core": "^4.3.0",
56
- "@jbrowse/mobx-state-tree": "^5.13.0",
57
+ "@jbrowse/mobx-state-tree": "^6.1.0",
57
58
  "@jbrowse/plugin-linear-genome-view": "^4.3.0",
58
- "@mui/icons-material": "^9.2.0",
59
- "@mui/material": "^9.2.0",
60
- "@mui/system": "^9.2.0",
61
- "@types/node": "^26.1.1",
62
- "@types/react": "^19.2.17",
59
+ "@mui/icons-material": "^9.3.1",
60
+ "@mui/material": "^9.3.1",
61
+ "@mui/system": "^9.3.0",
62
+ "@types/node": "^26.2.0",
63
+ "@types/react": "^19.2.18",
63
64
  "esbuild": "^0.28.1",
64
- "eslint": "^10.7.0",
65
+ "eslint": "^10.8.1",
65
66
  "eslint-plugin-import-x": "^4.17.1",
66
67
  "eslint-plugin-react": "^7.37.5",
67
68
  "eslint-plugin-react-hooks": "^7.1.1",
68
- "mobx": "^6.16.1",
69
- "mobx-react": "^9.2.2",
69
+ "mobx": "^7.0.0",
70
+ "mobx-react": "^10.0.0",
70
71
  "prettier": "^3.9.6",
71
72
  "pretty-bytes": "^7.1.1",
72
- "puppeteer": "^25.3.0",
73
+ "puppeteer": "^25.5.0",
73
74
  "react": "^19.2.8",
74
75
  "react-dom": "^19.2.8",
75
76
  "react-msaview": "^5.7.1",
@@ -77,7 +78,7 @@
77
78
  "tss-react": "^4.9.21",
78
79
  "tsx": "^4.20.6",
79
80
  "typescript": "^6.0.2",
80
- "typescript-eslint": "^8.65.0",
81
+ "typescript-eslint": "^8.66.0",
81
82
  "vitest": "^4.1.10"
82
83
  }
83
84
  }
@@ -301,26 +301,34 @@ function splitIntoUnits(seq: string, consensus: string) {
301
301
  return units
302
302
  }
303
303
 
304
- // The tiled alignment below is O(len * len), so it scores a prefix rather than
305
- // the whole insert. A sequence that is copies of the unit for its first 300
306
- // bases is copies of the unit.
304
+ // The tiled alignment below is O(len^2), so it scores windows of the insert
305
+ // rather than all of it.
307
306
  const IDENTITY_PROBE_LEN = 300
308
307
 
309
308
  /**
310
- * How much of `seq` is explained by `unit` repeated end to end: the fraction of
311
- * `seq`'s bases that align to a matching base of the tiling.
309
+ * Head, middle and tail of `seq`, or the whole of it when it is short enough to
310
+ * score outright.
312
311
  *
313
- * Free at both ends of the tiling, since an inserted run of copies can start
314
- * and stop mid-copy, and global on `seq`, since the question is about all of it.
315
- * That is what separates "more copies of this array" from "something else that
316
- * landed next to it" without asking the sequence to be in phase with the unit:
317
- * measured against the trio, the repeat alleles the aligner anchored just
318
- * outside an array score 0.94-1.00 and unrelated sequence of the same length
319
- * scores 0.67 or below.
312
+ * Scoring only the head is how a prefix probe lies: `unit x 12` followed by a
313
+ * kilobase of something else scores 1.00 on its first 300 bases and is not the
314
+ * array's. Three windows cost the same and cannot be fooled that way, because
315
+ * the sequence has to still be the unit where it ends as well as where it
316
+ * starts.
320
317
  */
321
- export function unitIdentity(seq: string, unit: string) {
322
- const probe =
323
- seq.length > IDENTITY_PROBE_LEN ? seq.slice(0, IDENTITY_PROBE_LEN) : seq
318
+ function probeWindows(seq: string) {
319
+ if (seq.length <= IDENTITY_PROBE_LEN) {
320
+ return [seq]
321
+ }
322
+ const middle = Math.floor((seq.length - IDENTITY_PROBE_LEN) / 2)
323
+ return [
324
+ seq.slice(0, IDENTITY_PROBE_LEN),
325
+ seq.slice(middle, middle + IDENTITY_PROBE_LEN),
326
+ seq.slice(-IDENTITY_PROBE_LEN),
327
+ ]
328
+ }
329
+
330
+ /** the fraction of `probe`'s bases that match `unit` tiled end to end */
331
+ function tiledIdentity(probe: string, unit: string) {
324
332
  const n = probe.length
325
333
  if (!n || !unit.length) {
326
334
  return 0
@@ -364,6 +372,27 @@ export function unitIdentity(seq: string, unit: string) {
364
372
  return bestMatches / n
365
373
  }
366
374
 
375
+ /**
376
+ * How much of `seq` is explained by `unit` repeated end to end, scored at three
377
+ * places along it and reported as the worst of them.
378
+ *
379
+ * Each window is aligned free at both ends of the tiling, since an inserted run
380
+ * of copies can start and stop mid-copy, and global on the window, since the
381
+ * question is about all of it. That is what separates "more copies of this
382
+ * array" from "something else that landed next to it" without asking the
383
+ * sequence to be in phase with the unit — the ABCA7 read that carries 1207bp of
384
+ * VNTR anchored outside the array begins six bases into a copy, and the FMR1
385
+ * one begins on the wrong base of the unit and carries the locus's own AGG
386
+ * interruptions.
387
+ *
388
+ * Measured against the trio: the repeat alleles the aligner anchored just
389
+ * outside an array score 0.9 and up, and unrelated sequence of the same length
390
+ * scores 0.67 or below.
391
+ */
392
+ export function unitIdentity(seq: string, unit: string) {
393
+ return Math.min(...probeWindows(seq).map(w => tiledIdentity(w, unit)))
394
+ }
395
+
367
396
  export interface PeriodicAlignment {
368
397
  /** repeat unit length in bp */
369
398
  period: number
@@ -70,109 +70,217 @@ export function extractAllele(read: ReadLayout, start: number, end: number) {
70
70
  return ret
71
71
  }
72
72
 
73
- /** Reference positions an array owns, including the insertion slot at its right edge. */
74
- export function arrayInsertionKeys(array: { start: number; end: number }) {
75
- const ret: number[] = []
76
- for (let pos = array.start; pos <= array.end; pos++) {
77
- ret.push(pos)
78
- }
79
- return ret
73
+ /**
74
+ * How far outside an array an insertion is looked for, in reference bases.
75
+ *
76
+ * GIAB's adotto tandem repeat catalog buffers every interval by +/-25bp before
77
+ * merging, to leave room for the alignment ambiguity that comes with capturing
78
+ * variation inside a repeat, and measured what the buffer misses: re-expanding
79
+ * every region by a further 10bp would move only 0.2% of its boundaries
80
+ * (English et al., Nat Biotechnol 42, 2024, doi:10.1038/s41587-024-02225-z). A
81
+ * whole copy is the floor for a unit longer than that, since a copy is the
82
+ * aligner's room to slide a repeat indel. Both cover the misplacements measured
83
+ * in this trio: ATXN3 at 1bp, FMR1 at 2bp of a 3bp unit, ABCA7 at 19bp of a
84
+ * 25bp one.
85
+ *
86
+ * It bounds the search, not the answer. Whether an insertion actually moves is
87
+ * decided exactly, by `shiftInsertion`, so this being generous costs nothing.
88
+ */
89
+ const FLANK_BP = 25
90
+
91
+ /** the read's aligned base at a reference position, if it has one there */
92
+ function readBase(read: ReadLayout, pos: number) {
93
+ const i = pos - read.start
94
+ return i >= 0 && i < read.refChars.length ? read.refChars[i] : undefined
80
95
  }
81
96
 
82
97
  /**
83
- * How far outside an array an insertion of its own unit can be anchored, in
84
- * copies. An indel made of repeat units has no unique placement inside the
85
- * array, and the flanking bases let the aligner carry it a little further still
86
- * — but only about a copy, because past that the sequence either side stops
87
- * matching. Every misplaced repeat allele in the trio sits within one copy of
88
- * the edge: ATXN3's at 1bp, FMR1's at 2bp of a 3bp unit, ABCA7's at 19bp of a
89
- * 25bp one.
98
+ * How much of an insertion the array's unit has to explain before it counts as
99
+ * the array's. The repeat alleles the aligner anchored just outside an array in
100
+ * the trio score 0.9 and up, and unrelated sequence scores 0.67 or below, so
101
+ * this sits in open space rather than on a boundary.
90
102
  */
91
- const ABSORB_COPIES = 1
103
+ const BELONGS_IDENTITY = 0.8
92
104
 
93
105
  /**
94
- * How much of the inserted sequence the array's unit has to explain before the
95
- * insertion counts as part of the array. The repeat alleles the aligner
96
- * anchored just outside an array in the trio score 0.94-1.00 here and unrelated
97
- * sequence scores 0.67 or below, so this sits in open space rather than on a
98
- * boundary.
106
+ * `ins`, inserted before reference position `from`, rewritten as an insertion
107
+ * before `to` — or undefined when the read's own bases do not allow it.
108
+ *
109
+ * An insertion has no unique position. `S` before a base `b` and `rotate(S)`
110
+ * after it spell the same read, so an aligner is free to anchor an expansion
111
+ * outside the array it belongs to, and at ATXN3 it did exactly that for most of
112
+ * the reads carrying one. Walking an indel through that equivalence class is
113
+ * the standard normalization for it (Tan, Abecasis & Kang, "Unified
114
+ * representation of genetic variants", Bioinformatics 31, 2015,
115
+ * doi:10.1093/bioinformatics/btv112, which walks left; this walks toward the
116
+ * array, the same operation with the array as the canonical anchor).
117
+ *
118
+ * The step is tested against the **read's** aligned base rather than the
119
+ * reference's, which is what makes the rewrite exact: the row still renders
120
+ * base for base as it did, and the only thing that changes is the reference
121
+ * position the bases are filed under. A step onto a deletion has no base to
122
+ * swap with and stops.
123
+ *
124
+ * Being exact, it is also incomplete, and measurably so. An aligner does not
125
+ * only choose among equivalent placements — it chooses the highest-scoring one,
126
+ * which for a repeat allele carrying an interruption is often not equivalent to
127
+ * any placement inside the array. FMR1's misplaced read is exactly that: 32bp
128
+ * of the locus's own CGG anchored two bases early, starting on a `C` where the
129
+ * read has a `G`, so no rewrite of it exists. Hence `reanchorInsertions` treats
130
+ * this as the preferred spelling and not as the test of whether to move.
99
131
  */
100
- const ABSORB_IDENTITY = 0.8
132
+ export function shiftInsertion(
133
+ read: ReadLayout,
134
+ from: number,
135
+ to: number,
136
+ ins: string,
137
+ ) {
138
+ let seq = ins
139
+ for (let pos = from; pos < to; pos++) {
140
+ const head = seq[0]!
141
+ if (readBase(read, pos) !== head) {
142
+ return undefined
143
+ }
144
+ seq = seq.slice(1) + head
145
+ }
146
+ for (let pos = from - 1; pos >= to; pos--) {
147
+ const tail = seq.at(-1)!
148
+ if (readBase(read, pos) !== tail) {
149
+ return undefined
150
+ }
151
+ seq = tail + seq.slice(0, -1)
152
+ }
153
+ return seq
154
+ }
155
+
156
+ /** an array with the span of reference positions whose insertions it may claim */
157
+ interface FlankWindow {
158
+ array: ReferenceArray
159
+ from: number
160
+ to: number
161
+ }
101
162
 
102
163
  /**
103
- * Widen each array to cover the insertions the aligner anchored just outside it
104
- * that are made of the array's own unit.
164
+ * The window around each array that its insertions may be re-anchored from.
105
165
  *
106
- * An allele is measured over a reference interval, which fixes the "one array
107
- * reports as several sites" problem for indels the aligner placed *inside* the
108
- * interval. It does not fix the ones it placed just outside: an aligner is free
109
- * to anchor an expansion at the base before the array starts, and there the
110
- * insertion is not part of any allele — it is left to become its own run of
111
- * insertion columns, and the read it belongs to is measured as if it carried
112
- * the reference allele. Both halves of that are wrong, and they are not rare:
113
- * at ATXN3 the aligner anchored 60 of 162 reads' expansions one base outside
114
- * the array, and at ABCA7 a 1207bp allele 19 bases outside.
166
+ * Two arrays may not claim one position: `extractAllele` reads the slot at an
167
+ * array's `end`, so a shared slot would be counted into two alleles. Neighbours
168
+ * split the reference between them down the middle — a property of the
169
+ * reference alone, so unlike the interval it replaces, no read can move it.
170
+ */
171
+ export function flankWindows(arrays: ReferenceArray[]): FlankWindow[] {
172
+ const ordered = [...arrays].sort((a, b) => a.start - b.start)
173
+ return ordered.map((array, i) => {
174
+ const pad = Math.max(FLANK_BP, array.period)
175
+ const previous = ordered[i - 1]
176
+ const next = ordered[i + 1]
177
+ return {
178
+ array,
179
+ from: Math.max(
180
+ array.start - pad,
181
+ previous ? Math.floor((previous.end + array.start) / 2) + 1 : -Infinity,
182
+ ),
183
+ to: Math.min(
184
+ array.end + pad,
185
+ next ? Math.floor((array.end + next.start) / 2) : Infinity,
186
+ ),
187
+ }
188
+ })
189
+ }
190
+
191
+ /** the array whose window `pos` falls in, if any */
192
+ function windowAt(pos: number, windows: FlankWindow[]) {
193
+ for (const window of windows) {
194
+ if (pos < window.from) {
195
+ return undefined
196
+ }
197
+ if (pos <= window.to) {
198
+ return window
199
+ }
200
+ }
201
+ return undefined
202
+ }
203
+
204
+ /**
205
+ * Re-file each read's insertions under the array they belong to, one read at a
206
+ * time.
115
207
  *
116
- * What is absorbed is decided by the inserted sequence, not by the count of
117
- * reads carrying it — a single read's expansion is as real as fifty, and the
118
- * whole point of measuring over an interval is that it does not need a vote.
119
- * Widening the interval costs every row the few reference bases in between,
120
- * which they all pay equally, so the counts stay comparable.
208
+ * Measuring an allele over a reference interval fixes the "one array reports as
209
+ * several sites" problem for indels the aligner placed *inside* the interval.
210
+ * It does not fix the ones placed just outside: there the insertion is part of
211
+ * no allele — it becomes its own run of insertion columns — and the read
212
+ * carrying it is measured as though it had the reference allele. Both halves of
213
+ * that are wrong, and neither is rare: at ATXN3 the aligner anchored 60 of 162
214
+ * reads' expansions one base outside the array.
215
+ *
216
+ * Doing this per read is the whole point. Widening the shared interval instead
217
+ * — which is what this replaces — made one read's misplacement everyone's: a
218
+ * single spurious copy anchored two bases early moved the array's left edge for
219
+ * every row, and the reference's own copy count with it. Re-anchoring touches
220
+ * only the read that carries the insertion, so a read can be wrong on its own.
221
+ *
222
+ * Nothing here consults the other reads, or how many of them agree. A single
223
+ * read's expansion is as real as fifty, which is what measuring over an
224
+ * interval buys and what a vote would give back. What decides an insertion is
225
+ * its own sequence: `unitIdentity` against the array's unit, since the aligner
226
+ * is free to place a repeat allele outside the array but is not free to make
227
+ * unrelated sequence out of the array's unit.
121
228
  */
122
- export function absorbAdjacentInsertions(
229
+ export function reanchorInsertions(
123
230
  reads: ReadLayout[],
124
231
  arrays: ReferenceArray[],
125
232
  ) {
126
- const ordered = [...arrays].sort((a, b) => a.start - b.start)
127
- // the widened end of the array to the left, which the next one may not reach
128
- let previousEnd = -Infinity
129
- return ordered.map((array, i) => {
130
- const margin = ABSORB_COPIES * array.period
131
- // Two arrays that met at a position would read the same insertion slot
132
- // twice — once as each one's allele — so they are held apart on both
133
- // sides: leftwards off whatever the previous array grew to, rightwards off
134
- // where the next one starts, which is as far left as that one can be
135
- // pushed in turn. Neither bound can cross the array's own edges, since
136
- // mergeArrays has already left a gap between every pair.
137
- const floor = Math.max(array.start - margin, previousEnd + 1)
138
- const ceiling = Math.min(
139
- array.end + margin,
140
- (ordered[i + 1]?.start ?? Infinity) - 1,
141
- )
142
- let { start, end } = array
143
- // memoized per distinct insert: one locus routinely has dozens of reads
144
- // carrying the same allele at the same site
145
- const belongs = new Map<string, boolean>()
146
- const isUnit = (ins: string) => {
147
- let ret = belongs.get(ins)
148
- if (ret === undefined) {
149
- ret = unitIdentity(ins, array.unit) >= ABSORB_IDENTITY
150
- belongs.set(ins, ret)
151
- }
152
- return ret
233
+ const windows = flankWindows(arrays)
234
+ if (!windows.length) {
235
+ return reads
236
+ }
237
+ // memoized per array and distinct insert: one locus routinely has dozens of
238
+ // reads carrying the same allele at the same site
239
+ const belongs = new Map<string, boolean>()
240
+ const isUnit = (window: FlankWindow, ins: string) => {
241
+ const key = `${window.array.start}:${ins}`
242
+ let ret = belongs.get(key)
243
+ if (ret === undefined) {
244
+ ret =
245
+ // a whole copy at least: a base or two of read error beside an array
246
+ // says nothing about where its allele ends, and the identity of a
247
+ // fragment shorter than the unit is not a measurement of anything
248
+ ins.length >= window.array.period &&
249
+ unitIdentity(ins, window.array.unit) >= BELONGS_IDENTITY
250
+ belongs.set(key, ret)
153
251
  }
154
- for (const read of reads) {
155
- for (const [pos, ins] of read.insertions) {
156
- // a whole copy at least: a base or two of read error next to an array
157
- // says nothing about where the array ends, and moving the interval for
158
- // it would lay flanking sequence out as repeat copies
159
- if (
160
- ins.length < array.period ||
161
- pos < floor ||
162
- pos > ceiling ||
163
- (pos >= array.start && pos <= array.end) ||
164
- !isUnit(ins)
165
- ) {
166
- continue
167
- }
168
- start = Math.min(start, pos)
169
- // an insertion is keyed to the position it precedes, and extractAllele
170
- // reads the slot at `end`, so covering it means reaching that position
171
- end = Math.max(end, pos)
172
- }
252
+ return ret
253
+ }
254
+ return reads.map(read => {
255
+ if (!read.insertions.size) {
256
+ return read
257
+ }
258
+ let moved = false
259
+ const next = new Map<number, string>()
260
+ // Insertions are re-filed in genomic order of where the aligner put them,
261
+ // so two events landing in one slot keep their order along the read.
262
+ for (const [pos, ins] of [...read.insertions].sort((a, b) => a[0] - b[0])) {
263
+ const window = windowAt(pos, windows)
264
+ const { start, end } = window?.array ?? {}
265
+ const target =
266
+ window === undefined || (pos >= start! && pos <= end!)
267
+ ? undefined
268
+ : isUnit(window, ins)
269
+ ? pos < start!
270
+ ? start!
271
+ : end!
272
+ : undefined
273
+ // an exact rewrite is preferred where one exists, so a row that can be
274
+ // re-spelled reads base for base as the aligner wrote it; where none
275
+ // exists the bases move as written, which preserves the length the
276
+ // measurement is made of
277
+ const at = target ?? pos
278
+ moved ||= target !== undefined
279
+ const seq =
280
+ target === undefined ? ins : (shiftInsertion(read, pos, target, ins) ?? ins)
281
+ next.set(at, (next.get(at) ?? '') + seq)
173
282
  }
174
- previousEnd = end
175
- return { ...array, start, end }
283
+ return moved ? { ...read, insertions: next } : read
176
284
  })
177
285
  }
178
286
 
@@ -16,19 +16,46 @@ import type { TviewPlan } from './tview'
16
16
  /**
17
17
  * Least support an allele needs before it is reported as one of a sample's,
18
18
  * as a fraction of that sample's spanning reads.
19
- *
20
- * Reads scatter around an allele — slippage in the read, slippage in the
21
- * aligner — so the counts either side of a real allele are populated too, and
22
- * a rule that took the top two would report the shoulder of one allele as the
23
- * other. A fraction of coverage rather than a distance in copies is what lets
24
- * two alleles a single copy apart both be reported, which at FMR1 is the
25
- * mother's genotype and at ATXN3 the father's.
26
19
  */
27
20
  const MIN_ALLELE_FRACTION = 0.15
28
21
 
29
22
  /** ...and never on one read, at any coverage. */
30
23
  const MIN_ALLELE_READS = 2
31
24
 
25
+ /**
26
+ * How far from an allele a read's copy count may fall and still be counted as
27
+ * that allele's, as a fraction of the allele's own size.
28
+ *
29
+ * Proportional rather than fixed because slippage scales with the array: the
30
+ * reads either side of an 89-copy allele scatter further than those either side
31
+ * of an 8-copy one. cuteSV refines a cluster of structural-variant signatures
32
+ * the same way, by a bandwidth taken as a fraction of the cluster's own mean
33
+ * length (Jiang et al., Genome Biol 21, 2020, doi:10.1186/s13059-020-02107-y);
34
+ * its constants are fractions of a length in bases and do not carry over to a
35
+ * count of copies, so this one is measured here instead. At 0.1 no call in the
36
+ * trio moves, merges or is lost, and the reads left out of one drop by three
37
+ * quarters.
38
+ */
39
+ const SHOULDER_SPREAD = 0.1
40
+
41
+ /**
42
+ * ...and how much support such a read may carry, relative to the allele it
43
+ * would join, before it is an allele of its own instead.
44
+ *
45
+ * This is the load-bearing half, and distance alone cannot replace it. At FMR1
46
+ * the mother carries two alleles one copy apart and at HTT a single allele has
47
+ * a shoulder one copy either side, so no bandwidth tells those two apart.
48
+ * Relative support does: a slippage shoulder in the trio runs at a fraction of
49
+ * its allele, and the mother's second allele runs at 87% of her first. The
50
+ * measured shelf is wide — 0.2 leaves reads uncounted, 0.4 starts merging the
51
+ * mother's two alleles into one.
52
+ *
53
+ * That shelf is 21 sample-locus calls in one trio, which is a shelf and not a
54
+ * proof: a locus carrying three real alleles within a copy of each other would
55
+ * defeat the rule, and this trio has none.
56
+ */
57
+ const SHOULDER_SUPPORT = 0.3
58
+
32
59
  export interface Tally {
33
60
  value: number
34
61
  reads: number
@@ -46,7 +73,15 @@ export function tally(values: number[]): Tally[] {
46
73
  }
47
74
 
48
75
  /**
49
- * The copy counts a sample carries, as the counts enough of its reads agree on.
76
+ * The copy counts a sample carries, each with the reads that fell on it or in
77
+ * its skirt.
78
+ *
79
+ * Reads scatter around an allele — slippage in the molecule, slippage in the
80
+ * aligner — so a rule that reported only exact agreement credited an allele
81
+ * with a fraction of the reads that actually support it, and left the rest
82
+ * looking like disagreement. Counts are gathered strongest first, so an allele
83
+ * is established before anything can be read as its shoulder, and a value joins
84
+ * one only if it is both near it and much weaker than it.
50
85
  *
51
86
  * This is a report of what the reads say, not a genotype call: it does not know
52
87
  * a ploidy, so a homozygote and a haploid locus both come back as one number,
@@ -54,18 +89,36 @@ export function tally(values: number[]): Tally[] {
54
89
  */
55
90
  export function alleleModes(copies: number[]): Tally[] {
56
91
  const floor = Math.max(MIN_ALLELE_READS, MIN_ALLELE_FRACTION * copies.length)
57
- return tally(copies).filter(t => t.reads >= floor)
92
+ const peaks: Tally[] = []
93
+ for (const t of tally(copies).sort(
94
+ (a, b) => b.reads - a.reads || a.value - b.value,
95
+ )) {
96
+ const distance = (peak: Tally) => Math.abs(t.value - peak.value)
97
+ const host = peaks
98
+ .filter(
99
+ peak =>
100
+ distance(peak) <= Math.max(1, SHOULDER_SPREAD * peak.value) &&
101
+ t.reads <= SHOULDER_SUPPORT * peak.reads,
102
+ )
103
+ .sort((a, b) => distance(a) - distance(b))[0]
104
+ if (host) {
105
+ host.reads += t.reads
106
+ } else {
107
+ peaks.push({ ...t })
108
+ }
109
+ }
110
+ return peaks.filter(p => p.reads >= floor).sort((a, b) => a.value - b.value)
58
111
  }
59
112
 
60
113
  export interface SampleArrayStats {
61
114
  sample: string
62
115
  /** rows that reached both ends of the interval, i.e. that were measured */
63
116
  spanning: number
64
- /** copy counts enough of them agreed on */
117
+ /** the alleles found, each with the reads counted into it */
65
118
  modes: Tally[]
66
119
  /** every copy count seen, with its support */
67
120
  copies: Tally[]
68
- /** rows whose copy count is not one of the modes */
121
+ /** rows counted into no allele at all */
69
122
  offMode: number
70
123
  }
71
124
 
@@ -111,13 +164,15 @@ function arrayStats(
111
164
  .filter(([name]) => sampleOfRow(name) === sample)
112
165
  .map(([, n]) => n)
113
166
  const modes = alleleModes(copies)
114
- const called = new Set(modes.map(m => m.value))
115
167
  return {
116
168
  sample,
117
169
  spanning: copies.length,
118
170
  modes,
119
171
  copies: tally(copies),
120
- offMode: copies.filter(c => !called.has(c)).length,
172
+ // an allele carries the reads in its skirt as well as those exactly on
173
+ // it, so what is left over is counted off the alleles rather than off
174
+ // the distinct values they were called at
175
+ offMode: copies.length - modes.reduce((a, m) => a + m.reads, 0),
121
176
  }
122
177
  }),
123
178
  }
@@ -1,5 +1,5 @@
1
1
  import { alignInsertionSite } from './align'
2
- import { absorbAdjacentInsertions, buildArrayBlocks } from './alleles'
2
+ import { buildArrayBlocks, reanchorInsertions } from './alleles'
3
3
  import {
4
4
  ABSENT,
5
5
  SPANNED_GAP,
@@ -311,18 +311,16 @@ export function planTviewMsa({
311
311
  end,
312
312
  )
313
313
 
314
- // the interval comes from the reference, then widens over the repeat alleles
315
- // the aligner anchored just outside it — see absorbAdjacentInsertions, which
316
- // has to see the reads and so cannot live in the reference scan
317
- const arrays = sequence
318
- ? buildArrayBlocks(
319
- clipped,
320
- absorbAdjacentInsertions(
321
- clipped,
322
- mergeArrays(findReferenceArrays(sequence, start)),
323
- ),
324
- )
314
+ // The intervals come from the reference and nothing here moves them. What
315
+ // moves is each read's insertions, re-filed under the array they belong to
316
+ // before anything is measured or laid out — see reanchorInsertions. Both
317
+ // steps below read the re-anchored reads, so an insertion the array took over
318
+ // is rendered inside its block and not also as a column of its own.
319
+ const intervals = sequence
320
+ ? mergeArrays(findReferenceArrays(sequence, start))
325
321
  : []
322
+ const anchored = reanchorInsertions(clipped, intervals)
323
+ const arrays = buildArrayBlocks(anchored, intervals)
326
324
  const ownedByArray = new Set<number>()
327
325
  for (const array of arrays) {
328
326
  for (let pos = array.start; pos <= array.end; pos++) {
@@ -330,7 +328,7 @@ export function planTviewMsa({
330
328
  }
331
329
  }
332
330
 
333
- const aligned = alignInsertionColumns(clipped, ownedByArray)
331
+ const aligned = alignInsertionColumns(anchored, ownedByArray)
334
332
 
335
333
  // With several arrays in view the subject is the one the rows disagree most
336
334
  // about, since ordering rows by two copy numbers at once is not a thing rows