jbrowse-plugin-tview 3.0.0 → 3.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.
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "3.0.0";
1
+ export declare const version = "3.1.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '3.0.0';
1
+ export const version = '3.1.0';
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.0.0",
2
+ "version": "3.1.0",
3
3
  "license": "MIT",
4
4
  "name": "jbrowse-plugin-tview",
5
5
  "repository": {
@@ -76,7 +76,7 @@
76
76
  "puppeteer": "^25.9.0",
77
77
  "react": "^19.2.8",
78
78
  "react-dom": "^19.2.8",
79
- "react-msaview": "^11.0.0",
79
+ "react-msaview": "^11.1.0",
80
80
  "rimraf": "^6.1.3",
81
81
  "tss-react": "^4.9.21",
82
82
  "tsx": "^4.23.12",
@@ -151,6 +151,44 @@ export function shiftInsertion(
151
151
  return seq
152
152
  }
153
153
 
154
+ /**
155
+ * `ins`, inserted before `from`, moved to before `to` by re-dividing the read's
156
+ * own bases between the two: the bases it passes over and the inserted ones
157
+ * are one run of the read, and the move only changes which of them are called
158
+ * inserted. Unlike `shiftInsertion` it moves whether or not the bases agree,
159
+ * so the row may come out with mismatches it did not have; it still spells the
160
+ * read exactly. Undefined where the read has no base at a position passed
161
+ * over, or does not reach the target.
162
+ */
163
+ export function moveInsertion(
164
+ read: ReadLayout,
165
+ from: number,
166
+ to: number,
167
+ ins: string,
168
+ ) {
169
+ const lo = Math.min(from, to) - read.start
170
+ const hi = Math.max(from, to) - read.start
171
+ const passed = read.refChars.slice(lo, hi)
172
+ const rightward = from < to
173
+ const spelled = rightward ? ins + passed : passed + ins
174
+ return lo < 0 ||
175
+ hi > read.refChars.length ||
176
+ passed.includes(SPANNED_GAP) ||
177
+ passed.includes(ABSENT)
178
+ ? undefined
179
+ : {
180
+ seq: rightward
181
+ ? spelled.slice(passed.length)
182
+ : spelled.slice(0, ins.length),
183
+ refChars:
184
+ read.refChars.slice(0, lo) +
185
+ (rightward
186
+ ? spelled.slice(0, passed.length)
187
+ : spelled.slice(ins.length)) +
188
+ read.refChars.slice(hi),
189
+ }
190
+ }
191
+
154
192
  /** an array with the span of reference positions whose insertions it may claim */
155
193
  interface FlankWindow {
156
194
  array: ReferenceArray
@@ -350,6 +388,174 @@ export function normalizeInsertions(
350
388
  })
351
389
  }
352
390
 
