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,257 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The viewer's first page, which motifs mark each class and how the run chose its regions and seqlets, and its Effects page,
|
|
3
|
+
one motif against another. Every number comes from diffgrammar.selection, diffgrammar.effects and the report's tables; these
|
|
4
|
+
functions only lay them out. Both work on any run: a panel whose data the run does not have says so.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import altair as alt
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import streamlit as st
|
|
12
|
+
|
|
13
|
+
from .. import effects as E
|
|
14
|
+
from .. import expression as X
|
|
15
|
+
from .. import plotting as P
|
|
16
|
+
from . import data as V
|
|
17
|
+
from . import figures as F
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _picture(rendered, name: str, config: str, *args, width='stretch', dpi: int = 130) -> bool:
|
|
21
|
+
got = rendered(name, config, *args, dpi=dpi)
|
|
22
|
+
if got is None:
|
|
23
|
+
return False
|
|
24
|
+
st.image(got[0], width=width)
|
|
25
|
+
return True
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# -- summary ----------------------------------------------------------------------------------------------------------
|
|
29
|
+
REPORT_DPI = 300 # the Summary's report figures: sharp when the browser shrinks them into a column or zooms in
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def summary_page(an, config: str, rendered):
|
|
33
|
+
meta, thr = V.seqlet_meta(an), an.thresholds
|
|
34
|
+
thr = thr[thr['contrast'] == an.contrast.name]
|
|
35
|
+
rows = ['| | Regions | With a seqlet | Seqlets |', '|---|---:|---:|---:|']
|
|
36
|
+
for s in an.sets:
|
|
37
|
+
n = thr.loc[thr['set_name'] == s, 'coord'].nunique()
|
|
38
|
+
m = meta[meta['set_name'] == s]
|
|
39
|
+
w = m['coord'].nunique()
|
|
40
|
+
rows.append(f"| {an.set_labels.get(s, s)} | {n:,} | {w:,} ({100 * w / max(n, 1):.0f}%) | {len(m):,} |")
|
|
41
|
+
st.markdown('\n'.join(rows))
|
|
42
|
+
fams = f" in {meta['subfamily'].nunique()} motif families" if 'subfamily' in meta else ''
|
|
43
|
+
st.caption(f"{meta['cluster'].nunique()} motif clusters{fams}.")
|
|
44
|
+
|
|
45
|
+
st.markdown('#### Which motifs mark each class')
|
|
46
|
+
r = an.cfg['report']
|
|
47
|
+
level = r['level']
|
|
48
|
+
with st.spinner('Drawing the cluster figure and the bubble plot…', show_time=True):
|
|
49
|
+
got = {name: rendered(name, config, dpi=REPORT_DPI, tight=True) for name in ('cluster_report', 'motif_bubbles')}
|
|
50
|
+
got = {name: g for name, g in got.items() if g is not None}
|
|
51
|
+
if 'cluster_report' not in got:
|
|
52
|
+
st.caption("The cluster figure needs each condition's contribution at the seqlets: rerun `seqlets`.")
|
|
53
|
+
neg, pos = an.directions
|
|
54
|
+
if not got:
|
|
55
|
+
st.info('Needs the `families` step.')
|
|
56
|
+
else:
|
|
57
|
+
la, lb = an.label_a, an.label_b
|
|
58
|
+
pair = V.differential_sets(an)
|
|
59
|
+
text = {
|
|
60
|
+
'cluster_report': (("**Each cluster's seqlets**" if an.single else "**Each cluster's seqlets in the two sets**"),
|
|
61
|
+
f"The {r['n_clusters']} largest clusters of at least {r['min_cluster_size']} seqlets, " +
|
|
62
|
+
(f"those that raise {lb} on average above the dotted line, similar motifs together. Bars count "
|
|
63
|
+
f"the seqlets that lower and raise it; boxes are their contribution." if an.single else
|
|
64
|
+
f"stronger in {lb} on average above the dotted line and in {la} below it, similar motifs "
|
|
65
|
+
f"together. Bars count the seqlets {neg} and {pos}; boxes are each condition's contribution "
|
|
66
|
+
f"at them.")),
|
|
67
|
+
'motif_bubbles': (f"**Each {level}'s share of regions**",
|
|
68
|
+
f"By {level}, the {r['top_n']} in most regions of each set. Bubbles: the share of the set's "
|
|
69
|
+
"regions carrying it" + (f"; squares: log2 of the share in {an.set_labels.get(pair[1], pair[1])} "
|
|
70
|
+
f"over {an.set_labels.get(pair[0], pair[0])}" if pair else '') +
|
|
71
|
+
(f"; dots left of the bubbles: RNA-seq log2FC {an.label_b} / {an.label_a} of its candidate TFs, named and "
|
|
72
|
+
f"coloured by direction where padj < 0.05" if an.expression_table is not None else '') + '.'),
|
|
73
|
+
}
|
|
74
|
+
# columns as wide as the figures, so both are drawn at one scale
|
|
75
|
+
for col, (name, g) in zip(st.columns([g[1] for g in got.values()]), got.items()):
|
|
76
|
+
with col:
|
|
77
|
+
st.markdown(text[name][0])
|
|
78
|
+
st.image(g[0], width='stretch')
|
|
79
|
+
st.caption(text[name][1])
|
|
80
|
+
with st.expander('How this is computed'):
|
|
81
|
+
st.markdown(f"These are the report's figures (report/cluster_report, report/motif_bubbles). A condition's "
|
|
82
|
+
f"contribution at a seqlet is its own attribution at its strongest position, so the boxes show "
|
|
83
|
+
f"which condition the site acts in, not only which way the difference goes. A region carries a "
|
|
84
|
+
f"{level} when one of its seqlets falls in a cluster of at least {r['min_cluster_size']} seqlets whose "
|
|
85
|
+
f"best JASPAR match is in it; shares are over the {r['denominator']} regions of each set, and the "
|
|
86
|
+
"ratio adds one pseudo-region to each so that a motif missing from one stays finite. A motif's "
|
|
87
|
+
"candidate TFs are the TFs of its JASPAR matrices and the best matches of its largest cluster, as "
|
|
88
|
+
"the report takes them.")
|
|
89
|
+
|
|
90
|
+
with st.expander('How the regions and seqlets were chosen'):
|
|
91
|
+
t = an.region_table
|
|
92
|
+
left, right = st.columns(2)
|
|
93
|
+
with left:
|
|
94
|
+
st.markdown('**Regions kept at each filter**')
|
|
95
|
+
if _picture(rendered, 'selection_funnel', config):
|
|
96
|
+
st.caption('Each region counted at the first filter it fails; kept means it reached seqlet calling.')
|
|
97
|
+
else:
|
|
98
|
+
st.caption('No record of the region selection (no candidates.csv, no regions.parquet).')
|
|
99
|
+
with right:
|
|
100
|
+
st.markdown('**Measured against predicted**' if an.single else '**Predicted signal of the kept regions**')
|
|
101
|
+
if an.single:
|
|
102
|
+
if _picture(rendered, 'selection_scatter', config):
|
|
103
|
+
st.caption(f"Every candidate's measured against its predicted {an.label_b} (predicted alone without "
|
|
104
|
+
f"measured values), the kept regions coloured.")
|
|
105
|
+
elif _picture(rendered, 'predicted_signal', config):
|
|
106
|
+
null = 'shuffled sequences' if (an.out / 'selection_null.parquet').exists() else 'every candidate'
|
|
107
|
+
st.caption(f'Against {null}; each histogram a fraction of its own group.')
|
|
108
|
+
else:
|
|
109
|
+
st.caption('No predicted signal per region.')
|
|
110
|
+
left, right = st.columns(2)
|
|
111
|
+
with left:
|
|
112
|
+
st.markdown('**Seqlet threshold**')
|
|
113
|
+
_picture(rendered, 'seqlet_threshold', config)
|
|
114
|
+
st.caption(f"The cut is {an.pct:g} of each region's budget; a seqlet also needs a run of "
|
|
115
|
+
f"{an.cfg['seqlets']['min_size']} bp.")
|
|
116
|
+
with right:
|
|
117
|
+
if an.single:
|
|
118
|
+
return
|
|
119
|
+
st.markdown('**Measured against predicted**')
|
|
120
|
+
if _picture(rendered, 'measured_predicted', config):
|
|
121
|
+
st.caption('Each region coloured by the filter that removed it; dotted, predicted equals measured.')
|
|
122
|
+
else:
|
|
123
|
+
st.caption('Regions chosen on predictions alone: nothing measured to compare.' if t is not None
|
|
124
|
+
else 'No measured and predicted values per region.')
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _motif_options(an, level: str) -> list:
|
|
128
|
+
"""The names of a level, with most seqlets first under this contrast."""
|
|
129
|
+
meta = V.seqlet_meta(an)
|
|
130
|
+
col = {'Subfamily': 'subfamily', 'Family': 'group', 'Best JASPAR match': 'tf'}.get(level)
|
|
131
|
+
if col is None:
|
|
132
|
+
return [int(c) for c in meta['cluster'].value_counts().index]
|
|
133
|
+
return list(meta[col].dropna().value_counts().index) if col in meta else []
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _pick_motif(an, axis: str, default_rank: int) -> E.Motif:
|
|
137
|
+
st.markdown(f'**{axis}**')
|
|
138
|
+
kind = st.radio('Sites from', ['Seqlets', 'Sequence patterns'], horizontal=True, key=f'eff_kind_{axis}')
|
|
139
|
+
if kind == 'Sequence patterns':
|
|
140
|
+
text = st.text_area('name = pattern (IUPAC; several with |), one per line', 'strong = GTAAACA\nweak = GTAAATA|GTAAGCA', height=90, key=f'eff_pat_{axis}')
|
|
141
|
+
pats = {a.strip(): b.strip() for a, _, b in (ln.partition('=') for ln in text.splitlines()) if b.strip()}
|
|
142
|
+
label = st.text_input('Name on the axis', 'Pattern', key=f'eff_label_{axis}')
|
|
143
|
+
return E.Motif(label, patterns=pats)
|
|
144
|
+
level = st.radio('By', ['Subfamily', 'Family', 'Best JASPAR match', 'Cluster'], horizontal=True, key=f'eff_level_{axis}')
|
|
145
|
+
opts = _motif_options(an, level)
|
|
146
|
+
picked = st.multiselect('Motifs', opts, default=opts[default_rank:default_rank + 1], key=f'eff_motif_{axis}_{level}')
|
|
147
|
+
label = ' / '.join(str(p) for p in picked[:2]) + (' …' if len(picked) > 2 else '') or axis
|
|
148
|
+
if level == 'Cluster':
|
|
149
|
+
return E.Motif(f"cl{label.replace(' / ', ', cl')}", clusters=tuple(picked))
|
|
150
|
+
return E.Motif(label, **{{'Subfamily': 'subfamilies', 'Family': 'families', 'Best JASPAR match': 'tfs'}[level]: tuple(picked)})
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _scatter(table: pd.DataFrame, s: str, title: str, color: str, label: str, lim: float, scale: dict, colors: dict, x_title: str, y_title: str,
|
|
154
|
+
line: str, key: str, on_pick):
|
|
155
|
+
g = table[table['set_name'] == s].copy()
|
|
156
|
+
if colors:
|
|
157
|
+
g[color] = g[color].astype(str)
|
|
158
|
+
enc = alt.Color(f'{color}:N', title=label, scale=alt.Scale(domain=list(colors), range=list(colors.values())), legend=alt.Legend(orient='bottom', columns=2, labelLimit=240))
|
|
159
|
+
else:
|
|
160
|
+
g = g.dropna(subset=[color])
|
|
161
|
+
s_ = alt.Scale(scheme='redblue', reverse=True, domain=[scale['vmin'], scale['vmax']], clamp=True) if scale['diverging'] else \
|
|
162
|
+
alt.Scale(scheme='viridis', domain=[scale['vmin'], scale['vmax']], clamp=True)
|
|
163
|
+
enc = alt.Color(f'{color}:Q', title=label, scale=s_, legend=alt.Legend(orient='bottom', gradientLength=220))
|
|
164
|
+
g = g.reindex(g[color].abs().sort_values().index if scale['diverging'] else g[color].sort_values().index)
|
|
165
|
+
pick = alt.selection_point(fields=['coord'], name='pick')
|
|
166
|
+
tips = [alt.Tooltip('coord:N', title='Region'), alt.Tooltip('x:Q', title=x_title, format='.3f'), alt.Tooltip('y:Q', title=y_title, format='.3f'),
|
|
167
|
+
alt.Tooltip('x_variant:N', title='x variant'), alt.Tooltip('y_variant:N', title='y variant'), alt.Tooltip('x_seq:N', title='x site'),
|
|
168
|
+
alt.Tooltip('y_seq:N', title='y site'), alt.Tooltip('dist:Q', title='Distance (bp)', format='.0f')]
|
|
169
|
+
if 'genes' in g:
|
|
170
|
+
tips.append(alt.Tooltip('genes:N', title='Assigned genes'))
|
|
171
|
+
if color not in ('x_variant', 'y_variant'):
|
|
172
|
+
tips.append(alt.Tooltip(f'{color}:{"N" if colors else "Q"}', title=label, format='' if colors else '.3f'))
|
|
173
|
+
dom = alt.Scale(domain=[-lim, lim], nice=False)
|
|
174
|
+
pts = alt.Chart(g).mark_circle(size=34, opacity=0.75).encode(
|
|
175
|
+
x=alt.X('x:Q', title=x_title, scale=dom), y=alt.Y('y:Q', title=y_title, scale=dom), color=enc, tooltip=tips).add_params(pick)
|
|
176
|
+
guide = pd.DataFrame({'a': [-lim, lim], 'b': [lim, -lim] if line == 'sum' else [-lim, lim]})
|
|
177
|
+
red = alt.Chart(guide).mark_line(color='#B2182B', strokeWidth=1.1).encode(x=alt.X('a:Q', scale=dom), y=alt.Y('b:Q', scale=dom))
|
|
178
|
+
zx = alt.Chart(pd.DataFrame({'v': [0]})).mark_rule(color='#999999', strokeDash=[3, 3], strokeWidth=0.6).encode(x=alt.X('v:Q', scale=dom))
|
|
179
|
+
zy = alt.Chart(pd.DataFrame({'v': [0]})).mark_rule(color='#999999', strokeDash=[3, 3], strokeWidth=0.6).encode(y=alt.Y('v:Q', scale=dom))
|
|
180
|
+
chart = alt.layer(zx, zy, red, pts).properties(title=title, height=430).configure_axis(grid=False)
|
|
181
|
+
st.altair_chart(chart, key=key, on_select=on_pick, selection_mode='pick', width='stretch')
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def effects_page(an, config: str, load, rendered, region_panel):
|
|
185
|
+
st.subheader('One motif against another')
|
|
186
|
+
st.caption('One point per region: the effect of a site of each motif in it. Choose how the sites are found, and what colours them. '
|
|
187
|
+
'Click a point to open its region.')
|
|
188
|
+
pairs = E.configured_pairs(an.cfg)
|
|
189
|
+
names = list(pairs) + ['Choose motifs']
|
|
190
|
+
preset = st.selectbox('Pair', names, key='eff_pair')
|
|
191
|
+
if preset in pairs:
|
|
192
|
+
p = pairs[preset]
|
|
193
|
+
an_p = load(config, p['contrast']) if p.get('contrast') else an
|
|
194
|
+
with st.spinner('Reading the regions'):
|
|
195
|
+
t, x, y, sets0, value = E.stored_pair(an_p, preset)
|
|
196
|
+
missing = t.attrs.get('missing', 0)
|
|
197
|
+
an = an_p
|
|
198
|
+
st.caption(f"{p['y'].get('label', 'y')} against {p['x'].get('label', 'x')} in the contrast {an.contrast.name}, from [report] effect_pairs.")
|
|
199
|
+
else:
|
|
200
|
+
left, right = st.columns(2)
|
|
201
|
+
with right:
|
|
202
|
+
y = _pick_motif(an, 'Y', 0)
|
|
203
|
+
with left:
|
|
204
|
+
x = _pick_motif(an, 'X', 1)
|
|
205
|
+
c1, c2, c3 = st.columns([3, 3, 2])
|
|
206
|
+
all_sets = list(dict.fromkeys(list(an.sets) + list(V.seqlet_meta(an)['set_name'])))
|
|
207
|
+
sets0 = c1.multiselect('Region sets', all_sets, default=[s for s in an.sets if s in all_sets], format_func=lambda s: an.set_labels.get(s, s), key='eff_sets')
|
|
208
|
+
value = c2.radio('Effect', ['diff'] if an.single else ['diff', 'a', 'b'], horizontal=True, key='eff_value',
|
|
209
|
+
format_func={'diff': an.label_b if an.single else f'{an.label_b} − {an.label_a}',
|
|
210
|
+
'a': an.label_a, 'b': an.label_b}.get)
|
|
211
|
+
near = c3.number_input('Sites within (bp, 0 = any distance)', 0, 100000, 0, 10, key='eff_dist')
|
|
212
|
+
if not sets0 or not (x.patterns or x.cluster_ids(an)) or not (y.patterns or y.cluster_ids(an)):
|
|
213
|
+
st.info('Choose a motif for each axis and at least one region set.')
|
|
214
|
+
return
|
|
215
|
+
key = ('effects', repr(x), repr(y), tuple(sets0), value, near)
|
|
216
|
+
with st.spinner('Reading the regions'):
|
|
217
|
+
t = an._get(key, lambda: an.pair_effects(x, y, sets0, near or None, value))
|
|
218
|
+
missing = t.attrs.get('missing', 0)
|
|
219
|
+
if missing:
|
|
220
|
+
st.warning(f'{missing:,} regions could not be read for the sequence patterns, because their attributions are not in this folder.')
|
|
221
|
+
if t.empty:
|
|
222
|
+
st.info('No region of these sets has a site of both motifs.')
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
options = E.color_options(an, t, x, y)
|
|
226
|
+
c1, c2 = st.columns([3, 3])
|
|
227
|
+
color = c1.selectbox('Colour by', list(options), format_func=options.get, key='eff_color')
|
|
228
|
+
panels = [s for s in (sets0 or an.sets) if s in set(t['set_name'])]
|
|
229
|
+
shown = c2.multiselect('Panels', panels, default=panels, format_func=lambda s: an.set_labels.get(s, s), key=f'eff_panels_{preset}')
|
|
230
|
+
numeric = pd.api.types.is_numeric_dtype(t[color]) and color != 'set_name'
|
|
231
|
+
fixed = {'x_variant': x.colors, 'y_variant': y.colors, 'set_name': {s: c for s, c in an.set_colors.items() if str(c).startswith('#')}}.get(color, {})
|
|
232
|
+
colors = {} if numeric else P.category_colors(t[color].dropna().astype(str), fixed)
|
|
233
|
+
scale = P.effect_scale(t[color]) if numeric else {}
|
|
234
|
+
xy = t[['x', 'y']].to_numpy(float)
|
|
235
|
+
lim = float(np.abs(np.nanpercentile(xy, [1, 99], axis=0)).max()) * 1.1 or 1.0
|
|
236
|
+
what = {'diff': an.label_b if an.single else f'{an.label_b} − {an.label_a}', 'a': an.label_a, 'b': an.label_b}[value]
|
|
237
|
+
|
|
238
|
+
def on_pick(key):
|
|
239
|
+
def pick():
|
|
240
|
+
pts = st.session_state[key].get('selection', {}).get('pick', [])
|
|
241
|
+
if pts:
|
|
242
|
+
st.session_state['eff_coord'] = pts[0]['coord']
|
|
243
|
+
return pick
|
|
244
|
+
for col, s in zip(st.columns(max(len(shown), 1)), shown):
|
|
245
|
+
with col:
|
|
246
|
+
key = f'eff_chart_{preset}_{s}_{color}'
|
|
247
|
+
_scatter(t, s, f"{an.set_labels.get(s, s)} (n = {(t['set_name'] == s).sum():,})", color, options[color], lim, scale, colors,
|
|
248
|
+
f'{x.label} effect ({what})', f'{y.label} effect ({what})', 'sum' if value == 'diff' else 'equal', key, on_pick(key))
|
|
249
|
+
st.caption(('Red line: the two effects cancel (x + y = 0). ' if value == 'diff' else 'Red line: the two effects are equal. ') +
|
|
250
|
+
"Each region takes the strongest site of each motif" + ('.' if preset in pairs and not pairs[preset].get('max_dist') else ', or the strongest pair in the distance chosen.'))
|
|
251
|
+
with st.expander('The table'):
|
|
252
|
+
st.dataframe(t, hide_index=True, height=300)
|
|
253
|
+
st.download_button('Download as CSV', t.to_csv(index=False), file_name=f'effects_{preset}.csv', mime='text/csv', key='eff_csv')
|
|
254
|
+
coord = st.session_state.get('eff_coord')
|
|
255
|
+
if coord is not None and coord in set(t['coord']):
|
|
256
|
+
st.divider()
|
|
257
|
+
region_panel(coord)
|