jbrowse-plugin-tview 2.0.6 → 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 +47 -31
  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 +22 -22
  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 +5 -2
  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
@@ -1,99 +1,39 @@
1
- import { alignInsertions } from './align'
1
+ import { alignInsertionSite } from './align'
2
+ import { buildArrayBlocks } from './alleles'
3
+ import {
4
+ ABSENT,
5
+ SPANNED_GAP,
6
+ byStart,
7
+ clipInsertions,
8
+ getReadNames,
9
+ parseRead,
10
+ } from './readLayout'
11
+ import { findReferenceArrays, mergeArrays } from './repeats'
12
+ import { newickSafe } from './sampleTree'
2
13
 
3
- /** the subset of an @jbrowse/core Feature that the layout reads */
4
- export interface AlignmentFeature {
5
- get: (key: string) => any
6
- }
7
-
8
- /**
9
- * Only '-' and '.' are treated as gaps by react-msaview (anything else counts
10
- * as a base in the conservation track and column stats), so the two of them
11
- * carry the whole vocabulary for "no base here". They are split by meaning:
12
- *
13
- * - SPANNED_GAP: the read covers this reference position but aligns no base to
14
- * it, i.e. a deletion, or padding in an insertion column
15
- * - ABSENT: the read is not here at all, i.e. outside its bounds, or skipping
16
- * over the position through an N (an intron, not a deleted allele)
17
- */
18
- const SPANNED_GAP = '-'
19
- const ABSENT = '.'
14
+ import type { ArrayBlock } from './alleles'
15
+ import type { AlignmentFeature, ReadLayout } from './readLayout'
20
16
 
21
- export interface ReadLayout {
22
- name: string
23
- start: number
24
- /** one char per reference position consumed: the aligned base, or a gap */
25
- refChars: string
26
- /** reference position -> bases inserted immediately before that position */
27
- insertions: Map<number, string>
28
- }
29
-
30
- const cigarRegex = /([MIDNSHPX=])/
31
-
32
- const byStart = (a: ReadLayout, b: ReadLayout) => a.start - b.start
33
-
34
- export function parseCigar(cigar: string) {
35
- return cigar.split(cigarRegex).slice(0, -1)
36
- }
37
-
38
- export function parseRead(feature: AlignmentFeature, name: string): ReadLayout {
39
- const seq = feature.get('seq') as string
40
- const ops = parseCigar(feature.get('CIGAR') as string)
41
- const start = feature.get('start')
42
- const insertions = new Map<number, string>()
43
- let refChars = ''
44
- let seqOffset = 0
45
-
46
- for (let i = 0; i < ops.length; i += 2) {
47
- const len = +ops[i]!
48
- const op = ops[i + 1]!
49
- if (op === 'S') {
50
- seqOffset += len
51
- } else if (op === 'I') {
52
- // consecutive I ops (e.g. 3M2I3I3M) land on the same reference position
53
- const pos = start + refChars.length
54
- const prev = insertions.get(pos) ?? ''
55
- insertions.set(pos, prev + seq.slice(seqOffset, seqOffset + len))
56
- seqOffset += len
57
- } else if (op === 'D') {
58
- refChars += SPANNED_GAP.repeat(len)
59
- } else if (op === 'N') {
60
- refChars += ABSENT.repeat(len)
61
- } else if (op === 'M' || op === 'X' || op === '=') {
62
- refChars += seq.slice(seqOffset, seqOffset + len)
63
- seqOffset += len
64
- }
65
- // H and P consume neither the read sequence nor the reference
66
- }
67
- return { name, start, refChars, insertions }
68
- }
17
+ export type { AlignmentFeature, ReadLayout } from './readLayout'
18
+ export { clipInsertions, parseCigar, parseRead } from './readLayout'
69
19
 
70
20
  /**
71
- * Reads are fetched by overlap, so they carry insertions on either side of the
72
- * region. Those get no columns and are never rendered, so dropping them keeps
73
- * the pairwise alignment below off the wasted sites entirely.
21
+ * Mutually aligns the sequences inserted at each reference position, so reads
22
+ * sharing an insertion event line up inside it. Positions an array block has
23
+ * taken over are left alone: those bases are part of an allele the block
24
+ * already laid out, and giving them insertion columns as well would render
25
+ * them twice.
74
26
  */
