jbrowse-plugin-tview 2.2.3 → 3.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.
Files changed (110) hide show
  1. package/README.md +317 -105
  2. package/dist/AddHighlightModel/index.js +2 -13
  3. package/dist/AddHighlightModel/index.js.map +1 -1
  4. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.d.ts +44 -64
  5. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js +57 -81
  6. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js.map +1 -1
  7. package/dist/LaunchTView/TviewGetPlanRpc/index.d.ts +1 -1
  8. package/dist/LaunchTView/align.d.ts +11 -17
  9. package/dist/LaunchTView/align.js +190 -150
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +14 -0
  12. package/dist/LaunchTView/alleles.js +47 -0
  13. package/dist/LaunchTView/alleles.js.map +1 -1
  14. package/dist/LaunchTView/fetchTviewPlan.d.ts +5 -37
  15. package/dist/LaunchTView/fetchTviewPlan.js +7 -28
  16. package/dist/LaunchTView/fetchTviewPlan.js.map +1 -1
  17. package/dist/LaunchTView/index.js +45 -16
  18. package/dist/LaunchTView/index.js.map +1 -1
  19. package/dist/LaunchTView/launch.d.ts +50 -0
  20. package/dist/LaunchTView/launch.js +48 -0
  21. package/dist/LaunchTView/launch.js.map +1 -0
  22. package/dist/LaunchTView/launchView.d.ts +3 -8
  23. package/dist/LaunchTView/launchView.js +18 -12
  24. package/dist/LaunchTView/launchView.js.map +1 -1
  25. package/dist/LaunchTView/modifications.d.ts +64 -0
  26. package/dist/LaunchTView/modifications.js +131 -0
  27. package/dist/LaunchTView/modifications.js.map +1 -0
  28. package/dist/LaunchTView/readLayout.d.ts +35 -39
  29. package/dist/LaunchTView/readLayout.js +44 -24
  30. package/dist/LaunchTView/readLayout.js.map +1 -1
  31. package/dist/LaunchTView/repeatStats.d.ts +1 -1
  32. package/dist/LaunchTView/repeatStats.js +6 -21
  33. package/dist/LaunchTView/repeatStats.js.map +1 -1
  34. package/dist/LaunchTView/tview.d.ts +34 -23
  35. package/dist/LaunchTView/tview.js +127 -78
  36. package/dist/LaunchTView/tview.js.map +1 -1
  37. package/dist/TViewPanel/components/TViewPanel.js +9 -4
  38. package/dist/TViewPanel/components/TViewPanel.js.map +1 -1
  39. package/dist/TViewPanel/genome.d.ts +11 -0
  40. package/dist/TViewPanel/genome.js +32 -0
  41. package/dist/TViewPanel/genome.js.map +1 -0
  42. package/dist/TViewPanel/init.d.ts +38 -19
  43. package/dist/TViewPanel/init.js +66 -39
  44. package/dist/TViewPanel/init.js.map +1 -1
  45. package/dist/TViewPanel/initMenu.d.ts +28 -0
  46. package/dist/TViewPanel/initMenu.js +79 -0
  47. package/dist/TViewPanel/initMenu.js.map +1 -0
  48. package/dist/TViewPanel/model.d.ts +1057 -334
  49. package/dist/TViewPanel/model.js +298 -87
  50. package/dist/TViewPanel/model.js.map +1 -1
  51. package/dist/TViewPanel/modifications.d.ts +25 -0
  52. package/dist/TViewPanel/modifications.js +89 -0
  53. package/dist/TViewPanel/modifications.js.map +1 -0
  54. package/dist/index.d.ts +0 -1
  55. package/dist/index.js +0 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/jbrowse-plugin-tview.umd.production.min.js +125 -88
  58. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/package.json +8 -8
  62. package/src/AddHighlightModel/index.tsx +8 -14
  63. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +119 -157
  64. package/src/LaunchTView/TviewGetPlanRpc/index.ts +0 -1
  65. package/src/LaunchTView/align.ts +225 -176
  66. package/src/LaunchTView/alleles.ts +66 -0
  67. package/src/LaunchTView/fetchTviewPlan.ts +11 -54
  68. package/src/LaunchTView/index.ts +74 -16
  69. package/src/LaunchTView/launch.ts +98 -0
  70. package/src/LaunchTView/launchView.ts +28 -20
  71. package/src/LaunchTView/modifications.ts +200 -0
  72. package/src/LaunchTView/readLayout.ts +65 -41
  73. package/src/LaunchTView/repeatStats.ts +7 -23
  74. package/src/LaunchTView/tview.ts +158 -91
  75. package/src/TViewPanel/components/TViewPanel.tsx +33 -4
  76. package/src/TViewPanel/genome.ts +41 -0
  77. package/src/TViewPanel/init.ts +104 -51
  78. package/src/TViewPanel/initMenu.ts +126 -0
  79. package/src/TViewPanel/model.ts +350 -97
  80. package/src/TViewPanel/modifications.ts +127 -0
  81. package/src/index.ts +0 -2
  82. package/src/version.ts +1 -1
  83. package/dist/AddHighlightModel/GenomeMouseoverHighlight.d.ts +0 -6
  84. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js +0 -23
  85. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js.map +0 -1
  86. package/dist/AddHighlightModel/HighlightComponents.d.ts +0 -7
  87. package/dist/AddHighlightModel/HighlightComponents.js +0 -11
  88. package/dist/AddHighlightModel/HighlightComponents.js.map +0 -1
  89. package/dist/LaunchTView/components/ArrayReport.d.ts +0 -10
  90. package/dist/LaunchTView/components/ArrayReport.js +0 -59
  91. package/dist/LaunchTView/components/ArrayReport.js.map +0 -1
  92. package/dist/LaunchTView/components/LaunchTViewDialog.d.ts +0 -6
  93. package/dist/LaunchTView/components/LaunchTViewDialog.js +0 -124
  94. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +0 -1
  95. package/dist/LaunchTView/sampleTree.d.ts +0 -37
  96. package/dist/LaunchTView/sampleTree.js +0 -65
  97. package/dist/LaunchTView/sampleTree.js.map +0 -1
  98. package/dist/LaunchTView/useTviewMsa.d.ts +0 -18
  99. package/dist/LaunchTView/useTviewMsa.js +0 -24
  100. package/dist/LaunchTView/useTviewMsa.js.map +0 -1
  101. package/dist/TViewPanel/coords.d.ts +0 -25
  102. package/dist/TViewPanel/coords.js +0 -56
  103. package/dist/TViewPanel/coords.js.map +0 -1
  104. package/src/AddHighlightModel/GenomeMouseoverHighlight.tsx +0 -46
  105. package/src/AddHighlightModel/HighlightComponents.tsx +0 -25
  106. package/src/LaunchTView/components/ArrayReport.tsx +0 -64
  107. package/src/LaunchTView/components/LaunchTViewDialog.tsx +0 -212
  108. package/src/LaunchTView/sampleTree.ts +0 -73
  109. package/src/LaunchTView/useTviewMsa.ts +0 -39
  110. package/src/TViewPanel/coords.ts +0 -65
