jbrowse-plugin-tview 2.2.1 → 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 (113) hide show
  1. package/README.md +349 -69
  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 +18 -17
  9. package/dist/LaunchTView/align.js +198 -151
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +14 -0
  12. package/dist/LaunchTView/alleles.js +51 -3
  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 -6
  33. package/dist/LaunchTView/repeatStats.js.map +1 -1
  34. package/dist/LaunchTView/repeats.js +6 -4
  35. package/dist/LaunchTView/repeats.js.map +1 -1
  36. package/dist/LaunchTView/tview.d.ts +47 -24
  37. package/dist/LaunchTView/tview.js +188 -99
  38. package/dist/LaunchTView/tview.js.map +1 -1
  39. package/dist/TViewPanel/components/TViewPanel.js +9 -4
  40. package/dist/TViewPanel/components/TViewPanel.js.map +1 -1
  41. package/dist/TViewPanel/genome.d.ts +11 -0
  42. package/dist/TViewPanel/genome.js +32 -0
  43. package/dist/TViewPanel/genome.js.map +1 -0
  44. package/dist/TViewPanel/init.d.ts +38 -19
  45. package/dist/TViewPanel/init.js +66 -39
  46. package/dist/TViewPanel/init.js.map +1 -1
  47. package/dist/TViewPanel/initMenu.d.ts +28 -0
  48. package/dist/TViewPanel/initMenu.js +79 -0
  49. package/dist/TViewPanel/initMenu.js.map +1 -0
  50. package/dist/TViewPanel/model.d.ts +1178 -383
  51. package/dist/TViewPanel/model.js +298 -87
  52. package/dist/TViewPanel/model.js.map +1 -1
  53. package/dist/TViewPanel/modifications.d.ts +25 -0
  54. package/dist/TViewPanel/modifications.js +89 -0
  55. package/dist/TViewPanel/modifications.js.map +1 -0
  56. package/dist/index.d.ts +0 -1
  57. package/dist/index.js +0 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/jbrowse-plugin-tview.umd.production.min.js +125 -89
  60. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  61. package/dist/version.d.ts +1 -1
  62. package/dist/version.js +1 -1
  63. package/package.json +21 -18
  64. package/src/AddHighlightModel/index.tsx +8 -14
  65. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +119 -157
  66. package/src/LaunchTView/TviewGetPlanRpc/index.ts +0 -1
  67. package/src/LaunchTView/align.ts +233 -177
  68. package/src/LaunchTView/alleles.ts +70 -4
  69. package/src/LaunchTView/fetchTviewPlan.ts +11 -54
  70. package/src/LaunchTView/index.ts +74 -16
  71. package/src/LaunchTView/launch.ts +98 -0
  72. package/src/LaunchTView/launchView.ts +28 -20
  73. package/src/LaunchTView/modifications.ts +200 -0
  74. package/src/LaunchTView/readLayout.ts +65 -41
  75. package/src/LaunchTView/repeatStats.ts +7 -7
  76. package/src/LaunchTView/repeats.ts +6 -4
  77. package/src/LaunchTView/tview.ts +228 -112
  78. package/src/TViewPanel/components/TViewPanel.tsx +33 -4
  79. package/src/TViewPanel/genome.ts +41 -0
  80. package/src/TViewPanel/init.ts +104 -51
  81. package/src/TViewPanel/initMenu.ts +126 -0
  82. package/src/TViewPanel/model.ts +350 -97
  83. package/src/TViewPanel/modifications.ts +127 -0
  84. package/src/index.ts +0 -2
  85. package/src/version.ts +1 -1
  86. package/dist/AddHighlightModel/GenomeMouseoverHighlight.d.ts +0 -6
  87. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js +0 -23
  88. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js.map +0 -1
  89. package/dist/AddHighlightModel/HighlightComponents.d.ts +0 -7
  90. package/dist/AddHighlightModel/HighlightComponents.js +0 -11
  91. package/dist/AddHighlightModel/HighlightComponents.js.map +0 -1
  92. package/dist/LaunchTView/components/ArrayReport.d.ts +0 -10
  93. package/dist/LaunchTView/components/ArrayReport.js +0 -59
  94. package/dist/LaunchTView/components/ArrayReport.js.map +0 -1
  95. package/dist/LaunchTView/components/LaunchTViewDialog.d.ts +0 -6
  96. package/dist/LaunchTView/components/LaunchTViewDialog.js +0 -124
  97. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +0 -1
  98. package/dist/LaunchTView/sampleTree.d.ts +0 -37
  99. package/dist/LaunchTView/sampleTree.js +0 -65
  100. package/dist/LaunchTView/sampleTree.js.map +0 -1
  101. package/dist/LaunchTView/useTviewMsa.d.ts +0 -18
  102. package/dist/LaunchTView/useTviewMsa.js +0 -24
  103. package/dist/LaunchTView/useTviewMsa.js.map +0 -1
  104. package/dist/TViewPanel/coords.d.ts +0 -25
  105. package/dist/TViewPanel/coords.js +0 -56
  106. package/dist/TViewPanel/coords.js.map +0 -1
  107. package/src/AddHighlightModel/GenomeMouseoverHighlight.tsx +0 -46
  108. package/src/AddHighlightModel/HighlightComponents.tsx +0 -25
  109. package/src/LaunchTView/components/ArrayReport.tsx +0 -64
  110. package/src/LaunchTView/components/LaunchTViewDialog.tsx +0 -212
  111. package/src/LaunchTView/sampleTree.ts +0 -73
  112. package/src/LaunchTView/useTviewMsa.ts +0 -39
  113. 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))
