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,400 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The viewer's figures, drawn by the package's own plotting functions so that they match the report and the
|
|
3
|
+
walkthrough notebooks. Each returns a closed matplotlib figure; the app renders it.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from .. import plotting as P
|
|
13
|
+
from ..analysis import Analysis, Example
|
|
14
|
+
from . import data as V
|
|
15
|
+
|
|
16
|
+
TRACK_BARS = 1000 # longer tracks are drawn per bin: one bar per base is slow, and finer than the pixels
|
|
17
|
+
LOGO_BP = 1000 # the attribution logos show at most this many bases at a time (10 px per base)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_long(ex: Example) -> bool:
|
|
21
|
+
"""Whether the input is too long to show whole as attribution logos, so the panel shows one locus at a time."""
|
|
22
|
+
return len(ex.record['contributions']) > LOGO_BP
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _closed(fig):
|
|
26
|
+
import matplotlib.pyplot as plt
|
|
27
|
+
plt.close(fig)
|
|
28
|
+
return fig
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def motif_logos(an: Analysis, cluster: int, matrix_id: Optional[str] = None):
|
|
32
|
+
"""The cluster's contribution logo above one of its JASPAR matches in bits (default the best), aligned to it."""
|
|
33
|
+
hits = V.jaspar_hits(an, cluster)
|
|
34
|
+
if not len(hits):
|
|
35
|
+
return _closed(P.plot_logo_grid([[(an.logos[int(cluster)], f'cl{cluster} consensus')]], width=3.4))
|
|
36
|
+
h = hits.set_index('id').loc[matrix_id or hits['id'].iat[0]]
|
|
37
|
+
logo, jas = V.aligned_logos(an, cluster, h.name)
|
|
38
|
+
rows = [[(logo, f'cl{cluster} consensus')], [(jas, f"{h['tf']} ({h.name}) p = {h['pval']:.0e}")]]
|
|
39
|
+
return _closed(P.plot_logo_grid(rows, row_labels=['Consensus', 'JASPAR'], width=min(7.0, 0.9 + 0.22 * len(logo)),
|
|
40
|
+
row_height=1.0))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cluster_row(an: Analysis, cluster: int):
|
|
44
|
+
"""
|
|
45
|
+
The cluster's row of the report's cluster figure (plotting.plot_cluster_report): its seqlets stronger in each
|
|
46
|
+
condition per set, and each condition's contribution at them. The contribution axis is scaled to this cluster.
|
|
47
|
+
None for seqlets called before mot_max_a / mot_max_b were stored.
|
|
48
|
+
"""
|
|
49
|
+
meta = V.seqlet_meta(an)
|
|
50
|
+
if not {'mot_max_a', 'mot_max_b'} <= set(meta.columns):
|
|
51
|
+
return None
|
|
52
|
+
hits = an.hits.get(int(cluster))
|
|
53
|
+
name = f"cl{cluster}\n{hits[0]['tf']}" if hits else f'cl{cluster}'
|
|
54
|
+
attributed = an.thresholds.groupby(['set_name', 'contrast'])['coord'].nunique().to_dict()
|
|
55
|
+
fig = P.plot_cluster_report(meta, [int(cluster)], {int(cluster): an.logos[int(cluster)]}, {int(cluster): name},
|
|
56
|
+
an.sets, [an.contrast.name], attributed, set_labels=an.set_labels,
|
|
57
|
+
color_a=an.colors[an.label_a], color_b=an.colors[an.label_b],
|
|
58
|
+
label_a=an.label_a, label_b=an.label_b, row_height=0.9)
|
|
59
|
+
return _closed(fig)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def region_tracks(an: Analysis, ex: Example, highlight: Optional[int] = None, n_bins: int = 2000):
|
|
63
|
+
"""
|
|
64
|
+
The region's contributions under each condition and their difference: Analysis.plot_example_tracks on short
|
|
65
|
+
inputs; on long ones the largest and smallest contribution of each bin (so that one strong base still shows),
|
|
66
|
+
with the seqlets marked along the top and those of cluster `highlight` in colour.
|
|
67
|
+
"""
|
|
68
|
+
L = len(ex.record['contributions'])
|
|
69
|
+
if L <= TRACK_BARS:
|
|
70
|
+
return an.plot_example_tracks(ex)
|
|
71
|
+
import matplotlib.pyplot as plt
|
|
72
|
+
la, lb = an.label_a, an.label_b
|
|
73
|
+
r, tracks = ex.record, ex.tracks
|
|
74
|
+
colors = {ex.diff_name: (an.colors[la], an.colors[lb])}
|
|
75
|
+
edges = np.linspace(0, L, min(n_bins, L) + 1).astype(int)
|
|
76
|
+
fig, axes = plt.subplots(len(tracks), 1, figsize=(7.0, 1.3 * len(tracks) + 0.3), sharex=True,
|
|
77
|
+
constrained_layout=True)
|
|
78
|
+
for ax, (label, c) in zip(axes, tracks.items()):
|
|
79
|
+
hi, lo = np.maximum.reduceat(c, edges[:-1]), np.minimum.reduceat(c, edges[:-1])
|
|
80
|
+
neg, pos = colors.get(label, ('#999999', '#444444'))
|
|
81
|
+
ax.fill_between(edges, 0, np.r_[np.maximum(hi, 0), max(hi[-1], 0)], step='post', color=pos, lw=0)
|
|
82
|
+
ax.fill_between(edges, np.r_[np.minimum(lo, 0), min(lo[-1], 0)], 0, step='post', color=neg, lw=0)
|
|
83
|
+
ax.axhline(0, color='black', lw=0.5)
|
|
84
|
+
ax.set_xlim(0, L)
|
|
85
|
+
ax.set_ylabel(label)
|
|
86
|
+
for s in ex.seqlets:
|
|
87
|
+
hl = highlight is not None and int(s['cluster']) == int(highlight)
|
|
88
|
+
ax.vlines((s['start'] + s['end']) / 2, 0.88 if hl else 0.94, 1.0, transform=ax.get_xaxis_transform(),
|
|
89
|
+
color='#D98E04' if hl else '#777777', lw=0.8 if hl else 0.5)
|
|
90
|
+
axes[-1].set_xlabel('Input position (bp)')
|
|
91
|
+
axes[0].set_title(f"{r['coord']} ({r['set_name']}): budget {r['pred']:.1f} from {r['budget_source']}", fontsize=9)
|
|
92
|
+
return _closed(fig)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def region_logo(an: Analysis, ex: Example, highlight=None, locus: Optional[int] = None,
|
|
96
|
+
share_y: bool = True, window: Optional[tuple] = None, ymax: Optional[float] = None, pad: int = 40):
|
|
97
|
+
"""
|
|
98
|
+
The region as attribution logos (Analysis.plot_example_logos): each base at its contribution in A, B and
|
|
99
|
+
B − A, each seqlet named by its motif, those of cluster `highlight` in colour. The whole input up to LOGO_BP
|
|
100
|
+
bases; on a longer input one locus of data.seqlet_loci (default the one with the strongest seqlet of
|
|
101
|
+
`highlight`) with pad bases around it, at most LOGO_BP. An explicit `window` (lo, hi) overrides that, and may
|
|
102
|
+
reach beyond the input; ymax fixes the contribution scale (for several regions on one scale).
|
|
103
|
+
"""
|
|
104
|
+
L = len(ex.record['contributions'])
|
|
105
|
+
if window is not None:
|
|
106
|
+
window = (int(window[0]), int(window[1]))
|
|
107
|
+
elif L > LOGO_BP:
|
|
108
|
+
loci = V.seqlet_loci(ex)
|
|
109
|
+
if loci:
|
|
110
|
+
group = loci[V.strongest_locus(loci, highlight) if locus is None else locus]
|
|
111
|
+
lo, hi = max(0, group[0]['start'] - pad), min(L, group[-1]['end'] + pad)
|
|
112
|
+
if hi - lo > LOGO_BP:
|
|
113
|
+
lo = max(0, min((group[0]['start'] + group[-1]['end']) // 2 - LOGO_BP // 2, L - LOGO_BP))
|
|
114
|
+
hi = lo + LOGO_BP
|
|
115
|
+
window = (lo, hi)
|
|
116
|
+
else:
|
|
117
|
+
window = (0, LOGO_BP)
|
|
118
|
+
names = list(V.motif_names(pd.DataFrame(ex.seqlets))) if ex.seqlets else None
|
|
119
|
+
return an.plot_example_logos(ex, window=window, names=names, highlight=highlight, share_y=share_y, ymax=ymax)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def region_logos(an: Analysis, ex: Example, per_row: int = 5):
|
|
123
|
+
"""The region's seqlets as contribution logos, titled by motif, position and direction."""
|
|
124
|
+
if not ex.seqlets:
|
|
125
|
+
return None
|
|
126
|
+
names = V.motif_names(pd.DataFrame(ex.seqlets))
|
|
127
|
+
items = [(logo, f"{name} {s['start']}-{s['end']} {'+' if s['sign'] > 0 else '−'}")
|
|
128
|
+
for s, name, logo in zip(ex.seqlets, names, V.seqlet_logos(an, ex.seqlets))]
|
|
129
|
+
rows = [items[i:i + per_row] for i in range(0, len(items), per_row)]
|
|
130
|
+
return _closed(P.plot_logo_grid(rows, width=7.0))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def selection_funnel(an: Analysis):
|
|
134
|
+
"""Every contrast's selection, as bars per set (Analysis.plot_selection_funnel); None without a region table."""
|
|
135
|
+
return an.plot_selection_funnel()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def predicted_signal(an: Analysis):
|
|
139
|
+
return an.plot_predicted_signal()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def measured_predicted(an: Analysis):
|
|
143
|
+
return an.plot_measured_predicted()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def selection_scatter(an: Analysis):
|
|
147
|
+
"""The attribute step's candidates, measured against predicted (Analysis.plot_region_selection); None without them."""
|
|
148
|
+
if 'attribute' not in an.cfg:
|
|
149
|
+
return None
|
|
150
|
+
return an.plot_region_selection()
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def seqlet_threshold(an: Analysis):
|
|
154
|
+
return an.plot_seqlet_threshold()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def cluster_report(an: Analysis):
|
|
158
|
+
"""The report's cluster figure (report/cluster_report): None for a run whose seqlets predate mot_max_a / mot_max_b."""
|
|
159
|
+
return an.plot_cluster_report()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def cooc_counts(an: Analysis, level: str = 'subfamily'):
|
|
163
|
+
"""
|
|
164
|
+
Motif co-occurrence as absolute region counts, sign-matched (view.data.cooc_counts), one panel per class in its
|
|
165
|
+
colour: each motif's regions as bars, the regions carrying both as a heatmap, dots where a pair is more often
|
|
166
|
+
together than independence. None with fewer than two motifs.
|
|
167
|
+
"""
|
|
168
|
+
c = V.cooc_counts(an, level)
|
|
169
|
+
if len(c['keys']) < 2:
|
|
170
|
+
return None
|
|
171
|
+
panels = [{**p, 'title': f"{an.set_labels.get(p['set_name'], p['set_name'])} ({p['regions']:,} regions)",
|
|
172
|
+
'color': an.set_colors.get(p['set_name'], '#555555')} for p in c['panels']]
|
|
173
|
+
signed = any(p['sign'] for p in c['panels'])
|
|
174
|
+
sub = level == 'subfamily'
|
|
175
|
+
return _closed(P.plot_cooc_counts(
|
|
176
|
+
c['labels'], c['families'], panels,
|
|
177
|
+
title=f'Motif co-occurrence as absolute region counts\n{level} level',
|
|
178
|
+
legend_title='Subfamilies grouped and coloured by TF family' if sub else 'Clusters grouped and coloured by subfamily',
|
|
179
|
+
single='family with one subfamily here' if sub else 'subfamily with one cluster here',
|
|
180
|
+
dot_label=f"more often together than independence (Fisher, FDR < {c['alpha']:g})"))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def logo_thumbnail(an: Analysis, cluster: int, width: float = 1.4, height: float = 0.36, dpi: int = 120) -> str:
|
|
184
|
+
"""A cluster's contribution logo as a small transparent PNG data URI, for a table cell (plotting.draw_logo)."""
|
|
185
|
+
import base64
|
|
186
|
+
import io
|
|
187
|
+
import matplotlib.pyplot as plt
|
|
188
|
+
m = np.asarray(an.logos[int(cluster)], float)
|
|
189
|
+
fig = plt.figure(figsize=(width, height), dpi=dpi)
|
|
190
|
+
ax = fig.add_axes((0, 0, 1, 1))
|
|
191
|
+
P.draw_logo(ax, m)
|
|
192
|
+
ax.set_xlim(-0.5, len(m) - 0.5)
|
|
193
|
+
ax.set_ylim(min(float(np.clip(m, None, 0).sum(axis=1).min()), 0.0), max(float(np.clip(m, 0, None).sum(axis=1).max()), 1e-9))
|
|
194
|
+
ax.axis('off')
|
|
195
|
+
buf = io.BytesIO()
|
|
196
|
+
fig.savefig(buf, format='png', transparent=True)
|
|
197
|
+
plt.close(fig)
|
|
198
|
+
return 'data:image/png;base64,' + base64.b64encode(buf.getvalue()).decode()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def group_report(an: Analysis, level: str, key: str):
|
|
202
|
+
"""
|
|
203
|
+
The report's cluster figure (Analysis.plot_cluster_report) for the clusters of one name of view.data.group_table,
|
|
204
|
+
with [expression] a panel per set of the fold changes of the genes of the regions where each cluster has a seqlet.
|
|
205
|
+
"""
|
|
206
|
+
t = V.group_table(an, level)
|
|
207
|
+
rows = t[t['key'] == key] if len(t) else t
|
|
208
|
+
return an.plot_cluster_report(clusters=list(rows['clusters'].iat[0]), targets=True) if len(rows) else None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def motif_bubbles(an: Analysis):
|
|
212
|
+
"""
|
|
213
|
+
The report's bubble plot (report/motif_bubbles) at the report's level, for the analysis contrast: the motifs in most
|
|
214
|
+
regions of each set, the share of each set's regions carrying them and, with two classes (differential_sets: A, B),
|
|
215
|
+
the log2 prevalence ratio B over A in the classes' colours, and with [expression] the fold change of each motif's
|
|
216
|
+
candidate TFs (expression.tf_members). Its motif table is computed as the report step computes it, so the report
|
|
217
|
+
need not have run. None without the families step.
|
|
218
|
+
"""
|
|
219
|
+
import textwrap
|
|
220
|
+
from .. import summaries as S
|
|
221
|
+
r = an.cfg['report']
|
|
222
|
+
level = r['level']
|
|
223
|
+
if not V.has(an, 'families/cluster_families.csv'):
|
|
224
|
+
return None
|
|
225
|
+
meta, c = an.seqlets.meta, an.contrast.name
|
|
226
|
+
den = S.denominators(meta, an.thresholds, r['denominator'])
|
|
227
|
+
lab = S.label_seqlets(meta, an.families, min_cluster_size=r['min_cluster_size'])
|
|
228
|
+
table = S.motif_table(lab[lab['contrast'] == c], level=level, den=den)
|
|
229
|
+
sets = [s for s in an.sets if s in set(table['set_name'])]
|
|
230
|
+
motifs = list(dict.fromkeys(m for s in sets for m in S.top_motifs(table, level, s, n=r['top_n'])))
|
|
231
|
+
largest = an.families.sort_values('n_seqlets', ascending=False).drop_duplicates(level)
|
|
232
|
+
logos = {row[level]: an.logos[int(row['cluster'])] for _, row in largest.iterrows() if int(row['cluster']) in an.logos}
|
|
233
|
+
labels = ['\n'.join(textwrap.wrap(an.set_labels.get(s, s), 8, break_long_words=False)) +
|
|
234
|
+
f'\nn={int(den.get((s, c), 0)):,}' for s in sets]
|
|
235
|
+
pair = V.differential_sets(an)
|
|
236
|
+
A, B = pair if pair else (None, None)
|
|
237
|
+
colors = an.set_colors
|
|
238
|
+
de = None
|
|
239
|
+
if an.expression_table is not None:
|
|
240
|
+
from .. import expression as X
|
|
241
|
+
de = X.tf_members(an.expression_table, an.annotations, an.families, an.hits, level, motifs)
|
|
242
|
+
la, lb = an.set_labels.get(A, A), an.set_labels.get(B, B)
|
|
243
|
+
fig = P.plot_motif_bubbles(table, motifs, [(s, c) for s in sets], level=level, logos=logos,
|
|
244
|
+
column_labels=labels, color_a=colors.get(A, P.DEFAULT_A), color_b=colors.get(B, P.DEFAULT_B),
|
|
245
|
+
label_a=an.label_a, label_b=an.label_b, color_by=r['color_by'],
|
|
246
|
+
ratio=S.prevalence_ratio(table, level, B, A) if pair else None,
|
|
247
|
+
ratio_label=f'log$_2$ prevalence, {lb} / {la}' if pair else '', de=de,
|
|
248
|
+
de_label=f'TF log$_2$FC ({an.label_b} / {an.label_a})')
|
|
249
|
+
return _closed(fig)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def motif_expression(an: Analysis, cluster: int):
|
|
253
|
+
"""The genes assigned to the regions carrying a cluster, per set, against the set's other genes; None without [expression]."""
|
|
254
|
+
return an.plot_motif_targets('cluster', [int(cluster)], None)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def effect_scatter(an: Analysis, name: str, *color_by):
|
|
258
|
+
"""A configured pair of [report] effect_pairs, from the table the report step wrote or computed here."""
|
|
259
|
+
from ..effects import stored_pair, scatter_args
|
|
260
|
+
table, x, y, sets, value = stored_pair(an, name)
|
|
261
|
+
return _closed(P.plot_effect_scatter(*scatter_args(an, table, x, y, color_by, sets, value)))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
MAX_NAMED = 15 # the pairs named on each side of the differential volcano, most significant first
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _tf_name(label: str) -> str:
|
|
268
|
+
"""A motif label as one TF name: the first of 'ETV7/ETS1 +3'; cluster labels such as 'cl87 ETV7' stay whole."""
|
|
269
|
+
import re
|
|
270
|
+
return re.sub(r' \+\d+$', '', str(label).split('/')[0])
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _motif_colors(keys: list, avoid: tuple) -> dict:
|
|
274
|
+
"""One colour per motif key, in order, from tab10, tab20b, tab20c and tab20 without greys, pale colours and colours
|
|
275
|
+
close to those in `avoid` (the two classes')."""
|
|
276
|
+
import matplotlib.pyplot as plt
|
|
277
|
+
from matplotlib.colors import to_hex, to_rgb
|
|
278
|
+
reserved = [to_rgb(c) for c in avoid]
|
|
279
|
+
|
|
280
|
+
def usable(c):
|
|
281
|
+
r = to_rgb(c)
|
|
282
|
+
return (max(r) - min(r) >= 0.10 and sum(r) / 3 <= 0.80
|
|
283
|
+
and all(sum((a - b) ** 2 for a, b in zip(r, q)) > 0.06 for q in reserved))
|
|
284
|
+
pool = [to_hex(c) for cm in ('tab10', 'tab20b', 'tab20c', 'tab20') for c in plt.get_cmap(cm).colors]
|
|
285
|
+
palette = [c for c in dict.fromkeys(pool) if usable(c)]
|
|
286
|
+
return {k: palette[i % len(palette)] for i, k in enumerate(keys)}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _slots(targets, top: float = 0.90, bottom: float = 0.03, step: float = 0.05) -> list:
|
|
290
|
+
"""
|
|
291
|
+
Heights (axes fraction) for names next to markers at `targets`, highest first: each at its marker's height where
|
|
292
|
+
it can be, else just far enough below the one above (or above the one below, near the bottom) not to overlap.
|
|
293
|
+
"""
|
|
294
|
+
y = [min(t, top) for t in targets]
|
|
295
|
+
for i in range(1, len(y)):
|
|
296
|
+
y[i] = min(y[i], y[i - 1] - step)
|
|
297
|
+
if y and y[-1] < bottom:
|
|
298
|
+
y[-1] = bottom
|
|
299
|
+
for i in range(len(y) - 2, -1, -1):
|
|
300
|
+
y[i] = max(y[i], y[i + 1] + step)
|
|
301
|
+
return y
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def differential_volcano(an: Analysis, level: str = 'subfamily', colors: tuple = ('#1f77b4', '#d62728'),
|
|
305
|
+
source: str = 'seqlets'):
|
|
306
|
+
"""
|
|
307
|
+
pair_differential as a volcano: each compared pair at the difference of its odds ratios between the classes (x)
|
|
308
|
+
and -log10 p (y), drawn by split_volcano. colors: the two classes' (A, B); source: where the motifs come from
|
|
309
|
+
(view.data.motif_sites). None for a run without two classes.
|
|
310
|
+
"""
|
|
311
|
+
d = V.pair_differential(an, level, source)
|
|
312
|
+
if d.empty:
|
|
313
|
+
return None
|
|
314
|
+
A, B = d.attrs['sets']
|
|
315
|
+
labels = getattr(an, 'set_labels', None) or {}
|
|
316
|
+
la, lb = labels.get(A, A), labels.get(B, B)
|
|
317
|
+
t = d[d['tested']]
|
|
318
|
+
n_hit = int((t['q'] <= d.attrs['alpha']).sum())
|
|
319
|
+
return split_volcano(t, d.attrs['alpha'], (la, lb), colors, xlabel=f'log$_2$ odds ratio, {lb} minus {la}',
|
|
320
|
+
title=f'Differential motif pairing, Woolf homogeneity test\n{n_hit} of {len(t)} compared pairs '
|
|
321
|
+
f'at FDR < {d.attrs["alpha"]:g}' + (', motifs by scanning' if source == 'scan' else ''))
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def pair_regression_volcano(an: Analysis, colors: tuple = ('#1f77b4', '#d62728'), source: str = 'scan'):
|
|
325
|
+
"""
|
|
326
|
+
The pair-regression step's pairs from one source (view.data.pair_regression) as a volcano: each pair at its term on
|
|
327
|
+
the measured log2 fold change (x) and -log10 p (y), drawn by split_volcano. colors: the contrast's (A, B). None
|
|
328
|
+
without that source.
|
|
329
|
+
"""
|
|
330
|
+
d = V.pair_regression(an, source)
|
|
331
|
+
if d.empty:
|
|
332
|
+
return None
|
|
333
|
+
alpha = float(d.attrs.get('alpha', 0.05))
|
|
334
|
+
n_hit = int((d['q'] <= alpha).sum())
|
|
335
|
+
where = 'motifs by scanning' if source == 'scan' else 'seqlets of the attributed regions'
|
|
336
|
+
return split_volcano(d.rename(columns={'pair': 'diff'}), alpha, (an.label_a, an.label_b), colors,
|
|
337
|
+
xlabel=f'Pair term, log$_2$ fold change {an.label_b} / {an.label_a}',
|
|
338
|
+
title=f'Motif pairs against the measured differential, {where}, {d.attrs.get("regions", 0):,} '
|
|
339
|
+
f'regions\n{n_hit} of {len(d)} pairs at FDR < {alpha:g}')
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def split_volcano(t: pd.DataFrame, alpha: float, names_ab: tuple, colors: tuple, xlabel: str, title: str):
|
|
343
|
+
"""
|
|
344
|
+
Pairs (a, b, a_label, b_label, diff, p, q) at diff (x) and -log10 p (y). A pair at q <= alpha is a marker split
|
|
345
|
+
between its two motifs, each half in its motif's colour, and is named on its side in the same colours (the MAX_NAMED
|
|
346
|
+
most significant per side); the rest are grey. names_ab, colors: the sides' names and colours, negative first.
|
|
347
|
+
"""
|
|
348
|
+
import matplotlib.pyplot as plt
|
|
349
|
+
from collections import Counter
|
|
350
|
+
from matplotlib.markers import MarkerStyle
|
|
351
|
+
from matplotlib.offsetbox import AnnotationBbox, HPacker, TextArea
|
|
352
|
+
la, lb = names_ab
|
|
353
|
+
t = t.assign(nlp=lambda x: -np.log10(np.clip(x['p'].to_numpy(float), 1e-300, 1.0)))
|
|
354
|
+
hit = t['q'] <= alpha
|
|
355
|
+
hits = t[hit]
|
|
356
|
+
full = {**dict(zip(t['a'], t['a_label'])), **dict(zip(t['b'], t['b_label']))}
|
|
357
|
+
names = {k: _tf_name(v) for k, v in full.items()}
|
|
358
|
+
dup = pd.Series(names, dtype=object).duplicated(keep=False)
|
|
359
|
+
names = {k: (full[k] if dup[k] else v) for k, v in names.items()} # two motifs, one TF name: the labels
|
|
360
|
+
freq = Counter(list(hits['a']) + list(hits['b']))
|
|
361
|
+
col = _motif_colors([k for k, _ in sorted(freq.items(), key=lambda kv: (-kv[1], names[kv[0]]))], colors)
|
|
362
|
+
with plt.rc_context(P.RC):
|
|
363
|
+
fig, ax = plt.subplots(figsize=(8.4, 5.4), constrained_layout=True)
|
|
364
|
+
ax.axvline(0, lw=0.5, color='0.92', zorder=0)
|
|
365
|
+
ax.scatter(t.loc[~hit, 'diff'], t.loc[~hit, 'nlp'], s=9, c='#c9c9c9', alpha=0.7, linewidths=0, rasterized=True,
|
|
366
|
+
zorder=2)
|
|
367
|
+
for _, r in hits.iterrows():
|
|
368
|
+
for side, k in (('left', r['a']), ('right', r['b'])):
|
|
369
|
+
ax.plot(r['diff'], r['nlp'], ls='none', marker=MarkerStyle('o', fillstyle=side), ms=10, mfc=col[k],
|
|
370
|
+
mec='white', mew=0.8, zorder=4)
|
|
371
|
+
span = float(t['diff'].abs().max()) if len(t) else 1.0
|
|
372
|
+
lim = 1.1 * span * (1.8 if len(hits) else 1.0) # the outer part of each side for the names
|
|
373
|
+
top = max(2.0, 1.12 * float(t['nlp'].max())) if len(t) else 2.0
|
|
374
|
+
ax.set_xlim(-lim, lim)
|
|
375
|
+
ax.set_ylim(-0.04 * top, top)
|
|
376
|
+
|
|
377
|
+
def ladder(rows, x, align):
|
|
378
|
+
rows = rows.nlargest(MAX_NAMED, 'nlp')
|
|
379
|
+
at = _slots([ax.transLimits.transform((u, v))[1] for u, v in zip(rows['diff'], rows['nlp'])])
|
|
380
|
+
for y, (_, r) in zip(at, rows.iterrows()):
|
|
381
|
+
box = HPacker(pad=0, sep=0, align='center', children=[
|
|
382
|
+
TextArea(names[r['a']], textprops=dict(color=col[r['a']], size=7.2)),
|
|
383
|
+
TextArea(' \u00d7 ', textprops=dict(color='0.45', size=7.2)),
|
|
384
|
+
TextArea(names[r['b']], textprops=dict(color=col[r['b']], size=7.2))])
|
|
385
|
+
ax.add_artist(AnnotationBbox(box, (r['diff'], r['nlp']), xybox=(x, y), xycoords='data',
|
|
386
|
+
boxcoords='axes fraction', box_alignment=(align, 0.5), frameon=False, pad=0,
|
|
387
|
+
arrowprops=dict(arrowstyle='-', lw=0.5, color='0.55', shrinkA=2, shrinkB=5)))
|
|
388
|
+
ladder(hits[hits['diff'] < 0], 0.012, 0.0)
|
|
389
|
+
ladder(hits[hits['diff'] > 0], 0.988, 1.0)
|
|
390
|
+
ax.set_xlabel(xlabel)
|
|
391
|
+
ax.set_ylabel('\u2212log$_{10}$ $p$')
|
|
392
|
+
ax.set_title(title, linespacing=1.35)
|
|
393
|
+
ax.text(0.012, 0.985, f'higher in {la}', transform=ax.transAxes, ha='left', va='top', fontsize=8.5, color=colors[0])
|
|
394
|
+
ax.text(0.988, 0.985, f'higher in {lb}', transform=ax.transAxes, ha='right', va='top', fontsize=8.5, color=colors[1])
|
|
395
|
+
if len(hits):
|
|
396
|
+
note = 'Each marker is split between its two motifs; the label carries the same colours'
|
|
397
|
+
if max((hits['diff'] < 0).sum(), (hits['diff'] > 0).sum()) > MAX_NAMED:
|
|
398
|
+
note += f'; the {MAX_NAMED} most significant are named on each side'
|
|
399
|
+
ax.text(0.5, -0.135, note, transform=ax.transAxes, ha='center', va='top', fontsize=8, color='0.35')
|
|
400
|
+
return _closed(fig)
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<script src="https://unpkg.com/vis-network@9.1.9/standalone/umd/vis-network.min.js"></script>
|
|
6
|
+
<style>
|
|
7
|
+
html, body { margin: 0; padding: 0; font-family: sans-serif; background: transparent; }
|
|
8
|
+
#net { width: 100%; height: 600px; border: 1px solid #dddddd; border-radius: 6px; box-sizing: border-box; }
|
|
9
|
+
#hint { position: absolute; left: 10px; top: 8px; font-size: 11px; color: #666666; background: rgba(255,255,255,.85);
|
|
10
|
+
padding: 2px 6px; border-radius: 4px; pointer-events: none; }
|
|
11
|
+
#err { color: #b00020; font-size: 12px; padding: 6px; white-space: pre-wrap; }
|
|
12
|
+
</style>
|
|
13
|
+
</head>
|
|
14
|
+
<body>
|
|
15
|
+
<div id="net"></div>
|
|
16
|
+
<div id="hint">click: unfold / fold · ctrl-click: select several · drag, wheel to zoom, hover for numbers</div>
|
|
17
|
+
<div id="err"></div>
|
|
18
|
+
<script>
|
|
19
|
+
(function () {
|
|
20
|
+
var STEP = 15;
|
|
21
|
+
var S = { seq: 0, version: null, graph: null, net: null, nodes: null, edges: null, byId: {}, edgeById: {},
|
|
22
|
+
expanded: {}, reasons: {}, batch: {}, lit: [] };
|
|
23
|
+
var errBox = document.getElementById('err');
|
|
24
|
+
|
|
25
|
+
function send(type, data) {
|
|
26
|
+
var m = { isStreamlitMessage: true, type: type };
|
|
27
|
+
for (var k in data) { m[k] = data[k]; }
|
|
28
|
+
window.parent.postMessage(m, '*');
|
|
29
|
+
}
|
|
30
|
+
function setValue(v) { S.seq += 1; v.seq = S.seq; send('streamlit:setComponentValue', { value: v, dataType: 'json' }); }
|
|
31
|
+
function setHeight(h) { send('streamlit:setFrameHeight', { height: h }); }
|
|
32
|
+
window.onerror = function (msg, src, line) { errBox.textContent = 'network: ' + msg + ' (line ' + line + ')'; return false; };
|
|
33
|
+
|
|
34
|
+
function mix(hex, t) { // towards white by t
|
|
35
|
+
var c = hex.replace('#', '');
|
|
36
|
+
if (c.length !== 6) { return hex; }
|
|
37
|
+
var r = parseInt(c.substr(0, 2), 16), g = parseInt(c.substr(2, 2), 16), b = parseInt(c.substr(4, 2), 16);
|
|
38
|
+
var f = function (x) { return Math.round(x + (255 - x) * t).toString(16).padStart(2, '0'); };
|
|
39
|
+
return '#' + f(r) + f(g) + f(b);
|
|
40
|
+
}
|
|
41
|
+
function dark(hex) { return mix(hex, -0.25); }
|
|
42
|
+
|
|
43
|
+
function visNode(n, near) {
|
|
44
|
+
var v = { id: n.id, title: n.title || '' };
|
|
45
|
+
if (n.kind === 'class') {
|
|
46
|
+
v.shape = 'circle'; v.label = n.label; v.widthConstraint = { minimum: 96 };
|
|
47
|
+
v.color = { background: n.color, border: n.color, highlight: { background: n.color, border: '#222222' } };
|
|
48
|
+
v.font = { color: 'white', size: 15, face: 'sans-serif' };
|
|
49
|
+
v.fixed = true; v.x = S.graph.sets.indexOf(n.set) === 0 ? -380 : 380; v.y = 0;
|
|
50
|
+
} else if (n.kind === 'motif') {
|
|
51
|
+
v.shape = 'dot'; v.size = n.size; v.label = n.label;
|
|
52
|
+
v.color = { background: n.color, border: dark(n.color), highlight: { background: n.color, border: '#222222' } };
|
|
53
|
+
v.font = { size: 13, color: '#222222', strokeWidth: 3, strokeColor: '#ffffff' };
|
|
54
|
+
} else if (n.kind === 'region') {
|
|
55
|
+
v.shape = 'dot'; v.size = 6;
|
|
56
|
+
v.color = { background: mix(n.color, 0.45), border: n.color, highlight: { background: n.color, border: '#222222' } };
|
|
57
|
+
} else { // 'more'
|
|
58
|
+
v.shape = 'box'; v.label = n.label; v.font = { size: 11, color: '#444444' };
|
|
59
|
+
v.color = { background: '#f0f0f0', border: '#bbbbbb', highlight: { background: '#e0e0e0', border: '#888888' } };
|
|
60
|
+
}
|
|
61
|
+
if (near && S.net) {
|
|
62
|
+
var p = S.net.getPositions([near])[near];
|
|
63
|
+
if (p) { v.x = p.x + (Math.random() - 0.5) * 80; v.y = p.y + (Math.random() - 0.5) * 80; }
|
|
64
|
+
}
|
|
65
|
+
return v;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function visEdge(e) {
|
|
69
|
+
var v = { id: e.id, from: e.from, to: e.to, title: e.title || '' };
|
|
70
|
+
if (e.kind === 'usage') {
|
|
71
|
+
v.width = e.width; v.color = { color: e.color, opacity: 0.35, highlight: e.color }; v.smooth = false;
|
|
72
|
+
} else if (e.kind === 'co') {
|
|
73
|
+
v.width = e.width; v.color = { color: e.color, opacity: 0.9, highlight: '#222222' }; v.dashes = !!e.dashes;
|
|
74
|
+
v.smooth = { type: S.graph.sets.indexOf(e.set) === 0 ? 'curvedCW' : 'curvedCCW', roundness: 0.18 };
|
|
75
|
+
} else {
|
|
76
|
+
v.width = 0.6; v.color = { color: '#c8c8c8', opacity: 0.9, highlight: '#222222' }; v.smooth = false;
|
|
77
|
+
if (e.dashes) { v.dashes = true; }
|
|
78
|
+
}
|
|
79
|
+
return v;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function shown(id) { return S.nodes.get(id) !== null; }
|
|
83
|
+
function addReason(id, why) { if (!S.reasons[id]) { S.reasons[id] = {}; } S.reasons[id][why] = true; }
|
|
84
|
+
function showNode(id, why, near) {
|
|
85
|
+
var n = S.byId[id];
|
|
86
|
+
if (!n) { return; }
|
|
87
|
+
if (why) { addReason(id, why); }
|
|
88
|
+
if (!shown(id)) { S.nodes.add(visNode(n, near)); }
|
|
89
|
+
}
|
|
90
|
+
function addEdge(e) { if (S.edges.get(e.id) === null && shown(e.from) && shown(e.to)) { S.edges.add(visEdge(e)); } }
|
|
91
|
+
function connect() { var es = S.graph.edges; for (var i = 0; i < es.length; i++) { addEdge(es[i]); } }
|
|
92
|
+
function removeNode(id) {
|
|
93
|
+
if (!shown(id)) { return; }
|
|
94
|
+
S.edges.remove(S.net.getConnectedEdges(id));
|
|
95
|
+
S.nodes.remove(id);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function unfoldRegions(batchKey, why, list, attached, step) {
|
|
99
|
+
var done = S.batch[batchKey] || 0;
|
|
100
|
+
var next = list.slice(done, done + step);
|
|
101
|
+
for (var i = 0; i < next.length; i++) {
|
|
102
|
+
var rid = 'r:' + next[i];
|
|
103
|
+
showNode(rid, why, attached[0]);
|
|
104
|
+
for (var j = 0; j < attached.length; j++) {
|
|
105
|
+
addEdge({ id: 'h:' + attached[j] + '|' + rid, from: attached[j], to: rid, kind: 'has' });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
S.batch[batchKey] = done + next.length;
|
|
109
|
+
var moreId = 'more:' + batchKey, left = list.length - S.batch[batchKey];
|
|
110
|
+
if (left > 0) {
|
|
111
|
+
var lbl = '+' + Math.min(step, left) + ' more';
|
|
112
|
+
if (!shown(moreId)) {
|
|
113
|
+
S.byId[moreId] = { id: moreId, kind: 'more', label: lbl, title: left + ' more regions', batchKey: batchKey, why: why,
|
|
114
|
+
list: list, attached: attached, step: step };
|
|
115
|
+
addReason(moreId, why);
|
|
116
|
+
S.nodes.add(visNode(S.byId[moreId], attached[0]));
|
|
117
|
+
addEdge({ id: 'h:' + attached[0] + '|' + moreId, from: attached[0], to: moreId, kind: 'has', dashes: true });
|
|
118
|
+
} else {
|
|
119
|
+
S.nodes.update({ id: moreId, label: lbl, title: left + ' more regions' });
|
|
120
|
+
}
|
|
121
|
+
} else if (shown(moreId)) {
|
|
122
|
+
removeNode(moreId);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function collapse(id) {
|
|
127
|
+
delete S.expanded[id];
|
|
128
|
+
var ids = S.nodes.getIds();
|
|
129
|
+
for (var i = 0; i < ids.length; i++) {
|
|
130
|
+
var nid = ids[i], rs = S.reasons[nid];
|
|
131
|
+
if (!rs || !rs[id]) { continue; }
|
|
132
|
+
delete rs[id];
|
|
133
|
+
if (Object.keys(rs).length === 0 && !S.expanded[nid]) {
|
|
134
|
+
removeNode(nid);
|
|
135
|
+
var n = S.byId[nid];
|
|
136
|
+
if (n && n.kind === 'more') { delete S.batch[n.batchKey]; }
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
var keys = Object.keys(S.batch);
|
|
140
|
+
for (var k = 0; k < keys.length; k++) { if (keys[k] === id || keys[k].indexOf(id + '|') === 0) { delete S.batch[keys[k]]; } }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function expandNode(id) {
|
|
144
|
+
var n = S.byId[id];
|
|
145
|
+
if (!n) { return; }
|
|
146
|
+
if (S.expanded[id]) { collapse(id); return; }
|
|
147
|
+
S.expanded[id] = true;
|
|
148
|
+
var es = S.graph.edges, i;
|
|
149
|
+
if (n.kind === 'class') {
|
|
150
|
+
for (i = 0; i < es.length; i++) { if (es[i].kind === 'usage' && es[i].from === id) { showNode(es[i].to, id, id); } }
|
|
151
|
+
} else if (n.kind === 'motif') {
|
|
152
|
+
for (i = 0; i < es.length; i++) {
|
|
153
|
+
if (es[i].kind === 'co' && (es[i].from === id || es[i].to === id)) { showNode(es[i].from === id ? es[i].to : es[i].from, id, id); }
|
|
154
|
+
}
|
|
155
|
+
var sets = S.graph.sets;
|
|
156
|
+
for (i = 0; i < sets.length; i++) { unfoldRegions(id + '|' + sets[i], id, (n.regions && n.regions[sets[i]]) || [], [id], STEP); }
|
|
157
|
+
} else if (n.kind === 'more') {
|
|
158
|
+
delete S.expanded[id];
|
|
159
|
+
unfoldRegions(n.batchKey, n.why, n.list, n.attached, n.step);
|
|
160
|
+
}
|
|
161
|
+
connect();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function expandEdge(eid) {
|
|
165
|
+
var e = S.edgeById[eid];
|
|
166
|
+
if (!e || e.kind !== 'co') { return; }
|
|
167
|
+
if (S.expanded[eid]) { collapse(eid); return; }
|
|
168
|
+
S.expanded[eid] = true;
|
|
169
|
+
unfoldRegions(eid, eid, e.regions || [], [e.from, e.to], STEP);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function viaOf(id) { var rs = S.reasons[id] || {}; var ks = Object.keys(rs).filter(function (k) { return k !== 'start'; }); return ks.length ? ks[0] : null; }
|
|
173
|
+
|
|
174
|
+
function onClick(p) {
|
|
175
|
+
var ev = p.event && p.event.srcEvent, multi = !!(ev && (ev.ctrlKey || ev.metaKey || ev.shiftKey)), last = null;
|
|
176
|
+
if (p.nodes.length) {
|
|
177
|
+
var id = p.nodes[0], n = S.byId[id];
|
|
178
|
+
last = { type: 'node', id: id, kind: n ? n.kind : '', via: viaOf(id) };
|
|
179
|
+
if (!multi && n && n.kind !== 'region') { expandNode(id); }
|
|
180
|
+
} else if (p.edges.length) {
|
|
181
|
+
var eid = p.edges[0], e = S.edgeById[eid];
|
|
182
|
+
last = { type: 'edge', id: eid, kind: e ? e.kind : '' };
|
|
183
|
+
if (!multi && e && e.kind === 'co') { expandEdge(eid); }
|
|
184
|
+
}
|
|
185
|
+
setValue({ nodes: S.net.getSelectedNodes(), edges: S.net.getSelectedEdges(), last: last });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function applyHighlight(ids) {
|
|
189
|
+
var i, updates = [];
|
|
190
|
+
for (i = 0; i < S.lit.length; i++) { if (shown(S.lit[i])) { updates.push({ id: S.lit[i], borderWidth: 1, shadow: false }); } }
|
|
191
|
+
for (i = 0; i < ids.length; i++) { if (shown(ids[i])) { updates.push({ id: ids[i], borderWidth: 4, shadow: { enabled: true, size: 12, color: 'rgba(0,0,0,0.35)' } }); } }
|
|
192
|
+
if (updates.length) { S.nodes.update(updates); }
|
|
193
|
+
S.lit = ids.slice();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function build(graph) {
|
|
197
|
+
S.graph = graph; S.byId = {}; S.edgeById = {}; S.expanded = {}; S.reasons = {}; S.batch = {}; S.lit = [];
|
|
198
|
+
var i;
|
|
199
|
+
for (i = 0; i < graph.nodes.length; i++) { S.byId[graph.nodes[i].id] = graph.nodes[i]; }
|
|
200
|
+
for (i = 0; i < graph.edges.length; i++) { S.edgeById[graph.edges[i].id] = graph.edges[i]; }
|
|
201
|
+
S.nodes = new vis.DataSet([]); S.edges = new vis.DataSet([]);
|
|
202
|
+
var options = {
|
|
203
|
+
interaction: { hover: true, multiselect: true, tooltipDelay: 120 },
|
|
204
|
+
physics: { solver: 'forceAtlas2Based',
|
|
205
|
+
forceAtlas2Based: { gravitationalConstant: -45, centralGravity: 0.008, springLength: 120, springConstant: 0.07,
|
|
206
|
+
damping: 0.6, avoidOverlap: 0.4 },
|
|
207
|
+
stabilization: { iterations: 150, fit: true }, minVelocity: 0.6 },
|
|
208
|
+
nodes: { borderWidth: 1 }, edges: { selectionWidth: 2, hoverWidth: 1.5 }, layout: { improvedLayout: false }
|
|
209
|
+
};
|
|
210
|
+
if (S.net) { S.net.setData({ nodes: S.nodes, edges: S.edges }); }
|
|
211
|
+
else { S.net = new vis.Network(document.getElementById('net'), { nodes: S.nodes, edges: S.edges }, options); S.net.on('click', onClick); }
|
|
212
|
+
for (i = 0; i < graph.start.length; i++) { showNode(graph.start[i], 'start', null); }
|
|
213
|
+
connect();
|
|
214
|
+
S.net.fit();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function onRender(args) {
|
|
218
|
+
var h = args.height || 600;
|
|
219
|
+
document.getElementById('net').style.height = h + 'px';
|
|
220
|
+
setHeight(h + 4);
|
|
221
|
+
if (typeof vis === 'undefined') { errBox.textContent = 'The network needs the vis-network script from unpkg.com, which did not load. Is the browser online?'; return; }
|
|
222
|
+
if (args.version !== S.version && args.graph) { S.version = args.version; build(args.graph); }
|
|
223
|
+
applyHighlight(args.highlight || []);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
window.addEventListener('message', function (ev) { var d = ev.data; if (d && d.type === 'streamlit:render') { onRender(d.args || {}); } });
|
|
227
|
+
send('streamlit:componentReady', { apiVersion: 1 });
|
|
228
|
+
setHeight(604);
|
|
229
|
+
})();
|
|
230
|
+
</script>
|
|
231
|
+
</body>
|
|
232
|
+
</html>
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The explorer's network: a Streamlit component around vis-network (network/index.html) that draws the graph of
|
|
3
|
+
diffgrammar.view.data.network_graph and unfolds it on click. The browser holds the whole graph and does the
|
|
4
|
+
unfolding, dragging and zooming itself; only clicks come back to Python, as the component's value:
|
|
5
|
+
|
|
6
|
+
{'nodes': [selected node ids], 'edges': [selected edge ids], 'last': {'type', 'id', 'kind', 'via'}, 'seq': n}
|
|
7
|
+
|
|
8
|
+
Node ids are 'c:<set>', 'm:<key>' and 'r:<coord>'; co-occurrence edge ids 'p:<set>|<a>|<b>'. `seq` counts the
|
|
9
|
+
clicks, so a rerun can tell a new click from the last one. The vis-network script is loaded from unpkg.com.
|
|
10
|
+
"""
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Optional, Sequence
|
|
13
|
+
|
|
14
|
+
import streamlit.components.v1 as components
|
|
15
|
+
|
|
16
|
+
_component = components.declare_component('diffgrammar_network', path=str(Path(__file__).parent / 'network'))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def network(graph: dict, version: str, height: int = 600, highlight: Sequence[str] = (), key: str = 'network') -> Optional[dict]:
|
|
20
|
+
"""Draw `graph`; the browser rebuilds it only when `version` changes. highlight: node ids drawn with a thick border."""
|
|
21
|
+
return _component(graph=graph, version=version, height=int(height), highlight=list(highlight), key=key, default=None)
|