jbrowse-plugin-tview 2.1.0 → 2.2.1

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.1";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.1.0';
1
+ export const version = '2.2.1';
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.1",
3
3
  "license": "MIT",
4
4
  "name": "jbrowse-plugin-tview",
5
5
  "repository": {
@@ -23,6 +23,7 @@
23
23
  "format": "pnpm prettier --write .",
24
24
  "prebuild": "pnpm clean",
25
25
  "build": "tsc && NODE_ENV=production node esbuild.mjs && cp distconfig.json dist/config.json",
26
+ "typecheck": "tsc --noEmit",
26
27
  "lint": "eslint --report-unused-disable-directives --max-warnings 0",
27
28
  "test": "vitest run",
28
29
  "test:watch": "vitest",
@@ -36,45 +37,48 @@
36
37
  "postversion": "git push --follow-tags",
37
38
  "figures:repeats": "node scripts/repeat-figures.mjs",
38
39
  "prefigures:repeats": "pnpm pretest:e2e",
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"
43
45
  },
44
46
  "dependencies": {
45
47
  "@emotion/styled": "^11.14.1",
46
- "swr": "^2.4.2"
48
+ "swr": "^2.5.0"
47
49
  },
48
50
  "devDependencies": {
49
51
  "@emotion/react": "^11.14.0",
50
52
  "@eslint/js": "^10.0.1",
51
53
  "@fal-works/esbuild-plugin-global-externals": "^2.1.2",
52
- "@gmod/bam": "^7.3.4",
54
+ "@gmod/bam": "^8.3.0",
55
+ "@gmod/indexedfasta": "^5.0.9",
53
56
  "@jbrowse/core": "^4.3.0",
54
- "@jbrowse/mobx-state-tree": "^5.13.0",
57
+ "@jbrowse/mobx-state-tree": "^6.1.0",
55
58
  "@jbrowse/plugin-linear-genome-view": "^4.3.0",
56
- "@mui/icons-material": "^9.2.0",
57
- "@mui/material": "^9.2.0",
58
- "@mui/system": "^9.2.0",
59
- "@types/node": "^26.1.1",
60
- "@types/react": "^19.2.17",
59
+ "@mui/icons-material": "^9.3.1",
60
+ "@mui/material": "^9.3.1",
61
+ "@mui/system": "^9.3.0",
62
+ "@types/node": "^26.2.0",
63
+ "@types/react": "^19.2.18",
61
64
  "esbuild": "^0.28.1",
62
- "eslint": "^10.7.0",
65
+ "eslint": "^10.8.1",
63
66
  "eslint-plugin-import-x": "^4.17.1",
64
67
  "eslint-plugin-react": "^7.37.5",
65
68
  "eslint-plugin-react-hooks": "^7.1.1",
66
- "mobx": "^6.16.1",
67
- "mobx-react": "^9.2.2",
69
+ "mobx": "^7.0.0",
70
+ "mobx-react": "^10.0.0",
68
71
  "prettier": "^3.9.6",
69
72
  "pretty-bytes": "^7.1.1",
70
- "puppeteer": "^25.3.0",
73
+ "puppeteer": "^25.5.0",
71
74
  "react": "^19.2.8",
72
75
  "react-dom": "^19.2.8",
73
- "react-msaview": "^5.6.3",
76
+ "react-msaview": "^5.7.1",
74
77
  "rimraf": "^6.1.3",
75
78
  "tss-react": "^4.9.21",
79
+ "tsx": "^4.20.6",
76
80
  "typescript": "^6.0.2",
77
- "typescript-eslint": "^8.65.0",
81
+ "typescript-eslint": "^8.66.0",
78
82
  "vitest": "^4.1.10"
79
83
  }
80
84
  }
@@ -301,6 +301,98 @@ function splitIntoUnits(seq: string, consensus: string) {
301
301
  return units
302
302
  }
303
303
 