@@ -442,14 +473,21 @@ export function alignPeriodicInsertions(
442
473
  * which is a guess that one chimeric read overturns for the whole site. Measured
443
474
  * off the reference, it is a property of the locus, so every read is laid out
444
475
  * against the same unit whatever the reads happen to be.
476
+ *
477
+ * An empty sequence is one of the alleles, not a missing one: a row that
478
+ * deletes the whole array carries nought copies of it, which is a measurement
479
+ * and the most extreme contraction there is. It splits into no units and so
480
+ * lays out as a row of gaps the width of the block, which is what a deletion
481
+ * should look like. Dropping it instead left that row indistinguishable from
482
+ * one that never reached the array at all.
445
483
  */
446
484
  export function alignToUnit(
447
485
  seqs: string[],
448
486
  consensus: string,
449
487
  ): PeriodicAlignment | undefined {
450
- const distinct = [...new Set(seqs)].filter(s => s.length > 0)
488
+ const distinct = [...new Set(seqs)]
451
489
  const period = consensus.length
452
- if (!distinct.length || period < MIN_UNIT_PERIOD) {
490
+ if (!distinct.some(s => s.length) || period < MIN_PERIOD) {
453
491
  return undefined
454
492
  }
455
493
 
@@ -457,7 +495,7 @@ export function alignToUnit(
457
495
  (a, s) => a + Math.ceil(s.length / period),
458
496
  0,
459
497
  )
460
- if (totalUnits * (period + 1) * (2 * period + 1) > MAX_PERIODIC_CELLS) {
498
+ if (totalUnits * (period + 1) * (2 * period + 1) > MAX_SITE_CELLS) {
461
499
  return undefined
462
500
  }
463
501
 
@@ -511,62 +549,80 @@ export interface InsertionAlignment {
511
549
  }
512
550
 
513
551
  /**
514
- * Lay out the sequences inserted at one reference position, by whichever of the
515
- * two alignments the sequence itself calls for. The single place that decision
516
- * is made, so a caller reading the period cannot disagree with the layout it
517
- * gets.
518
- *
519
- * A tandem array goes unit-per-block, which is both the readable answer and the
520
- * affordable one — the size caps here are what the base-to-base alignment costs,
521
- * and an expansion is always past them. Everything else gets the center-star
522
- * alignment, or is left alone (`gapped` empty) when there is nothing to gain
523
- * 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.
524
556
  */
525
- export function alignInsertionSite(seqs: string[]): InsertionAlignment {
526
- const distinct = [...new Set(seqs)]
527
- // an array is worth unrolling even when every read agrees on it: the copies
528
- // still have to be squared up with each other before they can be counted
529
- const periodic = alignPeriodicInsertions(distinct)
530
- if (periodic) {
531
- return { gapped: periodic.gapped, periodic }
532
- }
533
- const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
534
- if (
535
- distinct.length < 2 ||
536
- distinct.length > MAX_DISTINCT ||
537
- longest.length > MAX_LEN
538
- ) {
539
- return { gapped: new Map<string, string>() }
540
- }
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
+ }
541
571
 
542
- const centerLen = longest.length
543
- const others = distinct.filter(s => s !== longest)
544
- const splits = others.map(s =>
545
- splitAgainstCenter(needlemanWunsch(longest, s), centerLen),
546
- )
547
- const centerSplit: CenterSplit = {
548
- slots: Array.from({ length: centerLen + 1 }, () => ''),
549
- 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
+ }
550
586
  }
551
-
552
- const slotWidths = Array.from({ length: centerLen + 1 }, (_, j) =>
587
+ const slotWidths = Array.from({ length: center.length + 1 }, (_, j) =>
553
588
  splits.reduce((max, s) => Math.max(max, s.slots[j]!.length), 0),
554
589
  )
555
- return {
556
- gapped: new Map([
557
- [longest, emit(centerSplit, slotWidths)],
558
- ...others.map((seq, i): [string, string] => [
559
- seq,
560
- emit(splits[i]!, slotWidths),
561
- ]),
562
- ]),
563
- }
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
564
603
  }
565
604
 
566
605
  /**
567
- * The gapped sequences alone, for callers with no use for the period. Every
568
- * 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.
569
615
  */
570
- export function alignInsertions(seqs: string[]) {
571
- 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
+ }
572
628
  }
@@ -1,4 +1,5 @@
1
1
  import { alignToUnit, unitIdentity } from './align'
2
+ import { ABSENT, SPANNED_GAP } from './readLayout'
2
3
 
3
4
  import type { ReadLayout } from './readLayout'
4
5
  import type { ReferenceArray } from './repeats'
@@ -32,9 +33,6 @@ export interface ArrayBlock {
32
33
  lengthByName: Map<string, number>
33
34
  }
34
35
 
35
- const SPANNED_GAP = '-'
36
- const ABSENT = '.'
37
-
38
36
  /**
39
37
  * What one row has between two reference positions: its matched bases, plus
40
38
  * whatever it inserted inside, minus whatever it deleted.
@@ -277,8 +275,76 @@ export function reanchorInsertions(
277
275
  const at = target ?? pos
278
276
  moved ||= target !== undefined
279
277
  const seq =
280
- target === undefined ? ins : (shiftInsertion(read, pos, target, ins) ?? ins)
278
+ target === undefined
279
+ ? ins
280
+ : (shiftInsertion(read, pos, target, ins) ?? ins)
281
+ next.set(at, (next.get(at) ?? '') + seq)
282
+ }
283
+ return moved ? { ...read, insertions: next } : read
284
+ })
285
+ }
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
+ )
281
345
  next.set(at, (next.get(at) ?? '') + seq)
346
+ moved ||= at !== pos
347
+ previous = at
282
348
  }
283
349
  return moved ? { ...read, insertions: next } : read
284
350
  })