jbrowse-plugin-tview 2.0.4 → 2.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.
Files changed (73) hide show
  1. package/README.md +157 -4
  2. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.d.ts +132 -0
  3. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js +152 -0
  4. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js.map +1 -0
  5. package/dist/LaunchTView/TviewGetPlanRpc/index.d.ts +3 -0
  6. package/dist/LaunchTView/TviewGetPlanRpc/index.js +5 -0
  7. package/dist/LaunchTView/TviewGetPlanRpc/index.js.map +1 -0
  8. package/dist/LaunchTView/align.d.ts +93 -9
  9. package/dist/LaunchTView/align.js +290 -15
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +57 -0
  12. package/dist/LaunchTView/alleles.js +94 -0
  13. package/dist/LaunchTView/alleles.js.map +1 -0
  14. package/dist/LaunchTView/components/ArrayReport.d.ts +10 -0
  15. package/dist/LaunchTView/components/ArrayReport.js +59 -0
  16. package/dist/LaunchTView/components/ArrayReport.js.map +1 -0
  17. package/dist/LaunchTView/components/LaunchTViewDialog.js +74 -37
  18. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +1 -1
  19. package/dist/LaunchTView/fetchTviewPlan.d.ts +20 -13
  20. package/dist/LaunchTView/fetchTviewPlan.js +27 -27
  21. package/dist/LaunchTView/fetchTviewPlan.js.map +1 -1
  22. package/dist/LaunchTView/launchView.d.ts +25 -0
  23. package/dist/LaunchTView/launchView.js +20 -0
  24. package/dist/LaunchTView/launchView.js.map +1 -0
  25. package/dist/LaunchTView/readLayout.d.ts +85 -0
  26. package/dist/LaunchTView/readLayout.js +96 -0
  27. package/dist/LaunchTView/readLayout.js.map +1 -0
  28. package/dist/LaunchTView/repeats.d.ts +68 -0
  29. package/dist/LaunchTView/repeats.js +200 -0
  30. package/dist/LaunchTView/repeats.js.map +1 -0
  31. package/dist/LaunchTView/sampleTree.d.ts +37 -0
  32. package/dist/LaunchTView/sampleTree.js +65 -0
  33. package/dist/LaunchTView/sampleTree.js.map +1 -0
  34. package/dist/LaunchTView/tview.d.ts +67 -44
  35. package/dist/LaunchTView/tview.js +190 -121
  36. package/dist/LaunchTView/tview.js.map +1 -1
  37. package/dist/LaunchTView/useTviewMsa.d.ts +13 -9
  38. package/dist/LaunchTView/useTviewMsa.js +15 -11
  39. package/dist/LaunchTView/useTviewMsa.js.map +1 -1
  40. package/dist/TViewPanel/coords.d.ts +9 -1
  41. package/dist/TViewPanel/coords.js +22 -2
  42. package/dist/TViewPanel/coords.js.map +1 -1
  43. package/dist/TViewPanel/init.d.ts +56 -0
  44. package/dist/TViewPanel/init.js +59 -0
  45. package/dist/TViewPanel/init.js.map +1 -0
  46. package/dist/TViewPanel/model.d.ts +56 -40
  47. package/dist/TViewPanel/model.js +73 -51
  48. package/dist/TViewPanel/model.js.map +1 -1
  49. package/dist/index.js +5 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/jbrowse-plugin-tview.umd.production.min.js +59 -21
  52. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/package.json +7 -3
  56. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +264 -0
  57. package/src/LaunchTView/TviewGetPlanRpc/index.ts +14 -0
  58. package/src/LaunchTView/align.ts +343 -17
  59. package/src/LaunchTView/alleles.ts +132 -0
  60. package/src/LaunchTView/components/ArrayReport.tsx +64 -0
  61. package/src/LaunchTView/components/LaunchTViewDialog.tsx +122 -39
  62. package/src/LaunchTView/fetchTviewPlan.ts +42 -42
  63. package/src/LaunchTView/launchView.ts +50 -0
  64. package/src/LaunchTView/readLayout.ts +145 -0
  65. package/src/LaunchTView/repeats.ts +218 -0
  66. package/src/LaunchTView/sampleTree.ts +73 -0
  67. package/src/LaunchTView/tview.ts +259 -157
  68. package/src/LaunchTView/useTviewMsa.ts +20 -17
  69. package/src/TViewPanel/coords.ts +23 -1
  70. package/src/TViewPanel/init.ts +127 -0
  71. package/src/TViewPanel/model.ts +82 -61
  72. package/src/index.ts +5 -1
  73. package/src/version.ts +1 -1
