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.
Files changed (47) hide show
  1. diffgrammar/__init__.py +6 -0
  2. diffgrammar/adapters/__init__.py +21 -0
  3. diffgrammar/adapters/peak_npz.py +114 -0
  4. diffgrammar/align.py +195 -0
  5. diffgrammar/analysis.py +744 -0
  6. diffgrammar/attribute.py +445 -0
  7. diffgrammar/calibrate.py +279 -0
  8. diffgrammar/cli.py +659 -0
  9. diffgrammar/cluster.py +439 -0
  10. diffgrammar/config.py +213 -0
  11. diffgrammar/contrast.py +223 -0
  12. diffgrammar/effects.py +317 -0
  13. diffgrammar/export.py +185 -0
  14. diffgrammar/expression.py +399 -0
  15. diffgrammar/jaspar.py +185 -0
  16. diffgrammar/marginalize/__init__.py +4 -0
  17. diffgrammar/marginalize/backgrounds.py +107 -0
  18. diffgrammar/marginalize/cooperativity.py +344 -0
  19. diffgrammar/marginalize/design.py +209 -0
  20. diffgrammar/marginalize/plots.py +546 -0
  21. diffgrammar/marginalize/predictor.py +109 -0
  22. diffgrammar/marginalize/readout.py +86 -0
  23. diffgrammar/marginalize/run.py +223 -0
  24. diffgrammar/marginalize/store.py +191 -0
  25. diffgrammar/pair_regression.py +323 -0
  26. diffgrammar/plotting.py +1186 -0
  27. diffgrammar/scan.py +151 -0
  28. diffgrammar/selection.py +174 -0
  29. diffgrammar/seqlets.py +376 -0
  30. diffgrammar/sequence.py +22 -0
  31. diffgrammar/summaries.py +140 -0
  32. diffgrammar/toy.py +129 -0
  33. diffgrammar/view/__init__.py +0 -0
  34. diffgrammar/view/app.py +1942 -0
  35. diffgrammar/view/data.py +1950 -0
  36. diffgrammar/view/figures.py +400 -0
  37. diffgrammar/view/network/index.html +232 -0
  38. diffgrammar/view/network.py +21 -0
  39. diffgrammar/view/pages.py +257 -0
  40. diffgrammar/view/tracks/index.html +459 -0
  41. diffgrammar/view/tracks.py +153 -0
  42. diffgrammar-0.1.0.dist-info/METADATA +204 -0
  43. diffgrammar-0.1.0.dist-info/RECORD +47 -0
  44. diffgrammar-0.1.0.dist-info/WHEEL +5 -0
  45. diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
  46. diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
  47. diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1942 @@