391
+ /*
392
+ * The four constants below were swept over HG002's PacBio HiFi reads at the
393
+ * NPHP4 Alu and at 80 insertions from the GIAB HG002 SV benchmark (v0.6,
394
+ * GRCh37: PASS, 50 to 2000bp, outside segmental duplications, 40 in tandem
395
+ * repeats and 40 not, taken evenly through the file), each in a 200bp window.
396
+ * Unmerged those windows have 102 insertion sites 10 or more columns wide,
397
+ * holding 34,876 insertion columns; at these values, 85 sites and 28,425.
398
+ */
399
+
400
+ /**
401
+ * Shortest insertion that is moved, or that draws others. Every value from 2
402
+ * to 20 merges the same sites. At 1 the 1bp read errors scattered through the
403
+ * windows are dragged into each other, 85 sites of them; at 50 a chr18 VNTR's
404
+ * 26 to 30bp allele stays split, and so does a 49 to 51bp insertion on chr5.
405
+ */
406
+ const MERGE_MIN_BP = 10
407
+
408
+ /**
409
+ * Farthest an insertion is moved. The farthest merge measured is 20bp: at
410
+ * 22:47,740,767 six reads carry a 61bp insertion 20bp from where fourteen
411
+ * others put it, and the bases between spell the same, so moving them costs
412
+ * nothing. Nothing more merges between 25 and 60.
413
+ */
414
+ const MERGE_REACH_BP = 25
415
+
416
+ /**
417
+ * How far a read's insertion length may be from the median at the site it
418
+ * joins, as a fraction of that median. One event read twice came out up to 13%
419
+ * apart (26 and 30bp of one chr18 VNTR allele; 8% for a 76bp one), and the
420
+ * different events within reach at least 53% apart (a 29bp allele beside a 62bp
421
+ * one, a 38bp insertion beside a 532bp one) — and both of those would have
422
+ * moved for free, so this is what keeps them apart, not the mismatches.
423
+ */
424
+ const MERGE_LENGTH_SPREAD = 0.2
425
+
426
+ /**
427
+ * Most mismatches against the reference a move may add to its row, net of
428
+ * those the bases it passes already had. Since a move cannot add more than the
429
+ * bases it passes, a read 1 or 2bp off always merges, and one farther off only
430
+ * where the bases between nearly agree. At this cap 49 reads move, 45 of them
431
+ * adding one mismatch or none. The costs do not fall into two groups: a cap of
432
+ * 3 moves 6 more reads, 3 to 7bp off, and each step up after that moves a few
433
+ * more, at about one mismatch for every two bases passed, which is what
434
+ * unrelated sequence costs.
435
+ */
436
+ const MERGE_MAX_MISMATCHES = 2
437
+
438
+ function median(values: number[]) {
439
+ return [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!
440
+ }
441
+
442
+ function differences(a: string, b: string) {
443
+ let ret = 0
444
+ for (let i = 0; i < a.length; i++) {
445
+ ret += a[i] === b[i] ? 0 : 1
446
+ }
447
+ return ret
448
+ }
449
+
450
+ /**
451
+ * `read` with its insertion `ins` moved from `from` to `to`, unless another of
452
+ * its insertions lies in between, it has no base on a position passed over, or
453
+ * the move adds more than `MERGE_MAX_MISMATCHES` against the reference.
454
+ */
455
+ function mergedRead(
456
+ read: ReadLayout,
457
+ from: number,
458
+ to: number,
459
+ ins: string,
460
+ reference: { seq: string; start: number },
461
+ ) {
462
+ const lo = Math.min(from, to)
463
+ const hi = Math.max(from, to)
464
+ const moved = [...read.insertions.keys()].some(
465
+ pos => pos !== from && pos >= lo && pos <= hi,
466
+ )
467
+ ? undefined
468
+ : moveInsertion(read, from, to, ins)
469
+ const passed = (refChars: string) =>
470
+ refChars.slice(lo - read.start, hi - read.start)
471
+ const ref = reference.seq.slice(lo - reference.start, hi - reference.start)
472
+ const insertions = new Map(read.insertions)
473
+ insertions.delete(from)
474
+ return moved &&
475
+ differences(passed(moved.refChars), ref) -
476
+ differences(passed(read.refChars), ref) <=
477
+ MERGE_MAX_MISMATCHES
478
+ ? {
479
+ ...read,
480
+ refChars: moved.refChars,
481
+ insertions: insertions.set(to, moved.seq),
482
+ }
483
+ : undefined
484
+ }
485
+
486
+ /**
487
+ * Move each long insertion to a nearby site more reads use, when the read
488
+ * inserts about as much there and the move costs its row no more than a
489
+ * mismatch or two against the reference.
490
+ *
491
+ * Left-normalization is exact, so it brings reads together only where their
492
+ * bases allow it. A read with a sequencing error at the boundary, or anchored a
493
+ * base or two off by the aligner, keeps a site of its own, and every other row
494
+ * pays for that site with a run of gap columns as wide as the insertion.
495
+ * `moveInsertion` re-divides the read's own bases, so the row still spells the
496
+ * read; what the move gives up is that some of them now sit on reference
497
+ * positions they do not match.
498
+ *
499
+ * Sites are visited by the reads inserting there, most first and ties to the
500
+ * leftmost. Each insertion at a site goes to the first site already kept that
501
+ * is within reach, of a similar length, and admits the move, and a site keeps
502
+ * its place if any read still inserts there. Like `normalizeInsertions`, this
503
+ * touches no position from an array's `start` to its `end`, keeps an insertion
504
+ * in view a base inside the region, and keeps a read's insertions in order.
505
+ */
506
+ export function mergeInsertionSites(
507
+ reads: ReadLayout[],
508
+ arrays: ReferenceArray[],
509
+ reference: { seq: string; start: number },
510
+ ) {
511
+ const touchesArray = (lo: number, hi: number) =>
512
+ arrays.some(array => array.start <= hi && array.end >= lo)
513
+ const holders = new Map<number, number[]>()
514
+ reads.forEach((read, i) => {
515
+ for (const [pos, ins] of read.insertions) {
516
+ if (ins.length >= MERGE_MIN_BP && !touchesArray(pos, pos)) {
517
+ holders.set(pos, [...(holders.get(pos) ?? []), i])
518
+ }
519
+ }
520
+ })
521
+ const reaches = (
522
+ target: { pos: number; length: number },
523
+ pos: number,
524
+ length: number,
525
+ ) =>
526
+ target.pos > reference.start &&
527
+ Math.abs(target.pos - pos) <= MERGE_REACH_BP &&
528
+ Math.abs(length - target.length) <= MERGE_LENGTH_SPREAD * target.length &&
529
+ !touchesArray(Math.min(pos, target.pos), Math.max(pos, target.pos))
530
+ const ret = [...reads]
531
+ const kept: { pos: number; length: number }[] = []
532
+ for (const [pos, indices] of [...holders].sort(
533
+ (a, b) => b[1].length - a[1].length || a[0] - b[0],
534
+ )) {
535
+ const stayed: number[] = []
536
+ for (const i of indices) {
537
+ const read = ret[i]!
538
+ const ins = read.insertions.get(pos) ?? ''
539
+ const moved = kept
540
+ .filter(target => reaches(target, pos, ins.length))
541
+ .reduce<ReadLayout | undefined>(
542
+ (found, target) =>
543
+ found ?? mergedRead(read, pos, target.pos, ins, reference),
544
+ undefined,
545
+ )
546
+ if (moved) {
547
+ ret[i] = moved
548
+ } else {
549
+ stayed.push(ins.length)
550
+ }
551
+ }
552
+ if (stayed.length) {
553
+ kept.push({ pos, length: median(stayed) })
554
+ }
555
+ }
556
+ return ret
557
+ }
558
+
353
559
  /**
354
560
  * Lay every row's allele out unit-per-block, one block per array.
355
561
  *
@@ -1,6 +1,7 @@
1
1
  import { alignInsertionSite } from './align'
2
2
  import {
3
3
  buildArrayBlocks,
4
+ mergeInsertionSites,
4
5
  normalizeInsertions,
5
6
  reanchorInsertions,
6
7
  } from './alleles'
@@ -340,11 +341,17 @@ export function planTviewMsa({
340
341
  const intervals = sequence
341
342
  ? mergeArrays(findReferenceArrays(sequence, start))
342
343
  : []
343
- const anchored = normalizeInsertions(
344
+ const normalized = normalizeInsertions(
344
345
  reanchorInsertions(clipped, intervals),
345
346
  intervals,
346
347
  start,
347
348
  )
349
+ const anchored = referenceRead
350
+ ? mergeInsertionSites(normalized, intervals, {
351
+ seq: referenceRead.refChars,
352
+ start,
353
+ })
354
+ : normalized
348
355
  const arrays = buildArrayBlocks(anchored, intervals)
349
356
  const ownedByArray = new Set<number>()
350
357
  for (const array of arrays) {
@@ -6,7 +6,6 @@ import { observer } from 'mobx-react'
6
6
  import { MSAView } from 'react-msaview'
7
7
 
8
8
  import type { JBrowsePluginTViewModel } from '../model'
9
- import type { MsaViewModel } from 'react-msaview'
10
9
 
11
10
  const padded = { padding: 20 }
12
11
 
@@ -17,10 +16,7 @@ const TViewPanel = observer(function TViewPanel2({
17
16
  }) {
18
17
  const state = model.viewState
19
18
  return state.kind === 'alignment' ? (
20
- // react-msaview types its model prop with type: 'MsaView' baked in, but a
21
- // JBrowse view model's `type` must equal its registered view type name.
22
- // That literal is the only difference, and the MSA renderer never reads it.
23
- <MSAView model={model as unknown as MsaViewModel} />
19
+ <MSAView model={model} />
24
20
  ) : (
25
21
  <div style={padded}>
26
22
  {state.kind === 'loading' ? (
@@ -8,7 +8,7 @@ import { hoverPosition, lowerBound } from './genome'
8
8
  import { initRegion, initSources, missingTrackIds } from './init'
9
9
  import { tviewInitMenuItems } from './initMenu'
10
10
  import {
11
- MODIFICATION_FILL,
11
+ MODIFICATION_MARK,
12
12
  modificationAnnotations,
13
13
  modificationMenu,
14
14
  } from './modifications'
@@ -26,7 +26,7 @@ import type { Instance } from '@jbrowse/mobx-state-tree'
26
26
  import type { LinearGenomeViewModel } from '@jbrowse/plugin-linear-genome-view'
27
27
  import type {
28
28
  Highlight,
29
- ResidueColor,
29
+ ResidueColorDefault,
30
30
  RowPanelSpec,
31
31
  RowTransform,
32
32
  } from 'react-msaview'
@@ -63,10 +63,11 @@ export type TViewState =
63
63
  const FIT_WIDTH_PX = 3000
64
64
 
65
65
  const GENOME_HOVER = 'genome-hover'
66
+ const LOAD_BRACKETS = 'tview-load'
66
67
 
67
68
  const ROW_HEIGHT = 12
68
69
 
69
- const DNA_COLORS: ResidueColor = {
70
+ const DNA_COLORS: ResidueColorDefault = {
70
71
  field: 'residue',
71
72
  scale: { scheme: 'jbrowse_dna' },
72
73
  }
@@ -97,8 +98,13 @@ function rowTransform(samples: string[], bySubject: boolean): RowTransform {
97
98
  * to hundreds of columns and at 10 almost none of it is on screen at once, so
98
99
  * the width shrinks to fit roughly two screen-widths.
99
100
  */
101
+ const MAX_COL_WIDTH = 10
102
+
100
103
  function fittedColWidth(columns: number) {
101
- return Math.max(1, Math.min(10, Math.floor(FIT_WIDTH_PX / columns)))
104
+ return Math.max(
105
+ 1,
106
+ Math.min(MAX_COL_WIDTH, Math.floor(FIT_WIDTH_PX / columns)),
107
+ )
102
108
  }
103
109
 
104
110
  const highlightKey = (h: Highlight) => JSON.stringify(h)
@@ -109,18 +115,20 @@ const highlightKey = (h: Highlight) => JSON.stringify(h)
109
115
  * - MSAModel from https://github.com/GMOD/react-msaview
110
116
  */
111
117
  export default function stateModelFactory() {
112
- const msaModel = MSAModelF({ maxInlineSnapshotBytes: 0 })
113
- const msaDefaults = {
114
- colWidth: msaModel.properties.colWidth.getDefaultInstanceOrSnapshot(),
115
- rowHeight: msaModel.properties.rowHeight.getDefaultInstanceOrSnapshot(),
116
- labelsAlignRight:
117
- msaModel.properties.labelsAlignRight.getDefaultInstanceOrSnapshot(),
118
- }
119
118
  return types
120
119
  .compose(
121
120
  'TView',
122
121
  BaseViewModel,
123
- msaModel,
122
+ MSAModelF({
123
+ maxInlineSnapshotBytes: 0,
124
+ defaults: {
125
+ colWidth: MAX_COL_WIDTH,
126
+ rowHeight: ROW_HEIGHT,
127
+ labelsAlignRight: true,
128
+ residueColor: DNA_COLORS,
129
+ turnedOffTracks: { 'position-ruler': false },
130
+ },
131
+ }),
124
132
  types.model({
125
133
  type: types.literal('TView'),
126
134
  /**
@@ -147,11 +155,6 @@ export default function stateModelFactory() {
147
155
  * the reference region the loaded alignment spans
148
156
  */
149
157
  loadedRegion: undefined as IRegion | undefined,
150
- /**
151
- * #volatile
152
- * the highlights the last load added, which the next one replaces
153
- */
154
- loadedHighlights: [] as Highlight[],
155
158
  /**
156
159
  * #volatile
157
160
  * the base modification calls the last load placed, when its reads had any
@@ -341,11 +344,8 @@ export default function stateModelFactory() {
341
344
  modifications ? modificationAnnotations(modifications) : [],
342
345
  )
343
346
  }
344
- if (
345
- modifications &&
346
- !self.encodings.some(e => e.channel === 'featureFill')
347
- ) {
348
- self.setEncodings([...self.encodings, MODIFICATION_FILL])
347
+ if (modifications && self.marks === undefined) {
348
+ self.setMarks([MODIFICATION_MARK])
349
349
  }
350
350
  self.loadedModifications = modifications
351
351
  ? {
@@ -358,40 +358,36 @@ export default function stateModelFactory() {
358
358
  /**
359
359
  * #action
360
360
  * shows a built alignment: its rows, how they are grouped, ordered and
361
- * marked, and the defaults a view that has not set its own takes
361
+ * marked, and numbered in the genome's coordinates. The brackets are
362
+ * transient, since every load rebuilds them, and a session saved by 3.0.0
363
+ * carries its own copies of them, which are dropped here
362
364
  */
363
365
  setAlignment(result: TviewPlanResult) {
366
+ const { region, highlights } = result
364
367
  const bySubject = result.hasSubject
365
- const replaced = new Set(
366
- [...self.loadedHighlights, ...result.highlights].map(highlightKey),
367
- )
368
- self.loadedRegion = result.region
369
- self.loadedHighlights = result.highlights
368
+ const rebuilt = new Set(highlights.map(highlightKey))
369
+ self.loadedRegion = region
370
370
  self.setMSA(result.msa)
371
371
  this.setModifications(result.modifications)
372
372
  self.data.setTree(undefined)
373
373
  self.setRowData(result.rowData)
374
374
  self.setRowTransform(rowTransform(result.samples, bySubject))
375
375
  self.setRowPanels(bySubject ? COPY_PANELS : [])
376
- self.setHighlights([
377
- ...self.highlights.filter(h => !replaced.has(highlightKey(h))),
378
- ...result.highlights,
376
+ self.setRowCoordinates([
377
+ { row: REFERENCE, start: region.start + 1, name: region.refName },
379
378
  ])
379
+ self.applyHighlight(LOAD_BRACKETS, highlights)
380
+ if (self.highlights.some(h => rebuilt.has(highlightKey(h)))) {
381
+ self.setHighlights(
382
+ self.highlights.filter(h => !rebuilt.has(highlightKey(h))),
383
+ )
384
+ }
380
385
  if (self.relativeTo === undefined) {
381
386
  self.drawRelativeTo(REFERENCE)
382
387
  }
383
- if (Object.keys(self.residueColor).length === 0) {
384
- self.setResidueColor(DNA_COLORS)
385
- }
386
- if (self.colWidth === msaDefaults.colWidth) {
388
+ if (self.colWidth === MAX_COL_WIDTH) {
387
389
  self.setColWidth(fittedColWidth(result.columnCount))
388
390
  }
389
- if (self.rowHeight === msaDefaults.rowHeight) {
390
- self.setRowHeight(ROW_HEIGHT)
391
- }
392
- if (self.labelsAlignRight === msaDefaults.labelsAlignRight) {
393
- self.setLabelsAlignRight(true)
394
- }
395
391
  },
396
392
  /**
397
393
  * #action
@@ -2,7 +2,7 @@ import { MAX_MODIFICATION_CALLS } from '../LaunchTView/modifications'
2
2
 
3
3
  import type { TviewModifications } from '../LaunchTView/modifications'
4
4
  import type { MenuItem } from '@jbrowse/core/ui'
5
- import type { Annotation, ColorEncoding, ResidueColor } from 'react-msaview'
5
+ import type { AlignmentMarkSpec, Annotation, ResidueColor } from 'react-msaview'
6
6
 
7
7
  /** the SAMtags codes, and the ChEBI ids JBrowse names */
8
8
  const NAMES: Record<string, string> = {
@@ -28,16 +28,21 @@ export interface ModificationSummary {
28
28
  unplaced: number
29
29
  }
30
30
 
31
- export const MODIFICATION_FILL: ColorEncoding = {
32
- channel: 'featureFill',
33
- field: 'probability',
34
- scale: {
35
- type: 'linear',
36
- domainMin: 0,
37
- domainMax: 100,
38
- range: ['#0000ff', '#ff0000'],
31
+ export const MODIFICATION_MARK: AlignmentMarkSpec = {
32
+ kind: 'features',
33
+ height: { band: 1 },
34
+ encoding: {
35
+ fill: {
36
+ field: 'probability',
37
+ scale: {
38
+ type: 'linear',
39
+ domainMin: 0,
40
+ domainMax: 100,
41
+ range: ['#0000ff', '#ff0000'],
42
+ },
43
+ legend: { title: 'modification %' },
44
+ },
39
45
  },
40
- legend: { title: 'modification %' },
41
46
  }
42
47
 
43
48
  export function modificationName(type: string) {
@@ -98,7 +103,7 @@ export function modificationMenu(
98
103
  summary: ModificationSummary,
99
104
  view: ColoredView,
100
105
  ) {
101
- const byModification = view.resolvedResidueColor.field === 'feature'
106
+ const alone = view.resolvedResidueColor.field === 'feature'
102
107
  const colorBy = (field: 'residue' | 'feature') => () => {
103
108
  view.setResidueColor({ ...view.residueColor, field })
104
109
  }
@@ -110,15 +115,15 @@ export function modificationMenu(
110
115
  label: 'Base modifications',
111
116
  subMenu: [
112
117
  {
113
- label: 'Color by bases',
118
+ label: 'Over base colors',
114
119
  type: 'radio',
115
- checked: !byModification,
120
+ checked: !alone,
116
121
  onClick: colorBy('residue'),
117
122
  },
118
123
  {
119
- label: 'Color by modification',
124
+ label: 'Without base colors',
120
125
  type: 'radio',
121
- checked: byModification,
126
+ checked: alone,
122
127
  onClick: colorBy('feature'),
123
128
  },
124
129
  ...summaryLine,
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '3.0.0'
1
+ export const version = '3.1.0'