jbrowse-plugin-tview 2.0.6 → 2.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.
Files changed (73) hide show
  1. package/README.md +157 -4
  2. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.d.ts +132 -0
  3. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js +152 -0
  4. package/dist/LaunchTView/TviewGetPlanRpc/TviewGetPlan.js.map +1 -0
  5. package/dist/LaunchTView/TviewGetPlanRpc/index.d.ts +3 -0
  6. package/dist/LaunchTView/TviewGetPlanRpc/index.js +5 -0
  7. package/dist/LaunchTView/TviewGetPlanRpc/index.js.map +1 -0
  8. package/dist/LaunchTView/align.d.ts +93 -9
  9. package/dist/LaunchTView/align.js +290 -15
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +57 -0
  12. package/dist/LaunchTView/alleles.js +94 -0
  13. package/dist/LaunchTView/alleles.js.map +1 -0
  14. package/dist/LaunchTView/components/ArrayReport.d.ts +10 -0
  15. package/dist/LaunchTView/components/ArrayReport.js +59 -0
  16. package/dist/LaunchTView/components/ArrayReport.js.map +1 -0
  17. package/dist/LaunchTView/components/LaunchTViewDialog.js +74 -37
  18. package/dist/LaunchTView/components/LaunchTViewDialog.js.map +1 -1
  19. package/dist/LaunchTView/fetchTviewPlan.d.ts +20 -13
  20. package/dist/LaunchTView/fetchTviewPlan.js +27 -27
  21. package/dist/LaunchTView/fetchTviewPlan.js.map +1 -1
  22. package/dist/LaunchTView/launchView.d.ts +25 -0
  23. package/dist/LaunchTView/launchView.js +20 -0
  24. package/dist/LaunchTView/launchView.js.map +1 -0
  25. package/dist/LaunchTView/readLayout.d.ts +85 -0
  26. package/dist/LaunchTView/readLayout.js +96 -0
  27. package/dist/LaunchTView/readLayout.js.map +1 -0
  28. package/dist/LaunchTView/repeats.d.ts +68 -0
  29. package/dist/LaunchTView/repeats.js +200 -0
  30. package/dist/LaunchTView/repeats.js.map +1 -0
  31. package/dist/LaunchTView/sampleTree.d.ts +37 -0
  32. package/dist/LaunchTView/sampleTree.js +65 -0
  33. package/dist/LaunchTView/sampleTree.js.map +1 -0
  34. package/dist/LaunchTView/tview.d.ts +67 -44
  35. package/dist/LaunchTView/tview.js +190 -121
  36. package/dist/LaunchTView/tview.js.map +1 -1
  37. package/dist/LaunchTView/useTviewMsa.d.ts +13 -9
  38. package/dist/LaunchTView/useTviewMsa.js +15 -11
  39. package/dist/LaunchTView/useTviewMsa.js.map +1 -1
  40. package/dist/TViewPanel/coords.d.ts +9 -1
  41. package/dist/TViewPanel/coords.js +22 -2
  42. package/dist/TViewPanel/coords.js.map +1 -1
  43. package/dist/TViewPanel/init.d.ts +56 -0
  44. package/dist/TViewPanel/init.js +59 -0
  45. package/dist/TViewPanel/init.js.map +1 -0
  46. package/dist/TViewPanel/model.d.ts +47 -31
  47. package/dist/TViewPanel/model.js +73 -51
  48. package/dist/TViewPanel/model.js.map +1 -1
  49. package/dist/index.js +5 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/jbrowse-plugin-tview.umd.production.min.js +22 -22
  52. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.js +1 -1
  55. package/package.json +5 -2
  56. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +264 -0
  57. package/src/LaunchTView/TviewGetPlanRpc/index.ts +14 -0
  58. package/src/LaunchTView/align.ts +343 -17
  59. package/src/LaunchTView/alleles.ts +132 -0
  60. package/src/LaunchTView/components/ArrayReport.tsx +64 -0
  61. package/src/LaunchTView/components/LaunchTViewDialog.tsx +122 -39
  62. package/src/LaunchTView/fetchTviewPlan.ts +42 -42
  63. package/src/LaunchTView/launchView.ts +50 -0
  64. package/src/LaunchTView/readLayout.ts +145 -0
  65. package/src/LaunchTView/repeats.ts +218 -0
  66. package/src/LaunchTView/sampleTree.ts +73 -0
  67. package/src/LaunchTView/tview.ts +259 -157
  68. package/src/LaunchTView/useTviewMsa.ts +20 -17
  69. package/src/TViewPanel/coords.ts +23 -1
  70. package/src/TViewPanel/init.ts +127 -0
  71. package/src/TViewPanel/model.ts +82 -61
  72. package/src/index.ts +5 -1
  73. package/src/version.ts +1 -1
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "2.0.6";
1
+ export declare const version = "2.1.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.0.6';
1
+ export const version = '2.1.0';
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.0.6",
2
+ "version": "2.1.0",
3
3
  "license": "MIT",
