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
@@ -1,9 +1,5 @@
1
- import { readConfObject } from '@jbrowse/core/configuration'
2
-
3
1
  import { MAX_CELLS } from './limits'
4
2
 
5
- import type { TviewPlanResult } from './TviewGetPlanRpc'
6
- import type { AnyConfigurationModel } from '@jbrowse/core/configuration'
7
3
  import type { AbstractSessionModel } from '@jbrowse/core/util'
8
4
 
9
5
  /** the RPC needs assemblyName to resolve refNameAliases for the file */
@@ -16,55 +12,11 @@ export interface FetchRegion {
16
12
 
17
13
  /** one track's worth of rows, and the name they are grouped under */
18
14
  export interface TviewSource {
19
- adapterConfig: unknown
20
- /** the label rows from this file carry; omitted when there is only one */
21
- sample?: string
15
+ adapterConfig: Record<string, unknown>
16
+ sample: string
22
17
  trackId: string
23
18
  }
24
19
 
25
- /**
26
- * The trackId -> config index, whose shape has changed across hosts still in
27
- * the wild: v4.0.0 exposes a `tracksById` getter, v4.1-v4.3 a `getTracksById()`
28
- * method, and newer cores a per-id reactive `getTrackById(id)` (with
29
- * `getTracksById()` kept but deprecated). All three resolve connection and
30
- * assembly-sequence tracks; the `tracks` scan is a last resort because it does
31
- * not, and it subscribes the caller to every track.
32
- */
33
- export interface SessionTrackLookup {
34
- tracks: AnyConfigurationModel[]
35
- getTrackById?: (id: string) => AnyConfigurationModel | undefined
36
- getTracksById?: () => Record<string, AnyConfigurationModel>
37
- tracksById?: Record<string, AnyConfigurationModel>
38
- }
39
-
40
- export function findTrackConf(session: SessionTrackLookup, trackId: string) {
41
- return session.getTrackById
42
- ? session.getTrackById(trackId)
43
- : session.getTracksById
44
- ? session.getTracksById()[trackId]
45
- : session.tracksById
46
- ? session.tracksById[trackId]
47
- : session.tracks.find(t => readConfObject(t, 'trackId') === trackId)
48
- }
49
-
50
- /**
51
- * The assembly's own sequence adapter, which is what makes the reference a row
52
- * and, through it, makes an array an interval rather than an insertion. An
53
- * assembly that cannot supply one still works: the alignment is then reads only
54
- * and no array is reported, which is the pre-reference behaviour.
55
- */
56
- export function sequenceAdapterConfig(
57
- session: AbstractSessionModel,
58
- assemblyName: string,
59
- ) {
60
- const assembly = session.assemblyManager.get(assemblyName)
61
- const conf = assembly?.configuration
62
- return conf
63
- ? (readConfObject(conf, ['sequence', 'adapter']) as
64
- Record<string, unknown> | undefined)
65
- : undefined
66
- }
67
-
68
20
  /**
69
21
  * One RPC per launch, however many files it draws from. The session id is
70
22
  * shared across the sources so the worker keeps one adapter cache for the view
@@ -75,21 +27,26 @@ export async function fetchTviewPlan({
75
27
  sources,
76
28
  region,
77
29
  maxCells = MAX_CELLS,
30
+ signal,
78
31
  }: {
79
32
  session: AbstractSessionModel
80
33
  sources: TviewSource[]
81
34
  region: FetchRegion
82
35
  maxCells?: number
36
+ signal?: AbortSignal
83
37
  }) {
84
38
  const rpcSessionId = `tview-${sources.map(s => s.trackId).join(',')}`
85
- return (await session.rpcManager.call(rpcSessionId, 'TviewGetPlan', {
86
- sessionId: rpcSessionId,
39
+ const assembly = session.assemblyManager.get(region.assemblyName)
40
+ return session.rpcManager.call(rpcSessionId, 'TviewGetPlan', {
87
41
  sources: sources.map(s => ({
88
42
  adapterConfig: s.adapterConfig,
89
43
  sample: s.sample,
90
44
  })),
91
- sequenceAdapterConfig: sequenceAdapterConfig(session, region.assemblyName),
45
+ assemblyName: region.assemblyName,
46
+ sequenceRefName:
47
+ assembly?.getSeqAdapterRefName(region.refName) ?? region.refName,
92
48
  region,
93
49
  maxCells,
94
- })) as TviewPlanResult
50
+ signal,
51
+ })
95
52
  }
@@ -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
+ }