@@ -8,8 +8,8 @@
8
8
  * There are two ways to do it, and which one applies is a property of the
9
9
  * inserted sequence rather than a setting:
10
10
  *
11
- * - **Aperiodic** (`alignInsertions`): one center-star alignment over the whole
12
- * inserted sequence. Right for a novel insertion, a mobile element, anything
11
+ * - **Aperiodic** (`alignInsertionSite`): one center-star alignment over the
12
+ * whole inserted sequence. Right for a novel insertion, a mobile element, anything
13
13
  * whose bases only make sense read straight through.
14
14
  * - **Periodic** (`alignPeriodicInsertions`): a tandem array, where the whole
15
15
  * inserted sequence is n copies of one unit. Aligning those base-to-base is
@@ -25,31 +25,12 @@
25
25
  * untouched either way.
26
26
  */
27
27
 
28
+ import { MAX_PERIOD, MIN_COPIES, MIN_PERIOD } from './repeats'
29
+
28
30
  const MATCH = 2
29
31
  const MISMATCH = -2
30
32
  const GAP = -3
31
33
 
32
- // each sequence costs an O(n*m) pairwise alignment against the center, so fall
33
- // back to left-justified layout rather than stall on a pathological site
34
- const MAX_LEN = 200
35
- const MAX_DISTINCT = 30
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
34
  // Fraction of positions that must agree at lag p for p to be the period. Loose
