jbrowse-plugin-tview 2.0.4

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 (81) hide show
  1. package/README.md +59 -0
  2. package/dist/AddHighlightModel/GenomeMouseoverHighlight.d.ts +6 -0
  3. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js +23 -0
  4. package/dist/AddHighlightModel/GenomeMouseoverHighlight.js.map +1 -0
  5. package/dist/AddHighlightModel/Highlight.d.ts +10 -0
  6. package/dist/AddHighlightModel/Highlight.js +15 -0
  7. package/dist/AddHighlightModel/Highlight.js.map +1 -0
  8. package/dist/AddHighlightModel/HighlightComponents.d.ts +7 -0
  9. package/dist/AddHighlightModel/HighlightComponents.js +11 -0
  10. package/dist/AddHighlightModel/HighlightComponents.js.map +1 -0
  11. package/dist/AddHighlightModel/MsaToGenomeHighlight.d.ts +6 -0
  12. package/dist/AddHighlightModel/MsaToGenomeHighlight.js +15 -0
  13. package/dist/AddHighlightModel/MsaToGenomeHighlight.js.map +1 -0
  14. package/dist/AddHighlightModel/index.d.ts +2 -0
  15. package/dist/AddHighlightModel/index.js +19 -0
  16. package/dist/AddHighlightModel/index.js.map +1 -0
  17. package/dist/AddHighlightModel/util.d.ts +9 -0
  18. package/dist/AddHighlightModel/util.js +14 -0
  19. package/dist/AddHighlightModel/util.js.map +1 -0
  20. package/dist/LaunchTView/align.d.ts +20 -0
  21. package/dist/LaunchTView/align.js +121 -0
  22. package/dist/LaunchTView/align.js.map +1 -0
  23. package/dist/LaunchTView/components/LaunchTViewDialog.d.ts +6 -0
  24. package/dist/LaunchTView/components/LaunchTViewDialog.js +87 -0
  25. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +1 -0
  26. package/dist/LaunchTView/fetchTviewPlan.d.ts +51 -0
  27. package/dist/LaunchTView/fetchTviewPlan.js +43 -0
  28. package/dist/LaunchTView/fetchTviewPlan.js.map +1 -0
  29. package/dist/LaunchTView/index.d.ts +2 -0
  30. package/dist/LaunchTView/index.js +41 -0
  31. package/dist/LaunchTView/index.js.map +1 -0
  32. package/dist/LaunchTView/limits.d.ts +2 -0
  33. package/dist/LaunchTView/limits.js +8 -0
  34. package/dist/LaunchTView/limits.js.map +1 -0
  35. package/dist/LaunchTView/tview.d.ts +95 -0
  36. package/dist/LaunchTView/tview.js +191 -0
  37. package/dist/LaunchTView/tview.js.map +1 -0
  38. package/dist/LaunchTView/useTviewMsa.d.ts +14 -0
  39. package/dist/LaunchTView/useTviewMsa.js +20 -0
  40. package/dist/LaunchTView/useTviewMsa.js.map +1 -0
  41. package/dist/TViewPanel/components/TViewPanel.d.ts +6 -0
  42. package/dist/TViewPanel/components/TViewPanel.js +11 -0
  43. package/dist/TViewPanel/components/TViewPanel.js.map +1 -0
  44. package/dist/TViewPanel/coords.d.ts +17 -0
  45. package/dist/TViewPanel/coords.js +36 -0
  46. package/dist/TViewPanel/coords.js.map +1 -0
  47. package/dist/TViewPanel/index.d.ts +2 -0
  48. package/dist/TViewPanel/index.js +15 -0
  49. package/dist/TViewPanel/index.js.map +1 -0
  50. package/dist/TViewPanel/model.d.ts +1028 -0
  51. package/dist/TViewPanel/model.js +246 -0
  52. package/dist/TViewPanel/model.js.map +1 -0
  53. package/dist/config.json +8 -0
  54. package/dist/index.d.ts +8 -0
  55. package/dist/index.js +19 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/jbrowse-plugin-tview.umd.production.min.js +104 -0
  58. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +7 -0
  59. package/dist/version.d.ts +1 -0
  60. package/dist/version.js +2 -0
  61. package/dist/version.js.map +1 -0
  62. package/package.json +76 -0
  63. package/src/AddHighlightModel/GenomeMouseoverHighlight.tsx +46 -0
  64. package/src/AddHighlightModel/Highlight.tsx +35 -0
  65. package/src/AddHighlightModel/HighlightComponents.tsx +25 -0
  66. package/src/AddHighlightModel/MsaToGenomeHighlight.tsx +31 -0
  67. package/src/AddHighlightModel/index.tsx +28 -0
  68. package/src/AddHighlightModel/util.ts +14 -0
  69. package/src/LaunchTView/align.ts +154 -0
  70. package/src/LaunchTView/components/LaunchTViewDialog.tsx +129 -0
  71. package/src/LaunchTView/fetchTviewPlan.ts +95 -0
  72. package/src/LaunchTView/index.ts +53 -0
  73. package/src/LaunchTView/limits.ts +8 -0
  74. package/src/LaunchTView/tview.ts +272 -0
  75. package/src/LaunchTView/useTviewMsa.ts +36 -0
  76. package/src/TViewPanel/components/TViewPanel.tsx +20 -0
  77. package/src/TViewPanel/coords.ts +43 -0
  78. package/src/TViewPanel/index.ts +20 -0
  79. package/src/TViewPanel/model.ts +289 -0
  80. package/src/index.ts +21 -0
  81. package/src/version.ts +1 -0
