jbrowse-plugin-tview 2.2.0 → 2.2.3

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.
@@ -8,6 +8,7 @@
8
8
  * back counts, which is what makes it testable without the network.
9
9
  */
10
10
  import { ABSENT, SPANNED_GAP } from './readLayout'
11
+ import { newickSafe } from './sampleTree'
11
12
  import { renderRow } from './tview'
12
13
 
13
14
  import type { ArrayBlock } from './alleles'
@@ -16,19 +17,46 @@ import type { TviewPlan } from './tview'
16
17
  /**
17
18
  * Least support an allele needs before it is reported as one of a sample's,
18
19
  * 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
20
  */
27
21
  const MIN_ALLELE_FRACTION = 0.15
28
22
 
29
23
  /** ...and never on one read, at any coverage. */
30
24
  const MIN_ALLELE_READS = 2
31
25
 
26
+ /**
27
+ * How far from an allele a read's copy count may fall and still be counted as
28
+ * that allele's, as a fraction of the allele's own size.
29
+ *
30
+ * Proportional rather than fixed because slippage scales with the array: the
31
+ * reads either side of an 89-copy allele scatter further than those either side
32
+ * of an 8-copy one. cuteSV refines a cluster of structural-variant signatures
33
+ * the same way, by a bandwidth taken as a fraction of the cluster's own mean
34
+ * length (Jiang et al., Genome Biol 21, 2020, doi:10.1186/s13059-020-02107-y);
35
+ * its constants are fractions of a length in bases and do not carry over to a
36
+ * count of copies, so this one is measured here instead. At 0.1 no call in the
37
+ * trio moves, merges or is lost, and the reads left out of one drop by three
38
+ * quarters.
39
+ */
40
+ const SHOULDER_SPREAD = 0.1
41
+
42
+ /**
43
+ * ...and how much support such a read may carry, relative to the allele it
44
+ * would join, before it is an allele of its own instead.
45
+ *
46
+ * This is the load-bearing half, and distance alone cannot replace it. At FMR1
47
+ * the mother carries two alleles one copy apart and at HTT a single allele has
48
+ * a shoulder one copy either side, so no bandwidth tells those two apart.
49
+ * Relative support does: a slippage shoulder in the trio runs at a fraction of
50
+ * its allele, and the mother's second allele runs at 87% of her first. The
51
+ * measured shelf is wide — 0.2 leaves reads uncounted, 0.4 starts merging the
52
+ * mother's two alleles into one.
53
+ *
54
+ * That shelf is 21 sample-locus calls in one trio, which is a shelf and not a
55
+ * proof: a locus carrying three real alleles within a copy of each other would
56
+ * defeat the rule, and this trio has none.
57
+ */
58
+ const SHOULDER_SUPPORT = 0.3
59
+
32
60
  export interface Tally {
33
61
  value: number
34
62
  reads: number
@@ -46,7 +74,15 @@ export function tally(values: number[]): Tally[] {
46
74
  }
47
75
 
48
76
  /**
49
- * The copy counts a sample carries, as the counts enough of its reads agree on.
77
+ * The copy counts a sample carries, each with the reads that fell on it or in
78
+ * its skirt.
79
+ *
80
+ * Reads scatter around an allele — slippage in the molecule, slippage in the
81
+ * aligner — so a rule that reported only exact agreement credited an allele
82
+ * with a fraction of the reads that actually support it, and left the rest
83
+ * looking like disagreement. Counts are gathered strongest first, so an allele
84
+ * is established before anything can be read as its shoulder, and a value joins
85
+ * one only if it is both near it and much weaker than it.
50
86
  *
51
87
  * This is a report of what the reads say, not a genotype call: it does not know
52
88
  * a ploidy, so a homozygote and a haploid locus both come back as one number,
@@ -54,18 +90,36 @@ export function tally(values: number[]): Tally[] {
54
90
  */
55
91
  export function alleleModes(copies: number[]): Tally[] {
56
92
  const floor = Math.max(MIN_ALLELE_READS, MIN_ALLELE_FRACTION * copies.length)
57
- return tally(copies).filter(t => t.reads >= floor)
93
+ const peaks: Tally[] = []
94
+ for (const t of tally(copies).sort(
95
+ (a, b) => b.reads - a.reads || a.value - b.value,
96
+ )) {
97
+ const distance = (peak: Tally) => Math.abs(t.value - peak.value)
98
+ const host = peaks
99
+ .filter(
100
+ peak =>
101
+ distance(peak) <= Math.max(1, SHOULDER_SPREAD * peak.value) &&
102
+ t.reads <= SHOULDER_SUPPORT * peak.reads,
103
+ )
104
+ .sort((a, b) => distance(a) - distance(b))[0]
105
+ if (host) {
106
+ host.reads += t.reads
107
+ } else {
108
+ peaks.push({ ...t })
109
+ }
110
+ }
111
+ return peaks.filter(p => p.reads >= floor).sort((a, b) => a.value - b.value)
58
112
  }
59
113
 
60
114
  export interface SampleArrayStats {
61
115
  sample: string
62
116
  /** rows that reached both ends of the interval, i.e. that were measured */
63
117
  spanning: number
64
- /** copy counts enough of them agreed on */
118
+ /** the alleles found, each with the reads counted into it */
65
119
  modes: Tally[]
66
120
  /** every copy count seen, with its support */
67
121
  copies: Tally[]
68
- /** rows whose copy count is not one of the modes */
122
+ /** rows counted into no allele at all */
69
123
  offMode: number
70
124
  }
71
125
 
@@ -90,6 +144,23 @@ function sampleOfRow(name: string) {
90
144
  return i < 0 ? undefined : name.slice(0, i)
91
145
  }
92
146
 
147
+ /**
148
+ * Rows are prefixed with the Newick-safe form of their sample's name, so a
149
+ * caller naming the samples it wants reported has to be met there rather than
150
+ * taken at its word. A track called `HG004 (mother)` otherwise matched no row
151
+ * and came back with nought spanning reads and no alleles — which is what a
152
+ * locus nobody sequenced looks like, not what a misspelt name should.
153
+ *
154
+ * The name the caller gave is what gets reported back; only the matching is
155
+ * sanitized.
156
+ */
157
+ function rowsOfSample(copiesByName: Map<string, number>, sample: string) {
158
+ const key = newickSafe(sample)
159
+ return [...copiesByName]
160
+ .filter(([name]) => sampleOfRow(name) === key)
161
+ .map(([, n]) => n)
162
+ }
163
+
93
164
  function arrayStats(
94
165
  array: ArrayBlock,
95
166
  plan: TviewPlan,
@@ -107,17 +178,17 @@ function arrayStats(
107
178
  : undefined,
108
179
  subject: array === plan.subject,
109
180
  samples: samples.map(sample => {
110
- const copies = [...array.copiesByName]
111
- .filter(([name]) => sampleOfRow(name) === sample)
112
- .map(([, n]) => n)
181
+ const copies = rowsOfSample(array.copiesByName, sample)
113
182
  const modes = alleleModes(copies)
114
- const called = new Set(modes.map(m => m.value))
115
183
  return {
116
184
  sample,
117
185
  spanning: copies.length,
118
186
  modes,
119
187
  copies: tally(copies),
120
- offMode: copies.filter(c => !called.has(c)).length,
188
+ // an allele carries the reads in its skirt as well as those exactly on
189
+ // it, so what is left over is counted off the alleles rather than off
190
+ // the distinct values they were called at
191
+ offMode: copies.length - modes.reduce((a, m) => a + m.reads, 0),
121
192
  }
122
193
  }),
123
194
  }
@@ -194,14 +194,16 @@ const RIVAL_SPAN_FRACTION = 0.5
194
194
  */
195
195
  export function mergeArrays(arrays: ReferenceArray[], gap = 0) {
196
196
  const groups: ReferenceArray[][] = []
197
+ // how far right the open group reaches, which is not its last member's end:
198
+ // sorting by start lets a long array be followed by one that ends inside it
199
+ let reach = -Infinity
197
200
  for (const array of [...arrays].sort((a, b) => a.start - b.start)) {
198
- const last = groups.at(-1)
199
- const end = last ? Math.max(...last.map(a => a.end)) : 0
200
- if (last && array.start <= end + gap) {
201
- last.push(array)
201
+ if (array.start <= reach + gap) {
202
+ groups.at(-1)!.push(array)
202
203
  } else {
203
204
  groups.push([array])
204
205
  }
206
+ reach = Math.max(reach, array.end)
205
207
  }
206
208
  return groups.map(group => {
207
209
  const span = (a: ReferenceArray) => a.end - a.start
@@ -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,
@@ -85,10 +85,16 @@ export interface ColumnLayout {
85
85
  */
86
86
  offsets: number[]
87
87
  totalColumns: number
88
- }
89
-
90
- function arrayStartIndex(arrays: ArrayBlock[]) {
91
- return new Map(arrays.map(a => [a.start, a]))
88
+ /** the array beginning at a position, for the positions one begins at */
89
+ arrayByStart: Map<number, ArrayBlock>
90
+ /**
91
+ * Ascending, the positions a row cannot be laid out in bulk over: an array
92
+ * block starts here, or some read inserts here. Between two of them every
93
+ * position is one reference column, so that stretch of a row is a slice of
94
+ * the read's own bases rather than a walk over them — which is what keeps
95
+ * rendering proportional to the indels in a region rather than to its width.
96
+ */
97
+ breaks: number[]
92
98
  }
93
99
 
94
100
  /**
@@ -103,15 +109,17 @@ export function buildColumnLayout(
103
109
  insWidths: Map<number, number>,
104
110
  arrays: ArrayBlock[] = [],
105
111
  ): ColumnLayout {
106
- const byStartPos = arrayStartIndex(arrays)
112
+ const arrayByStart = new Map(arrays.map(a => [a.start, a]))
107
113
  const offsets: number[] = []
114
+ const breaks: number[] = []
108
115
  let col = 0
109
116
  let pos = start
110
117
  while (pos < end) {
111
- const array = byStartPos.get(pos)
118
+ const array = arrayByStart.get(pos)
112
119
  if (array) {
113
120
  const stop = Math.min(array.end, end)
114
121
  offsets.push(col)
122
+ breaks.push(pos)
115
123
  col += array.width
116
124
  for (let p = pos + 1; p < stop; p++) {
117
125
  offsets.push(col)
@@ -119,12 +127,40 @@ export function buildColumnLayout(
119
127
  pos = stop
120
128
  } else {
121
129
  offsets.push(col)
122
- col += (insWidths.get(pos) ?? 0) + 1
130
+ const width = insWidths.get(pos) ?? 0
131
+ if (width) {
132
+ breaks.push(pos)
133
+ }
134
+ col += width + 1
123
135
  pos++
124
136
  }
125
137
  }
126
138
  offsets.push(col)
127
- return { start, end, insWidths, arrays, offsets, totalColumns: col }
139
+ return {
140
+ start,
141
+ end,
142
+ insWidths,
143
+ arrays,
144
+ offsets,
145
+ totalColumns: col,
146
+ arrayByStart,
147
+ breaks,
148
+ }
149
+ }
150
+
151
+ /** index of the first break at or after `pos` */
152
+ function breakIndex(breaks: number[], pos: number) {
153
+ let lo = 0
154
+ let hi = breaks.length
155
+ while (lo < hi) {
156
+ const mid = (lo + hi) >> 1
157
+ if (breaks[mid]! < pos) {
158
+ lo = mid + 1
159
+ } else {
160
+ hi = mid
161
+ }
162
+ }
163
+ return lo
128
164
  }
129
165
 
130
166
  /** the array covering `pos`, when `pos` is strictly inside one */
@@ -136,14 +172,17 @@ function arrayContaining(arrays: ArrayBlock[], pos: number) {
136
172
  * Lays a single row out across the whole region. Rows are typically a tiny
137
173
  * fraction of the region, so the columns on either side are filled in one shot
138
174
  * from the offsets rather than walked position by position — which works over
139
- * array blocks too, since the offsets already carry their width.
175
+ * array blocks too, since the offsets already carry their width. Inside its own
176
+ * span a row is walked only at the layout's breaks, and copied straight out of
177
+ * `refChars` between them.
140
178
  */
141
179
  export function renderRow(read: ReadLayout, layout: ColumnLayout) {
142
180
  const { start, end, insWidths, arrays, offsets, totalColumns } = layout
143
- const byStartPos = arrayStartIndex(arrays)
181
+ const { arrayByStart, breaks } = layout
144
182
  // a trailing insertion is keyed one past the last position the read spans
183
+ const lastPos = read.start + read.refChars.length
145
184
  let from = Math.max(start, read.start)
146
- let to = Math.min(end, read.start + read.refChars.length + 1)
185
+ let to = Math.min(end, lastPos + 1)
147
186
  // a row that begins or ends inside an array does not span it, so it gets no
148
187
  // block; snapping past the block keeps the walk from emitting part of one
149
188
  const startsInside = arrayContaining(arrays, from)
@@ -160,26 +199,36 @@ export function renderRow(read: ReadLayout, layout: ColumnLayout) {
160
199
 
161
200
  let ret = ABSENT.repeat(offsets[from - start]!)
162
201
  let pos = from
202
+ let next = breakIndex(breaks, from)
163
203
  while (pos < to) {
164
- const array = byStartPos.get(pos)
204
+ while (next < breaks.length && breaks[next]! < pos) {
205
+ next++
206
+ }
207
+ const stop = Math.min(next < breaks.length ? breaks[next]! : to, to)
208
+ if (stop > pos) {
209
+ // the walk never leaves the read's own bases except at its very last
210
+ // position, which is the slot a trailing insertion is keyed in
211
+ const cut = Math.min(stop, lastPos)
212
+ ret += read.refChars.slice(pos - read.start, cut - read.start)
213
+ ret += ABSENT.repeat(stop - cut)
214
+ pos = stop
215
+ continue
216
+ }
217
+ const array = arrayByStart.get(pos)
165
218
  if (array) {
166
- const row = array.rowByName.get(read.name)
167
- ret += row ?? SPANNED_GAP.repeat(array.width)
219
+ // a row with no allele here did not reach both edges of the array, or
220
+ // skipped it through an N — either way it is not here, and a block of
221
+ // deletion gaps would read as an allele it does not have
222
+ ret += array.rowByName.get(read.name) ?? ABSENT.repeat(array.width)
168
223
  pos = Math.min(array.end, to)
169
224
  continue
170
225
  }
171
- const idx = pos - read.start
172
- const spanned = idx >= 0 && idx < read.refChars.length
173
- const refChar = spanned ? read.refChars[idx]! : ABSENT
174
- const width = insWidths.get(pos) ?? 0
175
- if (width) {
176
- // a read that is not really here pads the insertion the same way it
177
- // pads the reference column, so an intron reads as one absence
178
- const pad = refChar === ABSENT ? ABSENT : SPANNED_GAP
179
- const ins = read.insertions.get(pos) ?? ''
180
- ret += ins + pad.repeat(width - ins.length)
181
- }
182
- ret += refChar
226
+ const refChar = pos < lastPos ? read.refChars[pos - read.start]! : ABSENT
227
+ // a read that is not really here pads the insertion the same way it pads
228
+ // the reference column, so an intron reads as one absence
229
+ const pad = refChar === ABSENT ? ABSENT : SPANNED_GAP
230
+ const ins = read.insertions.get(pos) ?? ''
231
+ ret += ins + pad.repeat(insWidths.get(pos)! - ins.length) + refChar
183
232
  pos++
184
233
  }
185
234
  return ret + ABSENT.repeat(totalColumns - offsets[to - start]!)
@@ -311,18 +360,16 @@ export function planTviewMsa({
311
360
  end,
312
361
  )
313
362
 
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
- )
363
+ // The intervals come from the reference and nothing here moves them. What
364
+ // moves is each read's insertions, re-filed under the array they belong to
365
+ // before anything is measured or laid out — see reanchorInsertions. Both
366
+ // steps below read the re-anchored reads, so an insertion the array took over
367
+ // is rendered inside its block and not also as a column of its own.
368
+ const intervals = sequence
369
+ ? mergeArrays(findReferenceArrays(sequence, start))
325
370
  : []
371
+ const anchored = reanchorInsertions(clipped, intervals)
372
+ const arrays = buildArrayBlocks(anchored, intervals)
326
373
  const ownedByArray = new Set<number>()
327
374
  for (const array of arrays) {
328
375
  for (let pos = array.start; pos <= array.end; pos++) {
@@ -330,7 +377,7 @@ export function planTviewMsa({
330
377
  }
331
378
  }
332
379
 
333
- const aligned = alignInsertionColumns(clipped, ownedByArray)
380
+ const aligned = alignInsertionColumns(anchored, ownedByArray)
334
381
 
335
382
  // With several arrays in view the subject is the one the rows disagree most
336
383
  // about, since ordering rows by two copy numbers at once is not a thing rows
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '2.2.0'
1
+ export const version = '2.2.3'