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
@@ -1,39 +1,78 @@
1
- import { getContainingTrack, getSession } from '@jbrowse/core/util'
1
+ import { addViewMenuItems } from '@jbrowse/core/pluggableElementTypes'
2
+ import {
3
+ getContainingTrack,
4
+ getContainingView,
5
+ getSession,
6
+ } from '@jbrowse/core/util'
2
7
  import AddIcon from '@mui/icons-material/Add'
3
8
 
4
- import LaunchTViewDialog from './components/LaunchTViewDialog'
9
+ import {
10
+ alignmentsTrackIds,
11
+ isGenomeView,
12
+ launchTView,
13
+ regionLaunch,
14
+ } from './launch'
5
15
 
16
+ import type { RegionLaunch } from './launch'
6
17
  import type PluginManager from '@jbrowse/core/PluginManager'
7
18
  import type { PluggableElementType } from '@jbrowse/core/pluggableElementTypes'
8
19
  import type DisplayType from '@jbrowse/core/pluggableElementTypes/DisplayType'
9
20
  import type { MenuItem } from '@jbrowse/core/ui'
21
+ import type { AbstractSessionModel } from '@jbrowse/core/util'
10
22
  import type { IAnyModelType } from '@jbrowse/mobx-state-tree'
11
23
 
24
+ const VISIBLE_REGION_LABEL = 'Launch tview for visible region'
25
+ const SELECTION_LABEL = 'Tview of all alignments tracks'
26
+
12
27
  function isDisplay(elt: { name: string }): elt is DisplayType {
13
28
  return elt.name === 'LinearAlignmentsDisplay'
14
29
  }
15
30
 
31
+ function launchItem({
32
+ label,
33
+ launch,
34
+ session,
35
+ tracks,
36
+ connectedViewId,
37
+ }: {
38
+ label: string
39
+ launch: RegionLaunch
40
+ session: AbstractSessionModel
41
+ tracks: string[]
42
+ connectedViewId: string
43
+ }): MenuItem {
44
+ return {
45
+ label,
46
+ icon: AddIcon,
47
+ disabled: launch.reason !== undefined,
48
+ subLabel: launch.reason,
49
+ onClick: () => {
50
+ if (launch.reason === undefined) {
51
+ launchTView(session, { ...launch, tracks, connectedViewId })
52
+ }
53
+ },
54
+ }
55
+ }
56
+
16
57
  function extendStateModel(stateModel: IAnyModelType) {
17
58
  return stateModel.views((self: { trackMenuItems: () => MenuItem[] }) => {
18
59
  const superTrackMenuItems = self.trackMenuItems
19
60
  return {
20
61
  trackMenuItems() {
62
+ const session = getSession(self)
63
+ const view = getContainingView(self)
64
+ const track = getContainingTrack(self)
21
65
  return [
22
66
  ...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
- },
67
+ launchItem({
68
+ label: VISIBLE_REGION_LABEL,
69
+ launch: isGenomeView(view)
70
+ ? regionLaunch(session, view.visibleWholeBaseRegions)
71
+ : { reason: 'Not in a linear genome view' },
72
+ session,
73
+ tracks: [track.configuration.trackId],
74
+ connectedViewId: view.id,
75
+ }),
37
76
  ]
38
77
  },
39
78
  }
@@ -50,4 +89,23 @@ export default function LaunchTViewF(pluginManager: PluginManager) {
50
89
  return elt
51
90
  },
52
91
  )
92
+
93
+ addViewMenuItems(pluginManager, 'LinearGenomeView', {
94
+ menu: 'rubberBandLaunchMenuItems',
95
+ items: self => {
96
+ const tracks = alignmentsTrackIds(self.tracks)
97
+ return tracks.length
98
+ ? launchItem({
99
+ label: SELECTION_LABEL,
100
+ launch: regionLaunch(
101
+ getSession(self),
102
+ self.getSelectedRegions(self.leftOffset, self.rightOffset),
103
+ ),
104
+ session: getSession(self),
105
+ tracks,
106
+ connectedViewId: self.id,
107
+ })
108
+ : undefined
109
+ },
110
+ })
53
111
  }