304
+ // The tiled alignment below is O(len^2), so it scores windows of the insert
305
+ // rather than all of it.
306
+ const IDENTITY_PROBE_LEN = 300
307
+
308
+ /**
309
+ * Head, middle and tail of `seq`, or the whole of it when it is short enough to
310
+ * score outright.
311
+ *
312
+ * Scoring only the head is how a prefix probe lies: `unit x 12` followed by a
313
+ * kilobase of something else scores 1.00 on its first 300 bases and is not the
314
+ * array's. Three windows cost the same and cannot be fooled that way, because
315
+ * the sequence has to still be the unit where it ends as well as where it
316
+ * starts.
317
+ */
318
+ function probeWindows(seq: string) {
319
+ if (seq.length <= IDENTITY_PROBE_LEN) {
320
+ return [seq]
321
+ }
322
+ const middle = Math.floor((seq.length - IDENTITY_PROBE_LEN) / 2)
323
+ return [
324
+ seq.slice(0, IDENTITY_PROBE_LEN),
325
+ seq.slice(middle, middle + IDENTITY_PROBE_LEN),
326
+ seq.slice(-IDENTITY_PROBE_LEN),
327
+ ]
328
+ }
329
+
330
+ /** the fraction of `probe`'s bases that match `unit` tiled end to end */
331
+ function tiledIdentity(probe: string, unit: string) {
332
+ const n = probe.length
333
+ if (!n || !unit.length) {
334
+ return 0
335
+ }
336
+ // two spare copies so the alignment can start mid-copy and still run off the
337
+ // end without paying for it
338
+ const tile = unit.repeat(Math.ceil(n / unit.length) + 2)
339
+ const m = tile.length
340
+ const stride = m + 1
341
+ const score = new Int32Array((n + 1) * stride)
342
+ const matches = new Int32Array((n + 1) * stride)
343
+ // row 0 stays zero: starting anywhere in the tiling is free
344
+ for (let i = 1; i <= n; i++) {
345
+ score[i * stride] = i * GAP
346
+ }
347
+ for (let i = 1; i <= n; i++) {
348
+ for (let j = 1; j <= m; j++) {
349
+ const hit = probe[i - 1] === tile[j - 1]
350
+ const diagonal =
351
+ score[(i - 1) * stride + j - 1]! + (hit ? MATCH : MISMATCH)
352
+ const up = score[(i - 1) * stride + j]! + GAP
353
+ const left = score[i * stride + j - 1]! + GAP
354
+ const best = Math.max(diagonal, up, left)
355
+ score[i * stride + j] = best
356
+ matches[i * stride + j] =
357
+ best === diagonal
358
+ ? matches[(i - 1) * stride + j - 1]! + (hit ? 1 : 0)
359
+ : best === up
360
+ ? matches[(i - 1) * stride + j]!
361
+ : matches[i * stride + j - 1]!
362
+ }
363
+ }
364
+ let best = score[n * stride]!
365
+ let bestMatches = matches[n * stride]!
366
+ for (let j = 1; j <= m; j++) {
367
+ if (score[n * stride + j]! > best) {
368
+ best = score[n * stride + j]!
369
+ bestMatches = matches[n * stride + j]!
370
+ }
371
+ }
372
+ return bestMatches / n
373
+ }
374
+
375
+ /**
376
+ * How much of `seq` is explained by `unit` repeated end to end, scored at three
377
+ * places along it and reported as the worst of them.
378
+ *
379
+ * Each window is aligned free at both ends of the tiling, since an inserted run
380
+ * of copies can start and stop mid-copy, and global on the window, since the
381
+ * question is about all of it. That is what separates "more copies of this
382
+ * array" from "something else that landed next to it" without asking the
383
+ * sequence to be in phase with the unit — the ABCA7 read that carries 1207bp of
384
+ * VNTR anchored outside the array begins six bases into a copy, and the FMR1
385
+ * one begins on the wrong base of the unit and carries the locus's own AGG
386
+ * interruptions.
387
+ *
388
+ * Measured against the trio: the repeat alleles the aligner anchored just
389
+ * outside an array score 0.9 and up, and unrelated sequence of the same length
390
+ * scores 0.67 or below.
391
+ */
392
+ export function unitIdentity(seq: string, unit: string) {
393
+ return Math.min(...probeWindows(seq).map(w => tiledIdentity(w, unit)))
394
+ }
395
+
304
396
  export interface PeriodicAlignment {
305
397
  /** repeat unit length in bp */
306
398
  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'
@@ -70,13 +70,218 @@ export function extractAllele(read: ReadLayout, start: number, end: number) {
70
70
  return ret
71
71
  }
72
72
 
73
- /** Reference positions an array owns, including the insertion slot at its right edge. */
74
- export function arrayInsertionKeys(array: { start: number; end: number }) {
75
- const ret: number[] = []
76
- for (let pos = array.start; pos <= array.end; pos++) {
77
- ret.push(pos)
73
+ /**
74
+ * How far outside an array an insertion is looked for, in reference bases.
75
+ *
76
+ * GIAB's adotto tandem repeat catalog buffers every interval by +/-25bp before
77
+ * merging, to leave room for the alignment ambiguity that comes with capturing
78
+ * variation inside a repeat, and measured what the buffer misses: re-expanding
79
+ * every region by a further 10bp would move only 0.2% of its boundaries
80
+ * (English et al., Nat Biotechnol 42, 2024, doi:10.1038/s41587-024-02225-z). A
81
+ * whole copy is the floor for a unit longer than that, since a copy is the
82
+ * aligner's room to slide a repeat indel. Both cover the misplacements measured
83
+ * in this trio: ATXN3 at 1bp, FMR1 at 2bp of a 3bp unit, ABCA7 at 19bp of a
84
+ * 25bp one.
85
+ *
86
+ * It bounds the search, not the answer. Whether an insertion actually moves is
87
+ * decided exactly, by `shiftInsertion`, so this being generous costs nothing.
88
+ */
89
+ const FLANK_BP = 25
90
+
91
+ /** the read's aligned base at a reference position, if it has one there */
92
+ function readBase(read: ReadLayout, pos: number) {
93
+ const i = pos - read.start
94
+ return i >= 0 && i < read.refChars.length ? read.refChars[i] : undefined
95
+ }
96
+
97
+ /**
98
+ * How much of an insertion the array's unit has to explain before it counts as
99
+ * the array's. The repeat alleles the aligner anchored just outside an array in
100
+ * the trio score 0.9 and up, and unrelated sequence scores 0.67 or below, so
101
+ * this sits in open space rather than on a boundary.
102
+ */
103
+ const BELONGS_IDENTITY = 0.8
104
+
105
+ /**
106
+ * `ins`, inserted before reference position `from`, rewritten as an insertion
107
+ * before `to` — or undefined when the read's own bases do not allow it.
108
+ *
109
+ * An insertion has no unique position. `S` before a base `b` and `rotate(S)`
110
+ * after it spell the same read, so an aligner is free to anchor an expansion
111
+ * outside the array it belongs to, and at ATXN3 it did exactly that for most of
112
+ * the reads carrying one. Walking an indel through that equivalence class is
113
+ * the standard normalization for it (Tan, Abecasis & Kang, "Unified
114
+ * representation of genetic variants", Bioinformatics 31, 2015,
115
+ * doi:10.1093/bioinformatics/btv112, which walks left; this walks toward the
116
+ * array, the same operation with the array as the canonical anchor).
117
+ *
118
+ * The step is tested against the **read's** aligned base rather than the
119
+ * reference's, which is what makes the rewrite exact: the row still renders
120
+ * base for base as it did, and the only thing that changes is the reference
121
+ * position the bases are filed under. A step onto a deletion has no base to
122
+ * swap with and stops.
123
+ *
124
+ * Being exact, it is also incomplete, and measurably so. An aligner does not
125
+ * only choose among equivalent placements — it chooses the highest-scoring one,
126
+ * which for a repeat allele carrying an interruption is often not equivalent to
127
+ * any placement inside the array. FMR1's misplaced read is exactly that: 32bp
128
+ * of the locus's own CGG anchored two bases early, starting on a `C` where the
129
+ * read has a `G`, so no rewrite of it exists. Hence `reanchorInsertions` treats
130
+ * this as the preferred spelling and not as the test of whether to move.
131
+ */
132
+ export function shiftInsertion(
133
+ read: ReadLayout,
134
+ from: number,
135
+ to: number,
136
+ ins: string,
137
+ ) {
138
+ let seq = ins
139
+ for (let pos = from; pos < to; pos++) {
140
+ const head = seq[0]!
141
+ if (readBase(read, pos) !== head) {
142
+ return undefined
143
+ }
144
+ seq = seq.slice(1) + head
78
145
  }
79
- return ret
146
+ for (let pos = from - 1; pos >= to; pos--) {
147
+ const tail = seq.at(-1)!
148
+ if (readBase(read, pos) !== tail) {
149
+ return undefined
150
+ }
151
+ seq = tail + seq.slice(0, -1)
152
+ }
153
+ return seq
154
+ }
155
+
156
+ /** an array with the span of reference positions whose insertions it may claim */
157
+ interface FlankWindow {
158
+ array: ReferenceArray
159
+ from: number
160
+ to: number
161
+ }
162
+
163
+ /**
164
+ * The window around each array that its insertions may be re-anchored from.
165
+ *
166
+ * Two arrays may not claim one position: `extractAllele` reads the slot at an
167
+ * array's `end`, so a shared slot would be counted into two alleles. Neighbours
168
+ * split the reference between them down the middle — a property of the
169
+ * reference alone, so unlike the interval it replaces, no read can move it.
170
+ */
171
+ export function flankWindows(arrays: ReferenceArray[]): FlankWindow[] {
172
+ const ordered = [...arrays].sort((a, b) => a.start - b.start)
173
+ return ordered.map((array, i) => {
174
+ const pad = Math.max(FLANK_BP, array.period)
175
+ const previous = ordered[i - 1]
176
+ const next = ordered[i + 1]
177
+ return {
178
+ array,
179
+ from: Math.max(
180
+ array.start - pad,
181
+ previous ? Math.floor((previous.end + array.start) / 2) + 1 : -Infinity,
182
+ ),
183
+ to: Math.min(
184
+ array.end + pad,
185
+ next ? Math.floor((array.end + next.start) / 2) : Infinity,
186
+ ),
187
+ }
188
+ })
189
+ }
190
+
191
+ /** the array whose window `pos` falls in, if any */
192
+ function windowAt(pos: number, windows: FlankWindow[]) {
193
+ for (const window of windows) {
194
+ if (pos < window.from) {
195
+ return undefined
196
+ }
197
+ if (pos <= window.to) {
198
+ return window
199
+ }
200
+ }
201
+ return undefined
202
+ }
203
+
204
+ /**
205
+ * Re-file each read's insertions under the array they belong to, one read at a
206
+ * time.
207
+ *
208
+ * Measuring an allele over a reference interval fixes the "one array reports as
209
+ * several sites" problem for indels the aligner placed *inside* the interval.
210
+ * It does not fix the ones placed just outside: there the insertion is part of
211
+ * no allele — it becomes its own run of insertion columns — and the read
212
+ * carrying it is measured as though it had the reference allele. Both halves of
213
+ * that are wrong, and neither is rare: at ATXN3 the aligner anchored 60 of 162
214
+ * reads' expansions one base outside the array.
215
+ *
216
+ * Doing this per read is the whole point. Widening the shared interval instead
217
+ * — which is what this replaces — made one read's misplacement everyone's: a
218
+ * single spurious copy anchored two bases early moved the array's left edge for
219
+ * every row, and the reference's own copy count with it. Re-anchoring touches
220
+ * only the read that carries the insertion, so a read can be wrong on its own.
221
+ *
222
+ * Nothing here consults the other reads, or how many of them agree. A single
223
+ * read's expansion is as real as fifty, which is what measuring over an
224
+ * interval buys and what a vote would give back. What decides an insertion is
225
+ * its own sequence: `unitIdentity` against the array's unit, since the aligner
226
+ * is free to place a repeat allele outside the array but is not free to make
227
+ * unrelated sequence out of the array's unit.
228
+ */
229
+ export function reanchorInsertions(
230
+ reads: ReadLayout[],
231
+ arrays: ReferenceArray[],
232
+ ) {
233
+ const windows = flankWindows(arrays)
234
+ if (!windows.length) {
235
+ return reads
236
+ }
237
+ // memoized per array and distinct insert: one locus routinely has dozens of
238
+ // reads carrying the same allele at the same site
239
+ const belongs = new Map<string, boolean>()
240
+ const isUnit = (window: FlankWindow, ins: string) => {
241
+ const key = `${window.array.start}:${ins}`
242
+ let ret = belongs.get(key)
243
+ if (ret === undefined) {
244
+ ret =
245
+ // a whole copy at least: a base or two of read error beside an array
246
+ // says nothing about where its allele ends, and the identity of a
247
+ // fragment shorter than the unit is not a measurement of anything
248
+ ins.length >= window.array.period &&
249
+ unitIdentity(ins, window.array.unit) >= BELONGS_IDENTITY
250
+ belongs.set(key, ret)
251
+ }
252
+ return ret
253
+ }
254
+ return reads.map(read => {
255
+ if (!read.insertions.size) {
256
+ return read
257
+ }
258
+ let moved = false
259
+ const next = new Map<number, string>()
260
+ // Insertions are re-filed in genomic order of where the aligner put them,
261
+ // so two events landing in one slot keep their order along the read.
262
+ for (const [pos, ins] of [...read.insertions].sort((a, b) => a[0] - b[0])) {
263
+ const window = windowAt(pos, windows)
264
+ const { start, end } = window?.array ?? {}
265
+ const target =
266
+ window === undefined || (pos >= start! && pos <= end!)
267
+ ? undefined
268
+ : isUnit(window, ins)
269
+ ? pos < start!
270
+ ? start!
271
+ : end!
272
+ : undefined
273
+ // an exact rewrite is preferred where one exists, so a row that can be
274
+ // re-spelled reads base for base as the aligner wrote it; where none
275
+ // exists the bases move as written, which preserves the length the
276
+ // measurement is made of
277
+ const at = target ?? pos
278
+ moved ||= target !== undefined
279
+ const seq =
280
+ target === undefined ? ins : (shiftInsertion(read, pos, target, ins) ?? ins)
281
+ next.set(at, (next.get(at) ?? '') + seq)
282
+ }
283
+ return moved ? { ...read, insertions: next } : read
284
+ })
80
285
  }
81
286
 
82
287
  /**
@@ -0,0 +1,225 @@
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
+ const MIN_ALLELE_FRACTION = 0.15
21
+
22
+ /** ...and never on one read, at any coverage. */
23
+ const MIN_ALLELE_READS = 2
24
+
25
+ /**
26
+ * How far from an allele a read's copy count may fall and still be counted as
27
+ * that allele's, as a fraction of the allele's own size.
28
+ *
29
+ * Proportional rather than fixed because slippage scales with the array: the
30
+ * reads either side of an 89-copy allele scatter further than those either side
31
+ * of an 8-copy one. cuteSV refines a cluster of structural-variant signatures
32
+ * the same way, by a bandwidth taken as a fraction of the cluster's own mean
33
+ * length (Jiang et al., Genome Biol 21, 2020, doi:10.1186/s13059-020-02107-y);
34
+ * its constants are fractions of a length in bases and do not carry over to a
35
+ * count of copies, so this one is measured here instead. At 0.1 no call in the
36
+ * trio moves, merges or is lost, and the reads left out of one drop by three
37
+ * quarters.
38
+ */
39
+ const SHOULDER_SPREAD = 0.1
40
+
41
+ /**
42
+ * ...and how much support such a read may carry, relative to the allele it
43
+ * would join, before it is an allele of its own instead.
44
+ *
45
+ * This is the load-bearing half, and distance alone cannot replace it. At FMR1
46
+ * the mother carries two alleles one copy apart and at HTT a single allele has
47
+ * a shoulder one copy either side, so no bandwidth tells those two apart.
48
+ * Relative support does: a slippage shoulder in the trio runs at a fraction of
49
+ * its allele, and the mother's second allele runs at 87% of her first. The
50
+ * measured shelf is wide — 0.2 leaves reads uncounted, 0.4 starts merging the
51
+ * mother's two alleles into one.
52
+ *
53
+ * That shelf is 21 sample-locus calls in one trio, which is a shelf and not a
54
+ * proof: a locus carrying three real alleles within a copy of each other would
55
+ * defeat the rule, and this trio has none.
56
+ */
57
+ const SHOULDER_SUPPORT = 0.3
58
+
59
+ export interface Tally {
60
+ value: number
61
+ reads: number
62
+ }
63
+
64
+ /** Each distinct value with how many rows carried it, smallest value first. */
65
+ export function tally(values: number[]): Tally[] {
66
+ const counts = new Map<number, number>()
67
+ for (const v of values) {
68
+ counts.set(v, (counts.get(v) ?? 0) + 1)
69
+ }
70
+ return [...counts]
71
+ .map(([value, reads]) => ({ value, reads }))
72
+ .sort((a, b) => a.value - b.value)
73
+ }
74
+
75
+ /**
76
+ * The copy counts a sample carries, each with the reads that fell on it or in
77
+ * its skirt.
78
+ *
79
+ * Reads scatter around an allele — slippage in the molecule, slippage in the
80
+ * aligner — so a rule that reported only exact agreement credited an allele
81
+ * with a fraction of the reads that actually support it, and left the rest
82
+ * looking like disagreement. Counts are gathered strongest first, so an allele
83
+ * is established before anything can be read as its shoulder, and a value joins
84
+ * one only if it is both near it and much weaker than it.
85
+ *
86
+ * This is a report of what the reads say, not a genotype call: it does not know
87
+ * a ploidy, so a homozygote and a haploid locus both come back as one number,
88
+ * and a sample whose reads scatter can come back with none.
89
+ */
90
+ export function alleleModes(copies: number[]): Tally[] {
91
+ const floor = Math.max(MIN_ALLELE_READS, MIN_ALLELE_FRACTION * copies.length)
92
+ const peaks: Tally[] = []
93
+ for (const t of tally(copies).sort(
94
+ (a, b) => b.reads - a.reads || a.value - b.value,
95
+ )) {
96
+ const distance = (peak: Tally) => Math.abs(t.value - peak.value)
97
+ const host = peaks
98
+ .filter(
99
+ peak =>
100
+ distance(peak) <= Math.max(1, SHOULDER_SPREAD * peak.value) &&
101
+ t.reads <= SHOULDER_SUPPORT * peak.reads,
102
+ )
103
+ .sort((a, b) => distance(a) - distance(b))[0]
104
+ if (host) {
105
+ host.reads += t.reads
106
+ } else {
107
+ peaks.push({ ...t })
108
+ }
109
+ }
110
+ return peaks.filter(p => p.reads >= floor).sort((a, b) => a.value - b.value)
111
+ }
112
+
113
+ export interface SampleArrayStats {
114
+ sample: string
115
+ /** rows that reached both ends of the interval, i.e. that were measured */
116
+ spanning: number
117
+ /** the alleles found, each with the reads counted into it */
118
+ modes: Tally[]
119
+ /** every copy count seen, with its support */
120
+ copies: Tally[]
121
+ /** rows counted into no allele at all */
122
+ offMode: number
123
+ }
124
+
125
+ export interface ArrayStats {
126
+ start: number
127
+ end: number
128
+ period: number
129
+ unit: string
130
+ /** reference positions the interval covers */
131
+ span: number
132
+ /** columns the block occupies */
133
+ width: number
134
+ /** the reference's own copy count, when the reference was a row */
135
+ referenceCopies?: number
136
+ /** whether the rows were ordered and labelled by this array */
137
+ subject: boolean
138
+ samples: SampleArrayStats[]
139
+ }
140
+
141
+ function sampleOfRow(name: string) {
142
+ const i = name.indexOf('|')
143
+ return i < 0 ? undefined : name.slice(0, i)
144
+ }
145
+
146
+ function arrayStats(
147
+ array: ArrayBlock,
148
+ plan: TviewPlan,
149
+ samples: string[],
150
+ ): ArrayStats {
151
+ return {
152
+ start: array.start,
153
+ end: array.end,
154
+ period: array.period,
155
+ unit: array.unit,
156
+ span: array.end - array.start,
157
+ width: array.width,
158
+ referenceCopies: plan.referenceName
159
+ ? array.copiesByName.get(plan.referenceName)
160
+ : undefined,
161
+ subject: array === plan.subject,
162
+ samples: samples.map(sample => {
163
+ const copies = [...array.copiesByName]
164
+ .filter(([name]) => sampleOfRow(name) === sample)
165
+ .map(([, n]) => n)
166
+ const modes = alleleModes(copies)
167
+ return {
168
+ sample,
169
+ spanning: copies.length,
170
+ modes,
171
+ copies: tally(copies),
172
+ // an allele carries the reads in its skirt as well as those exactly on
173
+ // it, so what is left over is counted off the alleles rather than off
174
+ // the distinct values they were called at
175
+ offMode: copies.length - modes.reduce((a, m) => a + m.reads, 0),
176
+ }
177
+ }),
178
+ }
179
+ }
180
+
181
+ export interface PlanStats {
182
+ rows: number
183
+ columns: number
184
+ /**
185
+ * columns exactly one row has a base in. One read's miscalled indel costs
186
+ * every row a column, so this is the size of what "hide columns w/ N% gaps"
187
+ * takes off a figure — read error, measured rather than estimated.
188
+ */
189
+ singleRowColumns: number
190
+ /** columns no row has a base in, which no setting is needed to justify */
191
+ emptyColumns: number
192
+ arrays: ArrayStats[]
193
+ }
194
+
195
+ /** Rows, columns, and every array, from a plan the view could equally render. */
196
+ export function summarizePlan(plan: TviewPlan, samples?: string[]): PlanStats {
197
+ const rows = plan.reads.map(read => renderRow(read, plan.layout))
198
+ const perColumn = new Int32Array(plan.layout.totalColumns)
199
+ for (const row of rows) {
200
+ for (let col = 0; col < row.length; col++) {
201
+ const char = row[col]!
202
+ if (char !== ABSENT && char !== SPANNED_GAP) {
203
+ perColumn[col] = perColumn[col]! + 1
204
+ }
205
+ }
206
+ }
207
+ let singleRowColumns = 0
208
+ let emptyColumns = 0
209
+ for (const count of perColumn) {
210
+ if (count === 0) {
211
+ emptyColumns++
212
+ } else if (count === 1) {
213
+ singleRowColumns++
214
+ }
215
+ }
216
+ return {
217
+ rows: plan.reads.length,
218
+ columns: plan.layout.totalColumns,
219
+ singleRowColumns,
220
+ emptyColumns,
221
+ arrays: plan.arrays.map(array =>
222
+ arrayStats(array, plan, samples ?? plan.samples),
223
+ ),
224
+ }
225
+ }
@@ -1,5 +1,5 @@
1
1
  import { alignInsertionSite } from './align'
2
- import { buildArrayBlocks } from './alleles'
2
+ import { buildArrayBlocks, reanchorInsertions } from './alleles'
3
3
  import {
4
4
  ABSENT,
5
5
  SPANNED_GAP,
@@ -311,12 +311,16 @@ export function planTviewMsa({
311
311
  end,
312
312
  )
313
313
 
314
- const arrays = sequence
315
- ? buildArrayBlocks(
316
- clipped,
317
- mergeArrays(findReferenceArrays(sequence, start)),
318
- )
314
+ // The intervals come from the reference and nothing here moves them. What
315
+ // moves is each read's insertions, re-filed under the array they belong to
316
+ // before anything is measured or laid out — see reanchorInsertions. Both
317
+ // steps below read the re-anchored reads, so an insertion the array took over
318
+ // is rendered inside its block and not also as a column of its own.
319
+ const intervals = sequence
320
+ ? mergeArrays(findReferenceArrays(sequence, start))
319
321
  : []
322
+ const anchored = reanchorInsertions(clipped, intervals)
323
+ const arrays = buildArrayBlocks(anchored, intervals)
320
324
  const ownedByArray = new Set<number>()
321
325
  for (const array of arrays) {
322
326
  for (let pos = array.start; pos <= array.end; pos++) {
@@ -324,7 +328,7 @@ export function planTviewMsa({
324
328
  }
325
329
  }
326
330
 
327
- const aligned = alignInsertionColumns(clipped, ownedByArray)
331
+ const aligned = alignInsertionColumns(anchored, ownedByArray)
328
332
 
329
333
  // With several arrays in view the subject is the one the rows disagree most
330
334
  // about, since ordering rows by two copy numbers at once is not a thing rows
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '2.1.0'
1
+ export const version = '2.2.1'