1
+ """
2
+ A finished run in the browser: the motif map and table, one motif's logos, report row, regions, positions and
3
+ JASPAR matches, which motif pairs differ between the classes and their regions, any region's tracks and seqlets,
4
+ and the marginalized pairs.
5
+
6
+ diffgrammar view # in the folder of the run's config.toml
7
+
8
+ Every number and figure comes from diffgrammar.view.data / figures (Python, kept for the session); this file
9
+ only lays them out and passes selections between them. The config is also read from DIFFGRAMMAR_CONFIG.
10
+ """
11
+ import base64
12
+ import html
13
+ import io
14
+ import json
15
+ import os
16
+ import struct
17
+ import sys
18
+ import warnings
19
+
20
+ import altair as alt
21
+ import numpy as np
22
+ import matplotlib
23
+ import matplotlib.colors as mcolors
24
+ import pandas as pd
25
+ import streamlit as st
26
+
27
+ matplotlib.use('Agg')
28
+ warnings.filterwarnings('ignore', message='Automatically deduplicated selection parameter') # one row pick, many columns
29
+
30
+ from diffgrammar import Analysis # noqa: E402
31
+ from diffgrammar.marginalize.plots import ABS_LINES, SECOND_C # noqa: E402
32
+ from diffgrammar.view import data as V # noqa: E402
33
+ from diffgrammar.view import figures as F # noqa: E402
34
+ from diffgrammar.view import pages as PG # noqa: E402
35
+ from diffgrammar.view import tracks as T # noqa: E402
36
+ from diffgrammar.plotting import plot_logo_grid as P_logo_grid # noqa: E402
37
+ from diffgrammar.plotting import SINGLE_FAMILY_C, TARGET_COLOR, family_colors # noqa: E402
38
+
39
+ st.set_page_config(page_title='diffgrammar', layout='wide', initial_sidebar_state='collapsed')
40
+
41
+
42
+ @st.cache_resource(show_spinner='Reading the run')
43
+ def load(config: str, contrast: str = None) -> Analysis:
44
+ return Analysis(config, contrast=contrast)
45
+
46
+
47
+ @st.cache_resource(max_entries=64, show_spinner=False)
48
+ def _figure(name: str, config: str, contrast, args: tuple):
49
+ an = load(config, contrast)
50
+ if name.startswith('region_'):
51
+ return getattr(F, name)(an, V.region(an, args[0]), *args[1:])
52
+ return getattr(F, name)(an, *args)
53
+
54
+
55
+ def figure(name: str, config: str, *args):
56
+ """A figure of diffgrammar.view.figures, drawn once per session, contrast and arguments."""
57
+ return _figure(name, config, st.session_state.get('contrast'), args)
58
+
59
+
60
+ @st.cache_data(max_entries=64, show_spinner=False)
61
+ def _rendered(name: str, config: str, contrast, args: tuple, dpi: int, tight: bool = False):
62
+ fig = _figure(name, config, contrast, args)
63
+ if fig is None:
64
+ return None
65
+ buf = io.BytesIO()
66
+ fig.savefig(buf, format='png', dpi=dpi, **({'bbox_inches': 'tight', 'pad_inches': 0.05} if tight else {}))
67
+ png = buf.getvalue()
68
+ w, h = struct.unpack('>II', png[16:24]) # the PNG's own size, which a tight box changes
69
+ return png, int(w), int(h)
70
+
71
+
72
+ def rendered(name: str, config: str, *args, dpi: int = 100, tight: bool = False):
73
+ """
74
+ A figure of diffgrammar.view.figures as PNG bytes and its size in pixels, once per session, contrast and arguments.
75
+ tight: cropped to what is drawn, for figures whose labels reach past their own edge (the report's).
76
+ """
77
+ return _rendered(name, config, st.session_state.get('contrast'), args, dpi, tight)
78
+
79
+
80
+ def show(fig, width='stretch'):
81
+ if fig is not None:
82
+ st.pyplot(fig, width=width)
83
+
84
+
85
+ # The bar stays under Streamlit's own header (3.75rem, which keeps the app menu) as the page scrolls: sticky
86
+ # within the main scroll area, above the page's charts and tables, below the header and the widgets' pop-ups.
87
+ # Streamlit draws a keyed container inside a layout wrapper as tall as the container, so the wrapper is what sticks.
88
+ BAR_CSS = """<style>
89
+ .stMain [data-testid="stMainBlockContainer"] {{ padding-top: 3.75rem !important; }}
90
+ [data-testid="stLayoutWrapper"]:has(> .st-key-topbar), [data-testid="stLayoutWrapper"]:has(> * > .st-key-topbar),
91
+ .st-key-topbar {{ position: sticky; top: 3.75rem; z-index: 999989; background: {bg}; }}
92
+ .st-key-topbar {{ border-bottom: 1px solid {line}; padding: 0.45rem 0 0.55rem 0; }}
93
+ </style>"""
94
+
95
+
96
+ def bar_style() -> str:
97
+ """BAR_CSS in the colours of the theme the browser shows."""
98
+ dark = getattr(getattr(st.context, 'theme', None), 'type', None) == 'dark'
99
+ bg = st.get_option('theme.backgroundColor') or ('#0e1117' if dark else '#ffffff')
100
+ return BAR_CSS.format(bg=bg, line='rgba(250, 250, 250, 0.2)' if dark else 'rgba(49, 51, 63, 0.2)')
101
+
102
+
103
+ def run_title(an, with_contrast: bool = True) -> str:
104
+ """
105
+ The run's name for the bar, as a title (ledidi_designs reads Ledidi designs): a slim bar shaded from B's colour to
106
+ A's, the name large, and the contrast as a soft pill with each condition in its colour. One line of HTML, as
107
+ markdown reads an indented line as code.
108
+ """
109
+ la, lb = an.label_a, an.label_b
110
+ name = (an.cfg['run'].get('name') or 'diffgrammar').replace('_', ' ')
111
+ pill = (f'<span style="font-size:0.95rem;font-weight:600;padding:0.25rem 0.75rem;border-radius:999px;'
112
+ f'background:rgba(128,128,128,0.12);white-space:nowrap"><span style="color:{an.colors[lb]}">{html.escape(lb)}</span>'
113
+ f' \u2212 <span style="color:{an.colors[la]}">{html.escape(la)}</span></span>') if with_contrast else ''
114
+ return (f'<div style="display:flex;align-items:center;gap:0.8rem">'
115
+ f'<span style="width:5px;height:2rem;border-radius:3px;background:linear-gradient(180deg,{an.colors[lb]},'
116
+ f'{an.colors[la]})"></span><span style="font-size:1.75rem;font-weight:700;letter-spacing:-0.02em;'
117
+ f'line-height:1.1">{html.escape(name[:1].upper() + name[1:])}</span>{pill}</div>')
118
+
119
+
120
+ config = next((a for a in sys.argv[1:] if a.endswith('.toml')), None) or os.environ.get('DIFFGRAMMAR_CONFIG') or \
121
+ st.text_input('Run config (TOML)')
122
+ if not config:
123
+ st.info('Give the config of a run: `diffgrammar view config.toml`.')
124
+ st.stop()
125
+ an = load(config)
126
+ contrasts = list(an.cfg['contrasts'])
127
+
128
+ # -- the bar: the run and its contrast here, the pages added at the end, once every page is defined ----------------
129
+ bar = st.container(key='topbar', horizontal=True, horizontal_alignment='distribute', vertical_alignment='center')
130
+ with bar:
131
+ st.html(bar_style())
132
+ st.markdown(run_title(an, with_contrast=len(contrasts) == 1), width='content', unsafe_allow_html=True)
133
+ if len(contrasts) > 1:
134
+ an = load(config, st.selectbox('Contrast', contrasts, key='contrast', label_visibility='collapsed', width=260,
135
+ format_func=lambda c: f'{c}: {an.cfg["contrasts"][c].get("label_b", "B")} − '
136
+ f'{an.cfg["contrasts"][c].get("label_a", "A")}'))
137
+ ca, cb = an.colors[an.label_a], an.colors[an.label_b]
138
+ lab = lambda s: an.set_labels.get(s, s) # noqa: E731
139
+
140
+
141
+ # -- one region ---------------------------------------------------------------------------------
142
+ def region_panel(coord: str, highlight=None, scan: bool = False):
143
+ try:
144
+ ex = V.region(an, coord)
145
+ except (KeyError, FileNotFoundError, StopIteration):
146
+ st.info(f'{coord}: its attributions are not in this folder, so there are no tracks to show. An export keeps '
147
+ 'the attributions of a sample of regions (attributions_kept.csv); the run itself has them all.')
148
+ return
149
+ hits = note = None
150
+ if scan:
151
+ try:
152
+ with st.spinner("Scanning the sequence with the subfamilies' JASPAR matrices…", show_time=True):
153
+ hits = V.region_scan(an, coord)
154
+ except ValueError:
155
+ note = 'This attribution store cannot give the input sequences, so there is nothing to scan.'
156
+ except (KeyError, FileNotFoundError, StopIteration):
157
+ note = 'Its input sequence is not in this folder, so there is nothing to scan.'
158
+ else:
159
+ if hits.empty:
160
+ lo, hi = hits.attrs['window']
161
+ note = (f"No subfamily matrix reaches p < {hits.attrs['threshold']:g} in the scanned part of this "
162
+ f'sequence ({lo:,}–{hi:,} bp of the input).')
163
+ hits = None
164
+ st.markdown(f'#### {coord} · {lab(ex.record["set_name"])}')
165
+ if V.gene_run(an):
166
+ gene_elements_panel(coord)
167
+ elif an.expression_table is not None:
168
+ got = an.region_genes[an.region_genes['coord'] == coord].merge(an.expression_table, on='gene', how='left')
169
+ if len(got):
170
+ st.caption('Assigned genes: ' + ', '.join(f'{g} (log2FC {v:+.2f}{", padj < 0.05" if q < 0.05 else ""})' if pd.notna(v) else f'{g} (not in the table)'
171
+ for g, v, q in zip(got['gene'], got['log2fc'], got['padj'])))
172
+ else:
173
+ st.caption('No gene assigned to this region.')
174
+ dark = getattr(getattr(st.context, 'theme', None), 'type', None) == 'dark'
175
+ page, height = T.track_view(an, ex, highlight, dark, scan=hits)
176
+ st.iframe(page, height=height)
177
+ if hits is not None:
178
+ lo, hi = hits.attrs['window']
179
+ extra = (f" Bottom rows, the sequence alone, no attributions: each subfamily's best JASPAR matrices scanned "
180
+ f"over the central {hi - lo:,} bp of the input ({lo:,}–{hi:,}, both strands, "
181
+ f"p < {hits.attrs['threshold']:g}), one row per family in its colour, its subfamilies as different "
182
+ 'shapes, a mark per hit over the span it covers. A motif can appear there that no seqlet supports, '
183
+ 'and a seqlet can have no match there. Hover a mark for the matrix, strand, score and p.')
184
+ else:
185
+ extra = f' Motifs by scanning the sequence: {note}' if note else ''
186
+ st.caption((f'Each base at its contribution to {an.label_b}: up where it raises the signal, down where it lowers it. '
187
+ if an.single else
188
+ f'Each base at its contribution in {an.label_a}, in {an.label_b} and in their difference by size: up where '
189
+ f'the base contributes more in {an.label_b}, down where more in {an.label_a}, whatever its sign (so a base '
190
+ f'repressing in both, more in {an.label_a}, points down). ') +
191
+ 'Bars zoomed out, the bases as letters zoomed in. Wheel, + and − or a double click zoom, drag moves, hover reads the numbers. '
192
+ 'Seqlets along the top in their subfamily’s colour (the Colour menu switches to family, cluster or ' +
193
+ ('the direction they act in' if an.single else 'the condition they are stronger in') +
194
+ ') and shaded down the tracks' +
195
+ (', those of the chosen cluster in gold' if highlight is not None else '') +
196
+ '; the cut dotted on the difference.' + extra)
197
+ n = len(ex.seqlets)
198
+ if n and st.toggle(f"Its {n} seqlet{'s' * (n != 1)} as a table, with their logos", key=f'seqlet_table_{coord}'):
199
+ t = pd.DataFrame(ex.seqlets).assign(motif=lambda d: V.motif_names(d))
200
+ cols = [c for c in ('motif', 'cluster', 'subfamily', 'start', 'end', 'seq', 'sign', 'mot_max') +
201
+ (() if an.single else ('mot_max_a', 'mot_max_b')) if c in t]
202
+ st.dataframe(t[cols].rename(columns={'mot_max_a': f'{an.label_a} contribution',
203
+ 'mot_max_b': f'{an.label_b} contribution'}),
204
+ hide_index=True, column_config={c: st.column_config.NumberColumn(format='%.3f')
205
+ for c in ('mot_max', f'{an.label_a} contribution',
206
+ f'{an.label_b} contribution')})
207
+ show(figure('region_logos', config, coord))
208
+
209
+
210
+ # -- families ---------------------------------------------------------------------------------------
211
+ GROUP_NAMES = {'subfamily': 'Subfamily', 'group': 'Family', 'tf': 'Best JASPAR match'}
212
+ GROUP_PLURAL = {'subfamily': 'subfamilies', 'group': 'families', 'tf': 'best JASPAR matches'}
213
+
214
+
215
+ @st.cache_data(show_spinner=False, max_entries=512)
216
+ def logo_uri(config: str, contrast, cluster: int) -> str:
217
+ """A cluster's logo as a small PNG data URI for a table cell, drawn once per run, contrast and cluster."""
218
+ return F.logo_thumbnail(load(config, contrast), cluster)
219
+
220
+
221
+ ROW_PX = 42 # one name of the Families list
222
+ BOX_PX = 680 # the Families list's box, and the cluster figure's box beside it
223
+ FAMILY_COLUMNS = ('Best matches', 'Clusters', 'Regions', 'Share of regions', 'TF RNA-seq', 'log2 ratio')
224
+ FAMILY_HIDDEN = ('Clusters', 'Regions', 'log2 ratio') # off until turned on under Columns, above the list
225
+ NAMED_TFS = 3 # TFs named per row of the Families list, the strongest significant ones
226
+ CHECK = 'M-0.8,0.05L-0.25,0.6L0.85,-0.55' # the tick of a row's box, a symbol path in [-1, 1]
227
+
228
+ # Streamlit draws a chart's toolbar (Show data, Download as PNG, Copy Vega-Lite spec, Fullscreen) above the chart and
229
+ # only on hover, which in the Families list's scroll box is outside the box, where the box cuts it off. There it sits
230
+ # in the box's top right corner instead, always shown and in front of the rows that scroll under it.
231
+ LIST_CSS = """<style>
232
+ :is(.st-key-family_list, .st-key-family_figure) [data-testid="stElementToolbar"] { position: sticky !important;
233
+ top: 0 !important; opacity: 1 !important; z-index: 3; display: flex; justify-content: flex-end;
234
+ padding: 0 0 0.3rem 0 !important; pointer-events: none; }
235
+ :is(.st-key-family_list, .st-key-family_figure) [data-testid="stElementToolbarButtonContainer"] { pointer-events: auto; }
236
+ </style>"""
237
+
238
+
239
+ def families_chart(t: pd.DataFrame, sets: list, expr: dict, lim: float, level: str, show=frozenset(FAMILY_COLUMNS)):
240
+ """
241
+ The Families list as one chart, a row per name, most regions first: a box ticked on the selected row, its logo,
242
+ name, best matches, clusters and regions, each class's share of its regions as a bar in the class's colour, and
243
+ its candidate TFs' RNA-seq fold changes as dots, named where padj < 0.05, gene, log2FC and padj on hover. A click on
244
+ a row selects it ('row'). The chart's own data is the list as a table, for the toolbar's Show data.
245
+ show: the FAMILY_COLUMNS to draw besides the box, the logo and the name.
246
+ """
247
+ n = len(t)
248
+ rows = t.reset_index(drop=True).assign(i=lambda d: np.arange(len(d)))
249
+ rows = rows.assign(y0=rows['i'] - 0.5, y1=rows['i'] + 0.5, box0=rows['i'] - 8 / ROW_PX, box1=rows['i'] + 8 / ROW_PX,
250
+ logo=[logo_uri(config, st.session_state.get('contrast'), cl[0]) if cl else None for cl in rows['clusters']])
251
+ rows = rows.drop(columns=['clusters'])
252
+ ys = alt.Scale(domain=[-0.5, n - 0.5], reverse=True, nice=False, zero=False)
253
+ y = alt.Y('i:Q', scale=ys, axis=None)
254
+ pick = alt.selection_point(fields=['key'], on='click', name='row', value=[{'key': rows['key'].iat[0]}], clear=False)
255
+ tips = [alt.Tooltip('key:N', title=GROUP_NAMES[level].lower()), alt.Tooltip('regions:Q', title='regions', format=','),
256
+ alt.Tooltip('n_clusters:Q', title='clusters')]
257
+
258
+ def column(width: int, title: str, *layers, data=None):
259
+ band = alt.Chart(rows).mark_rect(stroke='#ededed', strokeWidth=0.5).encode(
260
+ y=alt.Y('y0:Q', scale=ys, axis=None), y2='y1', x=alt.value(0), x2=alt.value(width),
261
+ fill=alt.condition(pick, alt.value('#fbe3e0'), alt.value('#ffffff')), tooltip=tips).add_params(pick)
262
+ return alt.layer(band, *layers).properties(
263
+ width=width, height=n * ROW_PX,
264
+ title=alt.Title(title, anchor='start', fontSize=12, fontWeight='normal', color='#555555'))
265
+
266
+ text = dict(baseline='middle', fontSize=12)
267
+ on = st.get_option('theme.primaryColor') or '#ff4b4b' # Streamlit's own ticked box
268
+ box = alt.Chart(rows).mark_rect(cornerRadius=3, strokeWidth=1.2).encode(
269
+ x=alt.value(5), x2=alt.value(21), y=alt.Y('box0:Q', scale=ys, axis=None), y2='box1', tooltip=tips,
270
+ fill=alt.condition(pick, alt.value(on), alt.value('#ffffff')),
271
+ stroke=alt.condition(pick, alt.value(on), alt.value('#9a9a9a')))
272
+ tick = alt.Chart(rows).mark_point(shape=CHECK, filled=False, size=90, strokeWidth=2, color='#ffffff').encode(
273
+ x=alt.value(13), y=y, opacity=alt.condition(pick, alt.value(1.0), alt.value(0.0)), tooltip=tips)
274
+ cols = [column(26, ' ', box, tick),
275
+ column(100, 'Logo', alt.Chart(rows).mark_image(width=92, height=ROW_PX - 10).encode(
276
+ x=alt.value(50), y=y, url='logo:N', tooltip=tips)),
277
+ column(200, GROUP_NAMES[level], alt.Chart(rows).mark_text(align='left', limit=192, **text).encode(
278
+ x=alt.value(4), y=y, text='key:N', tooltip=tips))]
279
+ if level != 'tf' and 'Best matches' in show:
280
+ cols.append(column(140, 'Best matches', alt.Chart(rows).mark_text(align='left', baseline='middle', fontSize=11,
281
+ color='#666666', limit=132).encode(
282
+ x=alt.value(4), y=y, text='top_tfs:N', tooltip=tips)))
283
+ if 'Clusters' in show:
284
+ cols.append(column(60, 'Clusters', alt.Chart(rows).mark_text(align='right', **text).encode(
285
+ x=alt.value(52), y=y, text='n_clusters:Q', tooltip=tips)))
286
+ if 'Regions' in show:
287
+ cols.append(column(70, 'Regions', alt.Chart(rows).mark_text(align='right', **text).encode(
288
+ x=alt.value(62), y=y, text=alt.Text('regions:Q', format=','), tooltip=tips)))
289
+ top = max(float(t[[f'pct|{s_}' for s_ in sets]].max().max()), 1.0)
290
+ k = len(sets)
291
+ share = pd.DataFrame([{'key': r_.key, 'class': lab(s_), 'pct': float(rows.at[r_.i, f'pct|{s_}']),
292
+ 'b0': r_.i - 0.38 + 0.76 * j / k, 'b1': r_.i - 0.38 + 0.76 * (j + 1) / k - 0.04,
293
+ 'bc': r_.i - 0.38 + 0.76 * (j + 0.5) / k - 0.02, 'zero': 0.0,
294
+ 'regions_class': int(rows.at[r_.i, f'regions|{s_}'])}
295
+ for r_ in rows[['i', 'key']].itertuples() for j, s_ in enumerate(sets)])
296
+ share['label'] = share['pct'].map(lambda v: f'{v:.0f}%')
297
+ xs = alt.Scale(domain=[0, top * 1.45], nice=False, zero=True)
298
+ cscale = alt.Scale(domain=[lab(s_) for s_ in sets], range=[set_color(s_) for s_ in sets])
299
+ stips = [alt.Tooltip('key:N', title=GROUP_NAMES[level].lower()), alt.Tooltip('class:N'),
300
+ alt.Tooltip('regions_class:Q', title='regions carrying it'), alt.Tooltip('pct:Q', title='% of the class', format='.1f')]
301
+ if 'Share of regions' in show:
302
+ cols.append(column(130, 'Share of regions',
303
+ alt.Chart(share).mark_rect().encode(x=alt.X('zero:Q', scale=xs, axis=None), x2='pct',
304
+ y=alt.Y('b0:Q', scale=ys, axis=None), y2='b1',
305
+ color=alt.Color('class:N', scale=cscale, legend=None), tooltip=stips),
306
+ alt.Chart(share).mark_text(align='left', baseline='middle', dx=3, fontSize=10, fontWeight='bold').encode(
307
+ x=alt.X('pct:Q', scale=xs, axis=None), y=alt.Y('bc:Q', scale=ys, axis=None), text='label:N',
308
+ color=alt.Color('class:N', scale=cscale, legend=None), tooltip=stips)))
309
+ if expr and 'TF RNA-seq' in show:
310
+ pts = []
311
+ for r_ in rows[['i', 'key']].itertuples():
312
+ d = expr.get(r_.key)
313
+ if d is None or not len(d):
314
+ continue
315
+ d = d.sort_values('log2fc')
316
+ off = np.linspace(-0.3, 0.3, len(d)) if len(d) > 1 else np.zeros(1)
317
+ for (g, v, q, bm), o in zip(d[['gene', 'log2fc', 'padj', 'base_mean']].itertuples(index=False, name=None), off):
318
+ pts.append({'key': r_.key, 'gene': g, 'log2fc': float(v), 'x': float(np.clip(v, -lim, lim)), 'yy': r_.i + o,
319
+ 'padj': float(q), 'base_mean': float(bm) if bm == bm else np.nan,
320
+ 'look': (f'up in {an.label_b}' if v > 0 else f'up in {an.label_a}') if q < 0.05 else 'not significant'})
321
+ pts = pd.DataFrame(pts)
322
+ xs_e = alt.Scale(domain=[-lim * 1.05, lim * 1.05], nice=False, zero=False)
323
+ looks = [f'up in {an.label_b}', f'up in {an.label_a}', 'not significant']
324
+ etips = [alt.Tooltip('gene:N'), alt.Tooltip('log2fc:Q', title=f'log2FC {an.label_b} / {an.label_a}', format='+.2f'),
325
+ alt.Tooltip('padj:Q', format='.2g'), alt.Tooltip('base_mean:Q', title='mean expression', format=',.0f'),
326
+ alt.Tooltip('key:N', title=GROUP_NAMES[level].lower())]
327
+ ex, ey = alt.X('x:Q', scale=xs_e, axis=None), alt.Y('yy:Q', scale=ys, axis=None)
328
+ named = (pts[pts['padj'] < 0.05].assign(strength=lambda d: d['log2fc'].abs()) # the 3 strongest named,
329
+ .sort_values('strength', ascending=False).groupby('key', sort=False).head(NAMED_TFS)) # the rest on hover
330
+ zero = alt.Chart(pd.DataFrame({'x': [0.0], 'y0': [-0.5], 'y1': [n - 0.5]})).mark_rule(color='#9a9a9a').encode(
331
+ x=alt.X('x:Q', scale=xs_e, axis=None), y=alt.Y('y0:Q', scale=ys, axis=None), y2='y1')
332
+ dots = alt.Chart(pts).mark_circle(opacity=1).encode(
333
+ x=ex, y=ey, tooltip=etips,
334
+ color=alt.Color('look:N', scale=alt.Scale(domain=looks, range=[cb, ca, '#c4c4c4']), legend=None),
335
+ size=alt.condition(alt.datum.look == 'not significant', alt.value(22), alt.value(55)))
336
+ names = [alt.Chart(part).mark_text(baseline='middle', fontSize=9, fontStyle='italic', dx=dx, align=align,
337
+ angle=angle).encode( # slanted away from the dot, so close names part
338
+ x=ex, y=ey, text='gene:N', tooltip=etips,
339
+ color=alt.Color('look:N', scale=alt.Scale(domain=looks, range=[cb, ca, '#c4c4c4']), legend=None))
340
+ for part, dx, align, angle in ((named[named['log2fc'] > 0], 5, 'left', 315), # 0 to 360 degrees,
341
+ (named[named['log2fc'] <= 0], -5, 'right', 45))] # clockwise
342
+ cols.append(column(230, f'TF RNA-seq, log2FC ±{lim:g}', zero, dots, *names))
343
+ if 'log2 ratio' in show and 'log2_ratio' in rows:
344
+ pair = V.differential_sets(an)
345
+ rr = rows.assign(towards=np.where(rows['log2_ratio'] > 0, lab(pair[1]), lab(pair[0])) if pair else '')
346
+ dirs = alt.Scale(domain=[lab(pair[1]), lab(pair[0])], range=[set_color(pair[1]), set_color(pair[0])]) if pair else alt.Undefined
347
+ cols.append(column(80, 'log2 ratio', alt.Chart(rr).mark_text(align='right', **text).encode(
348
+ x=alt.value(72), y=y, text=alt.Text('log2_ratio:Q', format='+.2f'), tooltip=tips,
349
+ color=alt.Color('towards:N', scale=dirs, legend=None))))
350
+ table = pd.DataFrame({GROUP_NAMES[level]: t['key'].to_numpy()}) # what Show data shows, every column
351
+ if level != 'tf':
352
+ table['Best matches'] = t['top_tfs'].to_numpy()
353
+ for c, name in (('n_clusters', 'Clusters'), ('seqlets', 'Seqlets'), ('regions', 'Regions')):
354
+ table[name] = t[c].to_numpy()
355
+ for s_ in sets:
356
+ table[f'{lab(s_)} regions'] = t[f'regions|{s_}'].to_numpy()
357
+ table[f'{lab(s_)} % of regions'] = t[f'pct|{s_}'].round(1).to_numpy()
358
+ if 'log2_ratio' in t:
359
+ table[f'log2 ratio {an.label_b} / {an.label_a}'] = t['log2_ratio'].round(2).to_numpy()
360
+ if expr:
361
+ sig = {k: d[d['padj'] < 0.05].sort_values('log2fc', ascending=False) for k, d in expr.items() if len(d)}
362
+ table[f'TFs, log2FC {an.label_b} / {an.label_a} (padj < 0.05)'] = [
363
+ ', '.join(f'{g} {v:+.2f}' for g, v in zip(sig[k]['gene'], sig[k]['log2fc'])) if k in sig else '' for k in t['key']]
364
+ return alt.hconcat(*cols, spacing=4, data=table).resolve_scale(color='independent').configure_view(
365
+ strokeWidth=0).properties(autosize=alt.AutoSizeParams(type='pad', contains='padding'))
366
+
367
+
368
+ GROUP_ROW_PX = (38, 78) # a cluster's row in the group chart, at least and at most; between, the rows fill the box
369
+ GROUP_W = {'label': 106, 'seqlets': 78, 'contribution': 84, 'genes': 84} # the group chart's columns, in px
370
+
371
+
372
+ def open_cluster(chart: str, pills: str):
373
+ """A click on a row of the group chart opens that cluster below, as its button would."""
374
+ def go():
375
+ got = st.session_state.get(chart, {}).get('selection', {}).get('cl', [])
376
+ if got:
377
+ st.session_state[pills] = int(got[0]['cluster'])
378
+ return go
379
+
380
+
381
+ def group_chart(g: pd.DataFrame, picked=None):
382
+ """
383
+ The report's cluster figure for one name of the Families list as one chart (view.data.group_report_table): per
384
+ cluster its logo, then per report set its seqlets stronger in each condition (stacked bars, the counts beside
385
+ them), each condition's contribution at them (boxes, whiskers by matplotlib's rule and no fliers, as the figure)
386
+ and, with [expression], the fold changes of its regions' genes (a box; dashed, the set's median). Stronger in B
387
+ first, a dotted line below them. The rows share the Families box's height; each axis reaches the farthest whisker
388
+ with zero and the medians in view. Hover for the numbers; a click on a row selects its cluster ('cl'), as `picked`
389
+ does. The chart's own data is its numbers as a table, for the toolbar's Show data.
390
+ """
391
+ sets, split, ref = g.attrs['sets'], g.attrs['split'], g.attrs['ref']
392
+ genes = 'g_n' in g
393
+ order = list(dict.fromkeys(g['cluster']))
394
+ n = len(order)
395
+ px = int(np.clip((BOX_PX - 150) / n, *GROUP_ROW_PX))
396
+ ys = alt.Scale(domain=[-0.5, n - 0.5], reverse=True, nice=False, zero=False)
397
+ pick = alt.selection_point(fields=['cluster'], on='click', name='cl', clear=False,
398
+ **({'value': [{'cluster': int(picked)}]} if picked is not None else {}))
399
+ rows = pd.DataFrame({'cluster': order, 'row': range(n)})
400
+ rows = rows.assign(y0=rows['row'] - 0.5, y1=rows['row'] + 0.5, odd=rows['row'] % 2, name=[cluster_label(c) for c in order])
401
+ g = g.assign(name=g['cluster'].map(dict(zip(rows['cluster'], rows['name']))), cls=g['set_name'].map(lab))
402
+ tip0 = [alt.Tooltip('name:N', title='cluster')]
403
+ row_y = alt.Y('row:Q', scale=ys, axis=None)
404
+ axis = dict(tickCount=3, grid=False, labelFontSize=9, labelFlush=True, titleFontSize=9.5, titleFontWeight='normal')
405
+
406
+ def panel(width: int, *layers):
407
+ band = alt.Chart(rows).mark_rect().encode(
408
+ y=alt.Y('y0:Q', scale=ys, axis=None), y2='y1', x=alt.value(0), x2=alt.value(width), tooltip=tip0,
409
+ fill=alt.when(pick, empty=False).then(alt.value('#fbe3e0')).when(alt.datum.odd == 1)
410
+ .then(alt.value('#f5f5f5')).otherwise(alt.value('#ffffff'))).add_params(pick)
411
+ line = [alt.Chart(pd.DataFrame({'y': [split - 0.5]})).mark_rule(color='#999999', strokeDash=[2, 2]).encode(
412
+ y=alt.Y('y:Q', scale=ys, axis=None))] if 0 < split < n else []
413
+ return alt.layer(band, *line, *layers).properties(width=width, height=n * px)
414
+
415
+ def title(text, sub):
416
+ return alt.Title(text, subtitle=sub, anchor='start', fontSize=11, subtitleFontSize=10, fontWeight='bold',
417
+ subtitleColor='#555555', offset=6)
418
+
419
+ W = GROUP_W
420
+ logos = rows.assign(logo=[logo_uri(config, st.session_state.get('contrast'), c) for c in order])
421
+ cols = [panel(W['label'],
422
+ alt.Chart(rows).mark_text(align='left', baseline='middle', fontSize=10, lineBreak=' ', limit=42).encode(
423
+ x=alt.value(2), y=row_y, text='name:N', tooltip=tip0),
424
+ alt.Chart(logos).mark_image(width=60, height=px - 12).encode(
425
+ x=alt.value(W['label'] - 31), y=row_y, url='logo:N', tooltip=tip0)
426
+ ).properties(title=title(' ', ' '))]
427
+
428
+ n_eq = g['n_eq'] if 'n_eq' in g else pd.Series(0, index=g.index) # sites equal in both conditions, grey
429
+ tot = g['n_a'] + n_eq + g['n_b'] # the counts sit beside the bar, A's above B's: room for them
430
+ room = 1 - (6 + 5.6 * np.maximum(g['n_a'].astype(str).str.len(), g['n_b'].astype(str).str.len())) / W['seqlets']
431
+ xs_n = alt.Scale(domain=[0, float((tot / room).max()) or 1.0], nice=False, zero=True)
432
+ g = g.assign(tot=tot, n_eq=n_eq, b0=g['row'] - 0.3, b1=g['row'] + 0.3, ya=g['row'] - 0.17, yb=g['row'] + 0.17)
433
+ EQUAL = 'equal in both'
434
+ neg, pos = an.directions # stronger in A / in B, or lowers / raises the one condition
435
+ bars = pd.concat([g.assign(who=neg, x0=0, x1=g['n_a']), g.assign(who=EQUAL, x0=g['n_a'], x1=g['n_a'] + g['n_eq']),
436
+ g.assign(who=pos, x0=g['n_a'] + g['n_eq'], x1=g['tot'])])
437
+ cscale = alt.Scale(domain=[neg, EQUAL, pos], range=[ca, '#b0b0b0', cb])
438
+ ntips = tip0 + [alt.Tooltip('cls:N', title='set'), alt.Tooltip('n_a:Q', title=neg),
439
+ alt.Tooltip('n_eq:Q', title=EQUAL), alt.Tooltip('n_b:Q', title=pos)]
440
+
441
+ boxes = pd.concat([g.assign(cond=c, yc=g['row'] + off, **{k: g[f'{p}{k}'] for k in ('whislo', 'q1', 'med', 'q3', 'whishi', 'n')})
442
+ for c, p, off in ((an.label_a, 'a_', -0.17), (an.label_b, 'b_', 0.17))
443
+ if f'{p}whislo' in g]) # a single-track run has B's boxes only
444
+ boxes = boxes[boxes['n'] > 0].assign(lo=lambda d: d['yc'] - 0.12, hi=lambda d: d['yc'] + 0.12)
445
+ lo, hi = min(0.0, float(boxes['whislo'].min())), max(0.0, float(boxes['whishi'].max()))
446
+ xs_c = alt.Scale(domain=[lo - 0.05 * (hi - lo), hi + 0.05 * (hi - lo)], nice=False, zero=False)
447
+ btips = tip0 + [alt.Tooltip('cls:N', title='set'), alt.Tooltip('cond:N', title='condition'),
448
+ alt.Tooltip('n:Q', title='seqlets'), alt.Tooltip('med:Q', title='median', format='.2f'),
449
+ alt.Tooltip('q1:Q', title='Q1', format='.2f'), alt.Tooltip('q3:Q', title='Q3', format='.2f'),
450
+ alt.Tooltip('whislo:Q', title='whisker low', format='.2f'),
451
+ alt.Tooltip('whishi:Q', title='whisker high', format='.2f')]
452
+ if genes:
453
+ gb = g[g['g_n'] > 0].assign(lo=lambda d: d['row'] - 0.22, hi=lambda d: d['row'] + 0.22)
454
+ refs = [v for v in ref.values() if np.isfinite(v)]
455
+ glo = min([0.0, float(gb['g_whislo'].min()) if len(gb) else 0.0] + refs)
456
+ ghi = max([0.0, float(gb['g_whishi'].max()) if len(gb) else 0.0] + refs)
457
+ xs_g = alt.Scale(domain=[glo - 0.05 * (ghi - glo or 1), ghi + 0.05 * (ghi - glo or 1)], nice=False, zero=False)
458
+ gtips = tip0 + [alt.Tooltip('cls:N', title='set'), alt.Tooltip('g_n:Q', title='genes'),
459
+ alt.Tooltip('g_med:Q', title='median log2FC', format='+.2f'),
460
+ alt.Tooltip('g_q1:Q', title='Q1', format='+.2f'), alt.Tooltip('g_q3:Q', title='Q3', format='+.2f')]
461
+
462
+ for s in sets:
463
+ gs, bs, xs = g[g['set_name'] == s], bars[bars['set_name'] == s], boxes[boxes['set_name'] == s]
464
+ shown = gs[gs['tot'] > 0]
465
+ block = [panel(W['seqlets'],
466
+ alt.Chart(bs).mark_rect().encode(
467
+ x=alt.X('x0:Q', scale=xs_n, axis=alt.Axis(title='Seqlets', **axis)), x2='x1',
468
+ y=alt.Y('b0:Q', scale=ys, axis=None), y2='b1',
469
+ color=alt.Color('who:N', scale=cscale, legend=None), tooltip=ntips),
470
+ alt.Chart(shown).mark_text(align='left', baseline='middle', dx=3, fontSize=9, color=ca).encode(
471
+ x=alt.X('tot:Q', scale=xs_n, axis=None), y=alt.Y('ya:Q', scale=ys, axis=None),
472
+ text='n_a:Q', tooltip=ntips),
473
+ alt.Chart(shown).mark_text(align='left', baseline='middle', dx=3, fontSize=9, color=cb).encode(
474
+ x=alt.X('tot:Q', scale=xs_n, axis=None), y=alt.Y('yb:Q', scale=ys, axis=None),
475
+ text='n_b:Q', tooltip=ntips)),
476
+ panel(W['contribution'],
477
+ alt.Chart(pd.DataFrame({'x': [0.0]})).mark_rule(color='#9a9a9a').encode(
478
+ x=alt.X('x:Q', scale=xs_c, axis=alt.Axis(title=['Contribution', 'at the seqlet'], **axis))),
479
+ alt.Chart(xs).mark_rule(color='#555555').encode(
480
+ x=alt.X('whislo:Q', scale=xs_c, axis=None), x2='whishi', y=alt.Y('yc:Q', scale=ys, axis=None),
481
+ tooltip=btips),
482
+ alt.Chart(xs).mark_rect(opacity=0.85).encode(
483
+ x=alt.X('q1:Q', scale=xs_c, axis=None), x2='q3', y=alt.Y('lo:Q', scale=ys, axis=None), y2='hi',
484
+ color=alt.Color('cond:N', scale=cscale, legend=None), tooltip=btips),
485
+ alt.Chart(xs).mark_rule(color='#000000', strokeWidth=1.2).encode(
486
+ x=alt.X('med:Q', scale=xs_c, axis=None), y=alt.Y('lo:Q', scale=ys, axis=None), y2='hi',
487
+ tooltip=btips))]
488
+ if genes:
489
+ gg = gb[gb['set_name'] == s]
490
+ block.append(panel(W['genes'],
491
+ alt.Chart(pd.DataFrame({'x': [0.0]})).mark_rule(color='#9a9a9a').encode(
492
+ x=alt.X('x:Q', scale=xs_g, axis=alt.Axis(
493
+ title=['Nearby genes', f'log2FC {an.label_b}/{an.label_a}'], **axis))),
494
+ *([alt.Chart(pd.DataFrame({'x': [ref[s]]})).mark_rule(color='#555555', strokeDash=[4, 3])
495
+ .encode(x=alt.X('x:Q', scale=xs_g, axis=None))] if np.isfinite(ref.get(s, np.nan)) else []),
496
+ alt.Chart(gg).mark_rule(color='#555555').encode(
497
+ x=alt.X('g_whislo:Q', scale=xs_g, axis=None), x2='g_whishi', y=row_y, tooltip=gtips),
498
+ alt.Chart(gg).mark_rect(opacity=0.85, color=TARGET_COLOR).encode(
499
+ x=alt.X('g_q1:Q', scale=xs_g, axis=None), x2='g_q3',
500
+ y=alt.Y('lo:Q', scale=ys, axis=None), y2='hi', tooltip=gtips),
501
+ alt.Chart(gg).mark_rule(color='#000000', strokeWidth=1.2).encode(
502
+ x=alt.X('g_med:Q', scale=xs_g, axis=None), y=alt.Y('lo:Q', scale=ys, axis=None),
503
+ y2='hi', tooltip=gtips)))
504
+ with_seqlet, attributed = g.attrs['header'][s]
505
+ cols.append(alt.hconcat(*block, spacing=6).properties(
506
+ title=title(lab(s), f'{with_seqlet:,} of {attributed:,} regions with a seqlet')))
507
+
508
+ table = g.assign(cluster=g['name'], set_name=g['cls'])[['cluster', 'set_name', 'n_a', 'n_eq', 'n_b', 'a_med', 'b_med'] +
509
+ (['g_n', 'g_med'] if genes else [])]
510
+ table = table.rename(columns={'set_name': 'set', 'n_a': f'stronger in {an.label_a}', 'n_eq': EQUAL,
511
+ 'n_b': f'stronger in {an.label_b}',
512
+ 'a_med': f'median contribution, {an.label_a}', 'b_med': f'median contribution, {an.label_b}',
513
+ 'g_n': 'nearby genes', 'g_med': f'median gene log2FC {an.label_b}/{an.label_a}'}).round(3)
514
+ return alt.hconcat(*cols, spacing=10, data=table).resolve_scale(color='independent').configure_view(
515
+ strokeWidth=0).properties(autosize=alt.AutoSizeParams(type='pad', contains='padding'))
516
+
517
+
518
+ def cluster_label(cluster: int) -> str:
519
+ """A cluster as the cluster figure names it: cl<id> and its best JASPAR match."""
520
+ hits = an.hits.get(int(cluster))
521
+ return f"cl{cluster} {hits[0]['tf']}" if hits else f'cl{cluster}'
522
+
523
+
524
+ def cluster_panel(cluster: int):
525
+ """
526
+ One cluster of the Families selection: its consensus above one of its JASPAR matches (the best by default),
527
+ aligned, and the regions carrying it as dots in their class's colour (region_map). Returns the region a click
528
+ picked, or None.
529
+ """
530
+ left, right = st.columns([2, 3])
531
+ with left:
532
+ st.markdown('**Which TF it looks like**')
533
+ hits = V.jaspar_hits(an, cluster).set_index('id')
534
+ mid = None
535
+ if len(hits):
536
+ mid = st.selectbox('JASPAR match', list(hits.index), key=f'hit_{cluster}',
537
+ format_func=lambda i: f"{hits.loc[i, 'tf']} ({i}), p {hits.loc[i, 'pval']:.0e}")
538
+ with st.spinner(f'Aligning {cluster_label(cluster)} to JASPAR…', show_time=True):
539
+ png, w, _ = rendered('motif_logos', config, cluster, mid, dpi=200, tight=True)
540
+ st.image(png, width=int(w / 2)) # at its own size, drawn at twice the pixels
541
+ st.caption('Its consensus above the matrix, aligned; the matches as the families step found them, best first.' +
542
+ (f" [{mid} on JASPAR]({hits.loc[mid, 'url']})" if mid else ' It has no JASPAR match.'))
543
+ with right:
544
+ st.markdown('**The regions that carry it**')
545
+ with st.spinner(f'Finding the regions that carry {cluster_label(cluster)}…', show_time=True):
546
+ regs = V.motif_regions(an, cluster)
547
+ info = V.region_table(an, 'cluster').set_index('coord')
548
+ regs = regs.assign(best=regs['mot_max'].abs(), n=regs['all_seqlets'],
549
+ motifs=info['motifs'].reindex(regs['coord']).to_numpy(),
550
+ budget=info['budget'].reindex(regs['coord']).to_numpy(),
551
+ measured=info['measured'].reindex(regs['coord']).to_numpy())
552
+ partial = V.available_regions(an) is not None
553
+ shown = regs[V.has_tracks(an, regs['coord']).to_numpy()] if partial else regs
554
+ picked = region_map(shown, {}, f'map_{cluster}', 'best', f'Strongest seqlet of cl{cluster}, |contribution|', 'set')
555
+ st.caption(f"{len(regs):,} regions carry it, a dot each in its class's colour. Hover for its motifs, click to "
556
+ 'open it below, wheel to zoom.' + (f' {len(shown):,} have their attributions in this folder.' if partial else ''))
557
+ return picked
558
+
559
+
560
+ def families_page():
561
+ """
562
+ The clusters by subfamily, family or best JASPAR match (view.data.group_table): every name with its clusters and
563
+ regions, most regions first; a row opens the report's cluster figure for its clusters beside the list, then one
564
+ of them its JASPAR evidence and its regions (cluster_panel) across the page, and a region its tracks below.
565
+ """
566
+ if not V.has(an, 'families/cluster_families.csv'):
567
+ st.info('Needs the `families` step.')
568
+ return
569
+ level = st.radio('Clusters by', list(GROUP_NAMES), horizontal=True, key='group_level', format_func=GROUP_NAMES.get)
570
+ t = V.group_table(an, level)
571
+ if t.empty:
572
+ st.info("No seqlet of this contrast in the report's sets.")
573
+ return
574
+ sets, pair = t.attrs['sets'], V.differential_sets(an)
575
+ st.markdown(f"**{len(t)} {GROUP_PLURAL[level]}** over {int(t['n_clusters'].sum())} clusters, most regions first.")
576
+ left, right = st.columns([3, 2])
577
+ expr = V.group_expression(an, level)
578
+ lim = float(np.ceil(max((float(np.abs(d['log2fc']).max()) for d in expr.values() if len(d)), default=1.0))) if expr else 1.0
579
+ with left:
580
+ offer = [c for c in FAMILY_COLUMNS if not (c == 'Best matches' and level == 'tf') and not (c == 'TF RNA-seq' and not expr)
581
+ and not (c == 'log2 ratio' and 'log2_ratio' not in t)]
582
+ with st.popover('Columns', icon=':material/view_column:', help='The columns of the list'):
583
+ show = frozenset(c for c in offer if st.toggle(c, value=c not in FAMILY_HIDDEN, key=f'fam_col_{c}'))
584
+ with st.spinner(f'Drawing the {GROUP_PLURAL[level]} and their logos…', show_time=True):
585
+ chart = families_chart(t, sets, expr, lim, level, show)
586
+ st.html(LIST_CSS)
587
+ with st.container(height=BOX_PX, key='family_list'):
588
+ st.altair_chart(chart, key=f'groups_{level}', on_select='rerun', selection_mode='row', width='content')
589
+ st.caption(f"Regions: those with a seqlet in one of its clusters, every cluster counted; bars: the share of each "
590
+ f"class's {t.attrs['denominator']} regions. Logo: its largest cluster. " +
591
+ (f"TF RNA-seq: its candidate TFs' log2 fold change {an.label_b} / {an.label_a}, named and coloured where "
592
+ 'padj < 0.05; hover a dot for its numbers. ' if expr else '') +
593
+ 'Click a row or its box to see all its clusters; Show data, top right of the list, gives the '
594
+ 'numbers as a table to download.')
595
+ picked = st.session_state.get(f'groups_{level}', {}).get('selection', {}).get('row', [])
596
+ hit = t[t['key'] == picked[0].get('key')] if picked else t.iloc[0:0]
597
+ r = hit.iloc[0] if len(hit) else t.iloc[0]
598
+ with right:
599
+ st.markdown(f"#### {r['key']}") # its numbers and candidate TFs are on its row of the list
600
+ pills = f"fam_cluster_{level}_{r['key']}"
601
+ with st.spinner(f"Drawing the clusters of {r['key']}…", show_time=True):
602
+ g = V.group_report_table(an, level, r['key'])
603
+ if g.empty:
604
+ st.info("The cluster figure needs each condition's contribution at the seqlets: rerun `seqlets`.")
605
+ else:
606
+ with st.container(height=BOX_PX, key='family_figure'): # beside the list, as tall
607
+ st.altair_chart(group_chart(g, st.session_state.get(pills)), key=f"group_{level}_{r['key']}",
608
+ on_select=open_cluster(f"group_{level}_{r['key']}", pills), selection_mode='cl',
609
+ width='content')
610
+ from diffgrammar import expression as X
611
+ st.caption(f'Per cluster: its seqlets stronger in {an.label_a} and in {an.label_b} (counts beside the bars; grey, '
612
+ 'equal in both: found on a condition alone, no differential) '
613
+ f"and each condition's contribution at them (box: quartiles and median; whiskers: the farthest "
614
+ f'seqlet within 1.5 box lengths); stronger in {an.label_b} on average above the dotted line.' +
615
+ (f' Nearby genes: the RNA-seq log2FC {an.label_b} / {an.label_a} of the genes of the regions where the '
616
+ f'cluster has a seqlet ({X.describe(an.cfg)}), each gene once; dashed, the median over all the '
617
+ "set's regions." if an.expression_table is not None else '') +
618
+ ' Hover for the numbers; click a row to open that cluster below.')
619
+ st.markdown(f"#### One cluster of {r['key']}")
620
+ st.caption('Pick one to see which TF its motif looks like and the regions that carry it; a click on a region opens '
621
+ 'its tracks below.')
622
+ cluster = st.pills('Cluster', [int(c) for c in r['clusters']], key=f"fam_cluster_{level}_{r['key']}",
623
+ format_func=cluster_label, label_visibility='collapsed') # or a click on the chart's row
624
+ region = cluster_panel(int(cluster)) if cluster is not None else None
625
+ if region is not None:
626
+ st.divider()
627
+ region_panel(region, highlight=int(cluster), scan=True)
628
+
629
+
630
+ # -- co-occurrence, in words --------------------------------------------------------------------
631
+ def cooc_method(src: str = 'seqlets') -> str:
632
+ """How co-occurrence within a class is tested (diffgrammar.view.data.pair_stats), in words, for a source of motifs."""
633
+ s = V.cooc_settings(an)
634
+ site = ("both motifs were called as seqlets above the region's cut" if src == 'seqlets' else
635
+ f"a scan finds both motifs' JASPAR matrices in the region at p < {float(s['scan_threshold']):g}")
636
+ return ("Chance: the motif labels shuffled among the sites of regions with the same number of sites, so a motif that "
637
+ f"tends to be alone in its region keeps that. A pair counts when {site}. Tested: pairs expected in at least "
638
+ f"{s['min_expected']:g} region(s); rarer ones are left out before the correction, as they can be neither "
639
+ 'depleted nor convincingly enriched. p: two-sided, by permutation of those labels. q: two stages, read the way '
640
+ "the page is (a motif, then its partners). First, whether a motif's partners together depart from chance "
641
+ '(Simes, BH over the motifs); then each partner, within the motifs that pass, at the level the first stage '
642
+ f"leaves (BH; Benjamini and Bogomolov 2014). A pair passes at q ≤ {ALPHA} when either of its motifs' lists "
643
+ 'keeps it.')
644
+
645
+
646
+ COOC_LOOK = {'passes': 'Passes', 'does not pass': 'Does not pass', 'motifs not selected': 'Does not pass',
647
+ 'not tested': 'Not tested'}
648
+
649
+
650
+ # -- regions: a motif, its partners per class, and example regions aligned on it ----------------------
651
+ X_COLOR, P_COLOR = '#F2C14E', '#8EC3EA' # the chosen motif's site, the partner's site, in the logos
652
+ MAP_MAX = 5000 # dots in a region map: the strongest of a larger pool
653
+
654
+
655
+ def set_color(s: str) -> str:
656
+ """The colour of a region set: its condition's colour when the set is named after it."""
657
+ if s.startswith(an.label_b):
658
+ return cb
659
+ if s.startswith(an.label_a):
660
+ return ca
661
+ return mcolors.to_hex(an.set_colors.get(s, '#888888'))
662
+
663
+
664
+ def region_map(pool: pd.DataFrame, colors: dict, key: str, y_field: str, y_title: str, color_by: str,
665
+ context: pd.DataFrame = None):
666
+ """
667
+ One dot per region of `pool` (a cluster's regions on the Families page): x the signed predicted difference, y `y_field`, colour by class
668
+ ('set') or by a motif key column through `colors`. Hover for details, click to open, wheel to zoom. Returns the
669
+ clicked region's coordinate, or None.
670
+ """
671
+ d = pool.sort_values('best', ascending=False).head(MAP_MAX).copy()
672
+ d['color'] = d['set_name'].map(set_color) if color_by == 'set' else d[color_by].map(lambda k: colors.get(k, '#d0d0d0'))
673
+ tips = [alt.Tooltip('coord:N', title='region'), alt.Tooltip('set_name:N', title='set'),
674
+ alt.Tooltip('motifs:N', title='motifs'),
675
+ alt.Tooltip('budget:Q', title=f'predicted {an.label_b} − {an.label_a}', format='.3f'),
676
+ alt.Tooltip('best:Q', title='strongest seqlet', format='.3f'), alt.Tooltip('n:Q', title='seqlets')]
677
+ if 'measured' in d and d['measured'].notna().any():
678
+ tips.append(alt.Tooltip('measured:Q', title='measured difference', format='.3g'))
679
+ pick = alt.selection_point(fields=['coord'], name='pick', on='click')
680
+ x = alt.X('budget:Q', title=f'Predicted {an.label_b} − {an.label_a} (the seqlet budget)')
681
+ y = alt.Y(f'{y_field}:Q', title=y_title)
682
+ layers = []
683
+ if context is not None and len(context):
684
+ ctx = context.sort_values('best', ascending=False).head(MAP_MAX)
685
+ layers.append(alt.Chart(ctx).mark_circle(size=12, color='#d9d9d9')
686
+ .encode(x=x, y=y, tooltip=[alt.Tooltip('coord:N', title='region, not on this path'),
687
+ alt.Tooltip('motifs:N', title='motifs')]))
688
+ layers.append(alt.Chart(d).mark_circle(size=44, stroke='black', strokeWidth=0.4)
689
+ .encode(x=x, y=y, color=alt.Color('color:N', scale=None, legend=None),
690
+ opacity=alt.condition(pick, alt.value(1.0), alt.value(0.8)), tooltip=tips)
691
+ .add_params(pick))
692
+ st.altair_chart(alt.layer(*layers).interactive().properties(height=360), key=key, on_select='rerun',
693
+ selection_mode='pick', width='stretch')
694
+ sel = st.session_state.get(key, {}).get('selection', {}).get('pick', [])
695
+ return sel[0]['coord'] if sel else None
696
+
697
+
698
+ # -- from a gene back to its regions ------------------------------------------------------------
699
+ def gene_elements_panel(coord: str):
700
+ """
701
+ A gene run's region is the gene itself: its seqlets as elements along the locus, each with its contribution to the
702
+ gene's predicted change, which the contributions together add up to.
703
+ """
704
+ with st.spinner('Placing the elements of this gene', show_time=True):
705
+ el, info = V.gene_elements(an, coord)
706
+ row = V.gene_expression(an, info['gene'])
707
+ meas = (f"; measured log2FC {float(row['log2fc']):+.2f}" if row is not None and pd.notna(row['log2fc']) else '')
708
+ if el.empty:
709
+ st.markdown(f"**{info['gene']}**: no seqlet in its window{meas}.")
710
+ return
711
+ big = el.loc[el['effect'].abs().idxmax()]
712
+ where = f"{big['kb']:+.1f} kb" + (' from the TSS' if info['relative_to_tss'] else ' into the window')
713
+ st.markdown(f"**{info['gene']}**: its {info['n']} elements carry **{info['share']:.0%}** of the predicted "
714
+ f"{an.label_b} − {an.label_a} change ({info['total']:+.3g}){meas}. Largest: {big['motif']} at {where}, "
715
+ f"{'repressing' if big['repressive'] else 'activating'} more in "
716
+ f"{an.label_b if big['effect'] > 0 else an.label_a} ({big['contribution']:+.3g} of the change).")
717
+ d = el.assign(colour=np.where(el['effect'] > 0, cb, ca), share=el['contribution'] / info['total'],
718
+ role=np.where(el['repressive'], 'represses', 'activates'), fill=np.where(el['repressive'], 0.0, 1.0))
719
+ x = alt.X('kb:Q', title='Element centre − TSS (kb, in the gene\'s direction)' if info['relative_to_tss']
720
+ else 'Element centre (kb into the window)')
721
+ y = alt.Y('effect:Q', title=f'Contribution, {an.label_b} ↑ {an.label_a} ↓')
722
+ tips = [alt.Tooltip('motif:N'), alt.Tooltip('kb:Q', title='kb', format='+.1f'), alt.Tooltip('role:N', title='on average it'),
723
+ alt.Tooltip('a:Q', title=an.label_a, format='+.3g'), alt.Tooltip('b:Q', title=an.label_b, format='+.3g'),
724
+ alt.Tooltip('contribution:Q', title=f'part of the {an.label_b} − {an.label_a} change', format='+.3g'),
725
+ alt.Tooltip('share:Q', title='share of the predicted change', format='+.1%')]
726
+ stems = alt.Chart(d).mark_rule(strokeWidth=1.2).encode(x=x, y=y, y2=alt.datum(0),
727
+ color=alt.Color('colour:N', scale=None, legend=None))
728
+ heads = alt.Chart(d).mark_point(filled=True, size=44, strokeWidth=1.4).encode(
729
+ x=x, y='effect:Q', color=alt.Color('colour:N', scale=None, legend=None),
730
+ fillOpacity=alt.FillOpacity('fill:Q', scale=None, legend=None), tooltip=tips)
731
+ layers = [alt.Chart(pd.DataFrame({'y': [0]})).mark_rule(color='#888').encode(y='y:Q'), stems, heads]
732
+ if info['relative_to_tss']:
733
+ layers.insert(0, alt.Chart(pd.DataFrame({'x': [0]})).mark_rule(color='#444', strokeDash=[4, 3]).encode(x='x:Q'))
734
+ st.altair_chart(alt.layer(*layers).interactive().properties(height=240), width='stretch')
735
+ st.caption(f"Each stem one seqlet of the gene, its contributions summed over its span: up where it acts more strongly "
736
+ f"in {an.label_b}, down where more in {an.label_a}, by size and whatever its sign. Hollow: it represses on "
737
+ f"average, so acting more in {an.label_a} raises {an.label_b} over {an.label_a}. Hover for its sum in each "
738
+ "condition and its part of the predicted change; all contributions, seqlets or not, add up to the change, so "
739
+ "together the seqlets can carry more than all of it when the rest of the window pushes the other way." +
740
+ ('' if info['relative_to_tss'] else
741
+ ' Set [run] tss_position (the input position of the TSS; Decima: 163840) to place them relative to the TSS.'))
742
+
743
+
744
+ def stacked_logos(items):
745
+ """Logo images one above the other in one frame that scrolls sideways, so windows of one width stay aligned;
746
+ items: ('heading', None, 0, 0) for a group heading, or (title, png, width, height)."""
747
+ html, height = [], 10
748
+ for title, png, w, h in items:
749
+ if png is None:
750
+ html.append(f'<div style="font:bold 13px sans-serif;color:#222;margin:14px 0 2px 4px">{title}</div>')
751
+ height += 30
752
+ else:
753
+ html.append(f'<div style="font:12px sans-serif;color:#444;margin:6px 0 2px 4px">{title}</div>'
754
+ f'<img src="data:image/png;base64,{base64.b64encode(png).decode()}" width="{w}" height="{h}" style="display:block">')
755
+ height += h + 24
756
+ st.iframe('<body style="margin:0">' + ''.join(html) + '</body>', height=height)
757
+
758
+
759
+ # -- the co-occurrence overview: which pairs differ between the classes, and within each class ------------
760
+ ALPHA = float(V.cooc_settings(an)['alpha']) # the [cooccurrence] level, at which pair_stats ran its two stages
761
+ LESS_C, CHANCE_C, BOTH_C, UNTESTED_C = '#6baed6', '#cccccc', '#525252', '#e8e8e8'
762
+
763
+
764
+ def pair_name(a_label: str, b_label: str) -> str:
765
+ return f'{a_label} & {b_label}'
766
+
767
+
768
+ def chart_keys(level: str) -> dict:
769
+ """The charts' keys by chart. `ov_rev` grows after each pick, so the charts come back with no selection and any
770
+ next click, also on the same pair, is new."""
771
+ rev = st.session_state.get('ov_rev', 0)
772
+ return {**{f'obs|{s_}': f'ov_obs_{level}_{s_}_{rev}' for s_ in an.sets}, 'pairing': f'ov_pairing_{level}_{rev}'}
773
+
774
+
775
+ def partner_key(level: str, x: str) -> str:
776
+ """The key of the partner picker of motif x in the pair panel."""
777
+ return f'partner_{level}_{x}'
778
+
779
+
780
+ def apply_pair(level: str, a: str, b: str, set_name=None):
781
+ """
782
+ Open a pair in the panel below: its motif becomes the more used of the two and the other its partner, with the
783
+ examples in the given class when the pair has regions there (else where it has most, else both classes; set_name
784
+ 'both', from a comparison of the classes, always both). A pair that shares no region opens too, as its 2x2 tables
785
+ say how rarely the two meet; a == b opens the motif with a second site of its own.
786
+ """
787
+ tot = V.motif_usage(an, level).groupby('key')['regions'].sum()
788
+ if a not in tot.index or b not in tot.index:
789
+ return
790
+ x, partner = (a, b) if tot[a] >= tot[b] else (b, a)
791
+ pc = V.pair_counts(an, level)
792
+ rows = pc[(pc['a'] == min(a, b)) & (pc['b'] == max(a, b))] if a != b else pc.iloc[0:0]
793
+ st.session_state['x_key'] = x
794
+ st.session_state[partner_key(level, x)] = partner
795
+ st.session_state['forced_partner'] = (x, partner)
796
+ by_set = rows.set_index('set_name')['shared'] if len(rows) else pd.Series(dtype=int)
797
+ if set_name != 'both' and set_name in by_set.index:
798
+ cls = set_name
799
+ elif set_name != 'both' and len(by_set):
800
+ cls = by_set.idxmax()
801
+ else:
802
+ cls = 'both'
803
+ st.session_state['examples_class'] = cls
804
+ st.session_state['picked_pair'] = {'x': x, 'partner': partner, 'set': None if cls == 'both' else cls,
805
+ 'other': b if x == a else a}
806
+
807
+
808
+ def passing_key(level: str) -> str:
809
+ """The key of the list of passing pairs, renewed with the charts so a picked row is used once."""
810
+ return f"ov_sig_{level}_{st.session_state.get('ov_rev', 0)}"
811
+
812
+
813
+ def differing_key(level: str) -> str:
814
+ """The key of the list of pairs that differ between the classes, renewed like passing_key."""
815
+ return f"ov_dsig_{level}_{st.session_state.get('ov_rev', 0)}"
816
+
817
+
818
+ SOURCE_NAMES = {'seqlets': 'Seqlets (the attributions)', 'scan': 'Scanning (JASPAR matrices)'}
819
+
820
+
821
+ def motif_source(level: str = 'subfamily') -> str:
822
+ """The page's source of motifs ("Motifs from"); a scan uses JASPAR matrices for subfamilies, a cluster's own for clusters."""
823
+ return st.session_state.get('motif_source', 'seqlets')
824
+
825
+
826
+ def differing_pairs(level: str) -> pd.DataFrame:
827
+ """The rows of pair_differential that pass (q <= ALPHA), in its order: the list the page shows."""
828
+ d = V.pair_differential(an, level, motif_source(level))
829
+ return d[d['q'] <= ALPHA].reset_index(drop=True) if len(d) else d
830
+
831
+
832
+ def regression_key() -> str:
833
+ """The key of the list of pairs from the pair-regression step, renewed like passing_key."""
834
+ return f"ov_rsig_{st.session_state.get('ov_rev', 0)}"
835
+
836
+
837
+ def regression_sources() -> list:
838
+ """The sources of motifs the run has the pair regression from, scanning first (it covers every region)."""
839
+ return [s_ for s_ in ('scan', 'seqlets') if len(V.pair_regression(an, s_))]
840
+
841
+
842
+ def regression_source() -> str:
843
+ """The source the Pair effects page reads the pair regression from: its own choice, else the first the run has."""
844
+ has = regression_sources()
845
+ s = st.session_state.get('regression_source')
846
+ return s if s in has else (has[0] if has else 'scan')
847
+
848
+
849
+ def regression_pairs(src: str) -> pd.DataFrame:
850
+ """The rows of the pair-regression step that pass (q <= its alpha), in its order: the list the page shows."""
851
+ d = V.pair_regression(an, src)
852
+ return d[d['q'] <= float(d.attrs.get('alpha', 0.05))].reset_index(drop=True) if len(d) else d
853
+
854
+
855
+ def take_regression_pick():
856
+ """
857
+ A row of the pair regression's list (Pair effects page) opens the pair on the Co-occurrence page, at the subfamily
858
+ level, the level the step names motifs at. Runs before the page picker is drawn, as it changes the page.
859
+ """
860
+ rows = st.session_state.get(regression_key(), {}).get('selection', {}).get('rows', [])
861
+ if not rows:
862
+ return
863
+ t = regression_pairs(regression_source())
864
+ if rows[0] < len(t):
865
+ r = t.iloc[rows[0]]
866
+ st.session_state['level'] = 'subfamily'
867
+ apply_pair('subfamily', r['a'], r['b'], 'both')
868
+ st.session_state['ov_rev'] = st.session_state.get('ov_rev', 0) + 1
869
+ st.session_state['page'] = 'Co-occurrence'
870
+
871
+
872
+ def take_picks(level: str):
873
+ """
874
+ Apply a click on a chart or a row of a list of pairs: the pair opens in the panel below (apply_pair). The charts
875
+ and lists are then renewed, so a pick is used once.
876
+ """
877
+ src = motif_source(level)
878
+ picked = None
879
+ for key, table, cls in ((differing_key(level), lambda: differing_pairs(level), lambda r: 'both'),
880
+ (passing_key(level), lambda: V.significant_pairs(an, level, src), lambda r: r['set_name'])):
881
+ rows = st.session_state.get(key, {}).get('selection', {}).get('rows', [])
882
+ if rows:
883
+ t = table()
884
+ if rows[0] < len(t):
885
+ r = t.iloc[rows[0]]
886
+ picked = (r['a'], r['b'], cls(r))
887
+ break
888
+ if picked is None:
889
+ for key in chart_keys(level).values():
890
+ sel = st.session_state.get(key, {}).get('selection', {}).get('pick', [])
891
+ if sel and sel[0].get('a') and sel[0].get('b'):
892
+ picked = (sel[0]['a'], sel[0]['b'], sel[0].get('set_name'))
893
+ break
894
+ if picked:
895
+ apply_pair(level, *picked)
896
+ st.session_state['ov_rev'] = st.session_state.get('ov_rev', 0) + 1
897
+ labels = V.motif_labels(an, level).drop_duplicates('key').set_index('key')['label']
898
+ st.toast(f'{pair_name(labels.get(picked[0], picked[0]), labels.get(picked[1], picked[1]))}: opened under '
899
+ '"One pair", below.')
900
+
901
+
902
+ def _tips(d_cols):
903
+ return [alt.Tooltip('pair:N', title='pair'), alt.Tooltip('set:N', title='class'),
904
+ alt.Tooltip('shared:Q', title='regions with both'),
905
+ alt.Tooltip('expected:Q', title='expected by chance', format='.1f'),
906
+ alt.Tooltip('log2_ratio:Q', title='log2 observed / expected', format='.2f'),
907
+ alt.Tooltip('look:N', title='test'), alt.Tooltip('p:Q', title='p (permutation)', format='.2g'),
908
+ alt.Tooltip('by_chance:Q', title='pairs as extreme by chance alone', format='.1f'),
909
+ alt.Tooltip('q:Q', title='q (two stages)', format='.2g'),
910
+ alt.Tooltip('median_gap:Q', title='median gap between the sites (bp)', format='.0f'),
911
+ alt.Tooltip('repeat_share:Q', title='regions with both sites in repeats', format='.0%')]
912
+
913
+
914
+ def _labels_layer(rows: pd.DataFrame, x: str, y: str, X: dict, Y: dict, right_of: float):
915
+ """Pair names next to their dots: to the right in the left part of the plot, to the left near its right edge."""
916
+ left = rows[rows[x] <= right_of]
917
+ right = rows[rows[x] > right_of]
918
+ layers = []
919
+ for part, align, dx in ((left, 'left', 7), (right, 'right', -7)):
920
+ if len(part):
921
+ layers.append(alt.Chart(part).mark_text(align=align, dx=dx, dy=-5, fontSize=11).encode(
922
+ x=alt.X(f'{x}:Q', **X), y=alt.Y(f'{y}:Q', **Y), text='pair:N'))
923
+ return layers
924
+
925
+
926
+ def obs_exp_chart(d: pd.DataFrame, s: str):
927
+ """One class: every pair at its expected (x) against its observed (y) number of regions; the dashed line is chance."""
928
+ top = max(float(d['expected'].max()), float(d['shared'].max()), 1.0) * 1.08
929
+ sc = alt.Scale(type='symlog', domain=[0, top], nice=False)
930
+ X = dict(scale=sc, title='Expected by chance (regions)')
931
+ Y = dict(scale=sc, title='Regions with both')
932
+ passes = d['status'] == 'passes'
933
+ status = np.select([~d['tested'].astype(bool), passes & (d['shared'] > d['expected']), passes],
934
+ ['Not tested', 'More often than chance', 'Less often than chance'], 'As chance')
935
+ rep = d['repeat_share'].fillna(0) >= 0.5
936
+ d = d.assign(status=status, look=d['status'].map(COOC_LOOK),
937
+ pair=[pair_name(x, y) + (' (repeats)' if r else '') for x, y, r in zip(d['a_label'], d['b_label'], rep)],
938
+ set=lab(s), set_name=s, close=d['median_gap'] <= V.GAP_ADJACENT)
939
+ domain = ['More often than chance', 'Less often than chance', 'As chance', 'Not tested']
940
+ pick = alt.selection_point(fields=['a', 'b', 'set_name'], name='pick', on='click')
941
+ diag = alt.Chart(pd.DataFrame({'v': [0.0, top]})).mark_line(color='#888888', strokeDash=[4, 3]).encode(
942
+ x=alt.X('v:Q', **X), y=alt.Y('v:Q', **Y))
943
+ pts = alt.Chart(d).mark_point(filled=True, stroke='black', strokeWidth=0.3).encode(
944
+ x=alt.X('expected:Q', **X), y=alt.Y('shared:Q', **Y),
945
+ color=alt.Color('status:N', title=None, scale=alt.Scale(domain=domain, range=[set_color(s), LESS_C, CHANCE_C, UNTESTED_C]),
946
+ legend=alt.Legend(orient='bottom')),
947
+ shape=alt.Shape('close:N', scale=alt.Scale(domain=[True, False], range=['diamond', 'circle']), legend=None),
948
+ size=alt.condition((alt.datum.status == 'As chance') | (alt.datum.status == 'Not tested'), alt.value(28), alt.value(80)),
949
+ opacity=alt.condition(pick, alt.value(1.0), alt.value(0.8)), tooltip=_tips(d)).add_params(pick)
950
+ rows = d[~d['status'].isin(['As chance', 'Not tested'])].assign(dev=lambda t: t['log2_ratio'].abs()).nlargest(6, 'dev')
951
+ return (alt.layer(diag, pts, *_labels_layer(rows, 'expected', 'shared', X, Y, top / 4))
952
+ .properties(title=lab(s), height=300).configure_axis(grid=False).configure_view(strokeWidth=0))
953
+
954
+
955
+ def more_in(s: str) -> str:
956
+ return f'More together in {lab(s)}'
957
+
958
+
959
+ def differential_points(d: pd.DataFrame, A: str, B: str) -> pd.DataFrame:
960
+ """The compared pairs of pair_differential under the short names the charts use; set_name 'both' for apply_pair."""
961
+ t = d[d['tested']]
962
+ return pd.DataFrame({
963
+ 'a': t['a'], 'b': t['b'], 'set_name': 'both', 'pair': [pair_name(x, y) for x, y in zip(t['a_label'], t['b_label'])],
964
+ 'category': np.where(t['prefers'] == B, more_in(B), np.where(t['prefers'] == A, more_in(A), 'No difference')),
965
+ 'diff': t['diff'], 'nlp': -np.log10(np.clip(t['p'].to_numpy(float), 1e-300, 1.0)), 'p': t['p'], 'q': t['q'],
966
+ 'pa': t[f'log2_or|{A}'], 'pb': t[f'log2_or|{B}'], 'sa': t[f'shared|{A}'], 'sb': t[f'shared|{B}'],
967
+ 'ra': t[f'n_regions|{A}'], 'rb': t[f'n_regions|{B}']}).reset_index(drop=True)
968
+
969
+
970
+ def _differential_tips(A: str, B: str) -> list:
971
+ return [alt.Tooltip('pair:N', title='pair'),
972
+ alt.Tooltip('sb:Q', title=f'{lab(B)}: regions with both'), alt.Tooltip('rb:Q', title=f'{lab(B)}: regions'),
973
+ alt.Tooltip('sa:Q', title=f'{lab(A)}: regions with both'), alt.Tooltip('ra:Q', title=f'{lab(A)}: regions'),
974
+ alt.Tooltip('pb:Q', title=f'{lab(B)}: log2 odds ratio', format='+.2f'),
975
+ alt.Tooltip('pa:Q', title=f'{lab(A)}: log2 odds ratio', format='+.2f'),
976
+ alt.Tooltip('diff:Q', title=f'difference, {lab(B)} − {lab(A)}', format='+.2f'),
977
+ alt.Tooltip('p:Q', title='p (Woolf)', format='.2g'), alt.Tooltip('q:Q', title='q (BH)', format='.2g')]
978
+
979
+
980
+ def _spread_labels(rows: pd.DataFrame, x: str, y: str, X: dict, Y: dict, right_of: float, span: float, height: int):
981
+ """
982
+ Pair names next to their dots (to the right in the left part of the plot, to the left past `right_of`), each a
983
+ line lower than the one above it where they would overlap, with a thin line back to a moved dot and a white halo
984
+ over the other dots. span: the y axis range, height: its pixels.
985
+ """
986
+ if rows.empty:
987
+ return []
988
+ step = 15 / height * span
989
+ rows = rows.sort_values(y, ascending=False).copy()
990
+ at, last = [], None
991
+ for v in rows[y]:
992
+ last = v if last is None else min(v, last - step)
993
+ at.append(last)
994
+ rows['label_y'] = at
995
+ layers = [alt.Chart(rows).mark_rule(color='#9e9e9e', strokeWidth=0.6).encode(
996
+ x=alt.X(f'{x}:Q', **X), y=alt.Y(f'{y}:Q', **Y), y2='label_y:Q')]
997
+ for part, align, dx in ((rows[rows[x] <= right_of], 'left', 7), (rows[rows[x] > right_of], 'right', -7)):
998
+ if len(part):
999
+ enc = dict(x=alt.X(f'{x}:Q', **X), y=alt.Y('label_y:Q', **Y), text='pair:N')
1000
+ layers += [alt.Chart(part).mark_text(align=align, baseline='middle', dx=dx, fontSize=11, stroke='white',
1001
+ strokeWidth=3, strokeOpacity=0.9).encode(**enc),
1002
+ alt.Chart(part).mark_text(align=align, baseline='middle', dx=dx, fontSize=11).encode(**enc)]
1003
+ return layers
1004
+
1005
+
1006
+ def _differential_marks(pts: pd.DataFrame, A: str, B: str, x: str, y: str, X: dict, Y: dict):
1007
+ """The pairs as dots coloured by the class they are more together in (grey: no difference), the clicked one opened."""
1008
+ domain = [more_in(B), more_in(A), 'No difference']
1009
+ pick = alt.selection_point(fields=['a', 'b', 'set_name'], name='pick', on='click')
1010
+ return alt.Chart(pts).mark_circle(stroke='black', strokeWidth=0.3).encode(
1011
+ x=alt.X(f'{x}:Q', **X), y=alt.Y(f'{y}:Q', **Y),
1012
+ color=alt.Color('category:N', title=None, legend=alt.Legend(orient='bottom'),
1013
+ scale=alt.Scale(domain=domain, range=[set_color(B), set_color(A), CHANCE_C])),
1014
+ size=alt.condition(alt.datum.category == 'No difference', alt.value(30), alt.value(90)),
1015
+ order=alt.Order('nlp:Q'), opacity=alt.condition(pick, alt.value(1.0), alt.value(0.85)),
1016
+ tooltip=_differential_tips(A, B)).add_params(pick)
1017
+
1018
+
1019
+ def pairing_chart(pts: pd.DataFrame, A: str, B: str):
1020
+ """The compared pairs in each class against chance, A (x) against B (y); on the dashed diagonal, the same in both."""
1021
+ lim = max(1.0, float(np.nanmax(np.abs(pts[['pa', 'pb']].to_numpy(float))))) * 1.12
1022
+ sc = alt.Scale(domain=[-lim, lim], nice=False)
1023
+ X = dict(scale=sc, title=f'{lab(A)}: log2 odds ratio')
1024
+ Y = dict(scale=sc, title=f'{lab(B)}: log2 odds ratio')
1025
+ zero = pd.DataFrame({'v': [0.0]})
1026
+ layers = [alt.Chart(zero).mark_rule(color='#d9d9d9').encode(x=alt.X('v:Q', **X)),
1027
+ alt.Chart(zero).mark_rule(color='#d9d9d9').encode(y=alt.Y('v:Q', **Y)),
1028
+ alt.Chart(pd.DataFrame({'v': [-lim, lim]})).mark_line(color='#888888', strokeDash=[4, 3]).encode(
1029
+ x=alt.X('v:Q', **X), y=alt.Y('v:Q', **Y)),
1030
+ _differential_marks(pts, A, B, 'pa', 'pb', X, Y)]
1031
+ named = pts[pts['category'] != 'No difference'].nlargest(8, 'nlp')
1032
+ return (alt.layer(*layers, *_spread_labels(named, 'pa', 'pb', X, Y, lim / 3, 2 * lim, 340))
1033
+ .properties(title='Each class against chance', height=340)
1034
+ .configure_axis(grid=False).configure_view(strokeWidth=0))
1035
+
1036
+
1037
+ def contingency_view(level: str, x: str, y: str):
1038
+ """The picked pair's 2x2 table per class, read from motif x: of the regions with x and of those without it, the share carrying y."""
1039
+ ct = V.pair_contingency(an, level, x, y, motif_source(level))
1040
+ if ct.empty:
1041
+ return
1042
+ labels = V.motif_labels(an, level).drop_duplicates('key').set_index('key')['label']
1043
+ xl, yl = labels.get(x, x), labels.get(y, y)
1044
+ rows = []
1045
+ for r in ct.itertuples():
1046
+ for grp, k, n in ((f'with {xl}', r.both, r.both + r.x_only), (f'without {xl}', r.y_only, r.y_only + r.neither)):
1047
+ rows.append({'set': lab(r.set_name), 'set_name': r.set_name, 'row': f'{lab(r.set_name)}, {grp}', 'has_x': grp.startswith('with '),
1048
+ 'pct': 100 * k / n if n else np.nan, 'text': f'{int(k)} of {int(n)}'})
1049
+ d = pd.DataFrame(rows)
1050
+ order = d['row'].tolist()
1051
+ sets_ = [lab(s) for s in d['set_name'].unique()]
1052
+ yax = alt.Y('row:N', sort=order, title=None, axis=alt.Axis(labelLimit=260))
1053
+ xt = f'Regions also carrying {yl} (%)'
1054
+ tips = [alt.Tooltip('row:N', title='regions'), alt.Tooltip('text:N', title=f'carrying {yl}'), alt.Tooltip('pct:Q', title='%', format='.1f')]
1055
+ bars = alt.Chart(d).mark_bar().encode(
1056
+ y=yax, x=alt.X('pct:Q', title=xt),
1057
+ color=alt.Color('set:N', title=None, legend=None, scale=alt.Scale(domain=sets_, range=[set_color(s) for s in d['set_name'].unique()])),
1058
+ opacity=alt.condition(alt.datum.has_x, alt.value(0.95), alt.value(0.45)), tooltip=tips)
1059
+ text = alt.Chart(d).mark_text(align='left', dx=6, fontSize=10, color='#444444').encode(
1060
+ y=yax, x=alt.X('pct:Q', title=xt), text='text:N')
1061
+ left, right = st.columns([3, 2])
1062
+ with left:
1063
+ st.altair_chart((bars + text).properties(height=34 * len(d)), width='stretch')
1064
+ st.caption(f'Of the regions of each class with {xl}, and of those without it, the share that also carry {yl}. The odds '
1065
+ 'ratio compares the two bars of a class; the test above asks whether it is the same in both classes.')
1066
+ with right:
1067
+ st.dataframe(ct.assign(set_name=ct['set_name'].map(lab))[['set_name', 'both', 'x_only', 'y_only', 'neither', 'log2_or']],
1068
+ hide_index=True, column_config={
1069
+ 'set_name': 'Class', 'both': 'Both', 'x_only': f'{xl} only', 'y_only': f'{yl} only', 'neither': 'Neither',
1070
+ 'log2_or': st.column_config.NumberColumn('log2 odds ratio', format='%+.2f')})
1071
+
1072
+
1073
+ def differential_summary(d: pd.DataFrame, hits: pd.DataFrame, A: str, B: str) -> str:
1074
+ """What the comparison of the classes found, in words: how many pairs differ, the motifs they share, what was left out."""
1075
+ t = d[d['tested']]
1076
+ n_t = len(t)
1077
+ if hits.empty:
1078
+ text = (f'**No pair differs** between {lab(B)} and {lab(A)} at q ≤ {ALPHA:g}, of the {n_t} pairs compared. '
1079
+ f'{int((t["p"] < 0.05).sum())} have p < 0.05, where noise alone would give about {0.05 * n_t:.0f}.')
1080
+ else:
1081
+ n_b, n_a = int((hits['prefers'] == B).sum()), int((hits['prefers'] == A).sum())
1082
+ text = (f'**{len(hits)} of the {n_t} pairs compared differ** at q ≤ {ALPHA:g}: {n_b} more together in {lab(B)}, '
1083
+ f'{n_a} in {lab(A)}.')
1084
+ hubs = pd.Series(list(hits['a_label']) + list(hits['b_label'])).value_counts()
1085
+ hubs = hubs[hubs > 1]
1086
+ if len(hubs):
1087
+ text += (' Pairs that share a motif are not separate findings: ' +
1088
+ ', '.join(f'{k} is in {v}' for k, v in hubs.items()) + '.')
1089
+ return text + (f' {len(d) - n_t} more pairs have both motifs in both classes but are too rare in one to compare '
1090
+ f'(a cell of its 2×2 table expected below {d.attrs["min_expected"]:g} regions).')
1091
+
1092
+
1093
+ def motifs_per_region(level: str, src: str) -> dict:
1094
+ """Per class, how many motifs a region of its 2x2 tables carries on average (a region with none counts as 0)."""
1095
+ sites, n = V.motif_sites(an, level, src), V.class_regions(an)
1096
+ if sites.empty or not n:
1097
+ return {}
1098
+ per = sites.groupby(['set_name', 'coord'])['key'].nunique().groupby('set_name').sum()
1099
+ return {s_: float(per.get(s_, 0)) / n[s_] for s_ in n if n[s_]}
1100
+
1101
+
1102
+ def differential_section(level: str, keys_now: dict, src: str) -> bool:
1103
+ """
1104
+ For two classes, which pairs differ between them (pair_differential): in words, every compared pair as a volcano and
1105
+ in each class against chance, then the pairs that differ in one list; how it is tested folded away. A row or a click
1106
+ opens the pair below (take_picks). False when the run has no two classes to compare.
1107
+ """
1108
+ d = V.pair_differential(an, level, src)
1109
+ if d.empty:
1110
+ return False
1111
+ A, B = d.attrs['sets']
1112
+ t, hits = d[d['tested']], differing_pairs(level)
1113
+ st.markdown(f'#### Which pairs differ between {lab(B)} and {lab(A)}')
1114
+ st.markdown(differential_summary(d, hits, A, B))
1115
+ busy = motifs_per_region(level, src)
1116
+ if A in busy and B in busy:
1117
+ st.caption(f'A {lab(B)} region carries {busy[B]:.2f} motifs on average, a {lab(A)} region {busy[A]:.2f}. Odds ratios '
1118
+ 'grow with the motifs a region holds, so read a difference against that (How this is tested, below).')
1119
+ if t.empty:
1120
+ st.info('No pair has both motifs common enough in both classes to compare.')
1121
+ return True
1122
+ left, right = st.columns([3, 2])
1123
+ with left:
1124
+ show(figure('differential_volcano', config, level, (set_color(A), set_color(B)), src))
1125
+ st.caption(f'Each dot is one of the {len(t)} pairs compared: how much larger its odds ratio is in {lab(B)} than in '
1126
+ f'{lab(A)} (x), and how surely (y).')
1127
+ with right:
1128
+ st.altair_chart(pairing_chart(differential_points(d, A, B), A, B), key=keys_now['pairing'], on_select='rerun',
1129
+ selection_mode='pick', width='stretch')
1130
+ st.caption(f'The same pairs, each class against chance: on the dashed diagonal the odds ratio is the same in both, '
1131
+ f'above it larger in {lab(B)}. Hover for the counts, click to open the pair below.')
1132
+ if len(hits):
1133
+ view = hits.assign(pair=[pair_name(x, y) for x, y in zip(hits['a_label'], hits['b_label'])],
1134
+ more=hits['prefers'].map(lab))
1135
+ cols_ = ['pair', 'more', f'shared|{B}', f'n_regions|{B}', f'shared|{A}', f'n_regions|{A}', f'log2_or|{B}',
1136
+ f'log2_or|{A}', 'diff', 'p', 'q']
1137
+ cfg = {'pair': 'Pair', 'more': 'More together in', 'diff': st.column_config.NumberColumn('Difference', format='%+.2f'),
1138
+ 'p': st.column_config.NumberColumn('p (Woolf)', format='%.1e'), 'q': st.column_config.NumberColumn('q', format='%.2g')}
1139
+ for s_ in (B, A):
1140
+ cfg.update({f'shared|{s_}': f'{lab(s_)}: with both', f'n_regions|{s_}': f'{lab(s_)}: regions',
1141
+ f'log2_or|{s_}': st.column_config.NumberColumn(f'{lab(s_)}: log2 odds ratio', format='%+.2f')})
1142
+ st.dataframe(view[cols_], key=differing_key(level), on_select='rerun', selection_mode='single-row', hide_index=True,
1143
+ height=min(400, 38 + 35 * len(view)), column_config=cfg)
1144
+ st.caption(f'The pairs that differ, by p. Difference: {lab(B)} minus {lab(A)}, in log2 odds ratio. Select a row to '
1145
+ 'open the pair below.')
1146
+ with st.expander('How this is tested'):
1147
+ st.markdown("Each class's regions as a 2×2 table per pair of motifs: with both, with one only, with neither" +
1148
+ (', where every attributed region counts, also one where no motif was found' if d.attrs.get('all_regions') else '') +
1149
+ '. Its odds ratio is the odds that a region with one motif carries the other, over the odds for a region '
1150
+ 'without it (0.5 added to every cell). A pair differs when its odds ratio differs between the two tables: '
1151
+ "Woolf's test, BH over the pairs compared, those whose every cell is expected to hold at least "
1152
+ f"{d.attrs['min_expected']:g} regions in both classes.\n\n"
1153
+ 'Two limits. An odds ratio of regions also follows how many motifs a region holds: regions with more '
1154
+ 'motifs hold more pairs, so classes that differ in that differ in their odds ratios without any pairing '
1155
+ '(on simulated runs without pairing, 42 to 56% of the pairs compared had p < 0.05 when the classes '
1156
+ 'differed in it, 4 to 5% when they matched). And the classes were chosen by the differential the motifs '
1157
+ 'drive, so two motifs that each already make a region one class cannot show more of it together. The '
1158
+ 'pair regression (Pair effects page) has neither limit.')
1159
+ return True
1160
+
1161
+
1162
+ def within_section(level: str, ps: pd.DataFrame, sets: list, min_shared: int, keys_now: dict, src: str):
1163
+ """
1164
+ Each class on its own (pair_stats): what the test found, one line per class; every pair's observed against expected
1165
+ regions, one chart per class; the pairs that pass in one list; how it is tested, with the spread of its p-values
1166
+ against noise alone, folded away. A click or a row opens the pair below (take_picks).
1167
+ """
1168
+ st.markdown('#### Which motifs are used together, within each class')
1169
+ sm = V.cooc_summary(an, level, source=src).set_index('set_name')
1170
+ lines = [f'**{lab(s_)}**: ' + (f'{int(sm.loc[s_, "n_pass"])} pair passes' if int(sm.loc[s_, 'n_pass']) == 1 else
1171
+ f'{int(sm.loc[s_, "n_pass"])} pairs pass' if int(sm.loc[s_, 'n_pass']) else 'no pair passes') +
1172
+ f' of {int(sm.loc[s_, "n_tested"]):,} tested' for s_ in sets if s_ in sm.index]
1173
+ st.markdown('; '.join(lines) + f' (motifs from {SOURCE_NAMES[src].lower()}).')
1174
+ cols = st.columns(len(sets)) if len(sets) <= 3 else [st.container() for _ in sets]
1175
+ for col, s_ in zip(cols, sets):
1176
+ d = ps[(ps['set_name'] == s_) & ((ps['shared'] >= min_shared) | (ps['expected'] >= min_shared))]
1177
+ with col:
1178
+ if d.empty:
1179
+ st.caption(f'{lab(s_)}: no pair shares, or is expected to share, {min_shared} regions or more.')
1180
+ else:
1181
+ st.altair_chart(obs_exp_chart(d, s_), key=keys_now[f'obs|{s_}'], on_select='rerun',
1182
+ selection_mode='pick', width='stretch')
1183
+ st.caption('Each dot is a pair of motifs in one class: above the dashed line, more regions carry both than chance '
1184
+ f'predicts. Click one to open it below. Shown: pairs sharing or expected to share at least {min_shared} '
1185
+ f'regions. Diamonds: in the median region the two sites are at most {V.GAP_ADJACENT} bp apart, which may '
1186
+ 'be one composite or extended site split in two rather than two motifs.' +
1187
+ (" '(repeats)': in most regions with both, both sites lie in soft-masked repeats, so the pair may be one "
1188
+ 'repeat element copied around the genome.' if ps['repeat_share'].notna().any() else ''))
1189
+ sig = V.significant_pairs(an, level, src)
1190
+ if len(sig):
1191
+ view = sig.assign(set=sig['set_name'].map(lab), pair=[pair_name(x, y) for x, y in zip(sig['a_label'], sig['b_label'])])
1192
+ st.dataframe(view[['set', 'pair', 'shared', 'expected', 'obs_exp', 'p', 'q', 'found_by', 'median_gap']],
1193
+ key=passing_key(level), on_select='rerun', selection_mode='single-row', hide_index=True,
1194
+ height=min(400, 38 + 35 * len(view)),
1195
+ column_config={'set': 'Class', 'pair': 'Pair', 'shared': 'Regions with both',
1196
+ 'expected': st.column_config.NumberColumn('Expected', format='%.1f'),
1197
+ 'obs_exp': st.column_config.NumberColumn('Observed / expected', format='%.2f'),
1198
+ 'p': st.column_config.NumberColumn('p (permutation)', format='%.1e'),
1199
+ 'q': st.column_config.NumberColumn('q', format='%.2g'),
1200
+ 'found_by': st.column_config.TextColumn('In the partners of',
1201
+ help='the motif, or both, whose list keeps the pair'),
1202
+ 'median_gap': st.column_config.NumberColumn('Median gap (bp)', format='%.0f')})
1203
+ st.caption('The pairs that pass, by q, then by how far from chance. Select a row to open the pair below.')
1204
+ with st.expander('How this is tested'):
1205
+ st.markdown(cooc_method(src) + " 'As chance' can also mean too few regions to tell.")
1206
+ for s_ in sets:
1207
+ if s_ not in sm.index:
1208
+ continue
1209
+ r = sm.loc[s_]
1210
+ st.markdown(f'**{lab(s_)}**: {int(r["n_left_out"])} more pairs are expected in fewer than {r["min_expected"]:g} '
1211
+ f'region(s) and are not tested. {int(r["n_p05"])} tested '
1212
+ f'{"pair has" if int(r["n_p05"]) == 1 else "pairs have"} p < 0.05, where noise alone would give about '
1213
+ f'{r["p05_by_chance"]:.0f}. {int(r["n_selected"])} of {int(r["n_motifs"])} motifs pass the first '
1214
+ 'stage.' + (f' p below {r["p_floor"]:.0e} cannot be told apart with {int(r["n_perm"]):,} shuffles '
1215
+ '([cooccurrence] max_permutations).' if r['n_perm'] < r['n_perm_needed'] else ''))
1216
+ shown = [s_ for s_ in sets if s_ in sm.index and sm.loc[s_, 'n_tested'] > 0]
1217
+ charts = []
1218
+ for s_ in shown:
1219
+ h = ps[(ps['set_name'] == s_) & ps['tested'].astype(bool)]
1220
+ bars = alt.Chart(h).mark_bar(color=set_color(s_), opacity=0.85).encode(
1221
+ x=alt.X('p:Q', bin=alt.Bin(extent=[0, 1], step=0.05), title='p of the tested pairs'),
1222
+ y=alt.Y('count():Q', title='Pairs'))
1223
+ even = alt.Chart(pd.DataFrame({'n': [len(h) / 20]})).mark_rule(
1224
+ color='#888888', strokeDash=[4, 3], strokeWidth=1.2).encode(y='n:Q')
1225
+ charts.append(alt.layer(bars, even).properties(title=lab(s_), height=110))
1226
+ for col, chart in zip(st.columns(max(len(charts), 1)), charts):
1227
+ col.altair_chart(chart, width='stretch')
1228
+ if charts:
1229
+ st.caption('Under noise alone the p-values spread evenly, at the dashed line; pairs that really co-occur more '
1230
+ 'or less often than chance pile up at the left. The permutation p is a little conservative, so bars '
1231
+ 'sit slightly below the line without signal.')
1232
+
1233
+
1234
+ def regression_section() -> bool:
1235
+ """
1236
+ The pair-regression step, when the run has it: which pairs change the measured B - A differential over every region
1237
+ of its table, not only the attributed ones; in words, the list of pairs that pass and the volcano. A row opens the
1238
+ pair on the Co-occurrence page (take_regression_pick). False when the run has none.
1239
+ """
1240
+ has = regression_sources()
1241
+ if not has:
1242
+ return False
1243
+ A, B = an.label_a, an.label_b
1244
+ st.markdown(f'#### Which pairs change the measured {B} \u2212 {A} differential')
1245
+ if len(has) > 1:
1246
+ st.radio('Motifs from', has, horizontal=True, key='regression_source', format_func=SOURCE_NAMES.get,
1247
+ help='Scanning covers every region of the step\'s table; seqlets only the attributed regions, which were '
1248
+ 'chosen by the differential.')
1249
+ src = regression_source()
1250
+ d = V.pair_regression(an, src)
1251
+ info = d.attrs
1252
+ alpha = float(info.get('alpha', 0.05))
1253
+ hits = regression_pairs(src)
1254
+ n_b, n_a = int((hits['pair'] > 0).sum()), int((hits['pair'] < 0).sum())
1255
+ n_c = int((d['q_cond'] <= alpha).sum()) if 'q_cond' in d else 0
1256
+ st.markdown(f'**{len(hits)} of {len(d):,} pairs change it** at q \u2264 {alpha:g}: {n_b} towards {B}, {n_a} towards '
1257
+ f'{A}; {n_c} still pass with the other pairs in the model.' if len(hits) else
1258
+ f'**No pair changes it** at q \u2264 {alpha:g}, of {len(d):,} pairs.')
1259
+ if len(hits):
1260
+ view = hits.assign(pair_name=[pair_name(x, y) for x, y in zip(hits['a_label'], hits['b_label'])],
1261
+ towards=np.where(hits['pair'] > 0, B, A))
1262
+ cols_ = ['pair_name', 'towards', 'both', 'pair', 'q', 'pair_cond', 'q_cond', 'close', 'n_close', 'far', 'n_far']
1263
+ cfg = {'pair_name': 'Pair', 'towards': 'Towards', 'both': 'Regions with both',
1264
+ 'pair': st.column_config.NumberColumn('Pair term', format='%+.3f'),
1265
+ 'q': st.column_config.NumberColumn('q', format='%.2g'),
1266
+ 'pair_cond': st.column_config.NumberColumn('Second pass', format='%+.3f'),
1267
+ 'q_cond': st.column_config.NumberColumn('q, second pass', format='%.2g'),
1268
+ 'close': st.column_config.NumberColumn('Close', format='%+.3f'), 'n_close': 'Close regions',
1269
+ 'far': st.column_config.NumberColumn('Far', format='%+.3f'), 'n_far': 'Far regions'}
1270
+ st.dataframe(view[[c for c in cols_ if c in view]], hide_index=True, height=min(400, 38 + 35 * len(view)),
1271
+ column_config=cfg)
1272
+ st.caption(f'By p. Terms in log2 fold change, {B} over {A}.')
1273
+ fig_col, _ = st.columns([5, 2])
1274
+ with fig_col:
1275
+ show(figure('pair_regression_volcano', config, (ca, cb), src))
1276
+ with st.expander('How this is computed'):
1277
+ where = (f"all {int(info.get('regions', 0)):,} regions of its table, differential or not, motifs by scanning with "
1278
+ 'JASPAR matrices' if src == 'scan' else
1279
+ f"the {int(info.get('regions', 0)):,} attributed regions, motifs from their seqlets; those regions were "
1280
+ 'chosen by the differential, so set this beside the scan')
1281
+ st.markdown(f"From `diffgrammar pair-regression`, over {where}: the measured log2 fold change ({B} over {A}) on "
1282
+ "every motif family's presence, the motif count and GC, plus one pair at a time. Pair term: what "
1283
+ 'carrying both adds beyond the two motifs and every other family. Weighted by the fold changes\' '
1284
+ f"standard errors, errors clustered by {int(info.get('block', 1e6)):,} bp "
1285
+ f"({int(info.get('blocks', 0)):,} blocks), BH over the pairs. Close and far: the two sites within "
1286
+ f"{int(info.get('close', 16))} bp, or farther. Second pass: each pair refitted with the other pairs that "
1287
+ 'pass; it can also split one signal between two families whose matrices hit the same sites.')
1288
+ with st.expander('Every pair of the regression as a table'):
1289
+ st.dataframe(d.assign(pair_name=[pair_name(x, y) for x, y in zip(d['a_label'], d['b_label'])])
1290
+ .drop(columns=['a', 'b', 'a_label', 'b_label']), hide_index=True, height=320)
1291
+ return True
1292
+
1293
+
1294
+ def pair_effects_page():
1295
+ """
1296
+ Whether a pair changes the outcome: in the data (the pair regression, over every region with a measured fold
1297
+ change) and in the model (the marginalization). Shown when the run has either.
1298
+ """
1299
+ shown = regression_section()
1300
+ if V.coop_dir(an) is not None:
1301
+ if shown:
1302
+ st.divider()
1303
+ pairs_page()
1304
+
1305
+
1306
+ def reset_pairs():
1307
+ for k in list(st.session_state):
1308
+ if k in ('x_key', 'examples_class', 'forced_partner', 'picked_pair') or str(k).startswith('partner_'):
1309
+ del st.session_state[k]
1310
+
1311
+
1312
+ def partner_table(level, x, partners, classes, lo, hi):
1313
+ """pair_region_table rows of every (class, partner) with the partner name, the class label and the pair id."""
1314
+ labels = V.motif_labels(an, level).drop_duplicates('key').set_index('key')['label']
1315
+ frames = []
1316
+ for pkey in partners:
1317
+ for s in classes:
1318
+ t = V.pair_region_table(an, level, s, x, 'alone', None, hi) if pkey == 'alone' else \
1319
+ V.pair_region_table(an, level, s, x, pkey, lo, hi)
1320
+ if len(t):
1321
+ frames.append(t.assign(partner=pkey, partner_label='alone' if pkey == 'alone' else labels.get(pkey, pkey),
1322
+ set_label=lab(s)))
1323
+ return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
1324
+
1325
+
1326
+ # -- co-occurrence on one set of tables: counts and Fisher per class, Woolf between them ------------------------------
1327
+ COUNT_SOURCES = {'seqlets': 'Seqlets, sign considered', 'scan': 'Scanning the sequence'}
1328
+ STRIP = (-2.1, -1.1) # the family strips sit left of the rows and above the columns, in cell units
1329
+ SINGLE_FAMILY = 'one motif of its family here'
1330
+
1331
+
1332
+ def _cell_px(n: int, panels: int) -> int:
1333
+ """Pixels per motif, so that the panels, the row names and the legends fit about 1,500 px."""
1334
+ return int(max(8, min(16, (1100 / panels) / (n + 1.8))))
1335
+
1336
+
1337
+ def _axes(labels: list, cell: int, show_y: bool):
1338
+ """The x and y encodings every layer of a heatmap shares: motif i at i, its strip at STRIP, its name as the label."""
1339
+ n, size = len(labels), max(8, min(11, cell - 2))
1340
+ names = json.dumps(labels)
1341
+ dom = [STRIP[0] - 0.2, n - 0.5]
1342
+ x = alt.X('x0:Q', scale=alt.Scale(domain=dom, nice=False, zero=False), title=None,
1343
+ axis=alt.Axis(values=list(range(n)), labelExpr=f'{names}[datum.value]', labelAngle=-90, labelAlign='right',
1344
+ labelBaseline='middle',
1345
+ labelFontSize=size, labelLimit=260, grid=False, ticks=False, domain=False, labelOverlap=False))
1346
+ y = alt.Y('y0:Q', scale=alt.Scale(domain=dom, nice=False, zero=False, reverse=True), title=None,
1347
+ axis=alt.Axis(values=list(range(n)), labelExpr=f'{names}[datum.value]', labelFontSize=size, labelLimit=320,
1348
+ grid=False, ticks=False, domain=False, labelOverlap=False) if show_y else None)
1349
+ return x, y, dom
1350
+
1351
+
1352
+ def _strips(c: dict, x, y, legend: bool):
1353
+ """The motifs' families as colour strips left of the rows and above the columns; grey for a family with one motif."""
1354
+ fams = c['families']
1355
+ multi = [g for g in dict.fromkeys(fams) if fams.count(g) > 1]
1356
+ col = dict(zip(multi, family_colors(len(multi))))
1357
+ rows = []
1358
+ for i, (name, f) in enumerate(zip(c['labels'], fams)):
1359
+ cat = f if f in col else SINGLE_FAMILY
1360
+ rows += [{'x0': STRIP[0], 'x1': STRIP[1], 'y0': i - .5, 'y1': i + .5, 'motif': name, 'family': f, 'cat': cat},
1361
+ {'x0': i - .5, 'x1': i + .5, 'y0': STRIP[0], 'y1': STRIP[1], 'motif': name, 'family': f, 'cat': cat}]
1362
+ domain = multi + ([SINGLE_FAMILY] if len(multi) < len(set(fams)) else [])
1363
+ return alt.Chart(pd.DataFrame(rows)).mark_rect(stroke='white', strokeWidth=0.5).encode(
1364
+ x=x, x2='x1', y=y, y2='y1',
1365
+ color=alt.Color('cat:N', scale=alt.Scale(domain=domain, range=[col.get(g, SINGLE_FAMILY_C) for g in domain]),
1366
+ legend=alt.Legend(title='Family', orient='right', symbolType='square') if legend else None),
1367
+ tooltip=[alt.Tooltip('motif:N', title='motif'), alt.Tooltip('family:N', title='family')])
1368
+
1369
+
1370
+ def _pair_rows(c: dict, k: int) -> pd.DataFrame:
1371
+ """Every cell of class k's heatmap: the pair's counts, its expectation under independence and its Fisher test."""
1372
+ p_, labels = c['panels'][k], c['labels']
1373
+ w, rows = p_['with'], []
1374
+ for i in range(len(labels)):
1375
+ for j in range(len(labels)):
1376
+ q_ = p_['q'][i, j]
1377
+ look = ('the motif itself' if i == j else 'not tested (absent from the class)' if not np.isfinite(q_) else
1378
+ 'more often together than independence' if p_['sig'][i, j] > 0 else
1379
+ 'less often together than independence' if p_['sig'][i, j] < 0 else 'as independence')
1380
+ rows.append({'x0': j - .5, 'x1': j + .5, 'y0': i - .5, 'y1': i + .5, 'xc': j, 'yc': i, 'diag': i == j,
1381
+ 'pair': labels[i] if i == j else f'{labels[i]} & {labels[j]}', 'both': int(p_['both'][i, j]),
1382
+ 'a': int(w[i]), 'b': int(w[j]), 'expected': p_['expected'][i, j], 'log2_or': p_['log2_or'][i, j],
1383
+ 'p': p_['p'][i, j], 'q': q_, 'sig': int(p_['sig'][i, j]), 'look': look})
1384
+ return pd.DataFrame(rows)
1385
+
1386
+
1387
+ def counts_chart(c: dict):
1388
+ """
1389
+ One panel per class: each motif's regions as bars, the regions carrying both motifs as a heatmap on one scale for
1390
+ every class, dots where a pair is more often together than independence and rings where less (Fisher, q < alpha).
1391
+ """
1392
+ n, k_p = len(c['labels']), len(c['panels'])
1393
+ cell = _cell_px(n, k_p)
1394
+ vmax = max(1, max(int(np.max(p_['both'])) for p_ in c['panels']))
1395
+ width = int(cell * (n + 1.8))
1396
+ panels = []
1397
+ for k, p_ in enumerate(c['panels']):
1398
+ s_, color = p_['set_name'], set_color(p_['set_name'])
1399
+ x, y, dom = _axes(c['labels'], cell, show_y=k == 0)
1400
+ d = _pair_rows(c, k)
1401
+ tips = [alt.Tooltip('pair:N', title='pair'), alt.Tooltip('both:Q', title='regions carrying both'),
1402
+ alt.Tooltip('a:Q', title='regions carrying the first'), alt.Tooltip('b:Q', title='regions carrying the second'),
1403
+ alt.Tooltip('expected:Q', title='expected under independence', format='.1f'),
1404
+ alt.Tooltip('log2_or:Q', title='log2 odds ratio', format='+.2f'), alt.Tooltip('p:Q', title='p (Fisher)', format='.2g'),
1405
+ alt.Tooltip('q:Q', title='q (BH)', format='.2g'), alt.Tooltip('look:N', title='test')]
1406
+ cells = alt.Chart(d[~d['diag']]).mark_rect(stroke='white', strokeWidth=0.4).encode(
1407
+ x=x, x2='x1', y=y, y2='y1', tooltip=tips,
1408
+ color=alt.Color('both:Q', scale=alt.Scale(type='pow', exponent=0.45, domain=[0, vmax], scheme='yellowgreenblue'),
1409
+ legend=alt.Legend(title='regions carrying both', orient='right', gradientLength=140)
1410
+ if k == k_p - 1 else None))
1411
+ diag = alt.Chart(d[d['diag']]).mark_rect(color='#d8d8d8', stroke='white', strokeWidth=0.4).encode(
1412
+ x=x, x2='x1', y=y, y2='y1', tooltip=[alt.Tooltip('pair:N', title='motif'), alt.Tooltip('a:Q', title='regions carrying it')])
1413
+ dots = d.assign(x0=d['xc'], y0=d['yc']) # at the cell centres, on the axes the cells use
1414
+ over = alt.Chart(dots[dots['sig'] > 0]).mark_circle(color='#16222B', size=max(10, cell * 1.4), opacity=1).encode(
1415
+ x=x, y=y, tooltip=tips)
1416
+ under = alt.Chart(dots[dots['sig'] < 0]).mark_point(color='#16222B', size=max(10, cell * 1.4), strokeWidth=1).encode(
1417
+ x=x, y=y, tooltip=tips)
1418
+ last = k == k_p - 1
1419
+ heat = alt.layer(_strips(c, x, y, legend=last), cells, diag, over, under).resolve_scale(color='independent')
1420
+ heat = heat.properties(width=width, height=width)
1421
+ b = pd.DataFrame({'x0': np.arange(n) - .36, 'x1': np.arange(n) + .36, 'xc': np.arange(n), 'n': p_['with'],
1422
+ 'motif': c['labels']})
1423
+ bx = alt.X('x0:Q', scale=alt.Scale(domain=dom, nice=False, zero=False), axis=None)
1424
+ bars = alt.Chart(b).mark_rect(color=color).encode(
1425
+ x=bx, x2='x1', y2=alt.datum(0),
1426
+ y=alt.Y('n:Q', title='regions with motif', axis=alt.Axis(titleColor=color, grid=False, tickCount=3)),
1427
+ tooltip=[alt.Tooltip('motif:N', title='motif'), alt.Tooltip('n:Q', title='regions carrying it')])
1428
+ nums = alt.Chart(b).mark_text(angle=270, align='left', baseline='middle', dx=3, fontSize=max(7, cell - 8),
1429
+ fontWeight='bold', color=color).encode(
1430
+ x=alt.X('xc:Q', scale=alt.Scale(domain=dom, nice=False, zero=False), axis=None), y='n:Q', text='n:Q')
1431
+ top = alt.layer(bars, nums).properties(width=width, height=90,
1432
+ title=alt.Title(f"{lab(s_)} ({p_['regions']:,} regions)", color=color, fontSize=15))
1433
+ panels.append(alt.vconcat(top, heat, spacing=4, bounds='flush'))
1434
+ return (alt.hconcat(*panels, spacing=36).configure_view(strokeWidth=0)
1435
+ .properties(autosize=alt.AutoSizeParams(type='pad', contains='padding')))
1436
+
1437
+
1438
+ def woolf_chart(c: dict):
1439
+ """
1440
+ Woolf's test on the tables of counts_chart: per pair, how much larger its odds ratio is in B than in A (log2), from
1441
+ A's colour to B's; outlined where the classes differ (q < alpha); grey where a table is too thin to compare.
1442
+ """
1443
+ w, n = c['woolf'], len(c['labels'])
1444
+ A, B = w['sets']
1445
+ k_a, k_b = (next(k for k, p_ in enumerate(c['panels']) if p_['set_name'] == s_) for s_ in (A, B))
1446
+ pa, pb = c['panels'][k_a], c['panels'][k_b]
1447
+ cell = _cell_px(n, 2)
1448
+ x, y, dom = _axes(c['labels'], cell, show_y=True)
1449
+ rows = []
1450
+ for i in range(n):
1451
+ for j in range(n):
1452
+ if i == j:
1453
+ continue
1454
+ q_ = w['q'][i, j]
1455
+ look = ('too thin to compare' if not w['compared'][i, j] else
1456
+ f'more together in {lab(B)}' if q_ <= c['alpha'] and w['diff'][i, j] > 0 else
1457
+ f'more together in {lab(A)}' if q_ <= c['alpha'] else 'no difference')
1458
+ rows.append({'x0': j - .5, 'x1': j + .5, 'y0': i - .5, 'y1': i + .5, 'pair': f"{c['labels'][i]} & {c['labels'][j]}",
1459
+ 'diff': w['diff'][i, j], 'compared': bool(w['compared'][i, j]), 'p': w['p'][i, j], 'q': q_,
1460
+ 'look': look, 'sig': bool(w['compared'][i, j] and q_ <= c['alpha']),
1461
+ 'or_b': pb['log2_or'][i, j], 'or_a': pa['log2_or'][i, j],
1462
+ 'both_b': int(pb['both'][i, j]), 'both_a': int(pa['both'][i, j])})
1463
+ d = pd.DataFrame(rows)
1464
+ on = d[d['compared']]
1465
+ lim = float(max(1.0, np.nanmax(np.abs(on['diff'])) if len(on) else 1.0))
1466
+ tips = [alt.Tooltip('pair:N', title='pair'), alt.Tooltip('both_b:Q', title=f'{lab(B)}: regions carrying both'),
1467
+ alt.Tooltip('both_a:Q', title=f'{lab(A)}: regions carrying both'),
1468
+ alt.Tooltip('or_b:Q', title=f'{lab(B)}: log2 odds ratio', format='+.2f'),
1469
+ alt.Tooltip('or_a:Q', title=f'{lab(A)}: log2 odds ratio', format='+.2f'),
1470
+ alt.Tooltip('diff:Q', title=f'difference, {lab(B)} − {lab(A)}', format='+.2f'),
1471
+ alt.Tooltip('p:Q', title='p (Woolf)', format='.2g'), alt.Tooltip('q:Q', title='q (BH)', format='.2g'),
1472
+ alt.Tooltip('look:N', title='test')]
1473
+ grey = alt.Chart(d[~d['compared']]).mark_rect(color='#ededed', stroke='white', strokeWidth=0.4).encode(
1474
+ x=x, x2='x1', y=y, y2='y1', tooltip=tips)
1475
+ diag = alt.Chart(pd.DataFrame({'x0': np.arange(n) - .5, 'x1': np.arange(n) + .5, 'y0': np.arange(n) - .5,
1476
+ 'y1': np.arange(n) + .5})).mark_rect(color='#d8d8d8', stroke='white', strokeWidth=0.4).encode(
1477
+ x=x, x2='x1', y=y, y2='y1')
1478
+ cells = alt.Chart(on).mark_rect(stroke='white', strokeWidth=0.4).encode(
1479
+ x=x, x2='x1', y=y, y2='y1', tooltip=tips,
1480
+ color=alt.Color('diff:Q', scale=alt.Scale(domain=[-lim, 0, lim], range=[set_color(A), '#f7f7f7', set_color(B)]),
1481
+ legend=alt.Legend(title=['log2 odds ratio', f'{lab(B)} − {lab(A)}'], orient='right',
1482
+ gradientLength=140)))
1483
+ ring = alt.Chart(d[d['sig']]).mark_rect(fill=None, stroke='#16222B', strokeWidth=1.6).encode(x=x, x2='x1', y=y, y2='y1', tooltip=tips)
1484
+ width = int(cell * (n + 1.8))
1485
+ return (alt.layer(_strips(c, x, y, legend=False), grey, diag, cells, ring).resolve_scale(color='independent')
1486
+ .properties(width=width, height=width, autosize=alt.AutoSizeParams(type='pad', contains='padding'))
1487
+ .configure_view(strokeWidth=0))
1488
+
1489
+
1490
+ def counts_section(level: str):
1491
+ """How many regions carry each pair of motifs, before any test (figures.cooc_counts): from the seqlets, sign-matched."""
1492
+ st.markdown('#### How many regions carry both motifs')
1493
+ c = V.cooc_counts(an, level)
1494
+ got = rendered('cooc_counts', config, level, dpi=200, tight=True)
1495
+ if got is None:
1496
+ st.caption(f"Fewer than two motifs sit in more than {c['min_regions']:g} regions over the classes "
1497
+ '([cooccurrence] counts_min_regions).')
1498
+ return
1499
+ st.image(got[0], width='stretch')
1500
+ signed = [p_ for p_ in c['panels'] if p_['sign']]
1501
+ how = ('; '.join(f"{lab(p_['set_name'])} counts the seqlets stronger in "
1502
+ f"{an.label_b if p_['sign'] > 0 else an.label_a}" for p_ in signed) if signed else 'every seqlet counts')
1503
+ st.caption(f"From the seqlets, whatever “Motifs from” says: {how}, each genomic site once (a site that the inputs of "
1504
+ f"two neighbouring regions both saw counts for the nearer one). Motifs in more than {c['min_regions']:g} "
1505
+ 'regions over the classes. Bars: regions carrying each motif; cells: regions carrying both. Dots: Fisher’s '
1506
+ f"test per class, BH over its pairs, q < {c['alpha']:g}, more often together than independence; it does "
1507
+ 'not allow for regions that carry many motifs, as the test below does.')
1508
+
1509
+
1510
+ def pair_spacing(level: str, x: str, y, classes: list, labels: pd.Series):
1511
+ """Where the partner sits around the motif, per class: one distance per region, from the seqlets."""
1512
+ if y is None:
1513
+ st.caption('Pick a partner to see where it sits.')
1514
+ return
1515
+ t = partner_table(level, x, [y], classes, None, None)
1516
+ if not len(t):
1517
+ st.caption('No region carries both as seqlets, so there are no distances to show.')
1518
+ return
1519
+ summ = (t.groupby('set_label')
1520
+ .agg(regions=('coord', 'size'), median_distance=('distance', lambda v: float(np.median(np.abs(v)))),
1521
+ within_25bp=('distance', lambda v: float((v.abs() <= 25).mean())),
1522
+ downstream=('distance', lambda v: float((v > 0).mean()))).reset_index())
1523
+ left, right = st.columns([3, 2])
1524
+ with left:
1525
+ st.altair_chart(alt.Chart(t).mark_bar(opacity=0.75).encode(
1526
+ x=alt.X('distance:Q', bin=alt.Bin(step=10), title=f'{labels.get(y, y)} site centre − {labels.get(x, x)} site centre (bp)'),
1527
+ y=alt.Y('count():Q', title='Regions', stack=None),
1528
+ color=alt.Color('set_label:N', title=None, scale=alt.Scale(domain=[lab(s) for s in an.sets], range=[set_color(s) for s in an.sets])),
1529
+ tooltip=['set_label', 'count()']).properties(height=200), width='stretch')
1530
+ with right:
1531
+ st.dataframe(summ, hide_index=True, column_config={
1532
+ 'set_label': 'Class', 'regions': 'Regions',
1533
+ 'median_distance': st.column_config.NumberColumn('Median |distance| (bp)', format='%.0f'),
1534
+ 'within_25bp': st.column_config.ProgressColumn('Within 25 bp', min_value=0, max_value=1, format='percent'),
1535
+ 'downstream': st.column_config.ProgressColumn('Partner downstream', min_value=0, max_value=1, format='percent')})
1536
+ st.caption('One distance per region: the partner site nearest to the strongest site of the motif. A peak means a '
1537
+ 'preferred spacing; a side preference shows as an uneven split.')
1538
+
1539
+
1540
+ def pair_examples(level: str, x: str, y, classes: list, labels: pd.Series):
1541
+ """Example regions of the pair as attribution logos aligned on the motif's site, with the motif alone beside them."""
1542
+ e1, e2, e3, e4 = st.columns([2, 3, 2, 1], vertical_alignment='bottom')
1543
+ if st.session_state.get('examples_class', 'both') not in ['both'] + classes:
1544
+ st.session_state['examples_class'] = 'both'
1545
+ cls = e1.radio('Class', ['both'] + classes, horizontal=True, key='examples_class', format_func=lambda s: s if s == 'both' else lab(s))
1546
+ lo, hi = e2.slider('Partner within this distance (bp)', 0, 200, (0, 60), 5, key='examples_distance')
1547
+ with_alone = e3.checkbox(f'Also {labels.get(x, x)} with no other motif within {hi} bp', True, key='examples_alone')
1548
+ with e4.popover('Window and count'):
1549
+ width = int(st.number_input('Example window (bp)', 60, 2000, 300, 20, key='align_width'))
1550
+ n_ex = int(st.number_input('Examples per group', 1, 8, 2, key='n_examples'))
1551
+ skip = int(st.number_input('Skip the strongest', 0, 500, 0, 1, key='skip_examples',
1552
+ help='Examples are the regions with the strongest site of the motif; skip some to see others.'))
1553
+ groups = ([y] if y is not None else []) + (['alone'] if with_alone or y is None else [])
1554
+ sel_classes = classes if cls == 'both' else [cls]
1555
+ table = partner_table(level, x, groups, sel_classes, lo, hi)
1556
+ if not len(table):
1557
+ st.caption('No region matches: widen the distance range or change the class.')
1558
+ return
1559
+ items, missing, picked = [], 0, []
1560
+ for g in groups:
1561
+ rows = table[table['partner'] == g].sort_values('x_strength', ascending=False).iloc[skip:skip + n_ex]
1562
+ picked.append((g, rows))
1563
+ exs = {}
1564
+ for g, rows in picked:
1565
+ for r in rows.itertuples():
1566
+ try:
1567
+ exs[r.coord] = V.region(an, r.coord)
1568
+ except (KeyError, FileNotFoundError, StopIteration):
1569
+ missing += 1
1570
+ ymax = max(float(np.abs(np.concatenate(list(ex.tracks.values()))).max()) for ex in exs.values()) if exs else None
1571
+ for g, rows in picked:
1572
+ name = f'with no other motif within {hi} bp' if g == 'alone' else \
1573
+ f'with {labels.get(g, g)}' + (' (a second site)' if g == x else '') + f' within {lo} to {hi} bp'
1574
+ items.append((f'{labels.get(x, x)} {name}: {len(table[table["partner"] == g])} regions' +
1575
+ (f', showing {skip + 1} to {skip + len(rows)} by site strength' if len(rows) else ''), None, 0, 0))
1576
+ for r in rows.itertuples():
1577
+ if r.coord not in exs:
1578
+ continue
1579
+ start = int(round(r.x_centre - width / 2))
1580
+ hl = {int(r.x_cluster): X_COLOR}
1581
+ if g != 'alone':
1582
+ hl[int(r.p_cluster)] = P_COLOR if int(r.p_cluster) != int(r.x_cluster) else X_COLOR
1583
+ png, w, h = rendered('region_logo', config, r.coord, hl, None, True, (start, start + width), ymax)
1584
+ near = '' if np.isnan(r.nearest) else f', nearest other motif at {r.nearest:+.0f} bp'
1585
+ title = f'{r.coord} · {lab(r.set_name)}' + (f' · no other motif within {hi} bp{near}' if g == 'alone'
1586
+ else f' · {labels.get(g, g)} at {r.distance:+.0f} bp')
1587
+ items.append((title, png, w, h))
1588
+ if missing:
1589
+ st.info(f'{missing} example regions have no attributions in this folder and were skipped.')
1590
+ st.caption(f'Windows of {width} bp centred on the strongest {labels.get(x, x)} site, one contribution scale; its site in '
1591
+ 'yellow, the partner in blue. Scroll sideways; all rows move together. Use "Skip the strongest" under '
1592
+ '"Window and count" to see other regions.')
1593
+ stacked_logos(items)
1594
+ shown_rows = pd.concat([rows for _, rows in picked if len(rows)]) if any(len(r) for _, r in picked) else pd.DataFrame()
1595
+ coords = [c for c in dict.fromkeys(shown_rows['coord']) if c in exs] if len(shown_rows) else []
1596
+ if coords:
1597
+ full = st.selectbox('Open an example in full: its seqlets, their logos and the whole input', coords, index=None,
1598
+ placeholder='choose a region', key=f'open_{x}')
1599
+ if full:
1600
+ x_cluster = dict(zip(shown_rows['coord'], shown_rows['x_cluster'])) # a region may sit in two groups
1601
+ st.divider()
1602
+ region_panel(full, highlight=int(x_cluster[full]))
1603
+
1604
+
1605
+ def pair_section(level: str, min_shared: int, src: str):
1606
+ """
1607
+ One pair in detail: its motif (default the most used) and partner (default the one sharing most regions with it),
1608
+ opened by any click or row above or picked here; then its 2x2 table per class (from the page's source of motifs),
1609
+ where the partner sits and example regions (from the seqlets).
1610
+ """
1611
+ st.markdown('#### One pair')
1612
+ labels = V.motif_labels(an, level).drop_duplicates('key').set_index('key')['label']
1613
+ use = V.motif_usage(an, level)
1614
+ totals = use.groupby('key')['regions'].sum().sort_values(ascending=False)
1615
+ if totals.empty:
1616
+ st.caption('No motif to open.')
1617
+ return
1618
+ per_class = use.pivot_table(index='key', columns='set_name', values='regions', fill_value=0)
1619
+ c1, c2 = st.columns(2)
1620
+ x = c1.selectbox('Motif', totals.index.tolist(), key='x_key',
1621
+ format_func=lambda k: f'{labels.get(k, k)} · ' + ', '.join(
1622
+ f'{int(per_class.loc[k, s])} {lab(s)}' for s in an.sets if s in per_class and per_class.loc[k, s] > 0))
1623
+ pt_all = V.partners_of(an, level, x)
1624
+ co = pt_all[(pt_all['partner'] != 'alone') & (pt_all['shared'] >= min_shared)]
1625
+ options = list(dict.fromkeys(co.sort_values('shared', ascending=False)['partner']))
1626
+ if len(V.pair_region_table(an, level, None, x, x)):
1627
+ options.append(x)
1628
+ forced = st.session_state.get('forced_partner')
1629
+ if forced and forced[0] == x and forced[1] not in options:
1630
+ options.append(forced[1]) # a pair opened from above that shares fewer regions
1631
+ pkey = partner_key(level, x)
1632
+ if pkey in st.session_state and st.session_state[pkey] not in options:
1633
+ del st.session_state[pkey]
1634
+ shared = co.pivot_table(index='partner', columns='set_name', values='shared', fill_value=0)
1635
+ y = c2.selectbox('Partner', options, key=pkey, index=0 if options else None,
1636
+ placeholder=f'no motif shares {min_shared} regions or more with it',
1637
+ format_func=lambda k: labels.get(k, k) + (' (a second site)' if k == x else '') + (
1638
+ ' · ' + ', '.join(f'{int(shared.loc[k, s])} {lab(s)}' for s in an.sets
1639
+ if s in shared and shared.loc[k, s] > 0) if k in shared.index else ''))
1640
+ classes = [s for s in an.sets if s in set(pt_all['set_name'])]
1641
+ if src == 'scan':
1642
+ st.caption('The 2×2 tables count the scanned sites; where the partner sits and the examples come from the seqlets.')
1643
+ tables, spacing, examples = st.tabs(['2×2 tables', 'Spacing', 'Examples'])
1644
+ with tables:
1645
+ if y is None or y == x:
1646
+ st.caption('A 2×2 table needs two motifs: pick a partner other than the motif itself.')
1647
+ else:
1648
+ contingency_view(level, x, y)
1649
+ with spacing:
1650
+ pair_spacing(level, x, y, classes, labels)
1651
+ with examples:
1652
+ pair_examples(level, x, y, classes, labels)
1653
+
1654
+
1655
+ def all_pairs_table(level: str, src: str):
1656
+ """
1657
+ Every pair in one table: per class its regions with both, the regions chance expects, their log2 ratio and q
1658
+ (pair_stats); with two classes also their comparison (pair_differential).
1659
+ """
1660
+ w = V.pair_wide(an, level, src)
1661
+ if w.empty:
1662
+ st.caption('No pair.')
1663
+ return
1664
+ sets = [s_ for s_ in an.sets if f'shared|{s_}' in w]
1665
+ cols_ = ['a_label', 'b_label', 'total_shared'] + [f'{c}|{s_}' for s_ in sets
1666
+ for c in ('shared', 'expected', 'log2_ratio', 'q', 'median_gap')]
1667
+ cfg = {'a_label': 'Motif', 'b_label': 'Motif', 'total_shared': 'Regions with both'}
1668
+ for s_ in sets:
1669
+ cfg.update({f'shared|{s_}': f'{lab(s_)}: with both',
1670
+ f'expected|{s_}': st.column_config.NumberColumn(f'{lab(s_)}: expected', format='%.1f'),
1671
+ f'log2_ratio|{s_}': st.column_config.NumberColumn(f'{lab(s_)}: log2 observed / expected', format='%.2f'),
1672
+ f'q|{s_}': st.column_config.NumberColumn(f'{lab(s_)}: q', format='%.2g'),
1673
+ f'median_gap|{s_}': st.column_config.NumberColumn(f'{lab(s_)}: median gap (bp)', format='%.0f')})
1674
+ d = V.pair_differential(an, level, src)
1675
+ if len(d):
1676
+ A, B = d.attrs['sets']
1677
+ w = w.merge(d[['a', 'b', 'diff', 'p', 'q', 'prefers']].rename(
1678
+ columns={'diff': 'between', 'p': 'between_p', 'q': 'between_q', 'prefers': 'more_together'}), on=['a', 'b'], how='left')
1679
+ w['more_together'] = w['more_together'].map(lambda v: lab(v) if isinstance(v, str) and v else '')
1680
+ cols_ += ['between', 'between_p', 'between_q', 'more_together']
1681
+ cfg.update({'between': st.column_config.NumberColumn(f'{lab(B)} − {lab(A)}, log2 odds ratio', format='%+.2f'),
1682
+ 'between_p': st.column_config.NumberColumn('p (Woolf)', format='%.1e'),
1683
+ 'between_q': st.column_config.NumberColumn('q (Woolf)', format='%.2g'), 'more_together': 'More together in'})
1684
+ st.dataframe(w.sort_values('total_shared', ascending=False)[cols_], hide_index=True, column_config=cfg, height=360)
1685
+
1686
+
1687
+ def fisher_section(c: dict):
1688
+ """Per class, how many regions carry each pair of motifs and whether more or less than independence (counts_chart)."""
1689
+ st.markdown('#### How many regions carry both motifs, in each class')
1690
+ lines = []
1691
+ for p_ in c['panels']:
1692
+ n_t = int(np.isfinite(p_['q']).sum() // 2)
1693
+ lines.append(f"**{lab(p_['set_name'])}**: {int((p_['sig'] > 0).sum() // 2)} pairs more often together than "
1694
+ f"independence, {int((p_['sig'] < 0).sum() // 2)} less, of {n_t} pairs")
1695
+ st.markdown('; '.join(lines) + '.')
1696
+ st.altair_chart(counts_chart(c), width='content')
1697
+ signed = [p_ for p_ in c['panels'] if p_['sign']]
1698
+ how = ('; '.join(f"{lab(p_['set_name'])} counts the seqlets stronger in {an.label_b if p_['sign'] > 0 else an.label_a}"
1699
+ for p_ in signed) + ', each genomic site once') if signed else (
1700
+ 'every site a scan with JASPAR matrices finds in the region' if c['source'] == 'scan' else 'every seqlet')
1701
+ st.caption(f"{how}. Shown: the motifs in at least {c['min_regions']:g} regions of one class. Bars: regions carrying "
1702
+ "each motif; cells: regions carrying both. Dot: more often together than independence; ring: less "
1703
+ f"(Fisher's test per class, BH over its pairs, q < {c['alpha']:g}). Hover for the numbers.")
1704
+
1705
+
1706
+ def woolf_section(c: dict):
1707
+ """Which pairs differ between the two classes, Woolf's test on the same tables (woolf_chart)."""
1708
+ w = c['woolf']
1709
+ if w is None:
1710
+ return
1711
+ A, B = w['sets']
1712
+ st.markdown(f'#### Which pairs differ between {lab(B)} and {lab(A)}')
1713
+ hit = w['compared'] & (np.nan_to_num(w['q'], nan=1.0) <= c['alpha'])
1714
+ n_c, n_h = int(w['compared'].sum() // 2), int(hit.sum() // 2)
1715
+ n_b = int((hit & (w['diff'] > 0)).sum() // 2)
1716
+ st.markdown(f"**{n_h} of the {n_c} pairs compared differ**: {n_b} more together in {lab(B)}, {n_h - n_b} in {lab(A)}. "
1717
+ f"{len(c['keys']) * (len(c['keys']) - 1) // 2 - n_c} more pairs are too thin to compare." if n_c else
1718
+ 'No pair is common enough in both classes to compare.')
1719
+ if n_c:
1720
+ st.altair_chart(woolf_chart(c), width='content')
1721
+ st.caption(f"The same tables as above. Colour: how much larger the pair's odds ratio is in {lab(B)} than in {lab(A)}, "
1722
+ f"in log2; outlined: the classes differ (Woolf's test, BH over the pairs compared, q < {c['alpha']:g}); grey: "
1723
+ f"a cell of a table expected below {c['min_expected']:g} regions, so not compared. Neither test allows for "
1724
+ 'regions that carry many motifs, which carry more pairs by chance.')
1725
+
1726
+
1727
+ def cooccurrence_page():
1728
+ """
1729
+ Which motifs the model uses together, on one set of tables: per class, how many regions carry each pair and
1730
+ whether more than independence (Fisher), then which pairs differ between the classes (Woolf).
1731
+ """
1732
+ t1, t2, t3 = st.columns([2, 3, 2])
1733
+ level = t1.radio('Motif level', list(V.LEVELS), horizontal=True, key='level', on_change=reset_pairs,
1734
+ help='Motifs named by the JASPAR subfamily of the best match, or by cluster.')
1735
+ t2.radio('Motifs from', list(COUNT_SOURCES), horizontal=True, key='motif_source', format_func=COUNT_SOURCES.get,
1736
+ on_change=reset_pairs,
1737
+ help='The seqlets of the attributions, each class counting those that push its way, or every site a scan '
1738
+ 'finds in the sequence: with the best JASPAR matrices of a subfamily, or at the cluster level with the '
1739
+ 'cluster\'s own matrix (its members\' bases and a few around them, over its informative columns).')
1740
+ n_min = int(t3.number_input('Motifs in at least this many regions of one class', 1, 100000,
1741
+ int(V.cooc_settings(an)['counts_min_regions']), 5, key='cooc_min_regions'))
1742
+ src = motif_source(level)
1743
+ how = "each cluster's own matrix" if level == 'cluster' else 'the JASPAR matrices'
1744
+ with st.spinner(f'Scanning every region with {how} (slow the first time, then kept)…' if src == 'scan' else
1745
+ 'Counting the motif pairs of each class…', show_time=True):
1746
+ c = V.cooc_counts(an, level, src, n_min)
1747
+ if src == 'scan' and (left := V.unscannable(an, level)):
1748
+ thr = float(V.cooc_settings(an)['scan_threshold'])
1749
+ st.caption(f"Not scanned, no matrix of theirs can reach p < {thr:g} (fewer than 7 bp of information): {len(left)} "
1750
+ f"{'clusters' if level == 'cluster' else 'subfamilies'}, " + ', '.join(left[:12]) +
1751
+ (f' and {len(left) - 12} more' if len(left) > 12 else '') + '.')
1752
+ if len(c['keys']) < 2:
1753
+ st.info(f'Fewer than two motifs sit in {n_min} or more regions of one class: lower the number above.')
1754
+ return
1755
+ fisher_section(c)
1756
+ st.divider()
1757
+ woolf_section(c)
1758
+
1759
+
1760
+ # -- pairs --------------------------------------------------------------------------------------
1761
+ PAIR_COLORS = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22',
1762
+ '#17becf']
1763
+ DASH = {'-': [1, 0], '--': [5, 3], ':': [1, 2]}
1764
+ TERM_STYLE = {lab: (col or SECOND_C, DASH[ls]) for _, lab, col, ls, _ in ABS_LINES} # as the step's figures
1765
+
1766
+
1767
+ def _domain(lo, hi, pad=0.04):
1768
+ lo, hi = float(lo.min()), float(hi.max())
1769
+ return [lo - pad * (hi - lo), hi + pad * (hi - lo)]
1770
+
1771
+
1772
+ def _zero():
1773
+ return alt.Chart(pd.DataFrame({'y': [0]})).mark_rule(color='black', strokeDash=[2, 2], strokeWidth=0.6) \
1774
+ .encode(y='y:Q')
1775
+
1776
+
1777
+ def spacing_view(a: str, p: str, pairs: list):
1778
+ """
1779
+ The line scan of the chosen pair: its cooperativity against the gap between the motifs, per condition, and the
1780
+ absolute signals it is built from (both motifs, the additive expectation, each motif alone, the background).
1781
+ """
1782
+ t = V.coop_table(an, 'line')
1783
+ t = t.assign(name=t['anchor'] + ' + ' + t['partner'], lo=t['cooperativity'] - t['cooperativity_sem'],
1784
+ hi=t['cooperativity'] + t['cooperativity_sem'])
1785
+ shown = st.multiselect('Pairs to compare', pairs, default=[f'{a} + {p}'], key='compare')
1786
+ t = t[t['name'].isin(shown)]
1787
+ if t.empty:
1788
+ st.info('Choose at least one pair.')
1789
+ return
1790
+ conds = V.coop_conditions(an)
1791
+ color = alt.Color('name:N', title=None, scale=alt.Scale(domain=pairs, range=PAIR_COLORS),
1792
+ legend=alt.Legend(orient='bottom'))
1793
+ tips = ['name:N', 'spacing:Q', alt.Tooltip('cooperativity:Q', format='.3f'),
1794
+ alt.Tooltip('cooperativity_sem:Q', title='SEM', format='.3f')]
1795
+ share = f'{conds[0]} and {conds[1]} share a scale. ' if len(conds) > 1 else ''
1796
+ st.markdown(f'**Cooperativity against spacing**{V.coop_space(an)}: mean over backgrounds, band ± SEM. '
1797
+ f'{share}Drag to pan, scroll to zoom.')
1798
+ for col, cs in zip(st.columns(len(conds)), conds):
1799
+ d = t[t['condition'] == cs]
1800
+ same = conds[:2] if cs in conds[:2] else [cs]
1801
+ y = alt.Scale(domain=_domain(*(t[t['condition'].isin(same)][k] for k in ('lo', 'hi'))))
1802
+ base = alt.Chart(d).encode(x=alt.X('spacing:Q', title='Motif spacing (bp)'))
1803
+ chart = alt.layer(
1804
+ base.mark_area(opacity=0.22).encode(y=alt.Y('lo:Q', scale=y, title='Cooperativity effect'), y2='hi:Q',
1805
+ color=color),
1806
+ base.mark_line(strokeWidth=1.4).encode(y=alt.Y('cooperativity:Q', scale=y), color=color),
1807
+ base.mark_point(opacity=0, size=60).encode(y=alt.Y('cooperativity:Q', scale=y), tooltip=tips),
1808
+ _zero()).properties(title=alt.Title(cs, anchor='start', offset=6), height=260,
1809
+ padding={'top': 14, 'left': 4, 'right': 4, 'bottom': 4}).interactive(bind_y=False)
1810
+ col.altair_chart(chart, width='stretch')
1811
+
1812
+ terms = V.spacing_terms(an, a, p)
1813
+ st.markdown(f'**Predicted signal, {a} + {p}**{V.coop_space(an)}: both motifs, the additive expectation, each '
1814
+ f'motif alone and the background without either.' +
1815
+ (f' {conds[0]} and {conds[1]} share a scale, the difference has its own.' if len(conds) > 1 else ''))
1816
+ names = list(TERM_STYLE)
1817
+ for col, cs in zip(st.columns(len(conds)), conds):
1818
+ same = conds[:2] if cs in conds[:2] else [cs]
1819
+ v = terms.loc[terms['condition'].isin(same), 'value']
1820
+ chart = alt.Chart(terms[terms['condition'] == cs]).mark_line(strokeWidth=1.2).encode(
1821
+ x=alt.X('spacing:Q', title='Motif spacing (bp)'),
1822
+ y=alt.Y('value:Q', scale=alt.Scale(domain=_domain(v, v)), title='Predicted signal'),
1823
+ color=alt.Color('term:N', title=None, scale=alt.Scale(domain=names, range=[TERM_STYLE[n][0] for n in names]),
1824
+ legend=alt.Legend(orient='bottom', columns=3)),
1825
+ strokeDash=alt.StrokeDash('term:N', scale=alt.Scale(domain=names, range=[TERM_STYLE[n][1] for n in names]),
1826
+ legend=None),
1827
+ tooltip=['term:N', 'spacing:Q', alt.Tooltip('value:Q', format='.3f'), alt.Tooltip('sem:Q', title='SEM',
1828
+ format='.3f')],
1829
+ ).properties(title=alt.Title(cs, anchor='start', offset=6), height=260,
1830
+ padding={'top': 14, 'left': 4, 'right': 4, 'bottom': 4}).interactive(bind_y=False)
1831
+ col.altair_chart(chart, width='stretch')
1832
+
1833
+
1834
+ def _heat(d: pd.DataFrame, limits, kind: str, title: str = '', size: int = 260, label: str = 'value'):
1835
+ """
1836
+ One offset grid: anchor offsets down, partner offsets across. kind: 'class' for a difference, in the two
1837
+ conditions' colours; 'diverging' for another quantity read around zero; 'sequential' for an absolute signal.
1838
+ """
1839
+ offs = sorted(d['partner_offset'].unique())
1840
+ ticks = [offs[0], offs[len(offs) // 2], offs[-1]]
1841
+ lo, hi = limits
1842
+ scale = alt.Scale(domain=[lo, 0.0, hi], range=[ca, '#ffffff', cb], clamp=True) if kind == 'class' else \
1843
+ alt.Scale(scheme='redblue', reverse=True, domain=[lo, hi], clamp=True) if kind == 'diverging' else \
1844
+ alt.Scale(scheme='viridis', domain=[lo, hi], clamp=True)
1845
+ return alt.Chart(d).mark_rect().encode(
1846
+ x=alt.X('partner_offset:O', title='Partner offset (bp)', axis=alt.Axis(values=ticks, labelAngle=0)),
1847
+ y=alt.Y('anchor_offset:O', title='Anchor offset (bp)', sort='descending', axis=alt.Axis(values=ticks)),
1848
+ color=alt.Color('value:Q', scale=scale, title=None,
1849
+ legend=alt.Legend(orient='bottom', gradientLength=min(size, 200))),
1850
+ tooltip=['anchor:N', 'partner:N', 'anchor_offset:O', 'partner_offset:O',
1851
+ alt.Tooltip('value:Q', title=label, format='.3f'),
1852
+ alt.Tooltip('raw:Q', title='mean', format='.3f'), alt.Tooltip('sem:Q', title='SEM', format='.3f')],
1853
+ ).properties(title=title, height=size)
1854
+
1855
+
1856
+ def offsets_view(a: str, p: str):
1857
+ """The heatmap scan of the chosen pair, for one quantity, per condition; then that quantity over every pair."""
1858
+ c1, c2 = st.columns([3, 2])
1859
+ value = c1.selectbox('Quantity', list(V.QUANTITIES), format_func=V.QUANTITIES.get, key='heat_value',
1860
+ help='The cooperativity, or one of the absolute signals it is built from.')
1861
+ default = float(an.cfg.get('marginalize', {}).get('heatmap_sigma', 1.0))
1862
+ sigma = c2.number_input('Smoothing (Gaussian sigma, offset steps; 0 for none)', 0.0, 5.0, default, 0.5,
1863
+ key='sigma')
1864
+ with st.spinner(f'Reading {V.QUANTITIES[value].lower()} over the offsets…', show_time=True):
1865
+ g, lim = V.offset_grids(an, sigma, value)
1866
+ conds = V.coop_conditions(an, 'heatmap')
1867
+ label = V.QUANTITIES[value]
1868
+ kind = lambda cs: ('class' if cs in conds[2:] else # noqa: E731
1869
+ 'diverging' if value == 'cooperativity' else 'sequential')
1870
+ st.markdown(f'**{label} over both offsets, {a} + {p}**{V.coop_space(an)}: ' +
1871
+ (f'{conds[0]} and {conds[1]} on one scale ({lim[conds[0]][0]:.2f} to {lim[conds[0]][1]:.2f}, the central '
1872
+ f'96% over every pair), the difference on its own ({lim[conds[-1]][0]:.2f} to {lim[conds[-1]][1]:.2f}).'
1873
+ if len(conds) > 1 else
1874
+ f'{lim[conds[0]][0]:.2f} to {lim[conds[0]][1]:.2f}, the central 96% over every pair.'))
1875
+ pair = g[(g['anchor'] == a) & (g['partner'] == p)]
1876
+ for col, cs in zip(st.columns(len(conds)), conds):
1877
+ col.altair_chart(_heat(pair[pair['condition'] == cs], lim[cs], kind(cs), cs, label=label), width='stretch')
1878
+
1879
+ st.markdown(f'**{label}, every pair**: anchors down, partners across.')
1880
+ cs = st.radio('Condition', conds, horizontal=True, key='overview_condition')
1881
+ ov = g[g['condition'] == cs]
1882
+ # Faceted on positions, labelled by name: Vega-Lite fills a grid with missing pairs with empty cells, which an
1883
+ # order given as a list of names sorts first, so every tile after them would sit under another pair's labels.
1884
+ rows, cols = list(dict.fromkeys(ov['anchor'])), list(dict.fromkeys(ov['partner']))
1885
+ ov = ov.assign(row=ov['anchor'].map({n: i for i, n in enumerate(rows)}),
1886
+ col=ov['partner'].map({n: i for i, n in enumerate(cols)}))
1887
+ names = lambda ns: alt.Header(labelExpr=f'{json.dumps(ns)}[datum.value]') # noqa: E731
1888
+ st.altair_chart(_heat(ov, lim[cs], kind(cs), size=110, label=label).properties(width=110)
1889
+ .facet(row=alt.Row('row:O', title=None, header=names(rows)),
1890
+ column=alt.Column('col:O', title=None, header=names(cols))),
1891
+ width='content')
1892
+
1893
+
1894
+ def pairs_page():
1895
+ """
1896
+ The marginalization: a pair chosen by its two motifs, then its line scan against spacing and its heatmap scan
1897
+ over both offsets, each quantity and each condition.
1898
+ """
1899
+ pt = V.pair_table(an)
1900
+ anchors, partners = list(dict.fromkeys(pt['anchor'])), list(dict.fromkeys(pt['partner']))
1901
+ st.subheader('Marginalized pairs')
1902
+ st.caption('Both motifs inserted into shuffled backgrounds at a grid of distances, read back as the model\'s '
1903
+ 'response; the anchor sits left of the centre, the partner right.')
1904
+ c1, c2 = st.columns(2)
1905
+ a = c1.pills('Anchor', anchors, default=anchors[0], key='pair_anchor') or anchors[0]
1906
+ p = c2.pills('Partner', partners, default=partners[0], key='pair_partner') or partners[0]
1907
+ row = pt[(pt['anchor'] == a) & (pt['partner'] == p)]
1908
+ if row.empty:
1909
+ st.info(f'{a} + {p} is not one of this design\'s pairs.')
1910
+ return
1911
+ conds = [c.split('|', 1)[1] for c in pt if c.startswith('peak|')]
1912
+ peaks = '; '.join(f"{c} {row[f'peak|{c}'].iat[0]:+.2f} at {row[f'at|{c}'].iat[0]} bp" for c in conds
1913
+ if pd.notna(row[f'peak|{c}'].iat[0]))
1914
+ st.markdown(f"**{a}** `{row['anchor_seq'].iat[0]}` **+ {p}** `{row['partner_seq'].iat[0]}`")
1915
+ if peaks:
1916
+ st.caption(f'Largest cooperativity in magnitude{V.coop_space(an)}, and the spacing it is at: {peaks}.')
1917
+ scans = [s for s in ('line', 'heatmap') if (V.coop_dir(an) / f'cooperativity_{s}.csv').exists()]
1918
+ tabs = st.tabs([{'line': 'Spacing', 'heatmap': 'Offsets (2D)'}[s] for s in scans] + ['Step figures'])
1919
+ for tab, scan in zip(tabs, scans):
1920
+ with tab:
1921
+ if scan == 'line':
1922
+ spacing_view(a, p, (pt['anchor'] + ' + ' + pt['partner']).tolist())
1923
+ else:
1924
+ offsets_view(a, p)
1925
+ with tabs[-1]:
1926
+ figs = sorted(f.name for f in V.coop_dir(an).glob('*.png'))
1927
+ if figs:
1928
+ f = st.selectbox('Figure', figs)
1929
+ st.image(str(V.coop_dir(an) / f))
1930
+ else:
1931
+ st.info('This run has no figures from the marginalize step, only its tables.')
1932
+
1933
+
1934
+ with bar:
1935
+ pages = ['Summary', 'Families', 'Co-occurrence'] + \
1936
+ (['Pair effects'] if V.coop_dir(an) is not None or regression_sources() else []) + ['Effects']
1937
+ page = st.segmented_control('Page', pages, default='Summary', required=True, key='page', bind='query-params',
1938
+ label_visibility='collapsed')
1939
+ with st.spinner(f'Loading {page}…', show_time=True): # the page draws below it; it goes when the page is done
1940
+ {'Summary': lambda: PG.summary_page(an, config, rendered), 'Families': families_page,
1941
+ 'Co-occurrence': cooccurrence_page, 'Pair effects': pair_effects_page,
1942
+ 'Effects': lambda: PG.effects_page(an, config, load, rendered, region_panel)}[page]()