@@ -0,0 +1,98 @@
1
+ import { assembleLocString } from '@jbrowse/core/util'
2
+
3
+ import { checkRegion } from '../TViewPanel/init'
4
+
5
+ import type { LocAssembly, TviewTrackInit } from '../TViewPanel/init'
6
+ import type { AbstractSessionModel } from '@jbrowse/core/util'
7
+
8
+ export interface WholeBaseRegion {
9
+ assemblyName: string
10
+ refName: string
11
+ start: number
12
+ end: number
13
+ }
14
+
15
+ export interface TrackLike {
16
+ configuration: { trackId: string }
17
+ displays: readonly { type: string }[]
18
+ }
19
+
20
+ export interface GenomeView {
21
+ id: string
22
+ tracks: readonly TrackLike[]
23
+ visibleWholeBaseRegions: WholeBaseRegion[]
24
+ }
25
+
26
+ export interface AssemblySource {
27
+ assemblyManager: {
28
+ get: (name: string) => (LocAssembly & { initialized: boolean }) | undefined
29
+ }
30
+ }
31
+
32
+ export interface TViewLaunch {
33
+ assembly: string
34
+ loc: string
35
+ tracks: TviewTrackInit[]
36
+ connectedViewId?: string
37
+ }
38
+
39
+ export type RegionLaunch =
40
+ { assembly: string; loc: string; reason?: undefined } | { reason: string }
41
+
42
+ export function isGenomeView(view: object): view is GenomeView {
43
+ return 'visibleWholeBaseRegions' in view && 'tracks' in view
44
+ }
45
+
46
+ export function alignmentsTrackIds(tracks: readonly TrackLike[]) {
47
+ return tracks
48
+ .filter(track =>
49
+ track.displays.some(d => d.type === 'LinearAlignmentsDisplay'),
50
+ )
51
+ .map(track => track.configuration.trackId)
52
+ }
53
+
54
+ /**
55
+ * The locus a tview over `regions` would show, or why there is none. The width
56
+ * and contig rules are {@link checkRegion}'s, so a menu offers exactly what the
57
+ * view would then agree to load.
58
+ */
59
+ export function regionLaunch(
60
+ session: AssemblySource,
61
+ regions: readonly WholeBaseRegion[],
62
+ ): RegionLaunch {
63
+ const [region] = regions
64
+ const assembly = region
65
+ ? session.assemblyManager.get(region.assemblyName)
66
+ : undefined
67
+ const loc = region
68
+ ? assembleLocString({
69
+ refName: region.refName,
70
+ start: region.start,
71
+ end: region.end,
72
+ })
73
+ : ''
74
+ const check = assembly?.initialized ? checkRegion(assembly, loc) : undefined
75
+ return !region
76
+ ? { reason: 'No region is in view' }
77
+ : regions.length > 1
78
+ ? { reason: 'Spans more than one region' }
79
+ : !check
80
+ ? { reason: `Assembly ${region.assemblyName} is not loaded` }
81
+ : check.error !== undefined
82
+ ? { reason: check.error }
83
+ : { assembly: region.assemblyName, loc }
84
+ }
85
+
86
+ export function launchTView(
87
+ session: Pick<AbstractSessionModel, 'addView'>,
88
+ { assembly, loc, tracks, connectedViewId }: TViewLaunch,
89
+ viewProps: Record<string, unknown> = {},
90
+ ) {
91
+ return session.addView('TView', {
92
+ displayName: loc,
93
+ connectedViewId,
94
+ ...viewProps,
95
+ type: 'TView',
96
+ init: { assembly, loc, tracks },
97
+ })
98
+ }
@@ -1,16 +1,14 @@
1
- import { initKeys } from '../TViewPanel/init'
1
+ import { launchTView } from './launch'
2
2
 