54
35
  // enough for the ~5-15% divergence between copies of a real VNTR unit and for
55
36
  // long-read error on top of it.
@@ -59,60 +40,97 @@ const PERIODIC_MATCH = 0.8
59
40
  // whole insert. An array that is periodic in its first 3kb is periodic.
60
41
  const PROBE_LEN = 3000
61
42
 
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.
43
+ // Backstops on the work done at one insertion site: decline and leave the site
44
+ // left-justified rather than stall on it.
64
45
  const MAX_UNITS = 1000
65
- const MAX_PERIODIC_CELLS = 20_000_000
46
+ const MAX_SITE_CELLS = 20_000_000
66
47
 
67
- function subst(a: string | undefined, b: string | undefined) {
68
- return a === b ? MATCH : MISMATCH
69
- }
48
+ const INITIAL_BAND = 8
70
49
 
71
- /** global alignment, returns both sequences with '-' inserted */
72
- function needlemanWunsch(a: string, b: string) {
50
+ const UNREACHABLE = -(2 ** 30)
51
+ const DIAGONAL = 1
52
+ const UP = 2
53
+ const LEFT = 4
54
+
55
+ /**
56
+ * Global alignment of `a` against `b` over the diagonals `lo..hi` (j - i) of
57
+ * the dynamic programming matrix, keeping every move that reaches each cell's
58
+ * best score. With `lo = -a.length` and `hi = b.length` it is the full matrix.
59
+ */
60
+ function fillBand(a: string, b: string, lo: number, hi: number) {
73
61
  const n = a.length
74
62
  const m = b.length
75
- const stride = m + 1
76
- const score = new Int32Array((n + 1) * stride)
77
- for (let i = 1; i <= n; i++) {
78
- score[i * stride] = i * GAP
79
- }
80
- for (let j = 1; j <= m; j++) {
81
- score[j] = j * GAP
63
+ const width = hi - lo + 1
64
+ const codesB = Uint16Array.from(b, c => c.charCodeAt(0))
65
+ const moves = new Uint8Array((n + 1) * width)
66
+ let previous = new Int32Array(width + 1).fill(UNREACHABLE)
67
+ let current = new Int32Array(width + 1).fill(UNREACHABLE)
68
+ for (let j = 0; j <= Math.min(m, hi); j++) {
69
+ previous[j - lo] = j * GAP
70
+ moves[j - lo] = LEFT
82
71
  }
83
72
  for (let i = 1; i <= n; i++) {
84
- for (let j = 1; j <= m; j++) {
85
- score[i * stride + j] = Math.max(
86
- score[(i - 1) * stride + j - 1]! + subst(a[i - 1], b[j - 1]),
87
- score[(i - 1) * stride + j]! + GAP,
88
- score[i * stride + j - 1]! + GAP,
89
- )
73
+ current.fill(UNREACHABLE)
74
+ const row = i * width
75
+ const codeA = a.charCodeAt(i - 1)
76
+ const first = Math.max(0, i + lo)
77
+ const last = Math.min(m, i + hi)
78
+ if (first === 0) {
79
+ current[-i - lo] = i * GAP
80
+ moves[row - i - lo] = UP
81
+ }
82
+ for (let j = Math.max(1, first); j <= last; j++) {
83
+ const k = j - i - lo
84
+ const diagonal =
85
+ previous[k]! + (codeA === codesB[j - 1] ? MATCH : MISMATCH)
86
+ const up = previous[k + 1]! + GAP
87
+ const left = k > 0 ? current[k - 1]! + GAP : UNREACHABLE
88
+ const best =
89
+ diagonal >= up
90
+ ? diagonal >= left
91
+ ? diagonal
92
+ : left
93
+ : up >= left
94
+ ? up
95
+ : left
96
+ current[k] = best
97
+ moves[row + k] =
98
+ (diagonal === best ? DIAGONAL : 0) |
99
+ (up === best ? UP : 0) |
100
+ (left === best ? LEFT : 0)
90
101
  }
102
+ ;[previous, current] = [current, previous]
91
103
  }
104
+ return { lo, width, moves, lastRow: previous }
105
+ }
106
+
107
+ type Band = ReturnType<typeof fillBand>
92
108
 
109
+ /**
110
+ * The alignment ending at cell (i, j), preferring a diagonal step, then a gap
111
+ * in `b`, then a gap in `a`, so equally-scoring alignments resolve the same way
112
+ * at every site.
113
+ */
114
+ function traceBand(a: string, b: string, band: Band, i: number, j: number) {
93
115
  const outA: string[] = []
94
116
  const outB: string[] = []
95
- let i = n
96
- let j = m
97
- while (i > 0 || j > 0) {
98
- const cur = score[i * stride + j]!
99
- const diagonal =
100
- i > 0 &&
101
- j > 0 &&
102
- cur === score[(i - 1) * stride + j - 1]! + subst(a[i - 1], b[j - 1])
103
- if (diagonal) {
104
- outA.push(a[i - 1]!)
105
- outB.push(b[j - 1]!)
106
- i--
107
- j--
108
- } else if (i > 0 && cur === score[(i - 1) * stride + j]! + GAP) {
109
- outA.push(a[i - 1]!)
117
+ let x = i
118
+ let y = j
119
+ while (x > 0 || y > 0) {
120
+ const move = band.moves[x * band.width + y - x - band.lo]!
121
+ if (move & DIAGONAL) {
122
+ outA.push(a[x - 1]!)
123
+ outB.push(b[y - 1]!)
124
+ x--
125
+ y--
126
+ } else if (move & UP) {
127
+ outA.push(a[x - 1]!)
110
128
  outB.push('-')
111
- i--
129
+ x--
112
130
  } else {
113
131
  outA.push('-')
114
- outB.push(b[j - 1]!)
115
- j--
132
+ outB.push(b[y - 1]!)
133
+ y--
116
134
  }
117
135
  }
118
136
  return {
@@ -121,6 +139,73 @@ function needlemanWunsch(a: string, b: string) {
121
139
  }
122
140
  }
123
141
 
142
+ /** the best score an alignment of `length` bases in all, `gaps` of them gapped, can reach */
143
+ function scoreCeiling(length: number, gaps: number) {
144
+ return (MATCH * (length - gaps)) / 2 + GAP * gaps
145
+ }
146
+
147
+ /** cells of the dynamic programming matrix a site may still fill */
148
+ interface Budget {
149
+ cells: number
150
+ }
151
+
152
+ /**
153
+ * One banded fill, `slack` diagonals either side of the ones joining the two
154
+ * corners, charged to `budget`. `proven` says no alignment leaving the band can
155
+ * score as well as the best one inside it, so the band's alignment is the
156
+ * global one, traceback included.
157
+ */
158
+ function fillWithin(a: string, b: string, slack: number, budget: Budget) {
159
+ const n = a.length
160
+ const m = b.length
161
+ const lo = Math.max(-n, Math.min(0, m - n) - slack)
162
+ const hi = Math.min(m, Math.max(0, m - n) + slack)
163
+ budget.cells -= (n + 1) * (hi - lo + 1)
164
+ const gapsThrough = (diagonal: number) =>
165
+ Math.abs(diagonal) + Math.abs(m - n - diagonal)
166
+ const outside = Math.min(
167
+ lo > -n ? gapsThrough(lo - 1) : Infinity,
168
+ hi < m ? gapsThrough(hi + 1) : Infinity,
169
+ )
170
+ const band = budget.cells < 0 ? undefined : fillBand(a, b, lo, hi)
171
+ const score = band?.lastRow[m - n - lo]
172
+ return band && score !== undefined
173
+ ? { band, score, proven: score > scoreCeiling(n + m, outside) }
174
+ : undefined
175
+ }
176
+
177
+ /**
178
+ * The slack whose band beats the score cap outside it, given a band that has
179
+ * already scored `score`. A wider band can only score higher, so it stays
180
+ * beaten.
181
+ */
182
+ function provingSlack(a: string, b: string, score: number) {
183
+ const gaps =
184
+ (scoreCeiling(a.length + b.length, 0) - score) / (MATCH / 2 - GAP)
185
+ return Math.max(
186
+ INITIAL_BAND + 1,
187
+ Math.floor((gaps - Math.abs(b.length - a.length)) / 2),
188
+ )
189
+ }
190
+
191
+ /**
192
+ * Global alignment in time proportional to length times divergence.
193
+ *
194
+ * A path through diagonal d needs at least |d| + |m - n - d| gaps, which caps
195
+ * its score, so a narrow band whose best score beats the cap on the first
196
+ * diagonal outside it holds the global alignment. When the first fill does not,
197
+ * its score says how wide a band has to be, and the second fill is that wide.
198
+ * Undefined once `budget` is spent.
199
+ */
200
+ function alignGlobal(a: string, b: string, budget: Budget) {
201
+ const first = fillWithin(a, b, INITIAL_BAND, budget)
202
+ const settled =
203
+ first && !first.proven
204
+ ? fillWithin(a, b, provingSlack(a, b, first.score), budget)
205
+ : first
206
+ return settled && traceBand(a, b, settled.band, a.length, b.length)
207
+ }
208
+
124
209
  /**
125
210
  * A pairwise alignment against the center, re-expressed in center coordinates:
126
211
  * what the other sequence contributes at each center position, and what it
@@ -216,74 +301,20 @@ export function consensusUnit(seq: string, period: number) {
216
301
  */
217
302
  function alignUnitAt(consensus: string, seq: string, from: number) {
218
303
  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
-
304
+ const window = seq.slice(from, from + 2 * n)
305
+ const band = fillBand(consensus, window, -n, window.length)
239
306
  // the copy ends at whichever window position scores best once the consensus
240
307
  // is spent
241
308
  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
309
+ for (let j = 1; j <= window.length; j++) {
310
+ if (band.lastRow[j]! > band.lastRow[consumed]!) {
247
311
  consumed = j
248
312
  }
249
313
  }
250
314
  // 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
- }
315
+ return consumed === 0
316
+ ? undefined
317
+ : { ...traceBand(consensus, window, band, n, consumed), consumed }
287
318
  }
288
319
 
289
320
  /** Every copy in `seq`, each as a pairwise alignment against the consensus. */
@@ -411,7 +442,7 @@ export interface PeriodicAlignment {
411
442
  * as wide as the widest version of that copy across the site, so a sequence with
412
443
  * fewer copies runs out of blocks rather than drifting out of register. Returns
413
444
  * undefined when the site is not a tandem array, or is too big to lay out this
414
- * way; the caller falls back to `alignInsertions`.
445
+ * way; the caller falls back to the center-star alignment.
415
446
  *
416
447
  * **Blocks are array order, not homology.** Copies are anchored at the left edge
417
448
  * of the insertion and counted rightward, so block k is "the kth copy along",
@@ -427,7 +458,7 @@ export function alignPeriodicInsertions(
427
458
  const distinct = [...new Set(seqs)]
428
459
  const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
429
460
  const period = detectPeriod(longest)
430
- if (period === undefined || period < MIN_UNIT_PERIOD) {
461
+ if (period === undefined || period < MIN_PERIOD) {
431
462
  return undefined
432
463
  }
433
464
  return alignToUnit(distinct, consensusUnit(longest, period))
@@ -456,7 +487,7 @@ export function alignToUnit(
456
487
  ): PeriodicAlignment | undefined {
457
488
  const distinct = [...new Set(seqs)]
458
489
  const period = consensus.length
459
- if (!distinct.some(s => s.length) || period < MIN_UNIT_PERIOD) {
490
+ if (!distinct.some(s => s.length) || period < MIN_PERIOD) {
460
491
  return undefined
461
492
  }
462
493
 
@@ -464,7 +495,7 @@ export function alignToUnit(
464
495
  (a, s) => a + Math.ceil(s.length / period),
465
496
  0,
466
497
  )
467
- if (totalUnits * (period + 1) * (2 * period + 1) > MAX_PERIODIC_CELLS) {
498
+ if (totalUnits * (period + 1) * (2 * period + 1) > MAX_SITE_CELLS) {
468
499
  return undefined
469
500
  }
470
501
 
@@ -518,62 +549,80 @@ export interface InsertionAlignment {
518
549
  }
519
550
 
520
551
  /**
521
- * Lay out the sequences inserted at one reference position, by whichever of the
522
- * two alignments the sequence itself calls for. The single place that decision
523
- * is made, so a caller reading the period cannot disagree with the layout it
524
- * gets.
525
- *
526
- * A tandem array goes unit-per-block, which is both the readable answer and the
527
- * affordable one — the size caps here are what the base-to-base alignment costs,
528
- * and an expansion is always past them. Everything else gets the center-star
529
- * alignment, or is left alone (`gapped` empty) when there is nothing to gain
530
- * from a single distinct sequence, or the site is too large to be worth it.
552
+ * The sequence every other one at a site is aligned against: the one the most
553
+ * reads carry, so a single chimeric outlier cannot gap every row. Ties go to
554
+ * the length nearest the median, then lexicographically, so the choice is a
555
+ * function of the input and not of the order reads arrived in.
531
556
  */
532
- export function alignInsertionSite(seqs: string[]): InsertionAlignment {
533
- const distinct = [...new Set(seqs)]
534
- // an array is worth unrolling even when every read agrees on it: the copies
535
- // still have to be squared up with each other before they can be counted
536
- const periodic = alignPeriodicInsertions(distinct)
537
- if (periodic) {
538
- return { gapped: periodic.gapped, periodic }
539
- }
540
- const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
541
- if (
542
- distinct.length < 2 ||
543
- distinct.length > MAX_DISTINCT ||
544
- longest.length > MAX_LEN
545
- ) {
546
- return { gapped: new Map<string, string>() }
547
- }
557
+ function chooseCenter(seqs: string[]) {
558
+ const counts = new Map<string, number>()
559
+ for (const seq of seqs) {
560
+ counts.set(seq, (counts.get(seq) ?? 0) + 1)
561
+ }
562
+ const lengths = seqs.map(s => s.length).sort((a, b) => a - b)
563
+ const median =
564
+ (lengths[(lengths.length - 1) >> 1]! + lengths[lengths.length >> 1]!) / 2
565
+ const offMedian = (seq: string) => Math.abs(seq.length - median)
566
+ return [...counts].sort(
567
+ ([a, countA], [b, countB]) =>
568
+ countB - countA || offMedian(a) - offMedian(b) || (a < b ? -1 : 1),
569
+ )[0]![0]
570
+ }
548
571
 
549
- const centerLen = longest.length
550
- const others = distinct.filter(s => s !== longest)
551
- const splits = others.map(s =>
552
- splitAgainstCenter(needlemanWunsch(longest, s), centerLen),
553
- )
554
- const centerSplit: CenterSplit = {
555
- slots: Array.from({ length: centerLen + 1 }, () => ''),
556
- atCenter: longest,
572
+ /**
573
+ * Every distinct sequence aligned to the center and widened to the same set of
574
+ * columns, or undefined when the alignments would exceed the site's budget.
575
+ */
576
+ function alignAroundCenter(seqs: string[], distinct: string[]) {
577
+ const center = chooseCenter(seqs)
578
+ const budget: Budget = { cells: MAX_SITE_CELLS }
579
+ const others = distinct.filter(s => s !== center)
580
+ const splits: CenterSplit[] = []
581
+ for (const seq of others) {
582
+ const pair = alignGlobal(center, seq, budget)
583
+ if (pair) {
584
+ splits.push(splitAgainstCenter(pair, center.length))
585
+ }
557
586
  }
558
-
559
- const slotWidths = Array.from({ length: centerLen + 1 }, (_, j) =>
587
+ const slotWidths = Array.from({ length: center.length + 1 }, (_, j) =>
560
588
  splits.reduce((max, s) => Math.max(max, s.slots[j]!.length), 0),
561
589
  )
562
- return {
563
- gapped: new Map([
564
- [longest, emit(centerSplit, slotWidths)],
565
- ...others.map((seq, i): [string, string] => [
566
- seq,
567
- emit(splits[i]!, slotWidths),
568
- ]),
569
- ]),
570
- }
590
+ const centerSplit: CenterSplit = {
591
+ slots: slotWidths.map(() => ''),
592
+ atCenter: center,
593
+ }
594
+ return splits.length === others.length
595
+ ? new Map([
596
+ [center, emit(centerSplit, slotWidths)],
597
+ ...others.map((seq, i): [string, string] => [
598
+ seq,
599
+ emit(splits[i]!, slotWidths),
600
+ ]),
601
+ ])
602
+ : undefined
571
603
  }
572
604
 
573
605
  /**
574
- * The gapped sequences alone, for callers with no use for the period. Every
575
- * decision lives in `alignInsertionSite`.
606
+ * Lay out the sequences inserted at one reference position, one entry per
607
+ * read, by whichever of the two alignments the sequence itself calls for. The
608
+ * single place that decision is made, so a caller reading the period cannot
609
+ * disagree with the layout it gets.
610
+ *
611
+ * A tandem array goes unit-per-block, which is the readable answer however many
612
+ * copies it has. Everything else gets the center-star alignment, or is left
613
+ * alone (`gapped` empty) when there is nothing to gain from a single distinct
614
+ * sequence, or the alignments would cost more than the site's budget.
576
615
  */
577
- export function alignInsertions(seqs: string[]) {
578
- return alignInsertionSite(seqs).gapped
616
+ export function alignInsertionSite(seqs: string[]): InsertionAlignment {
617
+ const distinct = [...new Set(seqs)]
618
+ // an array is worth unrolling even when every read agrees on it: the copies
619
+ // still have to be squared up with each other before they can be counted
620
+ const periodic = alignPeriodicInsertions(distinct)
621
+ return periodic
622
+ ? { gapped: periodic.gapped, periodic }
623
+ : {
624
+ gapped:
625
+ (distinct.length > 1 && alignAroundCenter(seqs, distinct)) ||
626
+ new Map<string, string>(),
627
+ }
579
628
  }
@@ -284,6 +284,72 @@ export function reanchorInsertions(
284
284
  })
285
285
  }
286
286
 
287
+ function mod(a: number, b: number) {
288
+ return ((a % b) + b) % b
289
+ }
290
+
291
+ /**
292
+ * `ins`, inserted before `pos`, walked left through the read's own bases for as
293
+ * long as each step spells the same read, and no further than `floor`.
294
+ */
295
+ function walkLeft(read: ReadLayout, pos: number, ins: string, floor: number) {
296
+ let at = pos
297
+ while (
298
+ at > floor &&
299
+ readBase(read, at - 1) === ins[mod(ins.length - 1 - (pos - at), ins.length)]
300
+ ) {
301
+ at--
302
+ }
303
+ const cut = ins.length - mod(pos - at, ins.length)
304
+ return { at, seq: ins.slice(cut) + ins.slice(0, cut) }
305
+ }
306
+
307
+ /**
308
+ * Re-file each insertion no array owns at the leftmost position that spells the
309
+ * same read, so reads carrying one event agree on its site.
310
+ *
311
+ * This is `shiftInsertion`'s equivalence walked as far as it holds rather than
312
+ * to a target, which is the left-normalization of Tan, Abecasis & Kang. It runs
313
+ * after `reanchorInsertions`, leaves alone any insertion from an array's `start`
314
+ * to its `end` inclusive, and walks none into that span, so no allele an array
315
+ * measures changes. The walk also stops one base inside the region's start, so
316
+ * an insertion in view keeps a reference base on both sides of it, at the
317
+ * read's own start, and at any position where the read has no base. Two insertions of one read that meet keep their order along
318
+ * it.
319
+ */
320
+ export function normalizeInsertions(
321
+ reads: ReadLayout[],
322
+ arrays: ReferenceArray[],
323
+ regionStart: number,
324
+ ) {
325
+ const owned = (pos: number) =>
326
+ arrays.some(array => pos >= array.start && pos <= array.end)
327
+ const arrayFloor = (pos: number) =>
328
+ Math.max(
329
+ -Infinity,
330
+ ...arrays.filter(array => array.end < pos).map(array => array.end + 1),
331
+ )
332
+ return reads.map(read => {
333
+ let moved = false
334
+ let previous = -Infinity
335
+ const next = new Map<number, string>()
336
+ for (const [pos, ins] of [...read.insertions].sort((a, b) => a[0] - b[0])) {
337
+ const { at, seq } = owned(pos)
338
+ ? { at: pos, seq: ins }
339
+ : walkLeft(
340
+ read,
341
+ pos,
342
+ ins,
343
+ Math.max(regionStart + 1, read.start, arrayFloor(pos), previous),
344
+ )
345
+ next.set(at, (next.get(at) ?? '') + seq)
346
+ moved ||= at !== pos
347
+ previous = at
348
+ }
349
+ return moved ? { ...read, insertions: next } : read
350
+ })
351
+ }
352
+
287
353
  /**
288
354
  * Lay every row's allele out unit-per-block, one block per array.
289
355
  *
@@ -1,9 +1,5 @@
1
- import { readConfObject } from '@jbrowse/core/configuration'
2
-
3
1
  import { MAX_CELLS } from './limits'
4
2
 
5
- import type { TviewPlanResult } from './TviewGetPlanRpc'
6
- import type { AnyConfigurationModel } from '@jbrowse/core/configuration'
7
3
  import type { AbstractSessionModel } from '@jbrowse/core/util'
8
4
 
9
5
  /** the RPC needs assemblyName to resolve refNameAliases for the file */
@@ -16,55 +12,11 @@ export interface FetchRegion {
16
12
 
17
13
  /** one track's worth of rows, and the name they are grouped under */
18
14
  export interface TviewSource {
19
- adapterConfig: unknown
20
- /** the label rows from this file carry; omitted when there is only one */
21
- sample?: string
15
+ adapterConfig: Record<string, unknown>
16
+ sample: string
22
17
  trackId: string
23
18
  }
24
19
 
25
- /**
26
- * The trackId -> config index, whose shape has changed across hosts still in
27
- * the wild: v4.0.0 exposes a `tracksById` getter, v4.1-v4.3 a `getTracksById()`
28
- * method, and newer cores a per-id reactive `getTrackById(id)` (with
29
- * `getTracksById()` kept but deprecated). All three resolve connection and
30
- * assembly-sequence tracks; the `tracks` scan is a last resort because it does
31
- * not, and it subscribes the caller to every track.
32
- */
33
- export interface SessionTrackLookup {
34
- tracks: AnyConfigurationModel[]
35
- getTrackById?: (id: string) => AnyConfigurationModel | undefined
36
- getTracksById?: () => Record<string, AnyConfigurationModel>
37
- tracksById?: Record<string, AnyConfigurationModel>
38
- }
39
-
40
- export function findTrackConf(session: SessionTrackLookup, trackId: string) {
41
- return session.getTrackById
42
- ? session.getTrackById(trackId)
43
- : session.getTracksById
44
- ? session.getTracksById()[trackId]
45
- : session.tracksById
46
- ? session.tracksById[trackId]
47
- : session.tracks.find(t => readConfObject(t, 'trackId') === trackId)
48
- }
49
-
50
- /**
51
- * The assembly's own sequence adapter, which is what makes the reference a row
52
- * and, through it, makes an array an interval rather than an insertion. An
53
- * assembly that cannot supply one still works: the alignment is then reads only
54
- * and no array is reported, which is the pre-reference behaviour.
55
- */
56
- export function sequenceAdapterConfig(
57
- session: AbstractSessionModel,
58
- assemblyName: string,
59
- ) {
60
- const assembly = session.assemblyManager.get(assemblyName)
61
- const conf = assembly?.configuration
62
- return conf
63
- ? (readConfObject(conf, ['sequence', 'adapter']) as
64
- Record<string, unknown> | undefined)
65
- : undefined
66
- }
67
-
68
20
  /**
69
21
  * One RPC per launch, however many files it draws from. The session id is
70
22
  * shared across the sources so the worker keeps one adapter cache for the view
@@ -75,21 +27,26 @@ export async function fetchTviewPlan({
75
27
  sources,
76
28
  region,
77
29
  maxCells = MAX_CELLS,
30
+ signal,
78
31
  }: {
79
32
  session: AbstractSessionModel
80
33
  sources: TviewSource[]
81
34
  region: FetchRegion
82
35
  maxCells?: number
36
+ signal?: AbortSignal
83
37
  }) {
84
38
  const rpcSessionId = `tview-${sources.map(s => s.trackId).join(',')}`
85
- return (await session.rpcManager.call(rpcSessionId, 'TviewGetPlan', {
86
- sessionId: rpcSessionId,
39
+ const assembly = session.assemblyManager.get(region.assemblyName)
40
+ return session.rpcManager.call(rpcSessionId, 'TviewGetPlan', {
87
41
  sources: sources.map(s => ({
88
42
  adapterConfig: s.adapterConfig,
89
43
  sample: s.sample,
90
44
  })),
91
- sequenceAdapterConfig: sequenceAdapterConfig(session, region.assemblyName),
45
+ assemblyName: region.assemblyName,
46
+ sequenceRefName:
47
+ assembly?.getSeqAdapterRefName(region.refName) ?? region.refName,
92
48
  region,
93
49
  maxCells,
94
- })) as TviewPlanResult
50
+ signal,
51
+ })
95
52
  }