jbrowse-plugin-tview 2.0.6 → 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.
Files changed (77) hide show
  1. package/README.md +222 -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 +106 -9
  9. package/dist/LaunchTView/align.js +349 -15
  10. package/dist/LaunchTView/align.js.map +1 -1
  11. package/dist/LaunchTView/alleles.d.ts +83 -0
  12. package/dist/LaunchTView/alleles.js +180 -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/repeatStats.d.ts +56 -0
  29. package/dist/LaunchTView/repeatStats.js +109 -0
  30. package/dist/LaunchTView/repeatStats.js.map +1 -0
  31. package/dist/LaunchTView/repeats.d.ts +68 -0
  32. package/dist/LaunchTView/repeats.js +200 -0
  33. package/dist/LaunchTView/repeats.js.map +1 -0
  34. package/dist/LaunchTView/sampleTree.d.ts +37 -0
  35. package/dist/LaunchTView/sampleTree.js +65 -0
  36. package/dist/LaunchTView/sampleTree.js.map +1 -0
  37. package/dist/LaunchTView/tview.d.ts +67 -44
  38. package/dist/LaunchTView/tview.js +193 -121
  39. package/dist/LaunchTView/tview.js.map +1 -1
  40. package/dist/LaunchTView/useTviewMsa.d.ts +13 -9
  41. package/dist/LaunchTView/useTviewMsa.js +15 -11
  42. package/dist/LaunchTView/useTviewMsa.js.map +1 -1
  43. package/dist/TViewPanel/coords.d.ts +9 -1
  44. package/dist/TViewPanel/coords.js +22 -2
  45. package/dist/TViewPanel/coords.js.map +1 -1
  46. package/dist/TViewPanel/init.d.ts +56 -0
  47. package/dist/TViewPanel/init.js +59 -0
  48. package/dist/TViewPanel/init.js.map +1 -0
  49. package/dist/TViewPanel/model.d.ts +109 -93
  50. package/dist/TViewPanel/model.js +73 -51
  51. package/dist/TViewPanel/model.js.map +1 -1
  52. package/dist/index.js +5 -1
  53. package/dist/index.js.map +1 -1
  54. package/dist/jbrowse-plugin-tview.umd.production.min.js +25 -25
  55. package/dist/jbrowse-plugin-tview.umd.production.min.js.map +4 -4
  56. package/dist/version.d.ts +1 -1
  57. package/dist/version.js +1 -1
  58. package/package.json +9 -3
  59. package/src/LaunchTView/TviewGetPlanRpc/TviewGetPlan.ts +264 -0
  60. package/src/LaunchTView/TviewGetPlanRpc/index.ts +14 -0
  61. package/src/LaunchTView/align.ts +406 -17
  62. package/src/LaunchTView/alleles.ts +229 -0
  63. package/src/LaunchTView/components/ArrayReport.tsx +64 -0
  64. package/src/LaunchTView/components/LaunchTViewDialog.tsx +122 -39
  65. package/src/LaunchTView/fetchTviewPlan.ts +42 -42
  66. package/src/LaunchTView/launchView.ts +50 -0
  67. package/src/LaunchTView/readLayout.ts +145 -0
  68. package/src/LaunchTView/repeatStats.ts +170 -0
  69. package/src/LaunchTView/repeats.ts +218 -0
  70. package/src/LaunchTView/sampleTree.ts +73 -0
  71. package/src/LaunchTView/tview.ts +265 -157
  72. package/src/LaunchTView/useTviewMsa.ts +20 -17
  73. package/src/TViewPanel/coords.ts +23 -1
  74. package/src/TViewPanel/init.ts +127 -0
  75. package/src/TViewPanel/model.ts +82 -61
  76. package/src/index.ts +5 -1
  77. package/src/version.ts +1 -1
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A Newick tree whose only job is to group rows.
3
+ *
4
+ * With one file the rows are a pileup and their order is the whole structure.
5
+ * With several, the rows of two samples interleave into a list nothing separates
6
+ * — and react-msaview already draws a tree, collapses its clades and can show
7
+ * one branch alone, all of it keyed off a Newick string it is currently never
8
+ * given. Handing it one grouped by sample turns those controls on for free: a
9
+ * clade per sample, collapsible, and the allele ladder inside each.
10
+ *
11
+ * The tree is a grouping, not a phylogeny. Branch lengths are all 1 and say
12
+ * nothing; the topology is the sample the row came from, and the leaf order
13
+ * inside a clade is the copy-number order the rows were already in.
14
+ */
15
+ /**
16
+ * Newick reserves these, and a name is not quoted when it goes in.
17
+ *
18
+ * **Applied where the row name is built, not here.** react-msaview joins a tree
19
+ * leaf to an alignment row by name, so sanitizing on the way into the Newick
20
+ * and leaving the FASTA defline alone matches nothing: every row whose name
21
+ * needed fixing renders blank, with its label still in the tree, which looks
22
+ * like a rendering bug rather than a naming one. A track named `HG004 (mother)`
23
+ * is enough to trigger it.
24
+ */
25
+ export declare function newickSafe(name: string): string;
26
+ export interface TreeRow {
27
+ name: string;
28
+ /** what the defline says, when that is not just the name */
29
+ label?: string;
30
+ sample?: string;
31
+ }
32
+ /**
33
+ * Groups rows by sample, keeping the order they arrive in both for the clades
34
+ * and inside them. Returns undefined when there is nothing to group — one
35
+ * sample, or none — since a tree of one clade is a line drawn beside a list.
36
+ */
37
+ export declare function buildSampleTree(rows: TreeRow[]): string | undefined;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * A Newick tree whose only job is to group rows.
3
+ *
4
+ * With one file the rows are a pileup and their order is the whole structure.
5
+ * With several, the rows of two samples interleave into a list nothing separates
6
+ * — and react-msaview already draws a tree, collapses its clades and can show
7
+ * one branch alone, all of it keyed off a Newick string it is currently never
8
+ * given. Handing it one grouped by sample turns those controls on for free: a
9
+ * clade per sample, collapsible, and the allele ladder inside each.
10
+ *
11
+ * The tree is a grouping, not a phylogeny. Branch lengths are all 1 and say
12
+ * nothing; the topology is the sample the row came from, and the leaf order
13
+ * inside a clade is the copy-number order the rows were already in.
14
+ */
15
+ /**
16
+ * Newick reserves these, and a name is not quoted when it goes in.
17
+ *
18
+ * **Applied where the row name is built, not here.** react-msaview joins a tree
19
+ * leaf to an alignment row by name, so sanitizing on the way into the Newick
20
+ * and leaving the FASTA defline alone matches nothing: every row whose name
21
+ * needed fixing renders blank, with its label still in the tree, which looks
22
+ * like a rendering bug rather than a naming one. A track named `HG004 (mother)`
23
+ * is enough to trigger it.
24
+ */
25
+ export function newickSafe(name) {
26
+ return name.replaceAll(/[(),:;[\]'\s]+/g, '_').replace(/_+$/, '');
27
+ }
28
+ /**
29
+ * Groups rows by sample, keeping the order they arrive in both for the clades
30
+ * and inside them. Returns undefined when there is nothing to group — one
31
+ * sample, or none — since a tree of one clade is a line drawn beside a list.
32
+ */
33
+ export function buildSampleTree(rows) {
34
+ const bySample = new Map();
35
+ const ungrouped = [];
36
+ for (const row of rows) {
37
+ // the leaf is the row's *defline*, already Newick-safe from getReadNames.
38
+ // The tree must not rewrite it, and must not use the identity where the
39
+ // defline carries a label — react-msaview joins the two by string, and a
40
+ // leaf naming no row leaves that row blank with its label still drawn
41
+ const leaf = row.label ?? row.name;
42
+ if (row.sample === undefined) {
43
+ ungrouped.push(leaf);
44
+ }
45
+ else {
46
+ const group = bySample.get(row.sample);
47
+ if (group) {
48
+ group.push(leaf);
49
+ }
50
+ else {
51
+ bySample.set(row.sample, [leaf]);
52
+ }
53
+ }
54
+ }
55
+ if (bySample.size < 2) {
56
+ return undefined;
57
+ }
58
+ const clades = [
59
+ // the reference has no sample and belongs above all of them
60
+ ...ungrouped.map(name => `${name}:1`),
61
+ ...[...bySample].map(([sample, names]) => `(${names.map(n => `${n}:1`).join(',')})${sample}:1`),
62
+ ];
63
+ return `(${clades.join(',')});`;
64
+ }
65
+ //# sourceMappingURL=sampleTree.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sampleTree.js","sourceRoot":"","sources":["../../src/LaunchTView/sampleTree.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;;;;;;;;;GASG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,OAAO,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AACnE,CAAC;AASD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAe;IAC7C,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAoB,CAAA;IAC5C,MAAM,SAAS,GAAa,EAAE,CAAA;IAC9B,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,0EAA0E;QAC1E,wEAAwE;QACxE,yEAAyE;QACzE,sEAAsE;QACtE,MAAM,IAAI,GAAG,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,IAAI,CAAA;QAClC,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC7B,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACtB,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;YACtC,IAAI,KAAK,EAAE,CAAC;gBACV,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YAClB,CAAC;iBAAM,CAAC;gBACN,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,CAAA;YAClC,CAAC;QACH,CAAC;IACH,CAAC;IACD,IAAI,QAAQ,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;QACtB,OAAO,SAAS,CAAA;IAClB,CAAC;IACD,MAAM,MAAM,GAAG;QACb,4DAA4D;QAC5D,GAAG,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,IAAI,CAAC;QACrC,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,CAClB,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,IAAI,CAC1E;KACF,CAAA;IACD,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAA;AACjC,CAAC"}
@@ -1,44 +1,34 @@
1
- /** the subset of an @jbrowse/core Feature that the layout reads */
2
- export interface AlignmentFeature {
3
- get: (key: string) => any;
4
- }
5
- export interface ReadLayout {
6
- name: string;
7
- start: number;
8
- /** one char per reference position consumed: the aligned base, or a gap */
9
- refChars: string;
10
- /** reference position -> bases inserted immediately before that position */
11
- insertions: Map<number, string>;
12
- }
13
- export declare function parseCigar(cigar: string): string[];
14
- export declare function parseRead(feature: AlignmentFeature, name: string): ReadLayout;
1
+ import type { ArrayBlock } from './alleles';
2
+ import type { AlignmentFeature, ReadLayout } from './readLayout';
3
+ export type { AlignmentFeature, ReadLayout } from './readLayout';
4
+ export { clipInsertions, parseCigar, parseRead } from './readLayout';
15
5
  /**
16
- * Reads are fetched by overlap, so they carry insertions on either side of the
17
- * region. Those get no columns and are never rendered, so dropping them keeps
18
- * the pairwise alignment below off the wasted sites entirely.
6
+ * Mutually aligns the sequences inserted at each reference position, so reads
7
+ * sharing an insertion event line up inside it. Positions an array block has
8
+ * taken over are left alone: those bases are part of an allele the block
9
+ * already laid out, and giving them insertion columns as well would render
10
+ * them twice.
19
11
  */
20
- export declare function clipInsertions(reads: ReadLayout[], start: number, end: number): {
12
+ export declare function alignInsertionColumns(reads: ReadLayout[], ownedByArray: Set<number>): {
21
13
  insertions: Map<number, string>;
22
14
  name: string;
15
+ label?: string;
16
+ sample?: string;
23
17
  start: number;
24
- /** one char per reference position consumed: the aligned base, or a gap */
25
18
  refChars: string;
26
19
  }[];
27
- /**
28
- * Mutually aligns the sequences inserted at each reference position, so reads
29
- * sharing an insertion event line up inside it. Sites the aligner declines are
30
- * returned unchanged and stay left-justified.
31
- */
32
- export declare function alignInsertionColumns(reads: ReadLayout[]): ReadLayout[];
33
20
  /** widest insertion any read has at each reference position (sparse) */
34
- export declare function maxInsertionWidths(reads: ReadLayout[]): Map<number, number>;
21
+ export declare function maxInsertionWidths(reads: ReadLayout[], ownedByArray: Set<number>): Map<number, number>;
35
22
  export interface ColumnLayout {
36
23
  start: number;
37
24
  end: number;
38
25
  insWidths: Map<number, number>;
26
+ arrays: ArrayBlock[];
39
27
  /**
40
28
  * column index at which each reference position's columns begin, for
41
- * start..end inclusive
29
+ * start..end inclusive. Positions inside an array block all begin where the
30
+ * block ends: the block is one run of columns and no position inside it owns
31
+ * any of them.
42
32
  */
43
33
  offsets: number[];
44
34
  totalColumns: number;
@@ -46,19 +36,41 @@ export interface ColumnLayout {
46
36
  /**
47
37
  * Each reference position contributes its insertion columns (widest across all
48
38
  * reads) followed by one reference column, so every row comes out the same
49
- * length and stays aligned.
39
+ * length and stays aligned — except where an array block takes over, and
40
+ * contributes one run of columns for the whole interval it covers.
50
41
  */
51
- export declare function buildColumnLayout(start: number, end: number, insWidths: Map<number, number>): ColumnLayout;
42
+ export declare function buildColumnLayout(start: number, end: number, insWidths: Map<number, number>, arrays?: ArrayBlock[]): ColumnLayout;
52
43
  /**
53
- * Lays a single read out across the whole region. Reads are typically a tiny
54
- * fraction of the region, so the columns on either side of the read are filled
55
- * in one shot rather than walked position by position.
44
+ * Lays a single row out across the whole region. Rows are typically a tiny
45
+ * fraction of the region, so the columns on either side are filled in one shot
46
+ * from the offsets rather than walked position by position — which works over
47
+ * array blocks too, since the offsets already carry their width.
56
48
  */
57
49
  export declare function renderRow(read: ReadLayout, layout: ColumnLayout): string;
50
+ /**
51
+ * What a row is called on screen. The one place `label` falls back to `name`,
52
+ * so the defline and the tree leaf cannot disagree about it — react-msaview
53
+ * joins them by string, and a row the tree names differently renders blank.
54
+ */
55
+ export declare function rowLabel(read: ReadLayout): string;
56
+ /**
57
+ * Rows ordered longest-allele-first and labelled with their copy count.
58
+ *
59
+ * Copy number is the measurement at a tandem array, and reading it off where a
60
+ * row runs out is the thing the unit-per-block layout exists to avoid, so it is
61
+ * stated in the label. Ordering by it puts the alleles in a ladder, which is
62
+ * what makes one row's array comparable to the next at a glance. Rows that do
63
+ * not span the array keep genomic order, below the ones that do; the reference
64
+ * stays on top whatever its allele, since it is what the columns are named
65
+ * after rather than one of the observations.
66
+ */
67
+ export declare function labelAndOrderByCopies(reads: ReadLayout[], array: ArrayBlock, referenceName?: string): ReadLayout[];
58
68
  export interface TviewPlan {
59
69
  reads: ReadLayout[];
60
70
  layout: ColumnLayout;
61
71
  insertionWidths: [number, number][];
72
+ /** [start, end, width] per array block, to rebuild the column mapping */
73
+ arraySpans: [number, number, number][];
62
74
  region: {
63
75
  refName: string;
64
76
  start: number;
@@ -66,30 +78,41 @@ export interface TviewPlan {
66
78
  };
67
79
  /** rows x columns, i.e. how big the alignment renderTviewMsa builds will be */
68
80
  cellCount: number;
81
+ /** tandem arrays the reference carries here, left to right */
82
+ arrays: ArrayBlock[];
83
+ /** the array the rows are ordered and labelled by, when there is one */
84
+ subject?: ArrayBlock;
85
+ /** name of the reference row, when the reference sequence was available */
86
+ referenceName?: string;
87
+ /** samples contributing rows, in the order they were given */
88
+ samples: string[];
89
+ }
90
+ export interface PlanArgs {
91
+ features: AlignmentFeature[];
92
+ refName: string;
93
+ start: number;
94
+ end: number;
95
+ /** reference bases for start..end, when the assembly could supply them */
96
+ sequence?: string;
97
+ /** which sample each feature came from, parallel to `features` */
98
+ sampleOf?: (index: number) => string | undefined;
69
99
  }
70
100
  /**
71
101
  * Works out the shape of the alignment without materializing it. Everything
72
102
  * here is proportional to the sequence data, unlike the render, which is
73
103
  * proportional to rows x columns and can be far larger.
74
104
  */
75
- export declare function planTviewMsa({ features, refName, start, end, }: {
76
- features: AlignmentFeature[];
77
- refName: string;
78
- start: number;
79
- end: number;
80
- }): TviewPlan;
105
+ export declare function planTviewMsa({ features, refName, start, end, sequence, sampleOf, }: PlanArgs): TviewPlan;
81
106
  export declare function renderTviewMsa({ reads, layout }: TviewPlan): string;
82
- export declare function buildTviewMsa(args: {
83
- features: AlignmentFeature[];
84
- refName: string;
85
- start: number;
86
- end: number;
87
- }): {
107
+ export declare function buildTviewMsa(args: PlanArgs): {
88
108
  msa: string;
89
109
  insertionWidths: [number, number][];
110
+ arraySpans: [number, number, number][];
90
111
  region: {
91
112
  refName: string;
92
113
  start: number;
93
114
  end: number;
94
115
  };
116
+ arrays: ArrayBlock[];
117
+ subject: ArrayBlock | undefined;
95
118
  };
@@ -1,75 +1,23 @@
1
- import { alignInsertions } from './align';
2
- /**
3
- * Only '-' and '.' are treated as gaps by react-msaview (anything else counts
4
- * as a base in the conservation track and column stats), so the two of them
5
- * carry the whole vocabulary for "no base here". They are split by meaning:
6
- *
7
- * - SPANNED_GAP: the read covers this reference position but aligns no base to
8
- * it, i.e. a deletion, or padding in an insertion column
9
- * - ABSENT: the read is not here at all, i.e. outside its bounds, or skipping
10
- * over the position through an N (an intron, not a deleted allele)
11
- */
12
- const SPANNED_GAP = '-';
13
- const ABSENT = '.';
14
- const cigarRegex = /([MIDNSHPX=])/;
15
- const byStart = (a, b) => a.start - b.start;
16
- export function parseCigar(cigar) {
17
- return cigar.split(cigarRegex).slice(0, -1);
18
- }
19
- export function parseRead(feature, name) {
20
- const seq = feature.get('seq');
21
- const ops = parseCigar(feature.get('CIGAR'));
22
- const start = feature.get('start');
23
- const insertions = new Map();
24
- let refChars = '';
25
- let seqOffset = 0;
26
- for (let i = 0; i < ops.length; i += 2) {
27
- const len = +ops[i];
28
- const op = ops[i + 1];
29
- if (op === 'S') {
30
- seqOffset += len;
31
- }
32
- else if (op === 'I') {
33
- // consecutive I ops (e.g. 3M2I3I3M) land on the same reference position
34
- const pos = start + refChars.length;
35
- const prev = insertions.get(pos) ?? '';
36
- insertions.set(pos, prev + seq.slice(seqOffset, seqOffset + len));
37
- seqOffset += len;
38
- }
39
- else if (op === 'D') {
40
- refChars += SPANNED_GAP.repeat(len);
41
- }
42
- else if (op === 'N') {
43
- refChars += ABSENT.repeat(len);
44
- }
45
- else if (op === 'M' || op === 'X' || op === '=') {
46
- refChars += seq.slice(seqOffset, seqOffset + len);
47
- seqOffset += len;
48
- }
49
- // H and P consume neither the read sequence nor the reference
50
- }
51
- return { name, start, refChars, insertions };
52
- }
53
- /**
54
- * Reads are fetched by overlap, so they carry insertions on either side of the
55
- * region. Those get no columns and are never rendered, so dropping them keeps
56
- * the pairwise alignment below off the wasted sites entirely.
57
- */
58
- export function clipInsertions(reads, start, end) {
59
- return reads.map(read => ({
60
- ...read,
61
- insertions: new Map([...read.insertions].filter(([pos]) => pos >= start && pos < end)),
62
- }));
63
- }
1
+ import { alignInsertionSite } from './align';
2
+ import { absorbAdjacentInsertions, buildArrayBlocks } from './alleles';
3
+ import { ABSENT, SPANNED_GAP, byStart, clipInsertions, getReadNames, parseRead, } from './readLayout';
4
+ import { findReferenceArrays, mergeArrays } from './repeats';
5
+ import { newickSafe } from './sampleTree';
6
+ export { clipInsertions, parseCigar, parseRead } from './readLayout';
64
7
  /**
65
8
  * Mutually aligns the sequences inserted at each reference position, so reads
66
- * sharing an insertion event line up inside it. Sites the aligner declines are
67
- * returned unchanged and stay left-justified.
9
+ * sharing an insertion event line up inside it. Positions an array block has
10
+ * taken over are left alone: those bases are part of an allele the block
11
+ * already laid out, and giving them insertion columns as well would render
12
+ * them twice.
68
13
  */
69
- export function alignInsertionColumns(reads) {
14
+ export function alignInsertionColumns(reads, ownedByArray) {
70
15
  const byPos = new Map();
71
16
  for (const read of reads) {
72
17
  for (const [pos, ins] of read.insertions) {
18
+ if (ownedByArray.has(pos)) {
19
+ continue;
20
+ }
73
21
  const seqs = byPos.get(pos);
74
22
  if (seqs) {
75
23
  seqs.push(ins);
@@ -79,113 +27,237 @@ export function alignInsertionColumns(reads) {
79
27
  }
80
28
  }
81
29
  }
82
- const gapped = new Map([...byPos].map(([pos, seqs]) => [pos, alignInsertions(seqs)]));
30
+ const aligned = new Map([...byPos].map(([pos, seqs]) => [pos, alignInsertionSite(seqs)]));
83
31
  return reads.map(read => ({
84
32
  ...read,
85
33
  insertions: new Map([...read.insertions].map(([pos, ins]) => [
86
34
  pos,
87
- gapped.get(pos)?.get(ins) ?? ins,
35
+ aligned.get(pos)?.gapped.get(ins) ?? ins,
88
36
  ])),
89
37
  }));
90
38
  }
91
39
  /** widest insertion any read has at each reference position (sparse) */
92
- export function maxInsertionWidths(reads) {
40
+ export function maxInsertionWidths(reads, ownedByArray) {
93
41
  const ret = new Map();
94
42
  for (const read of reads) {
95
43
  for (const [pos, ins] of read.insertions) {
96
- ret.set(pos, Math.max(ret.get(pos) ?? 0, ins.length));
44
+ if (!ownedByArray.has(pos)) {
45
+ ret.set(pos, Math.max(ret.get(pos) ?? 0, ins.length));
46
+ }
97
47
  }
98
48
  }
99
49
  return ret;
100
50
  }
51
+ function arrayStartIndex(arrays) {
52
+ return new Map(arrays.map(a => [a.start, a]));
53
+ }
101
54
  /**
102
55
  * Each reference position contributes its insertion columns (widest across all
103
56
  * reads) followed by one reference column, so every row comes out the same
104
- * length and stays aligned.
57
+ * length and stays aligned — except where an array block takes over, and
58
+ * contributes one run of columns for the whole interval it covers.
105
59
  */
106
- export function buildColumnLayout(start, end, insWidths) {
107
- const offsets = [0];
60
+ export function buildColumnLayout(start, end, insWidths, arrays = []) {
61
+ const byStartPos = arrayStartIndex(arrays);
62
+ const offsets = [];
108
63
  let col = 0;
109
- for (let pos = start; pos < end; pos++) {
110
- col += (insWidths.get(pos) ?? 0) + 1;
111
- offsets.push(col);
64
+ let pos = start;
65
+ while (pos < end) {
66
+ const array = byStartPos.get(pos);
67
+ if (array) {
68
+ const stop = Math.min(array.end, end);
69
+ offsets.push(col);
70
+ col += array.width;
71
+ for (let p = pos + 1; p < stop; p++) {
72
+ offsets.push(col);
73
+ }
74
+ pos = stop;
75
+ }
76
+ else {
77
+ offsets.push(col);
78
+ col += (insWidths.get(pos) ?? 0) + 1;
79
+ pos++;
80
+ }
112
81
  }
113
- return { start, end, insWidths, offsets, totalColumns: col };
82
+ offsets.push(col);
83
+ return { start, end, insWidths, arrays, offsets, totalColumns: col };
84
+ }
85
+ /** the array covering `pos`, when `pos` is strictly inside one */
86
+ function arrayContaining(arrays, pos) {
87
+ return arrays.find(a => a.start < pos && pos < a.end);
114
88
  }
115
89
  /**
116
- * Lays a single read out across the whole region. Reads are typically a tiny
117
- * fraction of the region, so the columns on either side of the read are filled
118
- * in one shot rather than walked position by position.
90
+ * Lays a single row out across the whole region. Rows are typically a tiny
91
+ * fraction of the region, so the columns on either side are filled in one shot
92
+ * from the offsets rather than walked position by position — which works over
93
+ * array blocks too, since the offsets already carry their width.
119
94
  */
120
95
  export function renderRow(read, layout) {
121
- const { start, end, insWidths, offsets, totalColumns } = layout;
96
+ const { start, end, insWidths, arrays, offsets, totalColumns } = layout;
97
+ const byStartPos = arrayStartIndex(arrays);
122
98
  // a trailing insertion is keyed one past the last position the read spans
123
- const from = Math.max(start, read.start);
124
- const to = Math.min(end, read.start + read.refChars.length + 1);
125
- let ret;
126
- if (to > from) {
127
- ret = ABSENT.repeat(offsets[from - start]);
128
- for (let pos = from; pos < to; pos++) {
129
- const idx = pos - read.start;
130
- const spanned = idx >= 0 && idx < read.refChars.length;
131
- const refChar = spanned ? read.refChars[idx] : ABSENT;
132
- const width = insWidths.get(pos) ?? 0;
133
- if (width) {
134
- // a read that is not really here pads the insertion the same way it
135
- // pads the reference column, so an intron reads as one absence
136
- const pad = refChar === ABSENT ? ABSENT : SPANNED_GAP;
137
- const ins = read.insertions.get(pos) ?? '';
138
- ret += ins + pad.repeat(width - ins.length);
139
- }
140
- ret += refChar;
141
- }
142
- ret += ABSENT.repeat(totalColumns - offsets[to - start]);
99
+ let from = Math.max(start, read.start);
100
+ let to = Math.min(end, read.start + read.refChars.length + 1);
101
+ // a row that begins or ends inside an array does not span it, so it gets no
102
+ // block; snapping past the block keeps the walk from emitting part of one
103
+ const startsInside = arrayContaining(arrays, from);
104
+ if (startsInside) {
105
+ from = Math.min(end, startsInside.end);
143
106
  }
144
- else {
145
- ret = ABSENT.repeat(totalColumns);
107
+ const endsInside = arrayContaining(arrays, to);
108
+ if (endsInside) {
109
+ to = endsInside.start;
146
110
  }
147
- return ret;
111
+ if (to <= from) {
112
+ return ABSENT.repeat(totalColumns);
113
+ }
114
+ let ret = ABSENT.repeat(offsets[from - start]);
115
+ let pos = from;
116
+ while (pos < to) {
117
+ const array = byStartPos.get(pos);
118
+ if (array) {
119
+ const row = array.rowByName.get(read.name);
120
+ ret += row ?? SPANNED_GAP.repeat(array.width);
121
+ pos = Math.min(array.end, to);
122
+ continue;
123
+ }
124
+ const idx = pos - read.start;
125
+ const spanned = idx >= 0 && idx < read.refChars.length;
126
+ const refChar = spanned ? read.refChars[idx] : ABSENT;
127
+ const width = insWidths.get(pos) ?? 0;
128
+ if (width) {
129
+ // a read that is not really here pads the insertion the same way it
130
+ // pads the reference column, so an intron reads as one absence
131
+ const pad = refChar === ABSENT ? ABSENT : SPANNED_GAP;
132
+ const ins = read.insertions.get(pos) ?? '';
133
+ ret += ins + pad.repeat(width - ins.length);
134
+ }
135
+ ret += refChar;
136
+ pos++;
137
+ }
138
+ return ret + ABSENT.repeat(totalColumns - offsets[to - start]);
148
139
  }
149
- function mateSuffix(flags) {
150
- return flags === undefined || !(flags & 1) ? '' : flags & 64 ? '/1' : '/2';
140
+ // A defline is truncated at its first space (msa-parsers' FastaMSA), so the
141
+ // count is joined on. `labelsAlignRight` puts it flush against the sequence.
142
+ const COPY_COUNT_SEPARATOR = '|';
143
+ /**
144
+ * What a row is called on screen. The one place `label` falls back to `name`,
145
+ * so the defline and the tree leaf cannot disagree about it — react-msaview
146
+ * joins them by string, and a row the tree names differently renders blank.
147
+ */
148
+ export function rowLabel(read) {
149
+ return read.label ?? read.name;
150
+ }
151
+ /**
152
+ * Rows ordered longest-allele-first and labelled with their copy count.
153
+ *
154
+ * Copy number is the measurement at a tandem array, and reading it off where a
155
+ * row runs out is the thing the unit-per-block layout exists to avoid, so it is
156
+ * stated in the label. Ordering by it puts the alleles in a ladder, which is
157
+ * what makes one row's array comparable to the next at a glance. Rows that do
158
+ * not span the array keep genomic order, below the ones that do; the reference
159
+ * stays on top whatever its allele, since it is what the columns are named
160
+ * after rather than one of the observations.
161
+ */
162
+ export function labelAndOrderByCopies(reads, array, referenceName) {
163
+ const rank = (read) => (read.name === referenceName ? 1 : 0);
164
+ return reads
165
+ .map(read => ({ read, copies: array.copiesByName.get(read.name) }))
166
+ .sort((a, b) => {
167
+ const byRef = rank(b.read) - rank(a.read);
168
+ if (byRef) {
169
+ return byRef;
170
+ }
171
+ if (a.copies === undefined || b.copies === undefined) {
172
+ return a.copies === b.copies
173
+ ? byStart(a.read, b.read)
174
+ : a.copies === undefined
175
+ ? 1
176
+ : -1;
177
+ }
178
+ return b.copies - a.copies || byStart(a.read, b.read);
179
+ })
180
+ .map(({ read, copies }) => copies === undefined
181
+ ? read
182
+ : { ...read, label: `${read.name}${COPY_COUNT_SEPARATOR}n=${copies}` });
151
183
  }
152
- /** MSA rows are keyed by name, so mates and duplicate names need disambiguating */
153
- function getReadNames(features) {
154
- const counts = new Map();
155
- return features.map(f => {
156
- const base = `${f.get('name')}${mateSuffix(f.get('flags'))}`;
157
- const n = (counts.get(base) ?? 0) + 1;
158
- counts.set(base, n);
159
- return n === 1 ? base : `${base}_${n}`;
160
- });
184
+ /** Widest spread of allele lengths, i.e. the array the reads disagree most about. */
185
+ function alleleSpread(array) {
186
+ const lengths = [...array.lengthByName.values()];
187
+ return lengths.length ? Math.max(...lengths) - Math.min(...lengths) : 0;
161
188
  }
162
189
  /**
163
190
  * Works out the shape of the alignment without materializing it. Everything
164
191
  * here is proportional to the sequence data, unlike the render, which is
165
192
  * proportional to rows x columns and can be far larger.
166
193
  */
167
- export function planTviewMsa({ features, refName, start, end, }) {
168
- const names = getReadNames(features);
169
- const reads = alignInsertionColumns(clipInsertions(features.map((f, i) => parseRead(f, names[i])).sort(byStart), start, end));
170
- const insWidths = maxInsertionWidths(reads);
171
- const layout = buildColumnLayout(start, end, insWidths);
194
+ export function planTviewMsa({ features, refName, start, end, sequence, sampleOf, }) {
195
+ const names = getReadNames(features, sampleOf);
196
+ const parsed = features
197
+ .map((f, i) => parseRead(f, names[i], sampleOf?.(i)))
198
+ .sort(byStart);
199
+ // The reference is laid out as a row like any other, which is what lets it be
200
+ // one of the alleles an array block squares up rather than a thing the block
201
+ // has to be compared against afterwards.
202
+ const referenceName = sequence ? newickSafe(refName) : undefined;
203
+ const referenceRead = sequence
204
+ ? {
205
+ name: referenceName,
206
+ start,
207
+ refChars: sequence.toUpperCase(),
208
+ insertions: new Map(),
209
+ }
210
+ : undefined;
211
+ const clipped = clipInsertions(referenceRead ? [referenceRead, ...parsed] : parsed, start, end);
212
+ // the interval comes from the reference, then widens over the repeat alleles
213
+ // the aligner anchored just outside it — see absorbAdjacentInsertions, which
214
+ // has to see the reads and so cannot live in the reference scan
215
+ const arrays = sequence
216
+ ? buildArrayBlocks(clipped, absorbAdjacentInsertions(clipped, mergeArrays(findReferenceArrays(sequence, start))))
217
+ : [];
218
+ const ownedByArray = new Set();
219
+ for (const array of arrays) {
220
+ for (let pos = array.start; pos <= array.end; pos++) {
221
+ ownedByArray.add(pos);
222
+ }
223
+ }
224
+ const aligned = alignInsertionColumns(clipped, ownedByArray);
225
+ // With several arrays in view the subject is the one the rows disagree most
226
+ // about, since ordering rows by two copy numbers at once is not a thing rows
227
+ // can do and an array every row agrees on orders nothing.
228
+ const subject = arrays.reduce((best, array) => best && alleleSpread(best) >= alleleSpread(array) ? best : array, undefined);
229
+ const reads = subject
230
+ ? labelAndOrderByCopies(aligned, subject, referenceName)
231
+ : aligned;
232
+ const insWidths = maxInsertionWidths(reads, ownedByArray);
233
+ const layout = buildColumnLayout(start, end, insWidths, arrays);
172
234
  return {
173
235
  reads,
174
236
  layout,
175
237
  insertionWidths: [...insWidths.entries()].sort((a, b) => a[0] - b[0]),
238
+ arraySpans: arrays.map(a => [a.start, a.end, a.width]),
176
239
  region: { refName, start, end },
177
240
  cellCount: reads.length * layout.totalColumns,
241
+ arrays,
242
+ subject,
243
+ referenceName,
244
+ samples: [
245
+ ...new Set(parsed.map(r => r.sample).filter(s => s !== undefined)),
246
+ ],
178
247
  };
179
248
  }
180
249
  export function renderTviewMsa({ reads, layout }) {
181
- return reads.map(r => `>${r.name}\n${renderRow(r, layout)}\n`).join('');
250
+ return reads.map(r => `>${rowLabel(r)}\n${renderRow(r, layout)}\n`).join('');
182
251
  }
183
252
  export function buildTviewMsa(args) {
184
253
  const plan = planTviewMsa(args);
185
254
  return {
186
255
  msa: renderTviewMsa(plan),
187
256
  insertionWidths: plan.insertionWidths,
257
+ arraySpans: plan.arraySpans,
188
258
  region: plan.region,
259
+ arrays: plan.arrays,
260
+ subject: plan.subject,
189
261
  };
190
262
  }
191
263
  //# sourceMappingURL=tview.js.map