75
- export function clipInsertions(
27
+ export function alignInsertionColumns(
76
28
  reads: ReadLayout[],
77
- start: number,
78
- end: number,
29
+ ownedByArray: Set<number>,
79
30
  ) {
80
- return reads.map(read => ({
81
- ...read,
82
- insertions: new Map(
83
- [...read.insertions].filter(([pos]) => pos >= start && pos < end),
84
- ),
85
- }))
86
- }
87
-
88
- /**
89
- * Mutually aligns the sequences inserted at each reference position, so reads
90
- * sharing an insertion event line up inside it. Sites the aligner declines are
91
- * returned unchanged and stay left-justified.
92
- */
93
- export function alignInsertionColumns(reads: ReadLayout[]): ReadLayout[] {
94
31
  const byPos = new Map<number, string[]>()
95
32
  for (const read of reads) {
96
33
  for (const [pos, ins] of read.insertions) {
34
+ if (ownedByArray.has(pos)) {
35
+ continue
36
+ }
97
37
  const seqs = byPos.get(pos)
98
38
  if (seqs) {
99
39
  seqs.push(ins)
@@ -102,26 +42,31 @@ export function alignInsertionColumns(reads: ReadLayout[]): ReadLayout[] {
102
42
  }
103
43
  }
104
44
  }
105
- const gapped = new Map(
106
- [...byPos].map(([pos, seqs]) => [pos, alignInsertions(seqs)] as const),
45
+ const aligned = new Map(
46
+ [...byPos].map(([pos, seqs]) => [pos, alignInsertionSite(seqs)] as const),
107
47
  )
108
48
  return reads.map(read => ({
109
49
  ...read,
110
50
  insertions: new Map(
111
51
  [...read.insertions].map(([pos, ins]) => [
112
52
  pos,
113
- gapped.get(pos)?.get(ins) ?? ins,
53
+ aligned.get(pos)?.gapped.get(ins) ?? ins,
114
54
  ]),
115
55
  ),
116
56
  }))
117
57
  }
118
58
 
119
59
  /** widest insertion any read has at each reference position (sparse) */
120
- export function maxInsertionWidths(reads: ReadLayout[]) {
60
+ export function maxInsertionWidths(
61
+ reads: ReadLayout[],
62
+ ownedByArray: Set<number>,
63
+ ) {
121
64
  const ret = new Map<number, number>()
122
65
  for (const read of reads) {
123
66
  for (const [pos, ins] of read.insertions) {
124
- ret.set(pos, Math.max(ret.get(pos) ?? 0, ins.length))
67
+ if (!ownedByArray.has(pos)) {
68
+ ret.set(pos, Math.max(ret.get(pos) ?? 0, ins.length))
69
+ }
125
70
  }
126
71
  }
127
72
  return ret
@@ -131,90 +76,202 @@ export interface ColumnLayout {
131
76
  start: number
132
77
  end: number
133
78
  insWidths: Map<number, number>
79
+ arrays: ArrayBlock[]
134
80
  /**
135
81
  * column index at which each reference position's columns begin, for
136
- * start..end inclusive
82
+ * start..end inclusive. Positions inside an array block all begin where the
83
+ * block ends: the block is one run of columns and no position inside it owns
84
+ * any of them.
137
85
  */
138
86
  offsets: number[]
139
87
  totalColumns: number
140
88
  }
141
89
 
90
+ function arrayStartIndex(arrays: ArrayBlock[]) {
91
+ return new Map(arrays.map(a => [a.start, a]))
92
+ }
93
+
142
94
  /**
143
95
  * Each reference position contributes its insertion columns (widest across all
144
96
  * reads) followed by one reference column, so every row comes out the same
145
- * length and stays aligned.
97
+ * length and stays aligned — except where an array block takes over, and
98
+ * contributes one run of columns for the whole interval it covers.
146
99
  */
147
100
  export function buildColumnLayout(
148
101
  start: number,
149
102
  end: number,
150
103
  insWidths: Map<number, number>,
104
+ arrays: ArrayBlock[] = [],
151
105
  ): ColumnLayout {
152
- const offsets = [0]
106
+ const byStartPos = arrayStartIndex(arrays)
107
+ const offsets: number[] = []
153
108
  let col = 0
154
- for (let pos = start; pos < end; pos++) {
155
- col += (insWidths.get(pos) ?? 0) + 1
156
- offsets.push(col)
109
+ let pos = start
110
+ while (pos < end) {
111
+ const array = byStartPos.get(pos)
112
+ if (array) {
113
+ const stop = Math.min(array.end, end)
114
+ offsets.push(col)
115
+ col += array.width
116
+ for (let p = pos + 1; p < stop; p++) {
117
+ offsets.push(col)
118
+ }
119
+ pos = stop
120
+ } else {
121
+ offsets.push(col)
122
+ col += (insWidths.get(pos) ?? 0) + 1
123
+ pos++
124
+ }
157
125
  }
158
- return { start, end, insWidths, offsets, totalColumns: col }
126
+ offsets.push(col)
127
+ return { start, end, insWidths, arrays, offsets, totalColumns: col }
128
+ }
129
+
130
+ /** the array covering `pos`, when `pos` is strictly inside one */
131
+ function arrayContaining(arrays: ArrayBlock[], pos: number) {
132
+ return arrays.find(a => a.start < pos && pos < a.end)
159
133
  }
160
134
 
161
135
  /**
162
- * Lays a single read out across the whole region. Reads are typically a tiny
163
- * fraction of the region, so the columns on either side of the read are filled
164
- * in one shot rather than walked position by position.
136
+ * Lays a single row out across the whole region. Rows are typically a tiny
137
+ * fraction of the region, so the columns on either side are filled in one shot
138
+ * from the offsets rather than walked position by position — which works over
139
+ * array blocks too, since the offsets already carry their width.
165
140
  */
166
141
  export function renderRow(read: ReadLayout, layout: ColumnLayout) {
167
- const { start, end, insWidths, offsets, totalColumns } = layout
142
+ const { start, end, insWidths, arrays, offsets, totalColumns } = layout
143
+ const byStartPos = arrayStartIndex(arrays)
168
144
  // a trailing insertion is keyed one past the last position the read spans
169
- const from = Math.max(start, read.start)
170
- const to = Math.min(end, read.start + read.refChars.length + 1)
145
+ let from = Math.max(start, read.start)
146
+ let to = Math.min(end, read.start + read.refChars.length + 1)
147
+ // a row that begins or ends inside an array does not span it, so it gets no
148
+ // block; snapping past the block keeps the walk from emitting part of one
149
+ const startsInside = arrayContaining(arrays, from)
150
+ if (startsInside) {
151
+ from = Math.min(end, startsInside.end)
152
+ }
153
+ const endsInside = arrayContaining(arrays, to)
154
+ if (endsInside) {
155
+ to = endsInside.start
156
+ }
157
+ if (to <= from) {
158
+ return ABSENT.repeat(totalColumns)
159
+ }
171
160
 
172
- let ret: string
173
- if (to > from) {
174
- ret = ABSENT.repeat(offsets[from - start]!)
175
- for (let pos = from; pos < to; pos++) {
176
- const idx = pos - read.start
177
- const spanned = idx >= 0 && idx < read.refChars.length
178
- const refChar = spanned ? read.refChars[idx]! : ABSENT
179
- const width = insWidths.get(pos) ?? 0
180
- if (width) {
181
- // a read that is not really here pads the insertion the same way it
182
- // pads the reference column, so an intron reads as one absence
183
- const pad = refChar === ABSENT ? ABSENT : SPANNED_GAP
184
- const ins = read.insertions.get(pos) ?? ''
185
- ret += ins + pad.repeat(width - ins.length)
186
- }
187
- ret += refChar
161
+ let ret = ABSENT.repeat(offsets[from - start]!)
162
+ let pos = from
163
+ while (pos < to) {
164
+ const array = byStartPos.get(pos)
165
+ if (array) {
166
+ const row = array.rowByName.get(read.name)
167
+ ret += row ?? SPANNED_GAP.repeat(array.width)
168
+ pos = Math.min(array.end, to)
169
+ continue
170
+ }
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)
188
181
  }
189
- ret += ABSENT.repeat(totalColumns - offsets[to - start]!)
190
- } else {
191
- ret = ABSENT.repeat(totalColumns)
182
+ ret += refChar
183
+ pos++
192
184
  }
193
- return ret
185
+ return ret + ABSENT.repeat(totalColumns - offsets[to - start]!)
194
186
  }
195
187
 
196
- function mateSuffix(flags: number | undefined) {
197
- return flags === undefined || !(flags & 1) ? '' : flags & 64 ? '/1' : '/2'
188
+ // A defline is truncated at its first space (msa-parsers' FastaMSA), so the
189
+ // count is joined on. `labelsAlignRight` puts it flush against the sequence.
190
+ const COPY_COUNT_SEPARATOR = '|'
191
+
192
+ /**
193
+ * What a row is called on screen. The one place `label` falls back to `name`,
194
+ * so the defline and the tree leaf cannot disagree about it — react-msaview
195
+ * joins them by string, and a row the tree names differently renders blank.
196
+ */
197
+ export function rowLabel(read: ReadLayout) {
198
+ return read.label ?? read.name
198
199
  }
199
200
 
200
- /** MSA rows are keyed by name, so mates and duplicate names need disambiguating */
201
- function getReadNames(features: AlignmentFeature[]) {
202
- const counts = new Map<string, number>()
203
- return features.map(f => {
204
- const base = `${f.get('name')}${mateSuffix(f.get('flags'))}`
205
- const n = (counts.get(base) ?? 0) + 1
206
- counts.set(base, n)
207
- return n === 1 ? base : `${base}_${n}`
208
- })
201
+ /**
202
+ * Rows ordered longest-allele-first and labelled with their copy count.
203
+ *
204
+ * Copy number is the measurement at a tandem array, and reading it off where a
205
+ * row runs out is the thing the unit-per-block layout exists to avoid, so it is
206
+ * stated in the label. Ordering by it puts the alleles in a ladder, which is
207
+ * what makes one row's array comparable to the next at a glance. Rows that do
208
+ * not span the array keep genomic order, below the ones that do; the reference
209
+ * stays on top whatever its allele, since it is what the columns are named
210
+ * after rather than one of the observations.
211
+ */
212
+ export function labelAndOrderByCopies(
213
+ reads: ReadLayout[],
214
+ array: ArrayBlock,
215
+ referenceName?: string,
216
+ ) {
217
+ const rank = (read: ReadLayout) => (read.name === referenceName ? 1 : 0)
218
+ return reads
219
+ .map(read => ({ read, copies: array.copiesByName.get(read.name) }))
220
+ .sort((a, b) => {
221
+ const byRef = rank(b.read) - rank(a.read)
222
+ if (byRef) {
223
+ return byRef
224
+ }
225
+ if (a.copies === undefined || b.copies === undefined) {
226
+ return a.copies === b.copies
227
+ ? byStart(a.read, b.read)
228
+ : a.copies === undefined
229
+ ? 1
230
+ : -1
231
+ }
232
+ return b.copies - a.copies || byStart(a.read, b.read)
233
+ })
234
+ .map(({ read, copies }) =>
235
+ copies === undefined
236
+ ? read
237
+ : { ...read, label: `${read.name}${COPY_COUNT_SEPARATOR}n=${copies}` },
238
+ )
209
239
  }
210
240
 
211
241
  export interface TviewPlan {
212
242
  reads: ReadLayout[]
213
243
  layout: ColumnLayout
214
244
  insertionWidths: [number, number][]
245
+ /** [start, end, width] per array block, to rebuild the column mapping */
246
+ arraySpans: [number, number, number][]
215
247
  region: { refName: string; start: number; end: number }
216
248
  /** rows x columns, i.e. how big the alignment renderTviewMsa builds will be */
217
249
  cellCount: number
250
+ /** tandem arrays the reference carries here, left to right */
251
+ arrays: ArrayBlock[]
252
+ /** the array the rows are ordered and labelled by, when there is one */
253
+ subject?: ArrayBlock
254
+ /** name of the reference row, when the reference sequence was available */
255
+ referenceName?: string
256
+ /** samples contributing rows, in the order they were given */
257
+ samples: string[]
258
+ }
259
+
260
+ /** Widest spread of allele lengths, i.e. the array the reads disagree most about. */
261
+ function alleleSpread(array: ArrayBlock) {
262
+ const lengths = [...array.lengthByName.values()]
263
+ return lengths.length ? Math.max(...lengths) - Math.min(...lengths) : 0
264
+ }
265
+
266
+ export interface PlanArgs {
267
+ features: AlignmentFeature[]
268
+ refName: string
269
+ start: number
270
+ end: number
271
+ /** reference bases for start..end, when the assembly could supply them */
272
+ sequence?: string
273
+ /** which sample each feature came from, parallel to `features` */
274
+ sampleOf?: (index: number) => string | undefined
218
275
  }
219
276
 
220
277
  /**
@@ -227,46 +284,91 @@ export function planTviewMsa({
227
284
  refName,
228
285
  start,
229
286
  end,
230
- }: {
231
- features: AlignmentFeature[]
232
- refName: string
233
- start: number
234
- end: number
235
- }): TviewPlan {
236
- const names = getReadNames(features)
237
- const reads = alignInsertionColumns(
238
- clipInsertions(
239
- features.map((f, i) => parseRead(f, names[i]!)).sort(byStart),
240
- start,
241
- end,
242
- ),
287
+ sequence,
288
+ sampleOf,
289
+ }: PlanArgs): TviewPlan {
290
+ const names = getReadNames(features, sampleOf)
291
+ const parsed = features
292
+ .map((f, i) => parseRead(f, names[i]!, sampleOf?.(i)))
293
+ .sort(byStart)
294
+
295
+ // The reference is laid out as a row like any other, which is what lets it be
296
+ // one of the alleles an array block squares up rather than a thing the block
297
+ // has to be compared against afterwards.
298
+ const referenceName = sequence ? newickSafe(refName) : undefined
299
+ const referenceRead: ReadLayout | undefined = sequence
300
+ ? {
301
+ name: referenceName!,
302
+ start,
303
+ refChars: sequence.toUpperCase(),
304
+ insertions: new Map(),
305
+ }
306
+ : undefined
307
+
308
+ const clipped = clipInsertions(
309
+ referenceRead ? [referenceRead, ...parsed] : parsed,
310
+ start,
311
+ end,
312
+ )
313
+
314
+ const arrays = sequence
315
+ ? buildArrayBlocks(
316
+ clipped,
317
+ mergeArrays(findReferenceArrays(sequence, start)),
318
+ )
319
+ : []
320
+ const ownedByArray = new Set<number>()
321
+ for (const array of arrays) {
322
+ for (let pos = array.start; pos <= array.end; pos++) {
323
+ ownedByArray.add(pos)
324
+ }
325
+ }
326
+
327
+ const aligned = alignInsertionColumns(clipped, ownedByArray)
328
+
329
+ // With several arrays in view the subject is the one the rows disagree most
330
+ // about, since ordering rows by two copy numbers at once is not a thing rows
331
+ // can do and an array every row agrees on orders nothing.
332
+ const subject = arrays.reduce<ArrayBlock | undefined>(
333
+ (best, array) =>
334
+ best && alleleSpread(best) >= alleleSpread(array) ? best : array,
335
+ undefined,
243
336
  )
244
- const insWidths = maxInsertionWidths(reads)
245
- const layout = buildColumnLayout(start, end, insWidths)
337
+ const reads = subject
338
+ ? labelAndOrderByCopies(aligned, subject, referenceName)
339
+ : aligned
340
+
341
+ const insWidths = maxInsertionWidths(reads, ownedByArray)
342
+ const layout = buildColumnLayout(start, end, insWidths, arrays)
246
343
 
247
344
  return {
248
345
  reads,
249
346
  layout,
250
347
  insertionWidths: [...insWidths.entries()].sort((a, b) => a[0] - b[0]),
348
+ arraySpans: arrays.map(a => [a.start, a.end, a.width]),
251
349
  region: { refName, start, end },
252
350
  cellCount: reads.length * layout.totalColumns,
351
+ arrays,
352
+ subject,
353
+ referenceName,
354
+ samples: [
355
+ ...new Set(parsed.map(r => r.sample).filter(s => s !== undefined)),
356
+ ],
253
357
  }
254
358
  }
255
359
 
256
360
  export function renderTviewMsa({ reads, layout }: TviewPlan) {
257
- return reads.map(r => `>${r.name}\n${renderRow(r, layout)}\n`).join('')
361
+ return reads.map(r => `>${rowLabel(r)}\n${renderRow(r, layout)}\n`).join('')
258
362
  }
259
363
 
260
- export function buildTviewMsa(args: {
261
- features: AlignmentFeature[]
262
- refName: string
263
- start: number
264
- end: number
265
- }) {
364
+ export function buildTviewMsa(args: PlanArgs) {
266
365
  const plan = planTviewMsa(args)
267
366
  return {
268
367
  msa: renderTviewMsa(plan),
269
368
  insertionWidths: plan.insertionWidths,
369
+ arraySpans: plan.arraySpans,
270
370
  region: plan.region,
371
+ arrays: plan.arrays,
372
+ subject: plan.subject,
271
373
  }
272
374
  }
@@ -1,10 +1,10 @@
1
- import { assembleLocString, getSession } from '@jbrowse/core/util'
2
1
  import useSWR from 'swr'
3
2
 
4
- import { fetchTviewPlan, sourceFromTrack } from './fetchTviewPlan'
3
+ import { fetchTviewPlan } from './fetchTviewPlan'
4
+ import { initRegion, initSources } from '../TViewPanel/init'
5
5
 
6
- import type { FetchRegion } from './fetchTviewPlan'
7
- import type { AbstractTrackModel } from '@jbrowse/core/util'
6
+ import type { TviewInit } from '../TViewPanel/init'
7
+ import type { AbstractSessionModel } from '@jbrowse/core/util'
8
8
 
9
9
  const staticSwrConfig = {
10
10
  revalidateOnFocus: false,
@@ -13,24 +13,27 @@ const staticSwrConfig = {
13
13
  shouldRetryOnError: false,
14
14
  }
15
15
 
16
+ /**
17
+ * A preview of what a `TviewInit` resolves to, for the dialog to report before
18
+ * the view is opened.
19
+ *
20
+ * Resolved through the same two functions the view itself uses, so what the
21
+ * dialog states and what the view then builds cannot disagree.
22
+ */
16
23
  export function useTviewMsa({
17
- model,
18
- region,
24
+ session,
25
+ init,
19
26
  }: {
20
- model: AbstractTrackModel
21
- region?: FetchRegion
27
+ session: AbstractSessionModel
28
+ init?: TviewInit
22
29
  }) {
23
- // the key carries the region so the fetcher receives it already narrowed
30
+ const region = init ? initRegion(session, init) : undefined
31
+ const sources = init ? initSources(session, init) : undefined
24
32
  return useSWR(
25
- region
26
- ? { tag: 'tview', loc: assembleLocString(region), id: model.id, region }
33
+ region && sources
34
+ ? { tag: 'tview', loc: init!.loc, tracks: init!.tracks, region, sources }
27
35
  : null,
28
- ({ region }) =>
29
- fetchTviewPlan({
30
- session: getSession(model),
31
- source: sourceFromTrack(model),
32
- region,
33
- }),
36
+ ({ region, sources }) => fetchTviewPlan({ session, sources, region }),
34
37
  staticSwrConfig,
35
38
  )
36
39
  }
@@ -2,24 +2,46 @@
2
2
  * Inverse of the column layout built by buildTviewMsa: the alignment emits each
3
3
  * reference position's insertion columns followed by its reference column, so a
4
4
  * flat column -> reference position array recovers the mapping.
5
+ *
6
+ * An array block is the exception. Its columns are copies rather than positions,
7
+ * and a copy is not at any one reference base — the whole point of the block is
8
+ * that reads disagree about where the bases are. Its columns therefore ramp
9
+ * evenly across the interval the array covers, which is right at the two edges
10
+ * and an interpolation in between; hovering a copy lands in the array, which is
11
+ * the honest answer.
5
12
  */
6
13
  export function buildColumnToRefPos({
7
14
  start,
8
15
  end,
9
16
  insertionWidths,
17
+ arraySpans = [],
10
18
  }: {
11
19
  start: number
12
20
  end: number
13
21
  insertionWidths: [number, number][]
22
+ arraySpans?: [number, number, number][]
14
23
  }) {
15
24
  const widths = new Map(insertionWidths)
25
+ const arrayAt = new Map(arraySpans.map(([s, e, w]) => [s, { end: e, w }]))
16
26
  const ret: number[] = []
17
- for (let pos = start; pos < end; pos++) {
27
+ let pos = start
28
+ while (pos < end) {
29
+ const array = arrayAt.get(pos)
30
+ if (array) {
31
+ const stop = Math.min(array.end, end)
32
+ const span = stop - pos
33
+ for (let i = 0; i < array.w; i++) {
34
+ ret.push(pos + Math.min(span - 1, Math.floor((i * span) / array.w)))
35
+ }
36
+ pos = stop
37
+ continue
38
+ }
18
39
  const width = widths.get(pos) ?? 0
19
40
  for (let i = 0; i < width; i++) {
20
41
  ret.push(pos)
21
42
  }
22
43
  ret.push(pos)
44
+ pos++
23
45
  }
24
46
  return ret
25
47
  }