diffgrammar 0.1.0__py3-none-any.whl
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.
- diffgrammar/__init__.py +6 -0
- diffgrammar/adapters/__init__.py +21 -0
- diffgrammar/adapters/peak_npz.py +114 -0
- diffgrammar/align.py +195 -0
- diffgrammar/analysis.py +744 -0
- diffgrammar/attribute.py +445 -0
- diffgrammar/calibrate.py +279 -0
- diffgrammar/cli.py +659 -0
- diffgrammar/cluster.py +439 -0
- diffgrammar/config.py +213 -0
- diffgrammar/contrast.py +223 -0
- diffgrammar/effects.py +317 -0
- diffgrammar/export.py +185 -0
- diffgrammar/expression.py +399 -0
- diffgrammar/jaspar.py +185 -0
- diffgrammar/marginalize/__init__.py +4 -0
- diffgrammar/marginalize/backgrounds.py +107 -0
- diffgrammar/marginalize/cooperativity.py +344 -0
- diffgrammar/marginalize/design.py +209 -0
- diffgrammar/marginalize/plots.py +546 -0
- diffgrammar/marginalize/predictor.py +109 -0
- diffgrammar/marginalize/readout.py +86 -0
- diffgrammar/marginalize/run.py +223 -0
- diffgrammar/marginalize/store.py +191 -0
- diffgrammar/pair_regression.py +323 -0
- diffgrammar/plotting.py +1186 -0
- diffgrammar/scan.py +151 -0
- diffgrammar/selection.py +174 -0
- diffgrammar/seqlets.py +376 -0
- diffgrammar/sequence.py +22 -0
- diffgrammar/summaries.py +140 -0
- diffgrammar/toy.py +129 -0
- diffgrammar/view/__init__.py +0 -0
- diffgrammar/view/app.py +1942 -0
- diffgrammar/view/data.py +1950 -0
- diffgrammar/view/figures.py +400 -0
- diffgrammar/view/network/index.html +232 -0
- diffgrammar/view/network.py +21 -0
- diffgrammar/view/pages.py +257 -0
- diffgrammar/view/tracks/index.html +459 -0
- diffgrammar/view/tracks.py +153 -0
- diffgrammar-0.1.0.dist-info/METADATA +204 -0
- diffgrammar-0.1.0.dist-info/RECORD +47 -0
- diffgrammar-0.1.0.dist-info/WHEEL +5 -0
- diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
- diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
- diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<style>
|
|
6
|
+
:root { --bg: #ffffff; --text: #31333f; --muted: #6b6f7b; --line: #d5d7de; --chip: #f0f2f6; --accent: #ff4b4b; }
|
|
7
|
+
body.dark { --bg: #0e1117; --text: #fafafa; --muted: #a3a8b8; --line: #3d4250; --chip: #262730; }
|
|
8
|
+
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); overflow: hidden;
|
|
9
|
+
font-family: "Source Sans Pro", "Source Sans 3", -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
|
|
10
|
+
#bar { display: flex; flex-wrap: nowrap; align-items: center; gap: 6px; height: 34px; font-size: 13px; overflow: hidden; }
|
|
11
|
+
#chips { display: flex; gap: 4px; overflow: hidden; flex: 1 1 auto; min-width: 0; }
|
|
12
|
+
button { font: inherit; font-size: 13px; line-height: 1.2; border: 1px solid var(--line); background: var(--bg);
|
|
13
|
+
color: var(--text); border-radius: 6px; padding: 3px 9px; cursor: pointer; white-space: nowrap; }
|
|
14
|
+
button:hover { border-color: var(--accent); color: var(--accent); }
|
|
15
|
+
button.chip { background: var(--chip); border-color: transparent; padding: 3px 8px; }
|
|
16
|
+
button.chip:hover { border-color: var(--accent); }
|
|
17
|
+
button.chip i { font-style: normal; display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 5px; }
|
|
18
|
+
button.chip.hl { box-shadow: inset 0 0 0 2px #f2c14e; }
|
|
19
|
+
.pick { display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; color: var(--muted); }
|
|
20
|
+
select { font: inherit; font-size: 13px; border: 1px solid var(--line); background: var(--bg); color: var(--text);
|
|
21
|
+
border-radius: 6px; padding: 2px 4px; cursor: pointer; }
|
|
22
|
+
select:hover { border-color: var(--accent); }
|
|
23
|
+
.switch { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; white-space: nowrap; }
|
|
24
|
+
.switch input { appearance: none; -webkit-appearance: none; width: 28px; height: 16px; border-radius: 8px; margin: 0;
|
|
25
|
+
background: #c3c6cf; position: relative; cursor: pointer; transition: background 0.15s; }
|
|
26
|
+
.switch input::after { content: ""; position: absolute; top: 2px; left: 2px; width: 12px; height: 12px;
|
|
27
|
+
border-radius: 50%; background: #ffffff; transition: left 0.15s; }
|
|
28
|
+
.switch input:checked { background: var(--accent); }
|
|
29
|
+
.switch input:checked::after { left: 14px; }
|
|
30
|
+
#where { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
|
31
|
+
canvas { display: block; cursor: grab; touch-action: none; }
|
|
32
|
+
canvas.drag { cursor: grabbing; }
|
|
33
|
+
#tip { position: fixed; pointer-events: none; display: none; z-index: 2; white-space: nowrap; font-size: 12px;
|
|
34
|
+
line-height: 1.4; padding: 5px 8px; border-radius: 6px; border: 1px solid var(--line);
|
|
35
|
+
background: var(--bg); color: var(--text); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); }
|
|
36
|
+
#tip .k { color: var(--muted); }
|
|
37
|
+
</style>
|
|
38
|
+
</head>
|
|
39
|
+
<body>
|
|
40
|
+
<div id="bar">
|
|
41
|
+
<button id="out" title="Zoom out (or the wheel, or a double click with Shift)">−</button>
|
|
42
|
+
<button id="in" title="Zoom in (or the wheel, or a double click)">+</button>
|
|
43
|
+
<button id="region" title="The region itself">Region</button>
|
|
44
|
+
<button id="all" title="The whole input">Whole input</button>
|
|
45
|
+
<span id="chips"></span>
|
|
46
|
+
<label class="pick" title="What colours the seqlets: their motif's subfamily, family or cluster, or the condition they are stronger in">Colour<select id="color"></select></label>
|
|
47
|
+
<label class="switch" title="One contribution scale for every track, else one per track"><input type="checkbox" id="share" checked>One scale</label>
|
|
48
|
+
<span id="where"></span>
|
|
49
|
+
</div>
|
|
50
|
+
<canvas id="cv"></canvas>
|
|
51
|
+
<div id="tip"></div>
|
|
52
|
+
<script type="application/json" id="data">/*DATA*/{}</script>
|
|
53
|
+
<script>
|
|
54
|
+
(function () {
|
|
55
|
+
'use strict';
|
|
56
|
+
const D = JSON.parse(document.getElementById('data').textContent);
|
|
57
|
+
if (D.dark) document.body.classList.add('dark');
|
|
58
|
+
const L = D.length, seq = D.seq, lay = D.layout;
|
|
59
|
+
const LEFT = 112, RIGHT = 14, LETTER_PPB = 3, MIN_BP = 12;
|
|
60
|
+
const TEXT = D.dark ? '#fafafa' : '#31333f', MUTED = D.dark ? '#a3a8b8' : '#6b6f7b';
|
|
61
|
+
const RULE = D.dark ? '#8a8f9c' : '#31333f', GUIDE = D.dark ? 'rgba(250,250,250,0.35)' : 'rgba(49,51,63,0.3)';
|
|
62
|
+
const SHADE = D.dark ? 'rgba(160,160,160,0.16)' : 'rgba(153,153,153,0.16)', SHADE_HL = 'rgba(242,193,78,0.38)';
|
|
63
|
+
|
|
64
|
+
function decode(b64) {
|
|
65
|
+
const bin = atob(b64), u8 = new Uint8Array(bin.length);
|
|
66
|
+
for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
|
|
67
|
+
return new Float32Array(u8.buffer);
|
|
68
|
+
}
|
|
69
|
+
const tracks = D.tracks.map(t => Object.assign({}, t, {v: decode(t.values)}));
|
|
70
|
+
const CMAP = D.colors || {}, GREY = D.dark ? '#6b7080' : '#cfcfcf';
|
|
71
|
+
let colorBy = D.color_by || 'sign';
|
|
72
|
+
function colOf(q) {
|
|
73
|
+
if (colorBy === 'sign') return q.sign > 0 ? D.color_b : q.sign < 0 ? D.color_a : '#9a9a9a';
|
|
74
|
+
const k = colorBy === 'cluster' ? String(q.cluster) : q[colorBy];
|
|
75
|
+
return (k != null && CMAP[colorBy][k]) || GREY;
|
|
76
|
+
}
|
|
77
|
+
const glyphs = {};
|
|
78
|
+
for (const b of Object.keys(D.glyphs)) glyphs[b] = new Path2D(D.glyphs[b]);
|
|
79
|
+
const seqlets = D.seqlets;
|
|
80
|
+
const S = D.scan; // the sequence scan's hits as rows below the tracks, or null
|
|
81
|
+
const scanRow = S ? {} : null;
|
|
82
|
+
if (S) S.families.forEach((f, k) => { scanRow[f] = k; });
|
|
83
|
+
|
|
84
|
+
const cv = document.getElementById('cv'), ctx = cv.getContext('2d'), tip = document.getElementById('tip');
|
|
85
|
+
const where = document.getElementById('where');
|
|
86
|
+
let W = 0, dpr = 1, x0 = 0, x1 = L, share = true, hover = null, drag = null;
|
|
87
|
+
const scanH = () => (S ? lay.gap + lay.scan_head + S.families.length * lay.scan_row : 0);
|
|
88
|
+
const height = () => lay.lane + tracks.length * lay.track + (tracks.length - 1) * lay.gap + scanH() + lay.axis;
|
|
89
|
+
const px = i => LEFT + (i - x0) * W / (x1 - x0);
|
|
90
|
+
const top = k => lay.lane + k * (lay.track + lay.gap);
|
|
91
|
+
const g0 = D.genomic ? D.genomic[1] : 0;
|
|
92
|
+
const fmt = v => (Math.abs(v) >= 100 ? v.toFixed(1) : Math.abs(v) >= 1 ? v.toFixed(2) : v.toPrecision(2));
|
|
93
|
+
const esc = s => String(s).replace(/[&<>"]/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"'}[c]));
|
|
94
|
+
const pos = i => (D.genomic ? `${D.genomic[0]}:${(g0 + i).toLocaleString('en-US')}` : `${i.toLocaleString('en-US')} bp`);
|
|
95
|
+
const span = q => (D.genomic ? `${D.genomic[0]}:${(g0 + q.start).toLocaleString('en-US')}\u2013${(g0 + q.end - 1).toLocaleString('en-US')}`
|
|
96
|
+
: `${q.start.toLocaleString('en-US')}\u2013${(q.end - 1).toLocaleString('en-US')} bp`);
|
|
97
|
+
const num = v => String(+v.toPrecision(3)).replace('-', '\u2212');
|
|
98
|
+
|
|
99
|
+
function nice(v) { // the largest of 1, 2, 5 x 10^k not above v
|
|
100
|
+
const p = Math.pow(10, Math.floor(Math.log10(v))), m = v / p;
|
|
101
|
+
return (m >= 5 ? 5 : m >= 2 ? 2 : 1) * p;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function setWindow(a, b) {
|
|
105
|
+
const w = Math.min(Math.max(b - a, MIN_BP), L);
|
|
106
|
+
a = Math.min(Math.max(a, 0), L - w);
|
|
107
|
+
x0 = a; x1 = a + w;
|
|
108
|
+
draw();
|
|
109
|
+
}
|
|
110
|
+
function zoomAt(f, at) { // f < 1 zooms in, keeping input position `at` where it is
|
|
111
|
+
const w = (x1 - x0) * f, r = (at - x0) / (x1 - x0);
|
|
112
|
+
setWindow(at - r * w, at - r * w + w);
|
|
113
|
+
}
|
|
114
|
+
function focus(q) { // a seqlet at letter resolution, with some sequence around it
|
|
115
|
+
const c = (q.start + q.end) / 2, w = Math.max(W / (LETTER_PPB + 3), q.end - q.start + 16);
|
|
116
|
+
setWindow(c - w / 2, c + w / 2);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function resize() {
|
|
120
|
+
const cssW = Math.max(320, document.documentElement.clientWidth);
|
|
121
|
+
dpr = window.devicePixelRatio || 1;
|
|
122
|
+
cv.style.width = cssW + 'px';
|
|
123
|
+
cv.style.height = height() + 'px';
|
|
124
|
+
cv.width = Math.round(cssW * dpr);
|
|
125
|
+
cv.height = Math.round(height() * dpr);
|
|
126
|
+
W = cssW - LEFT - RIGHT;
|
|
127
|
+
draw();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function scales(i0, i1) { // per track the largest |contribution| in view
|
|
131
|
+
const m = tracks.map(t => {
|
|
132
|
+
let a = 0;
|
|
133
|
+
for (let i = i0; i < i1; i++) { const v = Math.abs(t.v[i]); if (v > a) a = v; }
|
|
134
|
+
return a || 1;
|
|
135
|
+
});
|
|
136
|
+
const all = Math.max.apply(null, m);
|
|
137
|
+
return m.map(v => (share ? all : v) * 1.08);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function letters(t, i0, i1, mid, s, ppb) {
|
|
141
|
+
const w = ppb * 0.92, pad = (ppb - w) / 2;
|
|
142
|
+
for (let i = i0; i < i1; i++) {
|
|
143
|
+
const v = t.v[i], g = glyphs[seq[i]];
|
|
144
|
+
if (!v) continue;
|
|
145
|
+
const x = px(i) + pad, h = v * s;
|
|
146
|
+
if (!g) {
|
|
147
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
148
|
+
ctx.fillStyle = MUTED;
|
|
149
|
+
ctx.fillRect(x, h > 0 ? mid - h : mid, w, Math.abs(h));
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
ctx.setTransform(dpr * w, 0, 0, -dpr * h, dpr * x, dpr * mid); // the unit glyph, stretched to the value
|
|
153
|
+
ctx.fillStyle = D.base_colors[seq[i]];
|
|
154
|
+
ctx.fill(g);
|
|
155
|
+
}
|
|
156
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function bars(t, i0, i1, mid, s, ppb) {
|
|
160
|
+
const up = new Path2D(), down = new Path2D(), w = Math.max(ppb - (ppb >= 4 ? 1 : 0), 1);
|
|
161
|
+
for (let i = i0; i < i1; i++) {
|
|
162
|
+
const v = t.v[i];
|
|
163
|
+
if (v > 0) up.rect(px(i), mid - v * s, w, v * s);
|
|
164
|
+
else if (v < 0) down.rect(px(i), mid, w, -v * s);
|
|
165
|
+
}
|
|
166
|
+
ctx.fillStyle = t.pos; ctx.fill(up);
|
|
167
|
+
ctx.fillStyle = t.neg; ctx.fill(down);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function envelope(t, mid, s, ppb) { // several bases per pixel: each pixel's largest and smallest
|
|
171
|
+
const up = new Path2D(), down = new Path2D(), bpp = 1 / ppb;
|
|
172
|
+
for (let p = 0; p < W; p++) {
|
|
173
|
+
const a = Math.max(0, Math.floor(x0 + p * bpp)), b = Math.min(L, Math.max(a + 1, Math.floor(x0 + (p + 1) * bpp)));
|
|
174
|
+
let hi = 0, lo = 0;
|
|
175
|
+
for (let i = a; i < b; i++) { const v = t.v[i]; if (v > hi) hi = v; else if (v < lo) lo = v; }
|
|
176
|
+
if (hi > 0) up.rect(LEFT + p, mid - hi * s, 1, hi * s);
|
|
177
|
+
if (lo < 0) down.rect(LEFT + p, mid, 1, -lo * s);
|
|
178
|
+
}
|
|
179
|
+
ctx.fillStyle = t.pos; ctx.fill(up);
|
|
180
|
+
ctx.fillStyle = t.neg; ctx.fill(down);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function lane() { // the seqlets along the top, named where the names fit
|
|
184
|
+
const y = lay.lane - 13, inView = seqlets.filter(q => q.end > x0 && q.start < x1);
|
|
185
|
+
ctx.save();
|
|
186
|
+
ctx.beginPath(); ctx.rect(LEFT, 0, W, lay.lane); ctx.clip();
|
|
187
|
+
for (const q of inView) {
|
|
188
|
+
const a = px(q.start), b = Math.max(px(q.end), a + 3);
|
|
189
|
+
ctx.fillStyle = colOf(q);
|
|
190
|
+
ctx.fillRect(a, y, b - a, 8);
|
|
191
|
+
if (q.hl) { ctx.strokeStyle = '#d99a04'; ctx.lineWidth = 1.5; ctx.strokeRect(a - 1, y - 1, b - a + 2, 10); }
|
|
192
|
+
}
|
|
193
|
+
const rows = [[], []];
|
|
194
|
+
for (const q of inView.slice().sort((p, q) => Math.abs(q.mot_max) - Math.abs(p.mot_max))) {
|
|
195
|
+
ctx.font = (q.hl ? 'bold ' : '') + '11px sans-serif';
|
|
196
|
+
const c = (px(q.start) + px(q.end)) / 2, half = ctx.measureText(q.name).width / 2 + 4;
|
|
197
|
+
const row = rows.findIndex(r => r.every(([lo, hi]) => c + half < lo || c - half > hi));
|
|
198
|
+
if (row < 0) continue;
|
|
199
|
+
rows[row].push([c - half, c + half]);
|
|
200
|
+
ctx.fillStyle = q.hl ? TEXT : MUTED;
|
|
201
|
+
ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
|
|
202
|
+
ctx.fillText(q.name, c, row === 0 ? y - 4 : y - 18);
|
|
203
|
+
}
|
|
204
|
+
ctx.restore();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const scanTop = () => top(tracks.length - 1) + lay.track + lay.gap;
|
|
208
|
+
|
|
209
|
+
function mark(shape, x, y, r, col) { // a scan hit's shape, filled in its family's colour
|
|
210
|
+
ctx.beginPath();
|
|
211
|
+
if (shape === 'square') ctx.rect(x - r * 0.85, y - r * 0.85, r * 1.7, r * 1.7);
|
|
212
|
+
else if (shape === 'diamond') { ctx.moveTo(x, y - r * 1.2); ctx.lineTo(x + r * 1.2, y); ctx.lineTo(x, y + r * 1.2); ctx.lineTo(x - r * 1.2, y); ctx.closePath(); }
|
|
213
|
+
else if (shape === 'triangle-up') { ctx.moveTo(x, y - r * 1.15); ctx.lineTo(x + r, y + r * 0.85); ctx.lineTo(x - r, y + r * 0.85); ctx.closePath(); }
|
|
214
|
+
else if (shape === 'triangle-down') { ctx.moveTo(x, y + r * 1.15); ctx.lineTo(x + r, y - r * 0.85); ctx.lineTo(x - r, y - r * 0.85); ctx.closePath(); }
|
|
215
|
+
else if (shape === 'triangle-right') { ctx.moveTo(x + r * 1.15, y); ctx.lineTo(x - r * 0.85, y + r); ctx.lineTo(x - r * 0.85, y - r); ctx.closePath(); }
|
|
216
|
+
else if (shape === 'triangle-left') { ctx.moveTo(x - r * 1.15, y); ctx.lineTo(x + r * 0.85, y + r); ctx.lineTo(x + r * 0.85, y - r); ctx.closePath(); }
|
|
217
|
+
else if (shape === 'cross') {
|
|
218
|
+
const t = r * 0.45;
|
|
219
|
+
ctx.moveTo(x - t, y - r); ctx.lineTo(x + t, y - r); ctx.lineTo(x + t, y - t); ctx.lineTo(x + r, y - t);
|
|
220
|
+
ctx.lineTo(x + r, y + t); ctx.lineTo(x + t, y + t); ctx.lineTo(x + t, y + r); ctx.lineTo(x - t, y + r);
|
|
221
|
+
ctx.lineTo(x - t, y + t); ctx.lineTo(x - r, y + t); ctx.lineTo(x - r, y - t); ctx.lineTo(x - t, y - t);
|
|
222
|
+
ctx.closePath();
|
|
223
|
+
} else ctx.arc(x, y, r, 0, 2 * Math.PI);
|
|
224
|
+
ctx.fillStyle = col; ctx.fill();
|
|
225
|
+
ctx.strokeStyle = D.dark ? '#0e1117' : '#333333'; ctx.lineWidth = 0.5; ctx.stroke();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function scan() { // the scan's hits, one row per family, below the tracks
|
|
229
|
+
const y0 = scanTop();
|
|
230
|
+
ctx.fillStyle = MUTED; ctx.font = '11px sans-serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
|
|
231
|
+
ctx.fillText(`Motifs by scanning the sequence (JASPAR, p < ${S.threshold})`, 4, y0 + lay.scan_head - 6);
|
|
232
|
+
const rows = y0 + lay.scan_head;
|
|
233
|
+
S.families.forEach((f, k) => {
|
|
234
|
+
const yc = rows + k * lay.scan_row + lay.scan_row / 2;
|
|
235
|
+
ctx.font = '11px sans-serif'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
|
|
236
|
+
ctx.fillStyle = S.colors[f] || MUTED;
|
|
237
|
+
let name = f;
|
|
238
|
+
while (name.length > 2 && ctx.measureText(name).width > LEFT - 10) name = name.slice(0, -2) + '…';
|
|
239
|
+
ctx.fillText(name, LEFT - 7, yc);
|
|
240
|
+
});
|
|
241
|
+
ctx.save();
|
|
242
|
+
ctx.beginPath(); ctx.rect(LEFT, rows, W, S.families.length * lay.scan_row); ctx.clip();
|
|
243
|
+
const lo = px(Math.max(S.window[0], x0)), hi = px(Math.min(S.window[1], x1));
|
|
244
|
+
ctx.fillStyle = D.dark ? 'rgba(163,168,184,0.3)' : 'rgba(107,111,123,0.22)';
|
|
245
|
+
for (let k = 0; k < S.families.length; k++) { // the scanned window, a rule per row
|
|
246
|
+
if (hi > lo) ctx.fillRect(lo, rows + k * lay.scan_row + lay.scan_row / 2 - 0.75, hi - lo, 1.5);
|
|
247
|
+
}
|
|
248
|
+
for (const h of S.hits) {
|
|
249
|
+
if (h.end <= x0 || h.start >= x1) continue;
|
|
250
|
+
const yc = rows + scanRow[h.family] * lay.scan_row + lay.scan_row / 2;
|
|
251
|
+
const a = px(h.start), b = px(h.end), col = S.colors[h.family] || GREY;
|
|
252
|
+
ctx.globalAlpha = 0.35; ctx.fillStyle = col;
|
|
253
|
+
ctx.fillRect(a, yc - 2, Math.max(b - a, 1), 4); // the span it covers
|
|
254
|
+
ctx.globalAlpha = 0.9;
|
|
255
|
+
mark(S.shapes[h.key] || 'circle', (a + b) / 2, yc, 4.5, col);
|
|
256
|
+
ctx.globalAlpha = 1;
|
|
257
|
+
}
|
|
258
|
+
ctx.restore();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function axis(bottom) {
|
|
262
|
+
ctx.strokeStyle = RULE; ctx.lineWidth = 1;
|
|
263
|
+
ctx.beginPath(); ctx.moveTo(LEFT, bottom + 0.5); ctx.lineTo(LEFT + W, bottom + 0.5); ctx.stroke();
|
|
264
|
+
const span = x1 - x0, raw = span / Math.max(2, W / 110);
|
|
265
|
+
const p10 = Math.pow(10, Math.floor(Math.log10(raw)));
|
|
266
|
+
const step = [1, 2, 5, 10].map(m => m * p10).find(v => v >= raw);
|
|
267
|
+
ctx.fillStyle = TEXT; ctx.font = '11px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'top';
|
|
268
|
+
for (let g = Math.ceil((g0 + x0) / step) * step; g < g0 + x1; g += step) {
|
|
269
|
+
const x = px(g - g0 + 0.5);
|
|
270
|
+
if (x < LEFT || x > LEFT + W) continue;
|
|
271
|
+
ctx.beginPath(); ctx.moveTo(x + 0.5, bottom); ctx.lineTo(x + 0.5, bottom + 4); ctx.stroke();
|
|
272
|
+
ctx.fillText(g.toLocaleString('en-US'), x, bottom + 6);
|
|
273
|
+
}
|
|
274
|
+
ctx.fillStyle = MUTED;
|
|
275
|
+
ctx.fillText(D.genomic ? `${D.genomic[0]} (bp)` : 'Input position (bp)', LEFT + W / 2, bottom + 22);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function draw() {
|
|
279
|
+
if (W <= 0) return;
|
|
280
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
281
|
+
ctx.clearRect(0, 0, cv.width / dpr, cv.height / dpr);
|
|
282
|
+
const ppb = W / (x1 - x0), i0 = Math.max(0, Math.floor(x0)), i1 = Math.min(L, Math.ceil(x1));
|
|
283
|
+
const ymax = scales(i0, i1);
|
|
284
|
+
tracks.forEach((t, k) => {
|
|
285
|
+
const y = top(k), mid = y + lay.track / 2, s = (lay.track / 2) / ymax[k];
|
|
286
|
+
ctx.save();
|
|
287
|
+
ctx.beginPath(); ctx.rect(LEFT, y, W, lay.track); ctx.clip();
|
|
288
|
+
for (const q of seqlets) {
|
|
289
|
+
if (q.end <= x0 || q.start >= x1) continue;
|
|
290
|
+
ctx.fillStyle = q.hl ? SHADE_HL : SHADE;
|
|
291
|
+
ctx.fillRect(px(q.start), y, px(q.end) - px(q.start), lay.track);
|
|
292
|
+
}
|
|
293
|
+
if (ppb >= LETTER_PPB) letters(t, i0, i1, mid, s, ppb);
|
|
294
|
+
else if (ppb >= 1) bars(t, i0, i1, mid, s, ppb);
|
|
295
|
+
else envelope(t, mid, s, ppb);
|
|
296
|
+
if (t.cut != null && t.cut * s < lay.track / 2) { // the seqlet cut, dotted
|
|
297
|
+
ctx.strokeStyle = MUTED; ctx.lineWidth = 0.8; ctx.setLineDash([2, 3]);
|
|
298
|
+
for (const c of [t.cut, -t.cut]) {
|
|
299
|
+
ctx.beginPath(); ctx.moveTo(LEFT, mid - c * s + 0.5); ctx.lineTo(LEFT + W, mid - c * s + 0.5); ctx.stroke();
|
|
300
|
+
}
|
|
301
|
+
ctx.setLineDash([]);
|
|
302
|
+
}
|
|
303
|
+
ctx.restore();
|
|
304
|
+
ctx.strokeStyle = RULE; ctx.lineWidth = 0.8;
|
|
305
|
+
ctx.beginPath(); ctx.moveTo(LEFT, mid + 0.5); ctx.lineTo(LEFT + W, mid + 0.5); ctx.stroke();
|
|
306
|
+
ctx.beginPath(); ctx.moveTo(LEFT - 0.5, y); ctx.lineTo(LEFT - 0.5, y + lay.track); ctx.stroke();
|
|
307
|
+
ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.font = 'bold 12px sans-serif';
|
|
308
|
+
ctx.fillStyle = t.label || TEXT;
|
|
309
|
+
let name = t.name; // beside the zero line, shortened to the margin
|
|
310
|
+
while (name.length > 2 && ctx.measureText(name).width > LEFT - 14) name = name.slice(0, -2) + '\u2026';
|
|
311
|
+
ctx.fillText(name, 4, mid);
|
|
312
|
+
const tick = nice(ymax[k] / 1.08);
|
|
313
|
+
ctx.font = '11px sans-serif'; ctx.fillStyle = MUTED; ctx.textAlign = 'right';
|
|
314
|
+
for (const v of [tick, 0, -tick]) {
|
|
315
|
+
const yy = mid - v * s;
|
|
316
|
+
if (v) ctx.fillText(num(v), LEFT - 7, yy);
|
|
317
|
+
ctx.beginPath(); ctx.moveTo(LEFT - 4, yy + 0.5); ctx.lineTo(LEFT, yy + 0.5); ctx.stroke();
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
lane();
|
|
321
|
+
if (S) scan();
|
|
322
|
+
const bottom = top(tracks.length - 1) + lay.track + scanH() + 4;
|
|
323
|
+
axis(bottom);
|
|
324
|
+
if (hover != null && hover >= i0 && hover < i1) {
|
|
325
|
+
ctx.fillStyle = GUIDE;
|
|
326
|
+
ctx.fillRect(px(hover + 0.5) - 0.5, lay.lane - 2, 1, bottom - lay.lane + 2);
|
|
327
|
+
}
|
|
328
|
+
const a = Math.floor(x0), b = Math.ceil(x1);
|
|
329
|
+
where.textContent = (D.genomic ? `${D.genomic[0]}:${(g0 + a).toLocaleString('en-US')}-${(g0 + b).toLocaleString('en-US')}`
|
|
330
|
+
: `${a.toLocaleString('en-US')}-${b.toLocaleString('en-US')}`) + ` · ${(b - a).toLocaleString('en-US')} bp`;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function place(e) {
|
|
334
|
+
tip.style.display = 'block';
|
|
335
|
+
const r = tip.getBoundingClientRect(), vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight;
|
|
336
|
+
tip.style.left = Math.max(4, e.clientX + 14 + r.width > vw ? e.clientX - 14 - r.width : e.clientX + 14) + 'px';
|
|
337
|
+
tip.style.top = Math.max(4, Math.min(e.clientY + 14, vh - r.height - 4)) + 'px';
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function showTip(e, i) {
|
|
341
|
+
let h = `<b>${esc(pos(i))}</b> <span class="k">base</span> ${esc(seq[i])}`;
|
|
342
|
+
for (const t of tracks) h += `<br><span style="color:${t.label || 'inherit'}">${esc(t.name)}</span> ${fmt(t.v[i])}`;
|
|
343
|
+
for (const q of seqlets.filter(q => q.start <= i && i < q.end)) {
|
|
344
|
+
h += `<br><i style="display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:4px;background:${colOf(q)}"></i>`
|
|
345
|
+
+ `<b>${esc(q.name)}</b> <span class="k">cl${q.cluster}${q.subfamily ? ', ' + esc(q.subfamily) : ''}, `
|
|
346
|
+
+ `${esc(span(q))}</span><br>`
|
|
347
|
+
+ (q.sign ? `<span class="k">stronger in</span> ${esc(q.sign > 0 ? D.label_b : D.label_a)} <span class="k">mot_max</span> ${fmt(q.mot_max)}`
|
|
348
|
+
: `<span class="k">equal in both</span>`)
|
|
349
|
+
+ (q.a != null ? ` <span class="k">${esc(D.label_a)}</span> ${fmt(q.a)}` : '')
|
|
350
|
+
+ (q.b != null ? ` <span class="k">${esc(D.label_b)}</span> ${fmt(q.b)}` : '')
|
|
351
|
+
+ (q.tracks ? `<br><span class="k">found on</span> ${esc(q.tracks)}` : '');
|
|
352
|
+
}
|
|
353
|
+
tip.innerHTML = h;
|
|
354
|
+
place(e);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function scanRowAt(my) { // the family row under the mouse, or -1
|
|
358
|
+
if (!S) return -1;
|
|
359
|
+
const k = Math.floor((my - scanTop() - lay.scan_head) / lay.scan_row);
|
|
360
|
+
return my >= scanTop() + lay.scan_head && k >= 0 && k < S.families.length ? k : -1;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function showScanTip(e, k, mx) { // the row's hits under the mouse, every one
|
|
364
|
+
const f = S.families[k];
|
|
365
|
+
const hs = S.hits.filter(h => h.family === f && mx >= px(h.start) - 5 && mx <= px(h.end) + 5);
|
|
366
|
+
if (!hs.length) { tip.style.display = 'none'; return; }
|
|
367
|
+
let h = '';
|
|
368
|
+
for (const q of hs) {
|
|
369
|
+
h += (h ? '<br>' : '')
|
|
370
|
+
+ `<i style="display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:4px;background:${S.colors[q.family] || GREY}"></i>`
|
|
371
|
+
+ `<b>${esc(q.key)}</b> <span class="k">${esc(q.family)}, ${esc(span(q))}</span><br>`
|
|
372
|
+
+ `<span class="k">matrix</span> ${esc(q.matrix)} <span class="k">strand</span> ${esc(q.strand)} `
|
|
373
|
+
+ `<span class="k">score</span> ${fmt(q.score)} <span class="k">p</span> ${q.p.toExponential(1)}`;
|
|
374
|
+
}
|
|
375
|
+
tip.innerHTML = h;
|
|
376
|
+
place(e);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function at(e) { // the input position under the mouse, as a float
|
|
380
|
+
const r = cv.getBoundingClientRect();
|
|
381
|
+
return x0 + Math.min(Math.max((e.clientX - r.left - LEFT) / W, 0), 1) * (x1 - x0);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
cv.addEventListener('wheel', e => {
|
|
385
|
+
e.preventDefault();
|
|
386
|
+
if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) { // sideways on a trackpad: move
|
|
387
|
+
const d = e.deltaX / W * (x1 - x0);
|
|
388
|
+
setWindow(x0 + d, x1 + d);
|
|
389
|
+
} else {
|
|
390
|
+
zoomAt(Math.exp((e.deltaMode === 1 ? e.deltaY * 33 : e.deltaY) * 0.0015), at(e));
|
|
391
|
+
}
|
|
392
|
+
}, {passive: false});
|
|
393
|
+
cv.addEventListener('dblclick', e => zoomAt(e.shiftKey ? 2 : 0.5, at(e)));
|
|
394
|
+
cv.addEventListener('mousedown', e => { drag = {x: e.clientX, a: x0, b: x1}; cv.classList.add('drag'); tip.style.display = 'none'; });
|
|
395
|
+
window.addEventListener('mouseup', () => { drag = null; cv.classList.remove('drag'); });
|
|
396
|
+
window.addEventListener('mousemove', e => {
|
|
397
|
+
if (drag) {
|
|
398
|
+
const d = (e.clientX - drag.x) / W * (drag.b - drag.a);
|
|
399
|
+
setWindow(drag.a - d, drag.b - d);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const r = cv.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
|
|
403
|
+
const inside = e.target === cv && mx >= LEFT && mx <= LEFT + W && my >= 0 && my <= height() - lay.axis;
|
|
404
|
+
const i = inside ? Math.min(L - 1, Math.floor(at(e))) : null;
|
|
405
|
+
if (i !== hover) { hover = i; draw(); }
|
|
406
|
+
const k = inside ? scanRowAt(my) : -1;
|
|
407
|
+
if (i == null) tip.style.display = 'none';
|
|
408
|
+
else if (k >= 0) showScanTip(e, k, mx);
|
|
409
|
+
else showTip(e, i);
|
|
410
|
+
});
|
|
411
|
+
cv.addEventListener('mouseleave', () => { if (!drag) { hover = null; tip.style.display = 'none'; draw(); } });
|
|
412
|
+
|
|
413
|
+
const centre = () => (x0 + x1) / 2;
|
|
414
|
+
document.getElementById('in').onclick = () => zoomAt(0.5, centre());
|
|
415
|
+
document.getElementById('out').onclick = () => zoomAt(2, centre());
|
|
416
|
+
document.getElementById('all').onclick = () => setWindow(0, L);
|
|
417
|
+
const reg = document.getElementById('region');
|
|
418
|
+
if (D.region) reg.onclick = () => setWindow(D.region[0], D.region[1]); else reg.style.display = 'none';
|
|
419
|
+
document.getElementById('share').onchange = e => { share = e.target.checked; draw(); };
|
|
420
|
+
const sel = document.getElementById('color'), names = {subfamily: 'Subfamily', family: 'Family', cluster: 'Cluster', sign: 'Direction'};
|
|
421
|
+
for (const k of ['subfamily', 'family', 'cluster'].filter(k => CMAP[k]).concat(['sign'])) {
|
|
422
|
+
const o = document.createElement('option');
|
|
423
|
+
o.value = k; o.textContent = names[k];
|
|
424
|
+
sel.appendChild(o);
|
|
425
|
+
}
|
|
426
|
+
try { const v = localStorage.getItem('seqletColorBy'); if (v === 'sign' || CMAP[v]) colorBy = v; } catch (e) {}
|
|
427
|
+
sel.value = colorBy;
|
|
428
|
+
sel.onchange = () => {
|
|
429
|
+
colorBy = sel.value;
|
|
430
|
+
try { localStorage.setItem('seqletColorBy', colorBy); } catch (e) {}
|
|
431
|
+
fillChips(); draw();
|
|
432
|
+
};
|
|
433
|
+
const chips = document.getElementById('chips');
|
|
434
|
+
const strongest = seqlets.map((q, k) => k).sort((a, b) => Math.abs(seqlets[b].mot_max) - Math.abs(seqlets[a].mot_max));
|
|
435
|
+
function fillChips() { // the strongest seqlets as buttons, in input order, as many as fit
|
|
436
|
+
for (let n = Math.min(D.chips, strongest.length); n >= 0; n--) {
|
|
437
|
+
chips.textContent = '';
|
|
438
|
+
for (const k of strongest.slice(0, n).sort((a, b) => seqlets[a].start - seqlets[b].start)) {
|
|
439
|
+
const q = seqlets[k], btn = document.createElement('button');
|
|
440
|
+
btn.className = 'chip' + (q.hl ? ' hl' : '');
|
|
441
|
+
btn.title = `Zoom to ${q.name}, ${span(q)}`;
|
|
442
|
+
btn.innerHTML = `<i style="background:${colOf(q)}"></i>${esc(q.name)}`;
|
|
443
|
+
btn.onclick = () => focus(q);
|
|
444
|
+
chips.appendChild(btn);
|
|
445
|
+
}
|
|
446
|
+
if (chips.scrollWidth <= chips.clientWidth) return;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
window.addEventListener('resize', () => { const a = x0, b = x1; fillChips(); resize(); setWindow(a, b); });
|
|
451
|
+
fillChips();
|
|
452
|
+
resize();
|
|
453
|
+
if (D.focus != null) focus(seqlets[D.focus]);
|
|
454
|
+
else if (D.region) setWindow(D.region[0], D.region[1]);
|
|
455
|
+
else setWindow(0, L);
|
|
456
|
+
})();
|
|
457
|
+
</script>
|
|
458
|
+
</body>
|
|
459
|
+
</html>
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The region panel's tracks as one interactive canvas (tracks/index.html), as a genome browser draws them: each base's
|
|
3
|
+
contribution under A, under B and B − A as bars when zoomed out (the largest and smallest of each pixel once a pixel
|
|
4
|
+
holds several bases), as the input's letters stretched to their contribution when zoomed in (as plotting.draw_logo
|
|
5
|
+
draws them, negatives upside down), the seqlets marked along the top in their subfamily's colour (the Colour menu
|
|
6
|
+
switches to family, cluster or the condition they are stronger in) and shaded down the tracks, the genome
|
|
7
|
+
coordinates along the bottom. Given the hits of view.data.region_scan, the motifs a scan of the sequence alone finds
|
|
8
|
+
join as rows below the tracks, one per family in its colour, its subfamilies as shapes, sharing the zoom, pan and
|
|
9
|
+
hover. The wheel, the buttons or a double click zoom,
|
|
10
|
+
a drag moves, hovering reads the numbers. Everything is computed here; the page only draws.
|
|
11
|
+
"""
|
|
12
|
+
import base64
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Optional, Tuple
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pandas as pd
|
|
20
|
+
|
|
21
|
+
from .. import plotting as P
|
|
22
|
+
from ..analysis import Analysis, Example
|
|
23
|
+
from . import data as V
|
|
24
|
+
|
|
25
|
+
PAGE = Path(__file__).with_name('tracks') / 'index.html'
|
|
26
|
+
TRACK_PX, GAP_PX, LANE_PX, AXIS_PX, BAR_PX = 110, 10, 46, 40, 40 # the page's layout, for the frame's height
|
|
27
|
+
SCAN_HEAD_PX, SCAN_ROW_PX = 18, 22 # the scan rows' header and one family's row
|
|
28
|
+
MAX_CHIPS = 12 # seqlets offered as buttons, the strongest; hovering names every one
|
|
29
|
+
#: the shapes of a family's subfamilies in the sequence scan, cycled when a family has more
|
|
30
|
+
SCAN_SHAPES = ('circle', 'square', 'triangle-up', 'diamond', 'triangle-down', 'cross', 'triangle-right', 'triangle-left')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _svg(path) -> str:
|
|
34
|
+
"""A matplotlib path as SVG path data in its own coordinates (the unit square, y up)."""
|
|
35
|
+
parts = []
|
|
36
|
+
for verts, code in path.iter_segments(simplify=False, curves=True):
|
|
37
|
+
pts = ' '.join(f'{v:.4f}' for v in np.asarray(verts, float).ravel())
|
|
38
|
+
parts.append({1: 'M', 2: 'L', 3: 'Q', 4: 'C', 79: 'Z'}[int(code)] + ('' if int(code) == 79 else ' ' + pts))
|
|
39
|
+
return ' '.join(parts)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _floats(v) -> str:
|
|
43
|
+
return base64.b64encode(np.ascontiguousarray(np.asarray(v, '<f4')).tobytes()).decode()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def seqlet_colors(an: Analysis) -> dict:
|
|
47
|
+
"""
|
|
48
|
+
One colour per family, subfamily and cluster of the contrast (plotting.family_colors, most seqlets first, ties
|
|
49
|
+
by name), the same in every region. Keys 'family', 'subfamily' (only once `families` ran) and 'cluster' (ids as
|
|
50
|
+
strings), each a {name: hex} map.
|
|
51
|
+
"""
|
|
52
|
+
def load():
|
|
53
|
+
meta = V.seqlet_meta(an)
|
|
54
|
+
|
|
55
|
+
def ranked(s):
|
|
56
|
+
c = s.value_counts()
|
|
57
|
+
return sorted(c.index, key=lambda k: (-int(c[k]), str(k)))
|
|
58
|
+
keys = ranked(meta['cluster'])
|
|
59
|
+
out = {'cluster': dict(zip((str(int(k)) for k in keys), P.family_colors(len(keys))))}
|
|
60
|
+
for name, col in (('family', 'group'), ('subfamily', 'subfamily')):
|
|
61
|
+
if col in meta:
|
|
62
|
+
keys = ranked(meta[col].dropna())
|
|
63
|
+
out[name] = dict(zip(map(str, keys), P.family_colors(len(keys))))
|
|
64
|
+
return out
|
|
65
|
+
return an._get('view/track_colors', load)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _scan_block(scan: Optional[pd.DataFrame], fam_col: dict) -> Optional[dict]:
|
|
69
|
+
"""The scan's hits (view.data.region_scan) as the page draws them: families most hits first, one shape per
|
|
70
|
+
subfamily of a family (most hits first, cycled), the scanned window and threshold."""
|
|
71
|
+
if scan is None or scan.empty:
|
|
72
|
+
return None
|
|
73
|
+
counts = scan.groupby(['family', 'key']).size().rename('n').reset_index().sort_values(
|
|
74
|
+
['family', 'n', 'key'], ascending=[True, False, True])
|
|
75
|
+
counts['shape'] = counts.groupby('family').cumcount() % len(SCAN_SHAPES)
|
|
76
|
+
shapes = {str(k): SCAN_SHAPES[int(i)] for k, i in zip(counts['key'], counts['shape'])}
|
|
77
|
+
fams = [str(f) for f in scan['family'].value_counts().index]
|
|
78
|
+
lo, hi = scan.attrs['window']
|
|
79
|
+
hits = [{'start': int(h.start), 'end': int(h.end), 'key': str(h.key), 'family': str(h.family),
|
|
80
|
+
'matrix': str(h.matrix), 'strand': str(h.strand), 'score': float(h.score), 'p': float(h.p)}
|
|
81
|
+
for h in scan.itertuples()]
|
|
82
|
+
return {'window': [int(lo), int(hi)], 'threshold': float(scan.attrs['threshold']), 'families': fams,
|
|
83
|
+
'colors': {f: fam_col.get(f, '#888888') for f in fams}, 'shapes': shapes, 'hits': hits}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _found_on(tracks, label_a: str, label_b: str) -> Optional[str]:
|
|
87
|
+
"""A site's `tracks` ('X:a,X:diff') in words: the conditions' labels and 'difference'; None when unknown."""
|
|
88
|
+
if not isinstance(tracks, str) or not tracks:
|
|
89
|
+
return None
|
|
90
|
+
names = {'a': label_a, 'b': label_b, 'diff': 'difference'}
|
|
91
|
+
return ', '.join(names.get(t.rsplit(':', 1)[-1], t) for t in tracks.split(','))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def track_data(an: Analysis, ex: Example, highlight: Optional[int] = None, dark: bool = False,
|
|
95
|
+
scan: Optional[pd.DataFrame] = None) -> dict:
|
|
96
|
+
"""What the page draws for region `ex` (view.data.region): bases, tracks, seqlets, genome offset and colours,
|
|
97
|
+
and with `scan` (view.data.region_scan) the sequence scan's hits as rows below the tracks."""
|
|
98
|
+
r, la, lb = ex.record, an.label_a, an.label_b
|
|
99
|
+
L = len(r['contributions'])
|
|
100
|
+
seq = np.where(ex.onehot.max(1) > 0, np.array(list('ACGT'))[ex.onehot.argmax(1)], 'N')
|
|
101
|
+
names = list(ex.tracks) # A mean, B mean, B − A
|
|
102
|
+
grey = ('#c8c8c8', '#7a7a7a') if dark else ('#444444', '#999999')
|
|
103
|
+
cut = float(an.pct * r['pred'])
|
|
104
|
+
last = len(ex.tracks) - 1 if ex.single else 2 # the row seqlets are called on, coloured by sign
|
|
105
|
+
tracks = [{'name': k, 'values': _floats(v), 'label': ([an.colors[lb]] if ex.single else [an.colors[la], an.colors[lb], None])[j],
|
|
106
|
+
'pos': an.colors[lb] if j == last else grey[0], 'neg': an.colors[la] if j == last else grey[1],
|
|
107
|
+
'cut': cut if j == last else None} for j, (k, v) in enumerate(ex.tracks.items())]
|
|
108
|
+
seqlets = []
|
|
109
|
+
if ex.seqlets:
|
|
110
|
+
motif = list(V.motif_names(pd.DataFrame(ex.seqlets)))
|
|
111
|
+
for s, m in zip(ex.seqlets, motif):
|
|
112
|
+
seqlets.append({'start': int(s['start']), 'end': int(s['end']), 'name': str(m), 'cluster': int(s['cluster']),
|
|
113
|
+
'subfamily': None if pd.isna(s.get('subfamily')) else str(s.get('subfamily')),
|
|
114
|
+
'family': None if pd.isna(s.get('group')) else str(s.get('group')),
|
|
115
|
+
'sign': int(s['sign']), 'mot_max': None if pd.isna(s['mot_max']) else float(s['mot_max']),
|
|
116
|
+
'a': None if pd.isna(s.get('mot_max_a', np.nan)) else float(s['mot_max_a']),
|
|
117
|
+
'b': None if pd.isna(s.get('mot_max_b', np.nan)) else float(s['mot_max_b']),
|
|
118
|
+
'tracks': _found_on(s.get('tracks'), la, lb),
|
|
119
|
+
'hl': highlight is not None and int(s['cluster']) == int(highlight)})
|
|
120
|
+
focus = None
|
|
121
|
+
if seqlets:
|
|
122
|
+
pool = [k for k, s in enumerate(seqlets) if s['hl']] or list(range(len(seqlets)))
|
|
123
|
+
focus = max(pool, key=lambda k: abs(seqlets[k]['mot_max'] or 0.0))
|
|
124
|
+
genomic = [r['genomic_chrom'], int(r['genomic_start'])] if r.get('genomic_start') is not None else None
|
|
125
|
+
region = None
|
|
126
|
+
m = re.fullmatch(r'(.+):(\d+)-(\d+)', str(r['coord']))
|
|
127
|
+
if genomic and m and m.group(1) == genomic[0]:
|
|
128
|
+
lo, hi = int(m.group(2)) - genomic[1], int(m.group(3)) - genomic[1]
|
|
129
|
+
if 0 <= lo < hi <= L:
|
|
130
|
+
region = [lo, hi]
|
|
131
|
+
cmap = seqlet_colors(an)
|
|
132
|
+
colors = {lvl: {k: m[k] for k in {str(q['cluster']) if lvl == 'cluster' else q[lvl] for q in seqlets}
|
|
133
|
+
if k is not None and k in m} for lvl, m in cmap.items()}
|
|
134
|
+
return {'length': L, 'seq': ''.join(seq), 'tracks': tracks, 'seqlets': seqlets, 'focus': focus,
|
|
135
|
+
'genomic': genomic, 'region': region, 'label_a': la, 'label_b': lb,
|
|
136
|
+
'colors': colors, 'color_by': 'subfamily' if 'subfamily' in colors else 'cluster',
|
|
137
|
+
'color_a': an.colors[la], 'color_b': an.colors[lb], 'dark': dark, 'chips': MAX_CHIPS,
|
|
138
|
+
'base_colors': P.BASE_COLORS, 'glyphs': {b: _svg(P._glyph(b)) for b in 'ACGT'},
|
|
139
|
+
'scan': _scan_block(scan, cmap.get('family', {})),
|
|
140
|
+
'layout': {'track': TRACK_PX, 'gap': GAP_PX, 'lane': LANE_PX, 'axis': AXIS_PX,
|
|
141
|
+
'scan_head': SCAN_HEAD_PX, 'scan_row': SCAN_ROW_PX}}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def track_view(an: Analysis, ex: Example, highlight: Optional[int] = None, dark: bool = False,
|
|
145
|
+
scan: Optional[pd.DataFrame] = None) -> Tuple[str, int]:
|
|
146
|
+
"""The page for st.iframe and its height in CSS pixels."""
|
|
147
|
+
d = track_data(an, ex, highlight, dark, scan)
|
|
148
|
+
blob = json.dumps(d, separators=(',', ':')).replace('</', '<\\/') # safe inside the page's script tag
|
|
149
|
+
n = len(d['tracks'])
|
|
150
|
+
h = BAR_PX + LANE_PX + n * TRACK_PX + (n - 1) * GAP_PX + AXIS_PX + 12
|
|
151
|
+
if d['scan']:
|
|
152
|
+
h += GAP_PX + SCAN_HEAD_PX + len(d['scan']['families']) * SCAN_ROW_PX
|
|
153
|
+
return PAGE.read_text(encoding='utf-8').replace('/*DATA*/{}', blob), h
|