@@ -5,10 +5,24 @@
5
5
  * shared event stops being readable. Aligning the inserted sequences against
6
6
  * each other fixes that.
7
7
  *
8
- * This is deliberately local to one reference position: the insertion still
9
- * occupies "as many columns as the widest gapped sequence", which is the only
10
- * thing buildColumnToRefPos knows about, so the column <-> reference mapping is
11
- * untouched.
8
+ * There are two ways to do it, and which one applies is a property of the
9
+ * inserted sequence rather than a setting:
10
+ *
11
+ * - **Aperiodic** (`alignInsertions`): one center-star alignment over the whole
12
+ * inserted sequence. Right for a novel insertion, a mobile element, anything
13
+ * whose bases only make sense read straight through.
14
+ * - **Periodic** (`alignPeriodicInsertions`): a tandem array, where the whole
15
+ * inserted sequence is n copies of one unit. Aligning those base-to-base is
16
+ * both unaffordable and wrong — it is free to align copy 5 of one read to
17
+ * copy 3 of another, and the difference that matters (how many copies) ends
18
+ * up expressed as where the row stops. Aligning unit-to-unit instead puts
19
+ * copy k of every read in the same columns, so copy number reads as a count
20
+ * of blocks and a divergent copy stands out as a column inside its block.
21
+ *
22
+ * Both are local to one reference position: the insertion still occupies "as
23
+ * many columns as the widest gapped sequence", which is the only thing
24
+ * buildColumnToRefPos knows about, so the column <-> reference mapping is
25
+ * untouched either way.
12
26
  */
13
27
 
14
28
  const MATCH = 2
@@ -20,6 +34,36 @@ const GAP = -3
20
34
  const MAX_LEN = 200
21
35
  const MAX_DISTINCT = 30
22
36
 
37
+ // Shortest unit that earns a unit-per-block layout. The scan below starts at 1
38
+ // so it reports the TRUE minimal period, which is what makes a homopolymer come
39
+ // back as 1 and get declined here: `AAAA...` is periodic at every lag, and
40
+ // laying it out as 2bp blocks would be an arbitrary reading of one run of A.
41
+ const MIN_UNIT_PERIOD = 2
42
+
43
+ // Longest unit the scan looks for. Covers STRs and the common VNTR range; the
44
+ // megabase-unit arrays (LPA KIV-2 at 5.5kb) need more copies than a read holds
45
+ // before they are periodic at all, so they are out of reach here regardless.
46
+ const MAX_PERIOD = 300
47
+
48
+ // Copies needed before a sequence counts as an array. Two copies of anything is
49
+ // a duplication, not a tandem repeat, and at two the period is unidentifiable
50
+ // from the sequence alone.
51
+ const MIN_COPIES = 3
52
+
53
+ // Fraction of positions that must agree at lag p for p to be the period. Loose
54
+ // enough for the ~5-15% divergence between copies of a real VNTR unit and for
55
+ // long-read error on top of it.
56
+ const PERIODIC_MATCH = 0.8
57
+
58
+ // The period scan is O(len * maxPeriod), so it runs on a prefix rather than the
59
+ // whole insert. An array that is periodic in its first 3kb is periodic.
60
+ const PROBE_LEN = 3000
61
+
62
+ // Backstops on the unit-level work, in the same spirit as MAX_LEN/MAX_DISTINCT:
63
+ // decline and leave the site to the aperiodic path rather than stall on it.
64
+ const MAX_UNITS = 1000
65
+ const MAX_PERIODIC_CELLS = 20_000_000
66
+
23
67
  function subst(a: string | undefined, b: string | undefined) {
24
68
  return a === b ? MATCH : MISMATCH
25
69
  }
@@ -115,21 +159,292 @@ function emit({ slots, atCenter }: CenterSplit, slotWidths: number[]) {
115
159
  }
116
160
 