4
4
  "name": "jbrowse-plugin-tview",
5
5
  "repository": {
@@ -33,7 +33,10 @@
33
33
  "prepack": "pnpm build",
34
34
  "preversion": "pnpm lint && pnpm build",
35
35
  "version": "node scripts/version.mjs",
36
- "postversion": "git push --follow-tags"
36
+ "postversion": "git push --follow-tags",
37
+ "figures:repeats": "node scripts/repeat-figures.mjs",
38
+ "prefigures:repeats": "pnpm pretest:e2e",
39
+ "qc:repeats": "tsx test/liveRepeats.qc.ts"
37
40
  },
38
41
  "jbrowse-plugin": {
39
42
  "name": "TView"
@@ -0,0 +1,264 @@
1
+ import { getAdapter } from '@jbrowse/core/data_adapters/dataAdapterCache'
2
+ import { RpcMethodType } from '@jbrowse/core/pluggableElementTypes'
3
+ import { renameRegionsIfNeeded } from '@jbrowse/core/util'
4
+
5
+ import { buildSampleTree } from '../sampleTree'
6
+ import { planTviewMsa, renderTviewMsa } from '../tview'
7
+
8
+ import type { AlignmentFeature } from '../readLayout'
9
+ import type PluginManager from '@jbrowse/core/PluginManager'
10
+ import type { Region } from '@jbrowse/core/util'
11
+
12
+ /** one BAM/CRAM to draw rows from, and the name its rows are grouped under */
13
+ export interface TviewSourceArgs {
14
+ adapterConfig: Record<string, unknown>
15
+ sample?: string
16
+ /**
17
+ * what this file calls the region's sequence. Filled in on the client, where
18
+ * the assembly's aliases live: two files over one assembly routinely spell it
19
+ * `4` and `chr4`, and a mismatched name fetches nothing and reports nothing.
20
+ */
21
+ refName?: string
22
+ }
23
+
24
+ export interface TviewGetPlanArgs {
25
+ sessionId: string
26
+ sources: TviewSourceArgs[]
27
+ /** the assembly's sequence adapter, when it has one */
28
+ sequenceAdapterConfig?: Record<string, unknown>
29
+ /** the sequence adapter's own spelling of the region */
30
+ sequenceRefName?: string
31
+ region: Region
32
+ /** stop before rendering an alignment bigger than this many cells */
33
+ maxCells: number
34
+ }
35
+
36
+ /** what crosses back: the alignment, and the numbers the dialog reports */
37
+ export interface TviewArrayReport {
38
+ start: number
39
+ end: number
40
+ period: number
41
+ unit: string
42
+ width: number
43
+ /** per row: copies carried, and allele length in bp */
44
+ copies: [string, number][]
45
+ lengths: [string, number][]
46
+ }
47
+
48
+ export interface TviewPlanResult {
49
+ msa: string
50
+ /** Newick grouping rows by sample; absent unless several were loaded */
51
+ tree?: string
52
+ rowCount: number
53
+ columnCount: number
54
+ cellCount: number
55
+ insertionWidths: [number, number][]
56
+ arraySpans: [number, number, number][]
57
+ region: { refName: string; start: number; end: number }
58
+ arrays: TviewArrayReport[]
59
+ subjectIndex?: number
60
+ referenceName?: string
61
+ samples: string[]
62
+ /** set when the alignment was over maxCells and `msa` is empty */
63
+ tooLarge?: boolean
64
+ }
65
+
66
+ /** the slice of a data adapter this reads, which is all of `getFeatures` */
67
+ interface FeatureSource {
68
+ getFeatures: (region: Region) => {
69
+ subscribe: (observer: {
70
+ next: (feature: AlignmentFeature) => void
71
+ error: (error: unknown) => void
72
+ complete: () => void
73
+ }) => unknown
74
+ }
75
+ }
76
+
77
+ function isFeatureSource(adapter: object): adapter is FeatureSource {
78
+ return 'getFeatures' in adapter && typeof adapter.getFeatures === 'function'
79
+ }
80
+
81
+ /**
82
+ * Drains an adapter's feature observable into an array.
83
+ *
84
+ * Hand-rolled rather than `firstValueFrom(...pipe(toArray()))` because rxjs is
85
+ * not a dependency here and `@jbrowse/core/util/rxjs` publishes only
86
+ * `ObservableCreate`. Subscribing directly needs neither.
87
+ */
88
+ async function fetchAll(
89
+ pluginManager: PluginManager,
90
+ sessionId: string,
91
+ adapterConfig: Record<string, unknown>,
92
+ region: Region,
93
+ ) {
94
+ const { dataAdapter } = await getAdapter(
95
+ pluginManager,
96
+ sessionId,
97
+ adapterConfig,
98
+ )
99
+ if (!isFeatureSource(dataAdapter)) {
100
+ throw new Error(`${adapterConfig.type as string} has no getFeatures`)
101
+ }
102
+ return new Promise<AlignmentFeature[]>((resolve, reject) => {
103
+ const ret: AlignmentFeature[] = []
104
+ dataAdapter.getFeatures(region).subscribe({
105
+ next: feature => ret.push(feature),
106
+ error: reject,
107
+ complete: () => {
108
+ resolve(ret)
109
+ },
110
+ })
111
+ })
112
+ }
113
+
114
+ /**
115
+ * Builds the whole alignment in the worker and sends back the FASTA.
116
+ *
117
+ * The work this moves is not the fetch — `CoreGetFeatures` already ran in a
118
+ * worker — but everything after it. Fetching from the client meant serializing
119
+ * every read's sequence and CIGAR across the boundary and then running the
120
+ * pairwise alignments and the string building on the main thread, where a
121
+ * region carrying a kilobase-scale array froze the UI for as long as it took.
122
+ * What comes back now is the alignment, which is smaller than the reads it was
123
+ * built from and is the only thing the view has a use for.
124
+ *
125
+ * It is also what makes several files one call: their rows are squared up
126
+ * against the same reference interval, so an array's copies are counted once,
127
+ * over rows from all of them.
128
+ */
129
+ export default class TviewGetPlan extends RpcMethodType {
130
+ name = 'TviewGetPlan'
131
+
132
+ /**
133
+ * Written against the 4.3.0 base class, which takes a bare
134
+ * `Record<string, unknown>` and has no `renameRegions` helper — that is the
135
+ * oldest host this bundle boots on, and the newer base class accepts the same
136
+ * shape.
137
+ */
138
+ async serializeArguments(
139
+ args: Record<string, unknown>,
140
+ rpcDriverClassName: string,
141
+ ) {
142
+ const typed = args as unknown as TviewGetPlanArgs
143
+ const assemblyManager =
144
+ this.pluginManager.rootModel?.session?.assemblyManager
145
+ if (!assemblyManager) {
146
+ throw new Error('no assembly manager')
147
+ }
148
+ const refNameFor = async (adapterConfig: Record<string, unknown>) => {
149
+ const { regions } = await renameRegionsIfNeeded(assemblyManager, {
150
+ sessionId: typed.sessionId,
151
+ adapterConfig,
152
+ regions: [typed.region],
153
+ })
154
+ return regions[0]!.refName
155
+ }
156
+ const sources = await Promise.all(
157
+ typed.sources.map(async source => ({
158
+ ...source,
159
+ refName: await refNameFor(source.adapterConfig),
160
+ })),
161
+ )
162
+ const sequenceRefName = typed.sequenceAdapterConfig
163
+ ? await refNameFor(typed.sequenceAdapterConfig)
164
+ : undefined
165
+
166
+ return super.serializeArguments(
167
+ { ...args, sources, sequenceRefName },
168
+ rpcDriverClassName,
169
+ )
170
+ }
171
+
172
+ async execute(args: TviewGetPlanArgs, rpcDriverClassName: string) {
173
+ const {
174
+ sessionId,
175
+ sources,
176
+ sequenceAdapterConfig,
177
+ sequenceRefName,
178
+ region,
179
+ maxCells,
180
+ } = await this.deserializeArguments(args, rpcDriverClassName)
181
+
182
+ const perSource = await Promise.all(
183
+ sources.map(source =>
184
+ fetchAll(this.pluginManager, sessionId, source.adapterConfig, {
185
+ ...region,
186
+ refName: source.refName ?? region.refName,
187
+ }),
188
+ ),
189
+ )
190
+ const features: AlignmentFeature[] = []
191
+ const sampleByIndex: (string | undefined)[] = []
192
+ for (const [i, feats] of perSource.entries()) {
193
+ for (const feature of feats) {
194
+ if (feature.get('seq')) {
195
+ features.push(feature)
196
+ sampleByIndex.push(sources[i]!.sample)
197
+ }
198
+ }
199
+ }
200
+
201
+ let sequence: string | undefined
202
+ if (sequenceAdapterConfig) {
203
+ const seqFeats = await fetchAll(
204
+ this.pluginManager,
205
+ sessionId,
206
+ sequenceAdapterConfig,
207
+ { ...region, refName: sequenceRefName ?? region.refName },
208
+ )
209
+ const seq = seqFeats[0]?.get('seq') as string | undefined
210
+ const seqStart = seqFeats[0]?.get('start') as number | undefined
211
+ // the adapter may answer with a wider block than it was asked for
212
+ const sliced =
213
+ seq !== undefined && seqStart !== undefined
214
+ ? seq.slice(region.start - seqStart, region.end - seqStart)
215
+ : undefined
216
+ // a short answer means the region runs off the end of the contig, and a
217
+ // reference row that stops early would misplace every column after it
218
+ sequence =
219
+ sliced?.length === region.end - region.start ? sliced : undefined
220
+ }
221
+
222
+ const plan = planTviewMsa({
223
+ features,
224
+ refName: region.refName,
225
+ start: region.start,
226
+ end: region.end,
227
+ sequence,
228
+ sampleOf: i => sampleByIndex[i],
229
+ })
230
+
231
+ const shared = {
232
+ rowCount: plan.reads.length,
233
+ columnCount: plan.layout.totalColumns,
234
+ cellCount: plan.cellCount,
235
+ insertionWidths: plan.insertionWidths,
236
+ arraySpans: plan.arraySpans,
237
+ region: plan.region,
238
+ arrays: plan.arrays.map(a => ({
239
+ start: a.start,
240
+ end: a.end,
241
+ period: a.period,
242
+ unit: a.unit,
243
+ width: a.width,
244
+ copies: [...a.copiesByName.entries()],
245
+ lengths: [...a.lengthByName.entries()],
246
+ })),
247
+ subjectIndex: plan.subject
248
+ ? plan.arrays.indexOf(plan.subject)
249
+ : undefined,
250
+ referenceName: plan.referenceName,
251
+ samples: plan.samples,
252
+ }
253
+
254
+ // the render is the expensive half and the only part bounded by rows x
255
+ // columns, so the size check happens before it rather than after
256
+ return plan.cellCount > maxCells
257
+ ? { ...shared, msa: '', tooLarge: true }
258
+ : {
259
+ ...shared,
260
+ msa: renderTviewMsa(plan),
261
+ tree: buildSampleTree(plan.reads),
262
+ }
263
+ }
264
+ }
@@ -0,0 +1,14 @@
1
+ import TviewGetPlan from './TviewGetPlan'
2
+
3
+ import type PluginManager from '@jbrowse/core/PluginManager'
4
+
5
+ export default function TviewGetPlanRpcF(pluginManager: PluginManager) {
6
+ pluginManager.addRpcMethod(() => new TviewGetPlan(pluginManager))
7
+ }
8
+
9
+ export type {
10
+ TviewArrayReport,
11
+ TviewGetPlanArgs,
12
+ TviewPlanResult,
13
+ TviewSourceArgs,
14
+ } from './TviewGetPlan'
@@ -5,10 +5,24 @@
5
5
  * shared event stops being readable. Aligning the inserted sequences against
6
6
  * each other fixes that.
7
7
  *
8
- * This is deliberately local to one reference position: the insertion still
9
- * occupies "as many columns as the widest gapped sequence", which is the only
10
- * thing buildColumnToRefPos knows about, so the column <-> reference mapping is
11
- * untouched.
8
+ * There are two ways to do it, and which one applies is a property of the
9
+ * inserted sequence rather than a setting:
10
+ *
11
+ * - **Aperiodic** (`alignInsertions`): one center-star alignment over the whole
12
+ * inserted sequence. Right for a novel insertion, a mobile element, anything
13
+ * whose bases only make sense read straight through.
14
+ * - **Periodic** (`alignPeriodicInsertions`): a tandem array, where the whole
15
+ * inserted sequence is n copies of one unit. Aligning those base-to-base is
16
+ * both unaffordable and wrong — it is free to align copy 5 of one read to
17
+ * copy 3 of another, and the difference that matters (how many copies) ends
18
+ * up expressed as where the row stops. Aligning unit-to-unit instead puts
19
+ * copy k of every read in the same columns, so copy number reads as a count
20
+ * of blocks and a divergent copy stands out as a column inside its block.
21
+ *
22
+ * Both are local to one reference position: the insertion still occupies "as
23
+ * many columns as the widest gapped sequence", which is the only thing
24
+ * buildColumnToRefPos knows about, so the column <-> reference mapping is
25
+ * untouched either way.
12
26
  */
13
27
 
14
28
  const MATCH = 2
@@ -20,6 +34,36 @@ const GAP = -3
20
34
  const MAX_LEN = 200
21
35
  const MAX_DISTINCT = 30
22
36
 
37
+ // Shortest unit that earns a unit-per-block layout. The scan below starts at 1
38
+ // so it reports the TRUE minimal period, which is what makes a homopolymer come
39
+ // back as 1 and get declined here: `AAAA...` is periodic at every lag, and
40
+ // laying it out as 2bp blocks would be an arbitrary reading of one run of A.
41
+ const MIN_UNIT_PERIOD = 2
42
+
43
+ // Longest unit the scan looks for. Covers STRs and the common VNTR range; the
44
+ // megabase-unit arrays (LPA KIV-2 at 5.5kb) need more copies than a read holds
45
+ // before they are periodic at all, so they are out of reach here regardless.
46
+ const MAX_PERIOD = 300
47
+
48
+ // Copies needed before a sequence counts as an array. Two copies of anything is
49
+ // a duplication, not a tandem repeat, and at two the period is unidentifiable
50
+ // from the sequence alone.
51
+ const MIN_COPIES = 3
52
+
53
+ // Fraction of positions that must agree at lag p for p to be the period. Loose
54
+ // enough for the ~5-15% divergence between copies of a real VNTR unit and for
55
+ // long-read error on top of it.
56
+ const PERIODIC_MATCH = 0.8
57
+
58
+ // The period scan is O(len * maxPeriod), so it runs on a prefix rather than the
59
+ // whole insert. An array that is periodic in its first 3kb is periodic.
60
+ const PROBE_LEN = 3000
61
+
62
+ // Backstops on the unit-level work, in the same spirit as MAX_LEN/MAX_DISTINCT:
63
+ // decline and leave the site to the aperiodic path rather than stall on it.
64
+ const MAX_UNITS = 1000
65
+ const MAX_PERIODIC_CELLS = 20_000_000
66
+
23
67
  function subst(a: string | undefined, b: string | undefined) {
24
68
  return a === b ? MATCH : MISMATCH
25
69
  }
@@ -115,21 +159,292 @@ function emit({ slots, atCenter }: CenterSplit, slotWidths: number[]) {
115
159
  }
116
160
 
117
161
  /**
118
- * Center-star multiple alignment of the sequences inserted at one reference
119
- * position. Returns each distinct input mapped to a gapped version, all of the
120
- * same length. Returns an empty map when there is nothing to gain (a single
121
- * distinct sequence) or when the site is too large to be worth aligning; the
122
- * caller then keeps the sequences as-is and left-justifies them.
162
+ * The smallest lag at which a sequence repeats, or undefined when it does not.
163
+ *
164
+ * Scanning up from 1 returns the true minimal period, which is what separates a
165
+ * tandem array from a homopolymer: `AAAA...` matches at every lag and comes back
166
+ * as 1, and a 30bp unit comes back as 30 rather than as 60 or 90.
123
167
  */
124
- export function alignInsertions(seqs: string[]) {
168
+ export function detectPeriod(seq: string): number | undefined {
169
+ const probe = seq.length > PROBE_LEN ? seq.slice(0, PROBE_LEN) : seq
170
+ const maxPeriod = Math.min(MAX_PERIOD, Math.floor(probe.length / MIN_COPIES))
171
+ for (let p = 1; p <= maxPeriod; p++) {
172
+ const n = probe.length - p
173
+ let matches = 0
174
+ for (let i = 0; i < n; i++) {
175
+ if (probe[i] === probe[i + p]) {
176
+ matches++
177
+ }
178
+ }
179
+ if (matches / n >= PERIODIC_MATCH) {
180
+ return p
181
+ }
182
+ }
183
+ return undefined
184
+ }
185
+
186
+ /**
187
+ * Majority base at each offset within the unit, over the whole-length copies of
188
+ * `seq`. The consensus is what every copy of every read is aligned to, so it has
189
+ * to be one fixed string for the site — deriving it per read would let two reads
190
+ * disagree about where a unit starts.
191
+ */
192
+ export function consensusUnit(seq: string, period: number) {
193
+ const copies = Math.floor(seq.length / period)
194
+ let ret = ''
195
+ for (let j = 0; j < period; j++) {
196
+ const counts = new Map<string, number>()
197
+ for (let k = 0; k < copies; k++) {
198
+ const c = seq[k * period + j]!
199
+ counts.set(c, (counts.get(c) ?? 0) + 1)
200
+ }
201
+ // ties break lexicographically so the consensus is a function of the input
202
+ // and not of Map iteration order
203
+ ret += [...counts].sort(
204
+ (a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1),
205
+ )[0]![0]
206
+ }
207
+ return ret
208
+ }
209
+
210
+ /**
211
+ * Align one copy of the consensus unit against `seq` starting at `from`: global
212
+ * on the consensus, since a copy is a whole copy, and free at the window's right
213
+ * edge, since the copy ends wherever it ends. `consumed` is where the next copy
214
+ * starts, which is what lets an indel inside one copy stay inside it rather than
215
+ * shifting every copy after it.
216
+ */
217
+ function alignUnitAt(consensus: string, seq: string, from: number) {
218
+ const n = consensus.length
219
+ const m = Math.min(2 * n, seq.length - from)
220
+ const stride = m + 1
221
+ const score = new Int32Array((n + 1) * stride)
222
+ for (let i = 1; i <= n; i++) {
223
+ score[i * stride] = i * GAP
224
+ }
225
+ for (let j = 1; j <= m; j++) {
226
+ score[j] = j * GAP
227
+ }
228
+ for (let i = 1; i <= n; i++) {
229
+ for (let j = 1; j <= m; j++) {
230
+ score[i * stride + j] = Math.max(
231
+ score[(i - 1) * stride + j - 1]! +
232
+ subst(consensus[i - 1], seq[from + j - 1]),
233
+ score[(i - 1) * stride + j]! + GAP,
234
+ score[i * stride + j - 1]! + GAP,
235
+ )
236
+ }
237
+ }
238
+
239
+ // the copy ends at whichever window position scores best once the consensus
240
+ // is spent
241
+ let consumed = 0
242
+ let best = score[n * stride]!
243
+ for (let j = 1; j <= m; j++) {
244
+ const s = score[n * stride + j]!
245
+ if (s > best) {
246
+ best = s
247
+ consumed = j
248
+ }
249
+ }
250
+ // a copy that consumed nothing would not advance the cursor
251
+ if (consumed === 0) {
252
+ return undefined
253
+ }
254
+
255
+ const outCenter: string[] = []
256
+ const outOther: string[] = []
257
+ let i = n
258
+ let j = consumed
259
+ while (i > 0 || j > 0) {
260
+ const cur = score[i * stride + j]!
261
+ const diagonal =
262
+ i > 0 &&
263
+ j > 0 &&
264
+ cur ===
265
+ score[(i - 1) * stride + j - 1]! +
266
+ subst(consensus[i - 1], seq[from + j - 1])
267
+ if (diagonal) {
268
+ outCenter.push(consensus[i - 1]!)
269
+ outOther.push(seq[from + j - 1]!)
270
+ i--
271
+ j--
272
+ } else if (i > 0 && cur === score[(i - 1) * stride + j]! + GAP) {
273
+ outCenter.push(consensus[i - 1]!)
274
+ outOther.push('-')
275
+ i--
276
+ } else {
277
+ outCenter.push('-')
278
+ outOther.push(seq[from + j - 1]!)
279
+ j--
280
+ }
281
+ }
282
+ return {
283
+ center: outCenter.reverse().join(''),
284
+ other: outOther.reverse().join(''),
285
+ consumed,
286
+ }
287
+ }
288
+
289
+ /** Every copy in `seq`, each as a pairwise alignment against the consensus. */
290
+ function splitIntoUnits(seq: string, consensus: string) {
291
+ const units: { center: string; other: string }[] = []
292
+ let cursor = 0
293
+ while (cursor < seq.length) {
294
+ const unit = alignUnitAt(consensus, seq, cursor)
295
+ if (!unit || units.length >= MAX_UNITS) {
296
+ return undefined
297
+ }
298
+ units.push(unit)
299
+ cursor += unit.consumed
300
+ }
301
+ return units
302
+ }
303
+
304
+ export interface PeriodicAlignment {
305
+ /** repeat unit length in bp */
306
+ period: number
307
+ /** each distinct input mapped to a gapped version, all the same length */
308
+ gapped: Map<string, string>
309
+ /** each distinct input mapped to its copy count */
310
+ copies: Map<string, number>
311
+ /** columns each copy occupies, left to right; sums to the gapped length */
312
+ unitWidths: number[]
313
+ }
314
+
315
+ /**
316
+ * Unit-per-block alignment of the sequences inserted at one reference position.
317
+ *
318
+ * Copy k of every sequence lands in the same block of columns, and a block is
319
+ * as wide as the widest version of that copy across the site, so a sequence with
320
+ * fewer copies runs out of blocks rather than drifting out of register. Returns
321
+ * undefined when the site is not a tandem array, or is too big to lay out this
322
+ * way; the caller falls back to `alignInsertions`.
323
+ *
324
+ * **Blocks are array order, not homology.** Copies are anchored at the left edge
325
+ * of the insertion and counted rightward, so block k is "the kth copy along",
326
+ * and arrays grow and shrink by unequal crossing over anywhere inside them —
327
+ * block 9 of a 12-copy allele and block 9 of a 20-copy allele need not be the
328
+ * same copy. What the layout does buy is that copies stay in register, so a
329
+ * single divergent copy shows up as a column instead of shifting every copy
330
+ * after it. Reading down one row is sound; reading across two is a hypothesis.
331
+ */
332
+ export function alignPeriodicInsertions(
333
+ seqs: string[],
334
+ ): PeriodicAlignment | undefined {
125
335
  const distinct = [...new Set(seqs)]
126
336
  const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
337
+ const period = detectPeriod(longest)
338
+ if (period === undefined || period < MIN_UNIT_PERIOD) {
339
+ return undefined
340
+ }
341
+ return alignToUnit(distinct, consensusUnit(longest, period))
342
+ }
343
+
344
+ /**
345
+ * Unit-per-block alignment against a unit the caller already knows.
346
+ *
347
+ * Separated from `alignPeriodicInsertions` because where the unit comes from is
348
+ * the whole difference between the two ways of finding an array. Measured off
349
+ * the inserted sequences, it can only be derived from one of them — the longest,
350
+ * which is a guess that one chimeric read overturns for the whole site. Measured
351
+ * off the reference, it is a property of the locus, so every read is laid out
352
+ * against the same unit whatever the reads happen to be.
353
+ */
354
+ export function alignToUnit(
355
+ seqs: string[],
356
+ consensus: string,
357
+ ): PeriodicAlignment | undefined {
358
+ const distinct = [...new Set(seqs)].filter(s => s.length > 0)
359
+ const period = consensus.length
360
+ if (!distinct.length || period < MIN_UNIT_PERIOD) {
361
+ return undefined
362
+ }
363
+
364
+ const totalUnits = distinct.reduce(
365
+ (a, s) => a + Math.ceil(s.length / period),
366
+ 0,
367
+ )
368
+ if (totalUnits * (period + 1) * (2 * period + 1) > MAX_PERIODIC_CELLS) {
369
+ return undefined
370
+ }
371
+
372
+ const splits = new Map<string, CenterSplit[]>()
373
+ for (const seq of distinct) {
374
+ const units = splitIntoUnits(seq, consensus)
375
+ if (!units) {
376
+ return undefined
377
+ }
378
+ splits.set(
379
+ seq,
380
+ units.map(u => splitAgainstCenter(u, period)),
381
+ )
382
+ }
383
+
384
+ const maxUnits = Math.max(...[...splits.values()].map(u => u.length))
385
+ const slotWidths: number[][] = []
386
+ for (let k = 0; k < maxUnits; k++) {
387
+ const widths = Array.from({ length: period + 1 }, () => 0)
388
+ for (const unitSplits of splits.values()) {
389
+ const split = unitSplits[k]
390
+ if (split) {
391
+ for (let j = 0; j <= period; j++) {
392
+ widths[j] = Math.max(widths[j]!, split.slots[j]!.length)
393
+ }
394
+ }
395
+ }
396
+ slotWidths.push(widths)
397
+ }
398
+ const unitWidths = slotWidths.map(w => period + w.reduce((a, b) => a + b, 0))
399
+
400
+ const gapped = new Map<string, string>()
401
+ const copies = new Map<string, number>()
402
+ for (const [seq, unitSplits] of splits) {
403
+ let row = ''
404
+ for (let k = 0; k < maxUnits; k++) {
405
+ const split = unitSplits[k]
406
+ row += split ? emit(split, slotWidths[k]!) : '-'.repeat(unitWidths[k]!)
407
+ }
408
+ gapped.set(seq, row)
409
+ copies.set(seq, unitSplits.length)
410
+ }
411
+ return { period, gapped, copies, unitWidths }
412
+ }
413
+
414
+ export interface InsertionAlignment {
415
+ /** each distinct input mapped to a gapped version, all of the same length */
416
+ gapped: Map<string, string>
417
+ /** present when the site is a tandem array */
418
+ periodic?: PeriodicAlignment
419
+ }
420
+
421
+ /**
422
+ * Lay out the sequences inserted at one reference position, by whichever of the
423
+ * two alignments the sequence itself calls for. The single place that decision
424
+ * is made, so a caller reading the period cannot disagree with the layout it
425
+ * gets.
426
+ *
427
+ * A tandem array goes unit-per-block, which is both the readable answer and the
428
+ * affordable one — the size caps here are what the base-to-base alignment costs,
429
+ * and an expansion is always past them. Everything else gets the center-star
430
+ * alignment, or is left alone (`gapped` empty) when there is nothing to gain
431
+ * from a single distinct sequence, or the site is too large to be worth it.
432
+ */
433
+ export function alignInsertionSite(seqs: string[]): InsertionAlignment {
434
+ const distinct = [...new Set(seqs)]
435
+ // an array is worth unrolling even when every read agrees on it: the copies
436
+ // still have to be squared up with each other before they can be counted
437
+ const periodic = alignPeriodicInsertions(distinct)
438
+ if (periodic) {
439
+ return { gapped: periodic.gapped, periodic }
440
+ }
441
+ const longest = distinct.reduce((a, b) => (b.length > a.length ? b : a), '')
127
442
  if (
128
443
  distinct.length < 2 ||
129
444
  distinct.length > MAX_DISTINCT ||
130
445
  longest.length > MAX_LEN
131
446
  ) {
132
- return new Map<string, string>()
447
+ return { gapped: new Map<string, string>() }
133
448
  }
134
449
 
135
450
  const centerLen = longest.length
@@ -145,10 +460,21 @@ export function alignInsertions(seqs: string[]) {
145
460
  const slotWidths = Array.from({ length: centerLen + 1 }, (_, j) =>
146
461
  splits.reduce((max, s) => Math.max(max, s.slots[j]!.length), 0),
147
462
  )
148
- return new Map([
149
- [longest, emit(centerSplit, slotWidths)],
150
- ...others.map(
151
- (seq, i): [string, string] => [seq, emit(splits[i]!, slotWidths)],
152
- ),
153
- ])
463
+ return {
464
+ gapped: new Map([
465
+ [longest, emit(centerSplit, slotWidths)],
466
+ ...others.map((seq, i): [string, string] => [
467
+ seq,
468
+ emit(splits[i]!, slotWidths),
469
+ ]),
470
+ ]),
471
+ }
472
+ }
473
+
474
+ /**
475
+ * The gapped sequences alone, for callers with no use for the period. Every
476
+ * decision lives in `alignInsertionSite`.
477
+ */
478
+ export function alignInsertions(seqs: string[]) {
479
+ return alignInsertionSite(seqs).gapped
154
480
  }