jbrowse-plugin-tview 2.1.0 → 2.2.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 = "2.1.0";
1
+ export declare const version = "2.2.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.1.0';
1
+ export const version = '2.2.0';
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.1.0",
2
+ "version": "2.2.0",
3
3
  "license": "MIT",
4
4
  "name": "jbrowse-plugin-tview",
5
5
  "repository": {
@@ -36,7 +36,9 @@
36
36
  "postversion": "git push --follow-tags",
37
37
  "figures:repeats": "node scripts/repeat-figures.mjs",
38
38
  "prefigures:repeats": "pnpm pretest:e2e",
39
- "qc:repeats": "tsx test/liveRepeats.qc.ts"
39
+ "qc:repeats": "tsx test/liveRepeats.qc.ts",
40
+ "report:repeats": "tsx scripts/repeat-report.mjs",
41
+ "readme:repeats": "tsx scripts/repeat-readme.mjs"
40
42
  },
41
43
  "jbrowse-plugin": {
42
44
  "name": "TView"
@@ -70,9 +72,10 @@
70
72
  "puppeteer": "^25.3.0",
71
73
  "react": "^19.2.8",
72
74
  "react-dom": "^19.2.8",
73
- "react-msaview": "^5.6.3",
75
+ "react-msaview": "^5.7.1",
74
76
  "rimraf": "^6.1.3",
75
77
  "tss-react": "^4.9.21",
78
+ "tsx": "^4.20.6",
76
79
  "typescript": "^6.0.2",
77
80
  "typescript-eslint": "^8.65.0",
78
81
  "vitest": "^4.1.10"
@@ -301,6 +301,69 @@ function splitIntoUnits(seq: string, consensus: string) {
301
301
  return units
302
302
  }
303
303
 
304
+ // The tiled alignment below is O(len * len), so it scores a prefix rather than
305
+ // the whole insert. A sequence that is copies of the unit for its first 300
306
+ // bases is copies of the unit.
307
+ const IDENTITY_PROBE_LEN = 300
308
+
309
+ /**
310
+ * How much of `seq` is explained by `unit` repeated end to end: the fraction of
311
+ * `seq`'s bases that align to a matching base of the tiling.
312
+ *
313
+ * Free at both ends of the tiling, since an inserted run of copies can start
314
+ * and stop mid-copy, and global on `seq`, since the question is about all of it.
315
+ * That is what separates "more copies of this array" from "something else that
316
+ * landed next to it" without asking the sequence to be in phase with the unit:
317
+ * measured against the trio, the repeat alleles the aligner anchored just
318
+ * outside an array score 0.94-1.00 and unrelated sequence of the same length
319
+ * scores 0.67 or below.
320
+ */
321
+ export function unitIdentity(seq: string, unit: string) {
322
+ const probe =
323
+ seq.length > IDENTITY_PROBE_LEN ? seq.slice(0, IDENTITY_PROBE_LEN) : seq
324
+ const n = probe.length
325
+ if (!n || !unit.length) {
326
+ return 0
327
+ }
328
+ // two spare copies so the alignment can start mid-copy and still run off the
329
+ // end without paying for it
330
+ const tile = unit.repeat(Math.ceil(n / unit.length) + 2)
331
+ const m = tile.length
332
+ const stride = m + 1
333
+ const score = new Int32Array((n + 1) * stride)
334
+ const matches = new Int32Array((n + 1) * stride)
335
+ // row 0 stays zero: starting anywhere in the tiling is free
336
+ for (let i = 1; i <= n; i++) {
337
+ score[i * stride] = i * GAP
338
+ }
339
+ for (let i = 1; i <= n; i++) {
340
+ for (let j = 1; j <= m; j++) {
341
+ const hit = probe[i - 1] === tile[j - 1]
342
+ const diagonal =
343
+ score[(i - 1) * stride + j - 1]! + (hit ? MATCH : MISMATCH)
344
+ const up = score[(i - 1) * stride + j]! + GAP
345
+ const left = score[i * stride + j - 1]! + GAP
346
+ const best = Math.max(diagonal, up, left)
347
+ score[i * stride + j] = best
348
+ matches[i * stride + j] =
349
+ best === diagonal
350
+ ? matches[(i - 1) * stride + j - 1]! + (hit ? 1 : 0)
351
+ : best === up
352
+ ? matches[(i - 1) * stride + j]!
353
+ : matches[i * stride + j - 1]!
354
+ }
355
+ }
356
+ let best = score[n * stride]!
357
+ let bestMatches = matches[n * stride]!
358
+ for (let j = 1; j <= m; j++) {
359
+ if (score[n * stride + j]! > best) {
360
+ best = score[n * stride + j]!
361
+ bestMatches = matches[n * stride + j]!
362
+ }
363
+ }
364
+ return bestMatches / n
365
+ }
366
+
304
367
  export interface PeriodicAlignment {
305
368
  /** repeat unit length in bp */
306
369
  period: number
@@ -1,4 +1,4 @@
1
- import { alignToUnit } from './align'
1
+ import { alignToUnit, unitIdentity } from './align'
2
2
 
3
3
  import type { ReadLayout } from './readLayout'
4
4
  import type { ReferenceArray } from './repeats'
@@ -79,6 +79,103 @@ export function arrayInsertionKeys(array: { start: number; end: number }) {
79
79
  return ret
80
80
  }
81
81
 
82
+ /**
83
+ * How far outside an array an insertion of its own unit can be anchored, in
84
+ * copies. An indel made of repeat units has no unique placement inside the
85
+ * array, and the flanking bases let the aligner carry it a little further still
86
+ * — but only about a copy, because past that the sequence either side stops
87
+ * matching. Every misplaced repeat allele in the trio sits within one copy of
88
+ * the edge: ATXN3's at 1bp, FMR1's at 2bp of a 3bp unit, ABCA7's at 19bp of a
89
+ * 25bp one.
90
+ */
91
+ const ABSORB_COPIES = 1
92
+
93
+ /**
94
+ * How much of the inserted sequence the array's unit has to explain before the
95
+ * insertion counts as part of the array. The repeat alleles the aligner
96
+ * anchored just outside an array in the trio score 0.94-1.00 here and unrelated
97
+ * sequence scores 0.67 or below, so this sits in open space rather than on a
98
+ * boundary.
99
+ */
100
+ const ABSORB_IDENTITY = 0.8
101
+
102
+ /**
103
+ * Widen each array to cover the insertions the aligner anchored just outside it
104
+ * that are made of the array's own unit.
105
+ *
106
+ * An allele is measured over a reference interval, which fixes the "one array
107
+ * reports as several sites" problem for indels the aligner placed *inside* the
108
+ * interval. It does not fix the ones it placed just outside: an aligner is free
109
+ * to anchor an expansion at the base before the array starts, and there the
110
+ * insertion is not part of any allele — it is left to become its own run of
111
+ * insertion columns, and the read it belongs to is measured as if it carried
112
+ * the reference allele. Both halves of that are wrong, and they are not rare:
113
+ * at ATXN3 the aligner anchored 60 of 162 reads' expansions one base outside
114
+ * the array, and at ABCA7 a 1207bp allele 19 bases outside.
115
+ *
116
+ * What is absorbed is decided by the inserted sequence, not by the count of
117
+ * reads carrying it — a single read's expansion is as real as fifty, and the
118
+ * whole point of measuring over an interval is that it does not need a vote.
119
+ * Widening the interval costs every row the few reference bases in between,
120
+ * which they all pay equally, so the counts stay comparable.
121
+ */
122
+ export function absorbAdjacentInsertions(
123
+ reads: ReadLayout[],
124
+ arrays: ReferenceArray[],
125
+ ) {
126
+ const ordered = [...arrays].sort((a, b) => a.start - b.start)
127
+ // the widened end of the array to the left, which the next one may not reach
128
+ let previousEnd = -Infinity
129
+ return ordered.map((array, i) => {
130
+ const margin = ABSORB_COPIES * array.period
131
+ // Two arrays that met at a position would read the same insertion slot
132
+ // twice — once as each one's allele — so they are held apart on both
133
+ // sides: leftwards off whatever the previous array grew to, rightwards off
134
+ // where the next one starts, which is as far left as that one can be
135
+ // pushed in turn. Neither bound can cross the array's own edges, since
136
+ // mergeArrays has already left a gap between every pair.
137
+ const floor = Math.max(array.start - margin, previousEnd + 1)
138
+ const ceiling = Math.min(
139
+ array.end + margin,
140
+ (ordered[i + 1]?.start ?? Infinity) - 1,
141
+ )
142
+ let { start, end } = array
143
+ // memoized per distinct insert: one locus routinely has dozens of reads
144
+ // carrying the same allele at the same site
145
+ const belongs = new Map<string, boolean>()
146
+ const isUnit = (ins: string) => {
147
+ let ret = belongs.get(ins)
148
+ if (ret === undefined) {
149
+ ret = unitIdentity(ins, array.unit) >= ABSORB_IDENTITY
150
+ belongs.set(ins, ret)
151
+ }
152
+ return ret
153
+ }
154
+ for (const read of reads) {
155
+ for (const [pos, ins] of read.insertions) {
156
+ // a whole copy at least: a base or two of read error next to an array
157
+ // says nothing about where the array ends, and moving the interval for
158
+ // it would lay flanking sequence out as repeat copies
159
+ if (
160
+ ins.length < array.period ||
161
+ pos < floor ||
162
+ pos > ceiling ||
163
+ (pos >= array.start && pos <= array.end) ||
164
+ !isUnit(ins)
165
+ ) {
166
+ continue
167
+ }
168
+ start = Math.min(start, pos)
169
+ // an insertion is keyed to the position it precedes, and extractAllele
170
+ // reads the slot at `end`, so covering it means reaching that position
171
+ end = Math.max(end, pos)
172
+ }
173
+ }
174
+ previousEnd = end
175
+ return { ...array, start, end }
176
+ })
177
+ }
178
+
82
179
  /**
83
180
  * Lay every row's allele out unit-per-block, one block per array.
84
181
  *
@@ -0,0 +1,170 @@
1
+ /**
2
+ * What a built alignment says about the arrays in it, as numbers rather than as
3
+ * a picture.
4
+ *
5
+ * Everything a report or a README claims about a locus is derived here, from
6
+ * the same plan the view renders, so a number in prose is a number something
7
+ * computed. Nothing in this file fetches or prints — it takes a plan and gives
8
+ * back counts, which is what makes it testable without the network.
9
+ */
10
+ import { ABSENT, SPANNED_GAP } from './readLayout'
11
+ import { renderRow } from './tview'
12
+
13
+ import type { ArrayBlock } from './alleles'
14
+ import type { TviewPlan } from './tview'
15
+
16
+ /**
17
+ * Least support an allele needs before it is reported as one of a sample's,
18
+ * as a fraction of that sample's spanning reads.
19
+ *
20
+ * Reads scatter around an allele — slippage in the read, slippage in the
21
+ * aligner — so the counts either side of a real allele are populated too, and
22
+ * a rule that took the top two would report the shoulder of one allele as the
23
+ * other. A fraction of coverage rather than a distance in copies is what lets
24
+ * two alleles a single copy apart both be reported, which at FMR1 is the
25
+ * mother's genotype and at ATXN3 the father's.
26
+ */
27
+ const MIN_ALLELE_FRACTION = 0.15
28
+
29
+ /** ...and never on one read, at any coverage. */
30
+ const MIN_ALLELE_READS = 2
31
+
32
+ export interface Tally {
33
+ value: number
34
+ reads: number
35
+ }
36
+
37
+ /** Each distinct value with how many rows carried it, smallest value first. */
38
+ export function tally(values: number[]): Tally[] {
39
+ const counts = new Map<number, number>()
40
+ for (const v of values) {
41
+ counts.set(v, (counts.get(v) ?? 0) + 1)
42
+ }
43
+ return [...counts]
44
+ .map(([value, reads]) => ({ value, reads }))
45
+ .sort((a, b) => a.value - b.value)
46
+ }
47
+
48
+ /**
49
+ * The copy counts a sample carries, as the counts enough of its reads agree on.
50
+ *
51
+ * This is a report of what the reads say, not a genotype call: it does not know
52
+ * a ploidy, so a homozygote and a haploid locus both come back as one number,
53
+ * and a sample whose reads scatter can come back with none.
54
+ */
55
+ export function alleleModes(copies: number[]): Tally[] {
56
+ const floor = Math.max(MIN_ALLELE_READS, MIN_ALLELE_FRACTION * copies.length)
57
+ return tally(copies).filter(t => t.reads >= floor)
58
+ }
59
+
60
+ export interface SampleArrayStats {
61
+ sample: string
62
+ /** rows that reached both ends of the interval, i.e. that were measured */
63
+ spanning: number
64
+ /** copy counts enough of them agreed on */
65
+ modes: Tally[]
66
+ /** every copy count seen, with its support */
67
+ copies: Tally[]
68
+ /** rows whose copy count is not one of the modes */
69
+ offMode: number
70
+ }
71
+
72
+ export interface ArrayStats {
73
+ start: number
74
+ end: number
75
+ period: number
76
+ unit: string
77
+ /** reference positions the interval covers */
78
+ span: number
79
+ /** columns the block occupies */
80
+ width: number
81
+ /** the reference's own copy count, when the reference was a row */
82
+ referenceCopies?: number
83
+ /** whether the rows were ordered and labelled by this array */
84
+ subject: boolean
85
+ samples: SampleArrayStats[]
86
+ }
87
+
88
+ function sampleOfRow(name: string) {
89
+ const i = name.indexOf('|')
90
+ return i < 0 ? undefined : name.slice(0, i)
91
+ }
92
+
93
+ function arrayStats(
94
+ array: ArrayBlock,
95
+ plan: TviewPlan,
96
+ samples: string[],
97
+ ): ArrayStats {
98
+ return {
99
+ start: array.start,
100
+ end: array.end,
101
+ period: array.period,
102
+ unit: array.unit,
103
+ span: array.end - array.start,
104
+ width: array.width,
105
+ referenceCopies: plan.referenceName
106
+ ? array.copiesByName.get(plan.referenceName)
107
+ : undefined,
108
+ subject: array === plan.subject,
109
+ samples: samples.map(sample => {
110
+ const copies = [...array.copiesByName]
111
+ .filter(([name]) => sampleOfRow(name) === sample)
112
+ .map(([, n]) => n)
113
+ const modes = alleleModes(copies)
114
+ const called = new Set(modes.map(m => m.value))
115
+ return {
116
+ sample,
117
+ spanning: copies.length,
118
+ modes,
119
+ copies: tally(copies),
120
+ offMode: copies.filter(c => !called.has(c)).length,
121
+ }
122
+ }),
123
+ }
124
+ }
125
+
126
+ export interface PlanStats {
127
+ rows: number
128
+ columns: number
129
+ /**
130
+ * columns exactly one row has a base in. One read's miscalled indel costs
131
+ * every row a column, so this is the size of what "hide columns w/ N% gaps"
132
+ * takes off a figure — read error, measured rather than estimated.
133
+ */
134
+ singleRowColumns: number
135
+ /** columns no row has a base in, which no setting is needed to justify */
136
+ emptyColumns: number
137
+ arrays: ArrayStats[]
138
+ }
139
+
140
+ /** Rows, columns, and every array, from a plan the view could equally render. */
141
+ export function summarizePlan(plan: TviewPlan, samples?: string[]): PlanStats {
142
+ const rows = plan.reads.map(read => renderRow(read, plan.layout))
143
+ const perColumn = new Int32Array(plan.layout.totalColumns)
144
+ for (const row of rows) {
145
+ for (let col = 0; col < row.length; col++) {
146
+ const char = row[col]!
147
+ if (char !== ABSENT && char !== SPANNED_GAP) {
148
+ perColumn[col] = perColumn[col]! + 1
149
+ }
150
+ }
151
+ }
152
+ let singleRowColumns = 0
153
+ let emptyColumns = 0
154
+ for (const count of perColumn) {
155
+ if (count === 0) {
156
+ emptyColumns++
157
+ } else if (count === 1) {
158
+ singleRowColumns++
159
+ }
160
+ }
161
+ return {
162
+ rows: plan.reads.length,
163
+ columns: plan.layout.totalColumns,
164
+ singleRowColumns,
165
+ emptyColumns,
166
+ arrays: plan.arrays.map(array =>
167
+ arrayStats(array, plan, samples ?? plan.samples),
168
+ ),
169
+ }
170
+ }
@@ -1,5 +1,5 @@
1
1
  import { alignInsertionSite } from './align'
2
- import { buildArrayBlocks } from './alleles'
2
+ import { absorbAdjacentInsertions, buildArrayBlocks } from './alleles'
3
3
  import {
4
4
  ABSENT,
5
5
  SPANNED_GAP,
@@ -311,10 +311,16 @@ export function planTviewMsa({
311
311
  end,
312
312
  )
313
313
 
314
+ // the interval comes from the reference, then widens over the repeat alleles
315
+ // the aligner anchored just outside it — see absorbAdjacentInsertions, which
316
+ // has to see the reads and so cannot live in the reference scan
314
317
  const arrays = sequence
315
318
  ? buildArrayBlocks(
316
319
  clipped,
317
- mergeArrays(findReferenceArrays(sequence, start)),
320
+ absorbAdjacentInsertions(
321
+ clipped,
322
+ mergeArrays(findReferenceArrays(sequence, start)),
323
+ ),
318
324
  )
319
325
  : []
320
326
  const ownedByArray = new Set<number>()
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '2.1.0'
1
+ export const version = '2.2.0'