117
161
  /**
118
- * Center-star multiple alignment of the sequences inserted at one reference
119
- * position. Returns each distinct input mapped to a gapped version, all of the
120
- * same length. Returns an empty map when there is nothing to gain (a single
121
- * distinct sequence) or when the site is too large to be worth aligning; the
122
- * caller then keeps the sequences as-is and left-justifies them.
162
+ * The smallest lag at which a sequence repeats, or undefined when it does not.
163
+ *
164
+ * Scanning up from 1 returns the true minimal period, which is what separates a
165
+ * tandem array from a homopolymer: `AAAA...` matches at every lag and comes back
166
+ * as 1, and a 30bp unit comes back as 30 rather than as 60 or 90.
123
167
  */
124
- export function alignInsertions(seqs: string[]) {
168
+ export function detectPeriod(seq: string): number | undefined {
169
+ const probe = seq.length > PROBE_LEN ? seq.slice(0, PROBE_LEN) : seq
170
+ const maxPeriod = Math.min(MAX_PERIOD, Math.floor(probe.length / MIN_COPIES))
171
+ for (let p = 1; p <= maxPeriod; p++) {
172
+ const n = probe.length - p
173
+ let matches = 0
174
+ for (let i = 0; i < n; i++) {
175
+ if (probe[i] === probe[i + p]) {
176
+ matches++
177
+ }
178
+ }
179
+ if (matches / n >= PERIODIC_MATCH) {
180
+ return p
181
+ }
182
+ }
183
+ return undefined
184
+ }
185
+
186
+ /**
187
+ * Majority base at each offset within the unit, over the whole-length copies of
188
+ * `seq`. The consensus is what every copy of every read is aligned to, so it has
189
+ * to be one fixed string for the site — deriving it per read would let two reads
190
+ * disagree about where a unit starts.
191
+ */
192
+ export function consensusUnit(seq: string, period: number) {
193
+ const copies = Math.floor(seq.length / period)
194
+ let ret = ''
195
+ for (let j = 0; j < period; j++) {
196
+ const counts = new Map<string, number>()
197
+ for (let k = 0; k < copies; k++) {
198
+ const c = seq[k * period + j]!
199
+ counts.set(c, (counts.get(c) ?? 0) + 1)
200
+ }
201
+ // ties break lexicographically so the consensus is a function of the input
202
+ // and not of Map iteration order
203
+ ret += [...counts].sort(
204
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1),
205
+ )[0]![0]
206
+ }
207
+ return ret
208
+ }
209
+
210
+ /**
211
+ * Align one copy of the consensus unit against `seq` starting at `from`: global
212
+ * on the consensus, since a copy is a whole copy, and free at the window's right
213
+ * edge, since the copy ends wherever it ends. `consumed` is where the next copy
214
+ * starts, which is what lets an indel inside one copy stay inside it rather than
215
+ * shifting every copy after it.
216
+ */
217
+ function alignUnitAt(consensus: string, seq: string, from: number) {
218
+ const n = consensus.length
219
+ const m = Math.min(2 * n, seq.length - from)
220
+ const stride = m + 1
221
+ const score = new Int32Array((n + 1) * stride)
222
+ for (let i = 1; i <= n; i++) {
223
+ score[i * stride] = i * GAP
224
+ }
225
+ for (let j = 1; j <= m; j++) {
226
+ score[j] = j * GAP
227
+ }
228
+ for (let i = 1; i <= n; i++) {
229
+ for (let j = 1; j <= m; j++) {
230
+ score[i * stride + j] = Math.max(
231
+ score[(i - 1) * stride + j - 1]! +
232
+ subst(consensus[i - 1], seq[from + j - 1]),
233
+ score[(i - 1) * stride + j]! + GAP,
234
+ score[i * stride + j - 1]! + GAP,
235
+ )
236
+ }
237
+ }
238
+
239
+ // the copy ends at whichever window position scores best once the consensus
240
+ // is spent
241
+ let consumed = 0
242
+ let best = score[n * stride]!
243
+ for (let j = 1; j <= m; j++) {
244
+ const s = score[n * stride + j]!
245
+ if (s > best) {
246
+ best = s
247
+ consumed = j
248
+ }
249
+ }
250
+ // a copy that consumed nothing would not advance the cursor
251
+ if (consumed === 0) {
252
+ return undefined
253
+ }
254
+
255
+ const outCenter: string[] = []
256
+ const outOther: string[] = []
257
+ let i = n
258
+ let j = consumed
259
+ while (i > 0 || j > 0) {
260
+ const cur = score[i * stride + j]!
261
+ const diagonal =
262
+ i > 0 &&
263
+ j > 0 &&
264
+ cur ===
265
+ score[(i - 1) * stride + j - 1]! +
266
+ subst(consensus[i - 1], seq[from + j - 1])
267
+ if (diagonal) {
268
+ outCenter.push(consensus[i - 1]!)
269
+ outOther.push(seq[from + j - 1]!)
270
+ i--
271
+ j--
272
+ } else if (i > 0 && cur === score[(i - 1) * stride + j]! + GAP) {
273
+ outCenter.push(consensus[i - 1]!)
274
+ outOther.push('-')
275
+ i--
276
+ } else {
277
+ outCenter.push('-')
278
+ outOther.push(seq[from + j - 1]!)
279
+ j--
280
+ }
281
+ }
282
+ return {
283
+ center: outCenter.reverse().join(''),
284
+ other: outOther.reverse().join(''),
285
+ consumed,
286
+ }
287
+ }
288
+
289
+ /** Every copy in `seq`, each as a pairwise alignment against the consensus. */
290
+ function splitIntoUnits(seq: string, consensus: string) {
291
+ const units: { center: string; other: string }[] = []
292
+ let cursor = 0
293
+ while (cursor < seq.length) {
294
+ const unit = alignUnitAt(consensus, seq, cursor)
295
+ if (!unit || units.length >= MAX_UNITS) {
296
+ return undefined
297
+ }
298
+ units.push(unit)
299
+ cursor += unit.consumed
300
+ }
301
+ return units
302
+ }
303
+
304
+ export interface PeriodicAlignment {
305
+ /** repeat unit length in bp */
306
+ period: number
307
+ /** each distinct input mapped to a gapped version, all the same length */
308
+ gapped: Map<string, string>
309
+ /** each distinct input mapped to its copy count */
310
+ copies: Map<string, number>
311
+ /** columns each copy occupies, left to right; sums to the gapped length */
312
+ unitWidths: number[]
313
+ }
314
+
315
+ /**
316
+ * Unit-per-block alignment of the sequences inserted at one reference position.
317
+ *
318
+ * Copy k of every sequence lands in the same block of columns, and a block is
319
+ * as wide as the widest version of that copy across the site, so a sequence with
320
+ * fewer copies runs out of blocks rather than drifting out of register. Returns
321
+ * undefined when the site is not a tandem array, or is too big to lay out this
322
+ * way; the caller falls back to `alignInsertions`.
323
+ *
324
+ * **Blocks are array order, not homology.** Copies are anchored at the left edge
325
+ * of the insertion and counted rightward, so block k is "the kth copy along",
326
+ * and arrays grow and shrink by unequal crossing over anywhere inside them —
327
+ * block 9 of a 12-copy allele and block 9 of a 20-copy allele need not be the
328
+ * same copy. What the layout does buy is that copies stay in register, so a
329
+ * single divergent copy shows up as a column instead of shifting every copy
330
+ * after it. Reading down one row is sound; reading across two is a hypothesis.
331
+ */
332
+ export function alignPeriodicInsertions(
333
+ seqs: string[],
334
+ ): PeriodicAlignment | undefined {
125
335
  const distinct = [...new Set(seqs)]
126
336
  const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
337
+ const period = detectPeriod(longest)
338
+ if (period === undefined || period < MIN_UNIT_PERIOD) {
339
+ return undefined
340
+ }
341
+ return alignToUnit(distinct, consensusUnit(longest, period))
342
+ }
343
+
344
+ /**
345
+ * Unit-per-block alignment against a unit the caller already knows.
346
+ *
347
+ * Separated from `alignPeriodicInsertions` because where the unit comes from is
348
+ * the whole difference between the two ways of finding an array. Measured off
349
+ * the inserted sequences, it can only be derived from one of them — the longest,
350
+ * which is a guess that one chimeric read overturns for the whole site. Measured
351
+ * off the reference, it is a property of the locus, so every read is laid out
352
+ * against the same unit whatever the reads happen to be.
353
+ */
354
+ export function alignToUnit(
355
+ seqs: string[],
356
+ consensus: string,
357
+ ): PeriodicAlignment | undefined {
358
+ const distinct = [...new Set(seqs)].filter(s => s.length > 0)
359
+ const period = consensus.length
360
+ if (!distinct.length || period < MIN_UNIT_PERIOD) {
361
+ return undefined
362
+ }
363
+
364
+ const totalUnits = distinct.reduce(
365
+ (a, s) => a + Math.ceil(s.length / period),
366
+ 0,
367
+ )
368
+ if (totalUnits * (period + 1) * (2 * period + 1) > MAX_PERIODIC_CELLS) {
369
+ return undefined
370
+ }
371
+
372
+ const splits = new Map<string, CenterSplit[]>()
373
+ for (const seq of distinct) {
374
+ const units = splitIntoUnits(seq, consensus)
375
+ if (!units) {
376
+ return undefined
377
+ }
378
+ splits.set(
379
+ seq,
380
+ units.map(u => splitAgainstCenter(u, period)),
381
+ )
382
+ }
383
+
384
+ const maxUnits = Math.max(...[...splits.values()].map(u => u.length))
385
+ const slotWidths: number[][] = []
386
+ for (let k = 0; k < maxUnits; k++) {
387
+ const widths = Array.from({ length: period + 1 }, () => 0)
388
+ for (const unitSplits of splits.values()) {
389
+ const split = unitSplits[k]
390
+ if (split) {
391
+ for (let j = 0; j <= period; j++) {
392
+ widths[j] = Math.max(widths[j]!, split.slots[j]!.length)
393
+ }
394
+ }
395
+ }
396
+ slotWidths.push(widths)
397
+ }
398
+ const unitWidths = slotWidths.map(w => period + w.reduce((a, b) => a + b, 0))
399
+
400
+ const gapped = new Map<string, string>()
401
+ const copies = new Map<string, number>()
402
+ for (const [seq, unitSplits] of splits) {
403
+ let row = ''
404
+ for (let k = 0; k < maxUnits; k++) {
405
+ const split = unitSplits[k]
406
+ row += split ? emit(split, slotWidths[k]!) : '-'.repeat(unitWidths[k]!)
407
+ }
408
+ gapped.set(seq, row)
409
+ copies.set(seq, unitSplits.length)
410
+ }
411
+ return { period, gapped, copies, unitWidths }
412
+ }
413
+
414
+ export interface InsertionAlignment {
415
+ /** each distinct input mapped to a gapped version, all of the same length */
416
+ gapped: Map<string, string>
417
+ /** present when the site is a tandem array */
418
+ periodic?: PeriodicAlignment
419
+ }
420
+
421
+ /**
422
+ * Lay out the sequences inserted at one reference position, by whichever of the
423
+ * two alignments the sequence itself calls for. The single place that decision
424
+ * is made, so a caller reading the period cannot disagree with the layout it
425
+ * gets.
426
+ *
427
+ * A tandem array goes unit-per-block, which is both the readable answer and the
428
+ * affordable one — the size caps here are what the base-to-base alignment costs,
429
+ * and an expansion is always past them. Everything else gets the center-star
430
+ * alignment, or is left alone (`gapped` empty) when there is nothing to gain
431
+ * from a single distinct sequence, or the site is too large to be worth it.
432
+ */
433
+ export function alignInsertionSite(seqs: string[]): InsertionAlignment {
434
+ const distinct = [...new Set(seqs)]
435
+ // an array is worth unrolling even when every read agrees on it: the copies
436
+ // still have to be squared up with each other before they can be counted
437
+ const periodic = alignPeriodicInsertions(distinct)
438
+ if (periodic) {
439
+ return { gapped: periodic.gapped, periodic }
440
+ }
441
+ const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
127
442
  if (
128
443
  distinct.length < 2 ||
129
444
  distinct.length > MAX_DISTINCT ||
130
445
  longest.length > MAX_LEN
131
446
  ) {
132
- return new Map<string, string>()
447
+ return { gapped: new Map<string, string>() }
133
448
  }
134
449
 
135
450
  const centerLen = longest.length
@@ -145,10 +460,21 @@ export function alignInsertions(seqs: string[]) {
145
460
  const slotWidths = Array.from({ length: centerLen + 1 }, (_, j) =>
146
461
  splits.reduce((max, s) => Math.max(max, s.slots[j]!.length), 0),
147
462
  )
148
- return new Map([
149
- [longest, emit(centerSplit, slotWidths)],
150
- ...others.map(
151
- (seq, i): [string, string] => [seq, emit(splits[i]!, slotWidths)],
152
- ),
153
- ])
463
+ return {
464
+ gapped: new Map([
465
+ [longest, emit(centerSplit, slotWidths)],
466
+ ...others.map((seq, i): [string, string] => [
467
+ seq,
468
+ emit(splits[i]!, slotWidths),
469
+ ]),
470
+ ]),
471
+ }
472
+ }
473
+
474
+ /**
475
+ * The gapped sequences alone, for callers with no use for the period. Every
476
+ * decision lives in `alignInsertionSite`.
477
+ */
478
+ export function alignInsertions(seqs: string[]) {
479
+ return alignInsertionSite(seqs).gapped
154
480
  }
@@ -0,0 +1,132 @@
1
+ import { alignToUnit } from './align'
2
+
3
+ import type { ReadLayout } from './readLayout'
4
+ import type { ReferenceArray } from './repeats'
5
+
6
+ /**
7
+ * A tandem array laid out as one block of columns per copy, replacing the
8
+ * reference columns the array covers.
9
+ *
10
+ * The interval comes from the reference and the unit comes with it, so every
11
+ * row is measured over the same span against the same unit. That is what makes
12
+ * the counts comparable: a read's allele is what it has between here and here,
13
+ * whatever the aligner did with the gap, and the reference is just the row whose
14
+ * allele the coordinates are named after.
15
+ */
16
+ export interface ArrayBlock {
17
+ /** reference position the array starts at, inclusive */
18
+ start: number
19
+ /** reference position the array ends at, exclusive */
20
+ end: number
21
+ period: number
22
+ unit: string
23
+ /** columns the block occupies */
24
+ width: number
25
+ /** columns each copy occupies, left to right; sums to `width` */
26
+ unitWidths: number[]
27
+ /** gapped block, by row name; only rows whose allele could be measured */
28
+ rowByName: Map<string, string>
29
+ /** copies carried, by row name */
30
+ copiesByName: Map<string, number>
31
+ /** allele length in bp, by row name */
32
+ lengthByName: Map<string, number>
33
+ }
34
+
35
+ const SPANNED_GAP = '-'
36
+ const ABSENT = '.'
37
+
38
+ /**
39
+ * What one row has between two reference positions: its matched bases, plus
40
+ * whatever it inserted inside, minus whatever it deleted.
41
+ *
42
+ * This is the measurement the insertion-anchored reading cannot make. An indel
43
+ * inside an array has no unique placement, so two reads carrying the same allele
44
+ * can disagree about which reference position it is inserted at and by how much;
45
+ * summed over the interval, those choices cancel and both come back the same
46
+ * length. Undefined when the row does not reach both edges — copies cannot be
47
+ * counted from a read that stops inside the array, and guessing from a partial
48
+ * one is how a truncated read reads as a contracted allele.
49
+ */
50
+ export function extractAllele(read: ReadLayout, start: number, end: number) {
51
+ const last = read.start + read.refChars.length
52
+ if (read.start > start || last < end) {
53
+ return undefined
54
+ }
55
+ let ret = ''
56
+ for (let pos = start; pos <= end; pos++) {
57
+ ret += read.insertions.get(pos) ?? ''
58
+ if (pos < end) {
59
+ const char = read.refChars[pos - read.start]!
60
+ if (char === ABSENT) {
61
+ // an N op skips the position rather than deleting it, so the row has no
62
+ // allele here at all rather than a shorter one
63
+ return undefined
64
+ }
65
+ if (char !== SPANNED_GAP) {
66
+ ret += char
67
+ }
68
+ }
69
+ }
70
+ return ret
71
+ }
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
80
+ }
81
+
82
+ /**
83
+ * Lay every row's allele out unit-per-block, one block per array.
84
+ *
85
+ * Arrays whose alleles are all one length still get a block: squaring the copies
86
+ * up against each other is what turns "this row is 63 bases long" into "this row
87
+ * has 21 copies and the 12th one differs", and that is true whether or not the
88
+ * rows disagree.
89
+ */
90
+ export function buildArrayBlocks(
91
+ reads: ReadLayout[],
92
+ arrays: ReferenceArray[],
93
+ ) {
94
+ const ret: ArrayBlock[] = []
95
+ for (const array of arrays) {
96
+ const alleleByName = new Map<string, string>()
97
+ for (const read of reads) {
98
+ const allele = extractAllele(read, array.start, array.end)
99
+ if (allele !== undefined) {
100
+ alleleByName.set(read.name, allele)
101
+ }
102
+ }
103
+ const aligned = alignToUnit([...alleleByName.values()], array.unit)
104
+ if (!aligned) {
105
+ continue
106
+ }
107
+ const rowByName = new Map<string, string>()
108
+ const copiesByName = new Map<string, number>()
109
+ const lengthByName = new Map<string, number>()
110
+ for (const [name, allele] of alleleByName) {
111
+ const row = aligned.gapped.get(allele)
112
+ const copies = aligned.copies.get(allele)
113
+ if (row !== undefined && copies !== undefined) {
114
+ rowByName.set(name, row)
115
+ copiesByName.set(name, copies)
116
+ lengthByName.set(name, allele.length)
117
+ }
118
+ }
119
+ ret.push({
120
+ start: array.start,
121
+ end: array.end,
122
+ period: aligned.period,
123
+ unit: array.unit,
124
+ width: aligned.unitWidths.reduce((a, b) => a + b, 0),
125
+ unitWidths: aligned.unitWidths,
126
+ rowByName,
127
+ copiesByName,
128
+ lengthByName,
129
+ })
130
+ }
131
+ return ret
132
+ }
@@ -0,0 +1,64 @@
1
+ import React from 'react'
2
+
3
+ import { Typography } from '@mui/material'
4
+
5
+ import type { TviewPlanResult } from '../TviewGetPlanRpc'
6
+
7
+ /** allele lengths seen, commonest first, as `63bp x12` */
8
+ function alleleTally(lengths: [string, number][]) {
9
+ const counts = new Map<number, number>()
10
+ for (const [, length] of lengths) {
11
+ counts.set(length, (counts.get(length) ?? 0) + 1)
12
+ }
13
+ return [...counts]
14
+ .sort((a, b) => b[1] - a[1] || a[0] - b[0])
15
+ .map(([length, n]) => `${length}bp x${n}`)
16
+ }
17
+
18
+ /**
19
+ * What the reads say about the arrays before the view is opened, since the
20
+ * number is often the whole reason for opening it and a picture of 400 columns
21
+ * is a slow way to read one off.
22
+ */
23
+ export default function ArrayReport({ data }: { data: TviewPlanResult }) {
24
+ const { arrays, subjectIndex, region } = data
25
+ const subject = subjectIndex === undefined ? undefined : arrays[subjectIndex]
26
+ if (!subject) {
27
+ return arrays.length ? null : (
28
+ <Typography variant="body2">
29
+ No tandem array in the reference here, so the reads are laid out base by
30
+ base.
31
+ </Typography>
32
+ )
33
+ }
34
+ const copies = subject.copies
35
+ return (
36
+ <>
37
+ <Typography variant="subtitle2">
38
+ Tandem array at {region.refName}:{subject.start.toLocaleString('en-US')}
39
+ -{subject.end.toLocaleString('en-US')}, {subject.period}bp unit{' '}
40
+ {subject.unit}
41
+ </Typography>
42
+ <Typography variant="body2">
43
+ {copies.length} of {data.rowCount} rows span it end to end and carry{' '}
44
+ {Math.min(...copies.map(c => c[1]))}&ndash;
45
+ {Math.max(...copies.map(c => c[1]))} copies. Allele lengths:{' '}
46
+ {alleleTally(subject.lengths).join(', ')}.
47
+ </Typography>
48
+ <Typography variant="body2">
49
+ Each copy gets its own block of columns, so one divergent copy shows up
50
+ as a column rather than shifting every copy after it. Blocks are array
51
+ order, not homology: copies are counted from the left edge, and arrays
52
+ expand and contract anywhere inside themselves, so the 9th copy of one
53
+ row need not be the 9th of another. Read down a row, not across two.
54
+ </Typography>
55
+ {arrays.length > 1 ? (
56
+ <Typography variant="body2">
57
+ {arrays.length - 1} shorter{' '}
58
+ {arrays.length === 2 ? 'array is' : 'arrays are'} also laid out per
59
+ copy; rows are ordered by this one.
60
+ </Typography>
61
+ ) : null}
62
+ </>
63
+ )
64
+ }