3
- import type { TviewInit } from '../TViewPanel/init'
3
+ import type { TviewTrackInit } from '../TViewPanel/init'
4
4
  import type PluginManager from '@jbrowse/core/PluginManager'
5
5
  import type { AbstractSessionModel } from '@jbrowse/core/util'
6
6
 
7
7
  /**
8
8
  * `LaunchView-TView`, so a session spec URL can open one.
9
9
  *
10
- * The two ways of writing a view are not the same shape, and JBrowse's spec
11
- * loader says so out loud: a spec view is **flat arguments** to this launcher,
12
- * while a config or defaultSession view is MST state, where anything needing
13
- * resolution on load lives under the view's own `init`. So the spec
10
+ * A spec view is flat arguments to this launcher, while a config or
11
+ * defaultSession view is MST state with the locus under `init`, so the spec
14
12
  *
15
13
  * { type: 'TView', assembly: 'hg19', loc: 'chrX:1..2', tracks: ['HG002'] }
16
14
  *
@@ -18,32 +16,42 @@ import type { AbstractSessionModel } from '@jbrowse/core/util'
18
16
  *
19
17
  * { type: 'TView', init: { assembly: 'hg19', loc: '…', tracks: […] } }
20
18
  *
21
- * are the same view, and this is the one line between them. Splitting on
22
- * `initKeys` rather than listing the pass-through props means every react-msaview
23
- * view prop — colWidth, rowHeight, colorSchemeName, the ones added next — rides
24
- * along without being enumerated here.
19
+ * are the same view. Every other key is passed through as a view prop.
25
20
  */
26
21
  export type LaunchTViewArgs = { session: AbstractSessionModel } & Record<
27
22
  string,
28
23
  unknown
29
24
  >
30
25
 