@@ -0,0 +1,53 @@
1
+ import { getContainingTrack, getSession } from '@jbrowse/core/util'
2
+ import AddIcon from '@mui/icons-material/Add'
3
+
4
+ import LaunchTViewDialog from './components/LaunchTViewDialog'
5
+
6
+ import type PluginManager from '@jbrowse/core/PluginManager'
7
+ import type { PluggableElementType } from '@jbrowse/core/pluggableElementTypes'
8
+ import type DisplayType from '@jbrowse/core/pluggableElementTypes/DisplayType'
9
+ import type { MenuItem } from '@jbrowse/core/ui'
10
+ import type { IAnyModelType } from '@jbrowse/mobx-state-tree'
11
+
12
+ function isDisplay(elt: { name: string }): elt is DisplayType {
13
+ return elt.name === 'LinearAlignmentsDisplay'
14
+ }
15
+
16
+ function extendStateModel(stateModel: IAnyModelType) {
17
+ return stateModel.views((self: { trackMenuItems: () => MenuItem[] }) => {
18
+ const superTrackMenuItems = self.trackMenuItems
19
+ return {
20
+ trackMenuItems() {
21
+ return [
22
+ ...superTrackMenuItems(),
23
+ {
24
+ label: 'Launch tview for visible region',
25
+ icon: AddIcon,
26
+ onClick: () => {
27
+ const track = getContainingTrack(self)
28
+ getSession(track).queueDialog(handleClose => [
29
+ LaunchTViewDialog,
30
+ {
31
+ model: track,
32
+ handleClose,
33
+ },
34
+ ])
35
+ },
36
+ },
37
+ ]
38
+ },
39
+ }
40
+ })
41
+ }
42
+
43
+ export default function LaunchTViewF(pluginManager: PluginManager) {
44
+ pluginManager.addToExtensionPoint(
45
+ 'Core-extendPluggableElement',
46
+ (elt: PluggableElementType) => {
47
+ if (isDisplay(elt)) {
48
+ elt.stateModel = extendStateModel(elt.stateModel)
49
+ }
50
+ return elt
51
+ },
52
+ )
53
+ }
@@ -0,0 +1,8 @@
1
+ // a tview row is one column per base, so a wide region produces an alignment
2
+ // too large to be useful (and slow to lay out)
3
+ export const MAX_BP = 20_000
4
+
5
+ // every read gets its own full-width row, so depth multiplies width. The
6
+ // alignment is held as one string for the life of the view, and MAX_BP alone
7
+ // does not bound it: 8k reads over 20kb is ~160M cells.
8
+ export const MAX_CELLS = 25_000_000
@@ -0,0 +1,272 @@
1
+ import { alignInsertions } from './align'
2
+
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 = '.'
20
+
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
+ }
69
+
70
+ /**
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.
74
+ */
75
+ export function clipInsertions(
76
+ reads: ReadLayout[],
77
+ start: number,
78
+ end: number,
79
+ ) {
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
+ const byPos = new Map<number, string[]>()
95
+ for (const read of reads) {
96
+ for (const [pos, ins] of read.insertions) {
97
+ const seqs = byPos.get(pos)
98
+ if (seqs) {
99
+ seqs.push(ins)
100
+ } else {
101
+ byPos.set(pos, [ins])
102
+ }
103
+ }
104
+ }
105
+ const gapped = new Map(
106
+ [...byPos].map(([pos, seqs]) => [pos, alignInsertions(seqs)] as const),
107
+ )
108
+ return reads.map(read => ({
109
+ ...read,
110
+ insertions: new Map(
111
+ [...read.insertions].map(([pos, ins]) => [
112
+ pos,
113
+ gapped.get(pos)?.get(ins) ?? ins,
114
+ ]),
115
+ ),
116
+ }))
117
+ }
118
+
119
+ /** widest insertion any read has at each reference position (sparse) */
120
+ export function maxInsertionWidths(reads: ReadLayout[]) {
121
+ const ret = new Map<number, number>()
122
+ for (const read of reads) {
123
+ for (const [pos, ins] of read.insertions) {
124
+ ret.set(pos, Math.max(ret.get(pos) ?? 0, ins.length))
125
+ }
126
+ }
127
+ return ret
128
+ }
129
+
130
+ export interface ColumnLayout {
131
+ start: number
132
+ end: number
133
+ insWidths: Map<number, number>
134
+ /**
135
+ * column index at which each reference position's columns begin, for
136
+ * start..end inclusive
137
+ */
138
+ offsets: number[]
139
+ totalColumns: number
140
+ }
141
+
142
+ /**
143
+ * Each reference position contributes its insertion columns (widest across all
144
+ * reads) followed by one reference column, so every row comes out the same
145
+ * length and stays aligned.
146
+ */
147
+ export function buildColumnLayout(
148
+ start: number,
149
+ end: number,
150
+ insWidths: Map<number, number>,
151
+ ): ColumnLayout {
152
+ const offsets = [0]
153
+ let col = 0
154
+ for (let pos = start; pos < end; pos++) {
155
+ col += (insWidths.get(pos) ?? 0) + 1
156
+ offsets.push(col)
157
+ }
158
+ return { start, end, insWidths, offsets, totalColumns: col }
159
+ }
160
+
161
+ /**
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.
165
+ */
166
+ export function renderRow(read: ReadLayout, layout: ColumnLayout) {
167
+ const { start, end, insWidths, offsets, totalColumns } = layout
168
+ // 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)
171
+
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
188
+ }
189
+ ret += ABSENT.repeat(totalColumns - offsets[to - start]!)
190
+ } else {
191
+ ret = ABSENT.repeat(totalColumns)
192
+ }
193
+ return ret
194
+ }
195
+
196
+ function mateSuffix(flags: number | undefined) {
197
+ return flags === undefined || !(flags & 1) ? '' : flags & 64 ? '/1' : '/2'
198
+ }
199
+
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
+ })
209
+ }
210
+
211
+ export interface TviewPlan {
212
+ reads: ReadLayout[]
213
+ layout: ColumnLayout
214
+ insertionWidths: [number, number][]
215
+ region: { refName: string; start: number; end: number }
216
+ /** rows x columns, i.e. how big the alignment renderTviewMsa builds will be */
217
+ cellCount: number
218
+ }
219
+
220
+ /**
221
+ * Works out the shape of the alignment without materializing it. Everything
222
+ * here is proportional to the sequence data, unlike the render, which is
223
+ * proportional to rows x columns and can be far larger.
224
+ */
225
+ export function planTviewMsa({
226
+ features,
227
+ refName,
228
+ start,
229
+ 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
+ ),
243
+ )
244
+ const insWidths = maxInsertionWidths(reads)
245
+ const layout = buildColumnLayout(start, end, insWidths)
246
+
247
+ return {
248
+ reads,
249
+ layout,
250
+ insertionWidths: [...insWidths.entries()].sort((a, b) => a[0] - b[0]),
251
+ region: { refName, start, end },
252
+ cellCount: reads.length * layout.totalColumns,
253
+ }
254
+ }
255
+
256
+ export function renderTviewMsa({ reads, layout }: TviewPlan) {
257
+ return reads.map(r => `>${r.name}\n${renderRow(r, layout)}\n`).join('')
258
+ }
259
+
260
+ export function buildTviewMsa(args: {
261
+ features: AlignmentFeature[]
262
+ refName: string
263
+ start: number
264
+ end: number
265
+ }) {
266
+ const plan = planTviewMsa(args)
267
+ return {
268
+ msa: renderTviewMsa(plan),
269
+ insertionWidths: plan.insertionWidths,
270
+ region: plan.region,
271
+ }
272
+ }
@@ -0,0 +1,36 @@
1
+ import { assembleLocString, getSession } from '@jbrowse/core/util'
2
+ import useSWR from 'swr'
3
+
4
+ import { fetchTviewPlan, sourceFromTrack } from './fetchTviewPlan'
5
+
6
+ import type { FetchRegion } from './fetchTviewPlan'
7
+ import type { AbstractTrackModel } from '@jbrowse/core/util'
8
+
9
+ const staticSwrConfig = {
10
+ revalidateOnFocus: false,
11
+ revalidateOnReconnect: false,
12
+ revalidateIfStale: false,
13
+ shouldRetryOnError: false,
14
+ }
15
+
16
+ export function useTviewMsa({
17
+ model,
18
+ region,
19
+ }: {
20
+ model: AbstractTrackModel
21
+ region?: FetchRegion
22
+ }) {
23
+ // the key carries the region so the fetcher receives it already narrowed
24
+ return useSWR(
25
+ region
26
+ ? { tag: 'tview', loc: assembleLocString(region), id: model.id, region }
27
+ : null,
28
+ ({ region }) =>
29
+ fetchTviewPlan({
30
+ session: getSession(model),
31
+ source: sourceFromTrack(model),
32
+ region,
33
+ }),
34
+ staticSwrConfig,
35
+ )
36
+ }
@@ -0,0 +1,20 @@
1
+ import React from 'react'
2
+
3
+ import { observer } from 'mobx-react'
4
+ import { MSAView } from 'react-msaview'
5
+
6
+ import type { JBrowsePluginTViewModel } from '../model'
7
+ import type { MsaViewModel } from 'react-msaview'
8
+
9
+ const TViewPanel = observer(function TViewPanel2({
10
+ model,
11
+ }: {
12
+ model: JBrowsePluginTViewModel
13
+ }) {
14
+ // react-msaview types its model prop with type: 'MsaView' baked in, but a
15
+ // JBrowse view model's `type` must equal its registered view type name. That
16
+ // literal is the only difference, and the MSA renderer never reads it.
17
+ return <MSAView model={model as unknown as MsaViewModel} />
18
+ })
19
+
20
+ export default TViewPanel
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Inverse of the column layout built by buildTviewMsa: the alignment emits each
3
+ * reference position's insertion columns followed by its reference column, so a
4
+ * flat column -> reference position array recovers the mapping.
5
+ */
6
+ export function buildColumnToRefPos({
7
+ start,
8
+ end,
9
+ insertionWidths,
10
+ }: {
11
+ start: number
12
+ end: number
13
+ insertionWidths: [number, number][]
14
+ }) {
15
+ const widths = new Map(insertionWidths)
16
+ const ret: number[] = []
17
+ for (let pos = start; pos < end; pos++) {
18
+ const width = widths.get(pos) ?? 0
19
+ for (let i = 0; i < width; i++) {
20
+ ret.push(pos)
21
+ }
22
+ ret.push(pos)
23
+ }
24
+ return ret
25
+ }
26
+
27
+ /**
28
+ * react-msaview drops all-gap columns from the rendering when hideGaps is
29
+ * effective (a row is collapsed, or allowedGappyness < 100), so the column
30
+ * index its mouse handlers report counts only visible columns. Expand it back
31
+ * to an index into the full alignment. `blanks` is ascending.
32
+ */
33
+ export function renderedColToMsaCol(blanks: number[], col: number) {
34
+ let ret = col
35
+ for (const blank of blanks) {
36
+ if (blank <= ret) {
37
+ ret++
38
+ } else {
39
+ break
40
+ }
41
+ }
42
+ return ret
43
+ }
@@ -0,0 +1,20 @@
1
+ import { lazy } from 'react'
2
+
3
+ import ViewType from '@jbrowse/core/pluggableElementTypes/ViewType'
4
+
5
+ import stateModelFactory from './model'
6
+
7
+ import type PluginManager from '@jbrowse/core/PluginManager'
8
+
9
+ // lazies
10
+ const TViewPanel = lazy(() => import('./components/TViewPanel'))
11
+
12
+ export default function TViewF(pluginManager: PluginManager) {
13
+ pluginManager.addViewType(() => {
14
+ return new ViewType({
15
+ name: 'TView',
16
+ stateModel: stateModelFactory(),
17
+ ReactComponent: TViewPanel,
18
+ })
19
+ })
20
+ }