26
+ function isTrackInit(entry: unknown): entry is TviewTrackInit {
27
+ return (
28
+ typeof entry === 'string' ||
29
+ (typeof entry === 'object' &&
30
+ entry !== null &&
31
+ 'trackId' in entry &&
32
+ typeof entry.trackId === 'string' &&
33
+ (!('sample' in entry) || typeof entry.sample === 'string'))
34
+ )
35
+ }
36
+
31
37
  export default function LaunchTViewF(pluginManager: PluginManager) {
32
38
  /** #extensionPoint LaunchView-TView | async | Programmatically launch a tview */
33
39
  pluginManager.addToExtensionPoint(
34
40
  'LaunchView-TView',
35
41
  (args: LaunchTViewArgs) => {
36
- const { session, ...spec } = args
37
- const init: Record<string, unknown> = {}
38
- const viewProps: Record<string, unknown> = {}
39
- for (const [key, value] of Object.entries(spec)) {
40
- ;(initKeys.has(key) ? init : viewProps)[key] = value
42
+ const { session, assembly, loc, tracks, ...viewProps } = args
43
+ if (
44
+ typeof assembly === 'string' &&
45
+ typeof loc === 'string' &&
46
+ Array.isArray(tracks) &&
47
+ tracks.every(isTrackInit)
48
+ ) {
49
+ launchTView(session, { assembly, loc, tracks }, viewProps)
50
+ } else {
51
+ throw new Error(
52
+ 'A TView spec needs an assembly name, a loc string and a tracks array of trackIds',
53
+ )
41
54
  }
42
- session.addView('TView', {
43
- type: 'TView',
44
- ...viewProps,
45
- init: init as unknown as TviewInit,
46
- })
47
55
  return args
48
56
  },
49
57
  )
@@ -0,0 +1,200 @@
1
+ import {
2
+ getModPositions,
3
+ getModProbabilityBytes,
4
+ getModTag,
5
+ modProbAt,
6
+ } from '@jbrowse/modifications-utils'
7
+
8
+ import { GAPS, queryIndexAt } from './readLayout'
9
+ import { rowSpan } from './tview'
10
+
11
+ import type { ReadLayout } from './readLayout'
12
+ import type { TviewPlan } from './tview'
13
+ import type { Feature } from '@jbrowse/core/util'
14
+
15
+ /**
16
+ * The most probable call on each modified base, as parallel arrays rather than
17
+ * one object per call to keep the worker's reply small: the row it is on, the
18
+ * 1-based index into that row's ungapped letters, its type and its ML byte.
19
+ */
20
+ export interface TviewModifications {
21
+ rows: string[]
22
+ /** the MM codes, `m`, `h`, `a` or a ChEBI number */
23
+ types: string[]
24
+ row: Uint32Array
25
+ residue: Uint32Array
26
+ type: Uint8Array
27
+ prob: Uint8Array
28
+ /** calls left out for being past the cap, the least probable first */
29
+ dropped: number
30
+ /** rows with calls whose letters are not one run of the read's sequence */
31
+ unplaced: number
32
+ }
33
+
34
+ /**
35
+ * Every call costs react-msaview on each load and each change of the row table,
36
+ * with no spatial index to skip the ones off screen: over 916 rows that was
37
+ * +90ms at 50k calls, +160ms at 100k and +415ms at 200k. A 20kb read carries
38
+ * ~200 CpG calls at the genome's average density, so 50k is ~250 reads across
39
+ * the widest window; 6mA called on every A does not fit.
40
+ */
41
+ export const MAX_MODIFICATION_CALLS = 50_000
42
+
43
+ /**
44
+ * The query index of a row's first letter, when its letters are one unbroken
45
+ * run of the read's own sequence. They are, unless the layout moved bases of
46
+ * the read past each other (an insertion re-filed into an array without an
47
+ * exact rewrite) or left some out (an array block the row has no allele for),
48
+ * and a call projected onto such a row would land on the wrong base.
49
+ */
50
+ export function rowInRead(
51
+ read: ReadLayout,
52
+ row: string,
53
+ layout: TviewPlan['layout'],
54
+ ) {
55
+ const { query } = read
56
+ const first = query
57
+ ? queryIndexAt(read, query, rowSpan(read, layout).from)
58
+ : 0
59
+ const letters = row.replaceAll(GAPS, '')
60
+ return query?.seq.startsWith(letters, first)
61
+ ? { seq: query.seq, first, length: letters.length }
62
+ : undefined
63
+ }
64
+
65
+ /**
66
+ * The most probable call at each base of `seq` in [from, from + length), packed
67
+ * as `(type + 1) << 8 | ML byte`, 0 where nothing is called.
68
+ */
69
+ function bestCalls(
70
+ feature: Feature,
71
+ mm: string,
72
+ { seq, first: from, length }: { seq: string; first: number; length: number },
73
+ typeIndex: (type: string) => number,
74
+ ) {
75
+ const strand = feature.get('strand') ?? 0
76
+ const bytes = getModProbabilityBytes(feature)
77
+ const ml = bytes ? Array.from(bytes) : undefined
78
+ const best = new Uint16Array(length)
79
+ for (const mod of getModPositions(mm, seq, strand, from, from + length)) {
80
+ const tag = (typeIndex(mod.type) + 1) << 8
81
+ const { positions, probStart, probStride } = mod
82
+ for (const [idx, pos] of positions.entries()) {
83
+ const at = pos - from
84
+ const prob = modProbAt(
85
+ ml,
86
+ probStart,
87
+ probStride,
88
+ strand === -1,
89
+ idx,
90
+ positions.length,
91
+ )
92
+ const prev = best[at]
93
+ if (prev !== undefined && (prev === 0 || (prev & 0xff) < prob)) {
94
+ best[at] = tag | prob
95
+ }
96
+ }
97
+ }
98
+ return best
99
+ }
100
+
101
+ /**
102
+ * The lowest probability byte whose calls all fit in `keep` together with every
103
+ * more probable one, and how many calls of the byte below it still fit.
104
+ */
105
+ function keepThreshold(probs: number[], keep: number) {
106
+ const counts = new Array<number>(256).fill(0)
107
+ for (const p of probs) {
108
+ counts[p]!++
109
+ }
110
+ let threshold = 256
111
+ let kept = 0
112
+ while (threshold > 0 && kept + counts[threshold - 1]! <= keep) {
113
+ threshold--
114
+ kept += counts[threshold]!
115
+ }
116
+ return { threshold, room: keep - kept }
117
+ }
118
+
119
+ interface ProjectArgs {
120
+ features: Feature[]
121
+ plan: TviewPlan
122
+ /** each read's rendered row, parallel to `plan.reads` */
123
+ rows: string[]
124
+ maxCalls?: number
125
+ }
126
+
127
+ function projectModifications(
128
+ tags: (string | undefined)[],
129
+ { features, plan, rows, maxCalls = MAX_MODIFICATION_CALLS }: ProjectArgs,
130
+ ) {
131
+ const rowOf = new Map(
132
+ plan.reads.map((read, i) => [read.name, { read, row: rows[i]! }]),
133
+ )
134
+ const types: string[] = []
135
+ const typeIndex = (type: string) => {
136
+ const i = types.indexOf(type)
137
+ return i >= 0 ? i : types.push(type) - 1
138
+ }
139
+ const callRows: string[] = []
140
+ const row: number[] = []
141
+ const residue: number[] = []
142
+ const type: number[] = []
143
+ const prob: number[] = []
144
+ let unplaced = 0
145
+ for (const [i, mm] of tags.entries()) {
146
+ const rendered = mm ? rowOf.get(plan.featureNames[i]!) : undefined
147
+ if (mm && rendered) {
148
+ const slice = rowInRead(rendered.read, rendered.row, plan.layout)
149
+ if (slice) {
150
+ const before = row.length
151
+ for (const [at, packed] of bestCalls(
152
+ features[i]!,
153
+ mm,
154
+ slice,
155
+ typeIndex,
156
+ ).entries()) {
157
+ if (packed) {
158
+ row.push(callRows.length)
159
+ residue.push(at + 1)
160
+ type.push((packed >> 8) - 1)
161
+ prob.push(packed & 0xff)
162
+ }
163
+ }
164
+ if (row.length > before) {
165
+ callRows.push(rendered.read.name)
166
+ }
167
+ } else {
168
+ unplaced++
169
+ }
170
+ }
171
+ }
172
+ const { threshold, room } = keepThreshold(prob, maxCalls)
173
+ let tiesLeft = room
174
+ const keep = prob.map(p =>
175
+ p >= threshold ? true : p === threshold - 1 && tiesLeft-- > 0,
176
+ )
177
+ const kept = (values: number[]) => values.filter((_, i) => keep[i])
178
+ return {
179
+ rows: callRows,
180
+ types,
181
+ row: Uint32Array.from(kept(row)),
182
+ residue: Uint32Array.from(kept(residue)),
183
+ type: Uint8Array.from(kept(type)),
184
+ prob: Uint8Array.from(kept(prob)),
185
+ dropped: keep.filter(k => !k).length,
186
+ unplaced,
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Each modified base the rendered rows show, as an index into its row's
192
+ * letters. Undefined when no read in the window has an MM tag, so a file
193
+ * without modifications pays for one tag lookup per read.
194
+ */
195
+ export function planModifications(args: ProjectArgs) {
196
+ const tags = args.features.map(f => getModTag(f))
197
+ return tags.some(t => t !== undefined)
198
+ ? projectModifications(tags, args)
199
+ : undefined
200
+ }
@@ -1,10 +1,10 @@
1
- import { newickSafe } from './sampleTree'
2
-
3
1
  /** the subset of an @jbrowse/core Feature that the layout reads */
4
2
  export interface AlignmentFeature {
5
- get: (key: string) => any
3
+ get: (key: string) => unknown
6
4
  }
7
5
 
6
+ const text = (value: unknown) => (typeof value === 'string' ? value : '')
7
+
8
8
  /**
9
9
  * Only '-' and '.' are treated as gaps by react-msaview (anything else counts
10
10
  * as a base in the conservation track and column stats), so the two of them
@@ -17,32 +17,36 @@ export interface AlignmentFeature {
17
17
  */
18
18
  export const SPANNED_GAP = '-'
19
19
  export const ABSENT = '.'
20
+ export const GAPS = /[-.]/g
20
21
 
21
22
  export interface ReadLayout {
22
23
  /**
23
- * Identity. Every per-row lookup is keyed by this — the array blocks, the
24
- * tree — so it is fixed once, here, and nothing downstream rewrites it.
24
+ * Identity, and the row's name in the alignment. Every per-row lookup is
25
+ * keyed by this — the array blocks, the row table — so it is fixed once,
26
+ * here, and nothing downstream rewrites it.
25
27
  */
26
28
  name: string
27
- /**
28
- * What the row is called on screen, when that is not just its name. Kept
29
- * apart from `name` because the copy-number label is added after the array
30
- * blocks are built and keyed: renaming in place instead left every labelled
31
- * row unable to find its own block, and the block fell back to gaps — a row
32
- * that silently loses its sequence while keeping its label.
33
- */
34
- label?: string
35
- /**
36
- * The sample the row belongs to, when several were loaded at once. Already
37
- * Newick-safe, and the same string the row's own name is prefixed with, so
38
- * the clade label and its leaves agree.
39
- */
29
+ /** the sample the row belongs to, as the caller named it */
40
30
  sample?: string
41
31
  start: number
42
32
  /** one char per reference position consumed: the aligned base, or a gap */
43
33
  refChars: string
44
34
  /** reference position -> bases inserted immediately before that position */
45
35
  insertions: Map<number, string>
36
+ /** where the row's bases came from in the read, for a row parsed from one */
37
+ query?: ReadQuery
38
+ }
39
+
40
+ /**
41
+ * The read's own sequence, SEQ as the file stores it, and enough of its CIGAR
42
+ * to find any base of the row in it: the query index of the first base at
43
+ * `start`, and how many bases the aligner inserted before each position. Kept
44
+ * as parsed, since the layout later moves and drops insertions.
45
+ */
46
+ export interface ReadQuery {
47
+ seq: string
48
+ offset: number
49
+ inserted: Map<number, number>
46
50
  }
47
51
 
48
52
  const cigarRegex = /([MIDNSHPX=])/
@@ -58,16 +62,21 @@ export function parseRead(
58
62
  name: string,
59
63
  sample?: string,
60
64
  ): ReadLayout {
61
- const seq = feature.get('seq') as string
62
- const ops = parseCigar(feature.get('CIGAR') as string)
63
- const start = feature.get('start')
65
+ const seq = text(feature.get('seq'))
66
+ const ops = parseCigar(text(feature.get('CIGAR')))
67
+ const start = Number(feature.get('start'))
64
68
  const insertions = new Map<number, string>()
69
+ const inserted = new Map<number, number>()
65
70
  let refChars = ''
66
71
  let seqOffset = 0
72
+ let offset: number | undefined
67
73
 
68
74
  for (let i = 0; i < ops.length; i += 2) {
69
75
  const len = +ops[i]!
70
76
  const op = ops[i + 1]!
77
+ if (op !== 'S' && op !== 'H' && op !== 'P') {
78
+ offset ??= seqOffset
79
+ }
71
80
  if (op === 'S') {
72
81
  seqOffset += len
73
82
  } else if (op === 'I') {
@@ -75,6 +84,7 @@ export function parseRead(
75
84
  const pos = start + refChars.length
76
85
  const prev = insertions.get(pos) ?? ''
77
86
  insertions.set(pos, prev + seq.slice(seqOffset, seqOffset + len))
87
+ inserted.set(pos, (inserted.get(pos) ?? 0) + len)
78
88
  seqOffset += len
79
89
  } else if (op === 'D') {
80
90
  refChars += SPANNED_GAP.repeat(len)
@@ -86,17 +96,33 @@ export function parseRead(
86
96
  }
87
97
  // H and P consume neither the read sequence nor the reference
88
98
  }
89
- // sanitized here, the same way getReadNames sanitizes the prefix it builds
90
- // from it, so the clade label and the leaves inside it are one string
91
99
  return {
92
100
  name,
93
- sample: sample === undefined ? undefined : newickSafe(sample),
101
+ sample,
94
102
  start,
95
103
  refChars,
96
104
  insertions,
105
+ query: { seq, offset: offset ?? seqOffset, inserted },
97
106
  }
98
107
  }
99
108
 
109
+ /**
110
+ * The query index of the first base a parsed read has at or after reference
111
+ * position `pos`, counting what it inserted at `pos` itself as coming first.
112
+ */
113
+ export function queryIndexAt(read: ReadLayout, query: ReadQuery, pos: number) {
114
+ const aligned = read.refChars
115
+ .slice(0, Math.max(0, pos - read.start))
116
+ .replaceAll(GAPS, '').length
117
+ let insertedBefore = 0
118
+ for (const [at, len] of query.inserted) {
119
+ if (at < pos) {
120
+ insertedBefore += len
121
+ }
122
+ }
123
+ return query.offset + aligned + insertedBefore
124
+ }
125
+
100
126
  /**
101
127
  * Reads are fetched by overlap, so they carry insertions on either side of the
102
128
  * region. Those get no columns and are never rendered, so dropping them keeps
@@ -120,26 +146,24 @@ function mateSuffix(flags: number | undefined) {
120
146
  }
121
147
 
122
148
  /**
123
- * MSA rows are keyed by name, so mates and duplicate names need disambiguating.
124
- * With several samples loaded at once the same read name can also arrive twice
125
- * from two files, which the sample prefix separates before the counter has to.
126
- *
127
- * The name is made Newick-safe here rather than where the tree is written,
128
- * because the tree names the same rows the FASTA does and the two have to agree
129
- * exactly. '|' separates the parts because ':' opens a branch length.
149
+ * MSA rows are keyed by name, and a FASTA defline names its row by the first
150
+ * whitespace-delimited word, dropping any later row whose word repeats. So a
151
+ * name loses its whitespace, mates are told apart by flag, and whatever still
152
+ * collides (the same read in two files, or a name in `reserved`) is numbered.
130
153
  */
131
154
  export function getReadNames(
132
155
  features: AlignmentFeature[],
133
- sampleOf?: (index: number) => string | undefined,
156
+ reserved: string[] = [],
134
157
  ) {
135
- const counts = new Map<string, number>()
136
- return features.map((f, i) => {
137
- const sample = sampleOf?.(i)
138
- const prefix = sample ? `${newickSafe(sample)}|` : ''
139
- const name = newickSafe(String(f.get('name')))
140
- const base = `${prefix}${name}${mateSuffix(f.get('flags'))}`
141
- const n = (counts.get(base) ?? 0) + 1
142
- counts.set(base, n)
143
- return n === 1 ? base : `${base}_${n}`
158
+ const taken = new Set(reserved)
159
+ return features.map(f => {
160
+ const flags = f.get('flags')
161
+ const base = `${String(f.get('name')).replaceAll(/\s+/g, '_')}${mateSuffix(typeof flags === 'number' ? flags : undefined)}`
162
+ let name = base
163
+ for (let n = 2; taken.has(name); n++) {
164
+ name = `${base}_${n}`
165
+ }
166
+ taken.add(name)
167
+ return name
144
168
  })
145
169
  }