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,1950 @@
1
+ """
2
+ The tables the viewer shows, computed in Python from the files of a finished run: one row per motif (cluster),
3
+ a motif's seqlets, regions, JASPAR matches and co-occurring partners, and one region read from the attribution
4
+ store when it is opened. The app only selects and draws; nothing here writes to the run directory but the co-occurrence cache below.
5
+
6
+ from diffgrammar import Analysis
7
+ from diffgrammar.view import data as V
8
+ an = Analysis('config.toml')
9
+ V.motif_table(an) # one row per cluster
10
+ ex = V.region(an, 'chr10:100095297-100095497') # an analysis.Example with the region's clustered seqlets
11
+
12
+ Two statistics the report does not have are computed here. The enrichment test of motif_table: regions carrying
13
+ the motif in one set against the other, over the report's denominator (two-sided Fisher, BH over clusters). And
14
+ co-occurrence, pair_stats: how often two motifs share a region against a shuffle of the motif labels, by
15
+ permutation, tested in two stages (motifs, then their partners). Its permutation p-values are the one thing saved
16
+ beside the run, in <out_dir>/view_cache, as they take seconds to minutes.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import re
22
+ from pathlib import Path
23
+ from typing import Dict, List, Optional, Tuple
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+ from .. import summaries as S
29
+ from ..analysis import Analysis, Example
30
+ from .. import scan as _scan
31
+ from ..attribute import _bh
32
+ from ..contrast import contrast_record
33
+ from .. import seqlets as SQ
34
+
35
+ JASPAR_URL = 'https://jaspar.elixir.no/matrix/{id}/'
36
+
37
+
38
+ def has(an: Analysis, path: str) -> bool:
39
+ """Whether the run directory holds path (a step's output), so a panel can say which step to run."""
40
+ return (an.out / path).exists()
41
+
42
+
43
+ def ratio_sets(an: Analysis) -> Optional[List[str]]:
44
+ """[numerator, denominator] of the prevalence ratio: B over A (differential_sets), as every comparison of the classes."""
45
+ d = differential_sets(an)
46
+ return [d[1], d[0]] if d else None
47
+
48
+
49
+ def seqlet_meta(an: Analysis) -> pd.DataFrame:
50
+ """
51
+ The seqlets of the analysis contrast (one row per site, with several tracks: Analysis.seqlets), each with idx (its
52
+ position in an.seqlets, for its CWM) and, once `families` ran, the tf / group / subfamily of its cluster's best
53
+ JASPAR match.
54
+ """
55
+ def load():
56
+ meta = an.seqlets.meta.assign(idx=np.arange(len(an.seqlets)))
57
+ meta = meta[meta['contrast'] == an.contrast.name]
58
+ if has(an, 'families/cluster_families.csv'):
59
+ meta = meta.merge(an.families[['cluster', 'tf', 'group', 'subfamily']], on='cluster', how='left')
60
+ if an.single: # one condition: a seqlet's own contribution is that condition's
61
+ meta = meta.assign(mot_max_a=np.nan, mot_max_b=meta['mot_max'])
62
+ return meta.reset_index(drop=True)
63
+ return an._get('view/meta', load)
64
+
65
+
66
+ def motif_table(an: Analysis) -> pd.DataFrame:
67
+ """
68
+ One row per cluster: its best JASPAR match, seqlets, regions and prevalence (%) in each set (n_<set>,
69
+ pct_<set>, over the report's denominator), the log2 prevalence ratio of the report (summaries.prevalence_ratio)
70
+ with its Fisher p and BH q, the share of seqlets stronger in B and equal in both (share_b, share_equal), and the
71
+ median contribution of each condition at the seqlets (mot_max_a, mot_max_b).
72
+ """
73
+ def load():
74
+ meta = seqlet_meta(an)
75
+ den = S.denominators(meta, an.thresholds, an.cfg['report']['denominator'])
76
+ long = S.motif_table(meta, level='cluster', den=den)
77
+ long = long[long['set_name'].isin(an.sets)]
78
+ g = meta.groupby('cluster')
79
+ t = pd.DataFrame({'seqlets': g.size(), 'regions': g['coord'].nunique(),
80
+ 'share_b': g['sign'].apply(lambda s: float((s > 0).mean())),
81
+ 'share_equal': g['sign'].apply(lambda s: float((s == 0).mean()))})
82
+ if {'mot_max_a', 'mot_max_b'} <= set(meta.columns):
83
+ t['median_a'], t['median_b'] = g['mot_max_a'].median(), g['mot_max_b'].median()
84
+ for s in an.sets:
85
+ ls = long[long['set_name'] == s].set_index('cluster')
86
+ t[f'n_{s}'] = ls['regions'].reindex(t.index).fillna(0).astype(int)
87
+ t[f'pct_{s}'] = ls['prevalence_pct'].reindex(t.index).fillna(0.0)
88
+ rs = ratio_sets(an)
89
+ if rs:
90
+ t['log2_ratio'] = S.prevalence_ratio(long, 'cluster', *rs).reindex(t.index)
91
+ t['p'] = _fisher(t, den, rs, an.contrast.name)
92
+ t['q'] = _bh(t['p'].to_numpy())
93
+ if has(an, 'families/cluster_families.csv'):
94
+ fam = an.families.set_index('cluster')
95
+ t = fam[['tf', 'subfamily', 'match_p']].join(t, how='right')
96
+ return t.reset_index().sort_values('seqlets', ascending=False, ignore_index=True)
97
+ return an._get('view/motifs', load)
98
+
99
+
100
+ GROUP_LEVELS = ('subfamily', 'group', 'tf') # the families table's names for subfamily, family and best JASPAR match
101
+
102
+
103
+ def group_table(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
104
+ """
105
+ The clusters by subfamily, family ('group') or best JASPAR match ('tf'), for the analysis contrast, every cluster
106
+ counted, also those under the report's min_cluster_size: one row per name with key, clusters (their ids, most
107
+ seqlets first), n_clusters, seqlets, regions (all sets), regions|<set> and pct|<set> (the set's regions with a
108
+ seqlet in one of its clusters, % of the report's denominator), log2_ratio (B over A, summaries.prevalence_ratio;
109
+ with two classes), share_b and share_equal (its seqlets stronger in B, and equal in both) and top_tfs (the best
110
+ matches of its seqlets, most first). Most regions first.
111
+ """
112
+ if level not in GROUP_LEVELS:
113
+ raise ValueError(f'level is one of {GROUP_LEVELS}, not {level!r}')
114
+
115
+ def load():
116
+ r = an.cfg['report']
117
+ meta, c = an.seqlets.meta, an.contrast.name
118
+ fam = an.families
119
+ den = S.denominators(meta, an.thresholds, r['denominator'])
120
+ lab = S.label_seqlets(meta, fam, min_cluster_size=1)
121
+ lab = lab[(lab['contrast'] == c) & lab['set_name'].isin(an.sets)]
122
+ if lab.empty:
123
+ return pd.DataFrame()
124
+ long = S.motif_table(lab, level=level, den=den)
125
+ sets = [s_ for s_ in an.sets if s_ in set(long['set_name'])]
126
+ g = lab.groupby(level)
127
+ out = pd.DataFrame({'clusters': g['cluster'].agg(lambda v: [int(k) for k in v.value_counts().index]),
128
+ 'seqlets': g.size(), 'share_b': g['sign'].agg(lambda v: float((v > 0).mean())),
129
+ 'share_equal': g['sign'].agg(lambda v: float((v == 0).mean())),
130
+ 'top_tfs': g['tf'].agg(lambda v: ', '.join(v.value_counts().index[:3]))})
131
+ out['n_clusters'] = out['clusters'].map(len)
132
+ for s_ in sets:
133
+ ls = long[long['set_name'] == s_].set_index(level)
134
+ out[f'regions|{s_}'] = ls['regions'].reindex(out.index).fillna(0).astype(int)
135
+ out[f'pct|{s_}'] = ls['prevalence_pct'].reindex(out.index).fillna(0.0)
136
+ out['regions'] = sum(out[f'regions|{s_}'] for s_ in sets)
137
+ pair = differential_sets(an)
138
+ if pair:
139
+ out['log2_ratio'] = S.prevalence_ratio(long, level, pair[1], pair[0]).reindex(out.index)
140
+ out = out.rename_axis('key').reset_index().sort_values(['regions', 'seqlets'], ascending=False, ignore_index=True)
141
+ out.attrs.update(level=level, sets=sets, denominator=r['denominator'])
142
+ return out
143
+ return an._get(f'view/groups/{level}', load)
144
+
145
+
146
+ def group_expression(an: Analysis, level: str = 'subfamily') -> Dict[str, pd.DataFrame]:
147
+ """
148
+ Per name of group_table at `level`, its candidate TFs in the run's expression table (expression.tf_members: the
149
+ TFs of its JASPAR matrices and the best matches of its largest cluster): gene, log2fc (B over A), padj. Empty
150
+ without [expression].
151
+ """
152
+ def load():
153
+ de = an.expression_table
154
+ t = group_table(an, level)
155
+ if de is None or t.empty:
156
+ return {}
157
+ from .. import expression as X
158
+ ann = an.annotations.assign(tf=an.annotations['name']) if level == 'tf' else an.annotations
159
+ return X.tf_members(de, ann, an.families, an.hits, level, t['key'].tolist())
160
+ return an._get(f'view/group_expression/{level}', load)
161
+
162
+
163
+ def group_report_table(an: Analysis, level: str, key: str) -> pd.DataFrame:
164
+ """
165
+ The numbers of the report's cluster figure (figures.group_report) for the clusters of one name of group_table, for
166
+ a chart to draw: one row per cluster and report set, in the figure's order (stronger in B first, similar logos
167
+ together, as cli._cluster_report orders them; `row`), with its seqlets stronger in A and in B and equal in both (n_a,
168
+ n_b, n_eq), the box of
169
+ each condition's contribution at them (a_ and b_ + whislo, q1, med, q3, whishi, n: matplotlib's boxplot_stats, as
170
+ the figure draws them) and, with [expression], the box of the fold changes of the genes of the regions where it has
171
+ a seqlet (g_ + the same; each gene once). attrs: sets, split (the rows stronger in B), header (set -> regions with
172
+ a seqlet, regions attributed) and ref (set -> the median fold change over the set's regions). Empty for seqlets
173
+ called before mot_max_a / mot_max_b were stored, as the figure is then None.
174
+ """
175
+ def load():
176
+ from matplotlib.cbook import boxplot_stats
177
+ from ..cluster import compute_distance_matrix
178
+ meta = an.seqlets.meta
179
+ if an.single: # one condition: a seqlet's own contribution is that condition's
180
+ meta = meta.assign(mot_max_a=np.nan, mot_max_b=meta['mot_max'])
181
+ t = group_table(an, level)
182
+ rows = t[t['key'] == key] if len(t) else t
183
+ if rows.empty or not {'mot_max_a', 'mot_max_b'} <= set(meta.columns):
184
+ return pd.DataFrame()
185
+ clusters = list(rows['clusters'].iat[0])
186
+ sets = an.cfg['report'].get('sets') or sorted(meta['set_name'].unique())
187
+ in_b, in_a = S.report_clusters(meta[meta['cluster'].isin(clusters)], sets, n=len(clusters), min_seqlets=1)
188
+ order = []
189
+ for grp in (in_b, in_a): # similar motifs together, within each direction
190
+ if len(grp) >= 3:
191
+ sim = 1.0 - compute_distance_matrix([an.logos[c] for c in grp], device=an.cfg['run']['device'],
192
+ metric='correlation')[0]
193
+ order += S.order_by_similarity(grp, sim)
194
+ else:
195
+ order += list(grp)
196
+ m = meta[(meta['contrast'] == an.contrast.name) & meta['set_name'].isin(sets)]
197
+ de, links = an.expression_table, an.region_genes
198
+ genes = de is not None and links is not None and len(links) > 0
199
+ if genes:
200
+ from .. import expression as X
201
+
202
+ def box(prefix: str, v) -> dict:
203
+ v = np.asarray(v, float)
204
+ v = v[np.isfinite(v)]
205
+ if not len(v):
206
+ return {f'{prefix}n': 0}
207
+ b = boxplot_stats(v)[0]
208
+ return {**{f'{prefix}{k}': float(b[k]) for k in ('whislo', 'q1', 'med', 'q3', 'whishi')}, f'{prefix}n': len(v)}
209
+ out = []
210
+ for i, c in enumerate(order):
211
+ for s in sets:
212
+ g = m[(m['cluster'] == c) & (m['set_name'] == s)]
213
+ row = {'row': i, 'cluster': int(c), 'set_name': s, 'n_a': int((g['sign'] < 0).sum()),
214
+ 'n_b': int((g['sign'] > 0).sum()), 'n_eq': int((g['sign'] == 0).sum()),
215
+ **box('a_', g['mot_max_a']), **box('b_', g['mot_max_b'])}
216
+ if genes:
217
+ row.update(box('g_', X.target_values(de, links, g['coord'].unique())))
218
+ out.append(row)
219
+ out = pd.DataFrame(out)
220
+ for col in (f'{p}{k}' for p in ('a_', 'b_') for k in ('whislo', 'q1', 'med', 'q3', 'whishi')):
221
+ if col not in out: # no seqlet with that condition's value (a single-track run has no A)
222
+ out[col] = np.nan
223
+ attributed = an.thresholds.groupby(['set_name', 'contrast'])['coord'].nunique()
224
+ ref = {}
225
+ if genes:
226
+ for s in sets:
227
+ v = X.target_values(de, links, m.loc[m['set_name'] == s, 'coord'].unique())
228
+ ref[s] = float(np.median(v)) if len(v) else np.nan
229
+ out.attrs.update(sets=sets, split=len(in_b), ref=ref,
230
+ header={s: (int(m.loc[m['set_name'] == s, 'coord'].nunique()),
231
+ int(attributed.get((s, an.contrast.name), 0))) for s in sets})
232
+ return out
233
+ return an._get(f'view/group_report/{level}/{key}', load)
234
+
235
+
236
+ def _fisher(t: pd.DataFrame, den: pd.Series, sets: List[str], contrast: str) -> pd.Series:
237
+ """Two-sided Fisher test of regions with the motif in sets[0] against sets[1], each over its denominator."""
238
+ from scipy.stats import fisher_exact
239
+ n1, n2 = int(den.get((sets[0], contrast), 0)), int(den.get((sets[1], contrast), 0))
240
+ a, c = t[f'n_{sets[0]}'].to_numpy(), t[f'n_{sets[1]}'].to_numpy()
241
+ return pd.Series([fisher_exact([[x, n1 - x], [y, n2 - y]])[1] for x, y in zip(a, c)], index=t.index)
242
+
243
+
244
+ def motif_seqlets(an: Analysis, cluster: int) -> pd.DataFrame:
245
+ """The seqlets of a cluster, with their centre in input coordinates."""
246
+ m = seqlet_meta(an)
247
+ m = m[m['cluster'] == cluster]
248
+ return m.assign(centre=(m['start'] + m['end'] - 1) / 2)
249
+
250
+
251
+ def motif_regions(an: Analysis, cluster: int) -> pd.DataFrame:
252
+ """
253
+ The regions carrying a cluster: its seqlets there, the strongest one's mot_max (a site equal in both conditions
254
+ has none and ranks last), every seqlet of the region, and the other motifs of the region, strongest region first.
255
+ """
256
+ meta = seqlet_meta(an)
257
+ meta = meta.assign(name=motif_names(meta))
258
+ mine = meta[meta['cluster'] == cluster]
259
+ sub = meta[meta['coord'].isin(mine['coord'].unique())]
260
+ top = mine.loc[mine['mot_max'].abs().fillna(0.0).groupby(mine['coord']).idxmax()].set_index('coord')
261
+ others = sub[sub['cluster'] != cluster].groupby('coord')['name'].agg(lambda v: ', '.join(dict.fromkeys(v)))
262
+ out = pd.DataFrame({'set_name': top['set_name'], 'seqlets': mine.groupby('coord').size(),
263
+ 'mot_max': top['mot_max'], 'all_seqlets': sub.groupby('coord').size(),
264
+ 'other_motifs': others}).fillna({'other_motifs': ''})
265
+ return (out.rename_axis('coord').reset_index()
266
+ .sort_values('mot_max', key=np.abs, ascending=False, ignore_index=True))
267
+
268
+
269
+ def motif_names(meta: pd.DataFrame) -> pd.Series:
270
+ """Each seqlet's motif name: its cluster's best JASPAR match, else cl<id>."""
271
+ cl = 'cl' + meta['cluster'].astype(str)
272
+ return meta['tf'].fillna(cl) if 'tf' in meta else cl
273
+
274
+
275
+ def jaspar_hits(an: Analysis, cluster: int) -> pd.DataFrame:
276
+ """The cluster's JASPAR matches as the families step stored them (best first), with a link to each matrix."""
277
+ hits = pd.DataFrame(an.hits.get(int(cluster), []), columns=['tf', 'id', 'pval'])
278
+ return hits.assign(url=hits['id'].map(lambda i: JASPAR_URL.format(id=i)))
279
+
280
+
281
+ def aligned_logos(an: Analysis, cluster: int, matrix_id: str) -> Tuple[np.ndarray, np.ndarray]:
282
+ """
283
+ The cluster's contribution logo and a JASPAR matrix in bits, on the strand and at the offset that align it best
284
+ to the cluster consensus (the alignment of orient_like, which plot_jaspar_matches uses for the strand only),
285
+ both zero-padded to one frame so that aligned positions share a column.
286
+ """
287
+ from ..align import compare
288
+ from ..jaspar import information_content
289
+ from ..seqlets import reverse_complement_cwm
290
+ ids, _, pwms = an.jaspar
291
+ ic = information_content(dict(zip(ids, pwms))[matrix_id])
292
+ _, off, rc = compare([ic], [an.consensus[int(cluster)]], metric='correlation_pvalue',
293
+ min_overlap=4, device='cpu', batchsize=256,
294
+ return_alignment=True)
295
+ jas = reverse_complement_cwm(ic) if rc[0, 0] else ic
296
+ logo, o = an.logos[int(cluster)], int(off[0, 0]) # jas[k] sits at logo position k + o
297
+ lo, hi = min(0, o), max(len(logo), o + len(jas))
298
+ a, b = np.zeros((hi - lo, 4)), np.zeros((hi - lo, 4))
299
+ a[-lo:-lo + len(logo)] = logo
300
+ b[o - lo:o - lo + len(jas)] = jas
301
+ return a, b
302
+
303
+
304
+ def regions_with_seqlets(an: Analysis) -> pd.DataFrame:
305
+ """Every region with a seqlet under the contrast: set, number of seqlets and the motifs present."""
306
+ meta = seqlet_meta(an)
307
+ return (meta.assign(name=motif_names(meta))
308
+ .groupby('coord').agg(set_name=('set_name', 'first'), seqlets=('cluster', 'size'),
309
+ motifs=('name', lambda v: ', '.join(dict.fromkeys(v))))
310
+ .reset_index().sort_values('seqlets', ascending=False, ignore_index=True))
311
+
312
+
313
+ def available_regions(an: Analysis) -> Optional[set]:
314
+ """
315
+ The regions whose attribution file is present, or None when the store covers every attributed region (then
316
+ nothing is checked). An export keeps a sample of the attributions (diffgrammar.export), so the viewer says
317
+ which regions open with tracks.
318
+ """
319
+ def load():
320
+ src = an.source
321
+ if not hasattr(src, 'files') or len(src.files()) >= an.thresholds['coord'].nunique():
322
+ return None
323
+ out = set()
324
+ for f in src.files():
325
+ m = src.metadata(f)
326
+ out.add(f"{m['chrom']}:{m['start']}-{m['end']}" if {'chrom', 'start', 'end'} <= set(m)
327
+ else m.get('peak_id', f.stem))
328
+ return out
329
+ return an._get('view/available', load)
330
+
331
+
332
+ def has_tracks(an: Analysis, coords: pd.Series) -> pd.Series:
333
+ """Whether each region opens with tracks (see available_regions)."""
334
+ avail = available_regions(an)
335
+ return pd.Series(True, index=coords.index) if avail is None else coords.isin(avail)
336
+
337
+
338
+ def region(an: Analysis, coord: str, set_name: Optional[str] = None) -> Example:
339
+ """
340
+ One region under the analysis contrast, read from the attribution store, with its stored seqlets (clustered,
341
+ polarity-corrected sign) in place of a fresh seqlet call. Example.tracks gives the A and B contributions and B − A
342
+ by size. A region in several sets has seqlets in each: it is read in `set_name`, by default the first set holding
343
+ the contrast.
344
+ As in Analysis.example, the record says where input 0 lies in the genome (genomic_chrom, genomic_start) when
345
+ the file's metadata allows it (Analysis.genomic_offset), so the figures label genome coordinates.
346
+ """
347
+ src = an.source
348
+ regions = (src.region(p) for p in src.paths_for(coord)) if hasattr(src, 'paths_for') else \
349
+ (x for x in src.regions() if x.region == coord)
350
+ rec, r = None, None
351
+ for r in regions:
352
+ if r is None or r.region != coord or (set_name is not None and r.set_name != set_name):
353
+ continue
354
+ rec = contrast_record(r, an.contrast, an.cfg['seqlets']['budget'])
355
+ if rec is not None:
356
+ break
357
+ if rec is None:
358
+ raise KeyError(coord)
359
+ g = an.genomic_offset(coord, len(rec['contributions']))
360
+ if g:
361
+ rec['genomic_chrom'], rec['genomic_start'] = g
362
+ rows = seqlet_meta(an)
363
+ rows = rows[(rows['coord'] == coord) & (rows['set_name'] == rec['set_name'])].sort_values('start')
364
+ return Example(rec, np.asarray(r.onehot, np.float32), rows.to_dict('records'), [], labels=(an.label_a, an.label_b))
365
+
366
+ def seqlet_loci(ex: Example, gap: int = 200) -> List[List[dict]]:
367
+ """The region's seqlets grouped along the input (region() sorts them): neighbours at most gap bp apart share a locus."""
368
+ loci: List[List[dict]] = []
369
+ for s in ex.seqlets:
370
+ if loci and s['start'] - loci[-1][-1]['end'] <= gap:
371
+ loci[-1].append(s)
372
+ else:
373
+ loci.append([s])
374
+ return loci
375
+
376
+
377
+ def strongest_locus(loci: List[List[dict]], cluster: Optional[int] = None) -> int:
378
+ """
379
+ The index of the locus holding the strongest seqlet of `cluster` (of any cluster when it has none here); a site
380
+ equal in both conditions, with no mot_max, counts as the weakest.
381
+ """
382
+ def best(keep):
383
+ return max((np.nan_to_num(abs(s['mot_max'])), k) for k, l in enumerate(loci) for s in l if keep(s))[1]
384
+ if cluster is not None and any(int(s['cluster']) == int(cluster) for l in loci for s in l):
385
+ return best(lambda s: int(s['cluster']) == int(cluster))
386
+ return best(lambda s: True)
387
+
388
+
389
+ def seqlet_logos(an: Analysis, rows: List[dict]) -> List[np.ndarray]:
390
+ """The contribution of each seqlet (rows from seqlet_meta / region), as stored by the seqlets step."""
391
+ return [an.seqlets.get_contribution(int(r['idx'])) for r in rows]
392
+
393
+
394
+ # -- the region browser (the Co-occurrence page) ----------------------------------------------------------
395
+
396
+ LEVELS = ('subfamily', 'cluster')
397
+ TOP_MOTIFS, TOP_PARTNERS = 8, 6
398
+
399
+
400
+ def motif_labels(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
401
+ """
402
+ One row per cluster: `key`, what the browser groups by at `level` (the JASPAR subfamily of the cluster's best
403
+ match, or the cluster itself), `label`, a key's short text (the best-match TFs of the subfamily's clusters, two
404
+ at most, or 'cl12 HNF4G'), and `full`, the subfamily's name.
405
+ """
406
+ if level not in LEVELS:
407
+ raise ValueError(f'level is one of {LEVELS}, not {level!r}')
408
+ cl = an.clusters[['cluster', 'n_seqlets']].astype({'cluster': int})
409
+ fam = an.families[['cluster', 'tf', 'subfamily']] if has(an, 'families/cluster_families.csv') else \
410
+ pd.DataFrame(columns=['cluster', 'tf', 'subfamily'])
411
+ t = cl.merge(fam, on='cluster', how='left')
412
+ t['tf'] = t['tf'].where(t['tf'].notna(), None)
413
+ cid = 'cl' + t['cluster'].astype(str)
414
+ if level == 'cluster':
415
+ t['key'] = cid
416
+ t['label'] = cid + t['tf'].map(lambda v: f' {v}' if v else '')
417
+ t['full'] = t['subfamily'].where(t['subfamily'].notna(), t['label'])
418
+ else:
419
+ t['key'] = t['subfamily'].where(t['subfamily'].notna(), cid)
420
+ names = (t.sort_values('n_seqlets', ascending=False).groupby('key')['tf']
421
+ .agg(lambda v: list(dict.fromkeys(x for x in v if x))))
422
+ t['label'] = t['key'].map(lambda k: '/'.join(names[k][:2]) + (f' +{len(names[k]) - 2}' if len(names[k]) > 2 else '')
423
+ if names[k] else k)
424
+ t['full'] = t['key']
425
+ return t[['cluster', 'key', 'label', 'full', 'n_seqlets']].sort_values('cluster').reset_index(drop=True)
426
+
427
+
428
+ def measured_difference(an: Analysis) -> pd.Series:
429
+ """The measured B − A difference per region from the attribute step's candidates table; empty without one."""
430
+ try:
431
+ c = an.candidates
432
+ except (FileNotFoundError, KeyError, ValueError, OSError):
433
+ return pd.Series(dtype=float)
434
+ if 'meas_diff' not in c:
435
+ return pd.Series(dtype=float)
436
+ coord = c['chrom'].astype(str) + ':' + c['start'].astype(int).astype(str) + '-' + c['end'].astype(int).astype(str)
437
+ return pd.Series(c['meas_diff'].to_numpy(float), index=coord).groupby(level=0).first()
438
+
439
+
440
+ def region_table(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
441
+ """
442
+ One row per region with a seqlet, what the browser draws: set_name; n, its seqlets; best, the |mot_max| of the
443
+ strongest; cluster, that seqlet's cluster; dominant / dominant_label, its key at `level`; partner /
444
+ partner_label, the key of the second strongest seqlet ('alone' without one; a second site of the same motif
445
+ reads '<key> x2'); motifs, every motif present; budget, the signed predicted B − A; measured, the measured
446
+ difference when the run has candidates; tracks, whether the region opens in this folder; n_jitter, n spread
447
+ a little for the map.
448
+ """
449
+ def load():
450
+ lab = motif_labels(an, level).set_index('cluster')
451
+ m = seqlet_meta(an)
452
+ m = m.assign(name=motif_names(m), key=m['cluster'].map(lab['key']), label=m['cluster'].map(lab['label']),
453
+ strength=m['mot_max'].abs().fillna(0.0)).sort_values(['coord', 'strength'], ascending=[True, False])
454
+ g = m.groupby('coord', sort=True)
455
+ first = g.head(1).set_index('coord')
456
+ second = g.nth(1).set_index('coord')
457
+ out = pd.DataFrame({'set_name': first['set_name'], 'n': g.size(), 'best': first['strength'],
458
+ 'cluster': first['cluster'].astype(int), 'dominant': first['key'],
459
+ 'dominant_label': first['label'],
460
+ 'motifs': g['name'].agg(lambda v: ', '.join(dict.fromkeys(v)))})
461
+ out['partner'] = second['key'].reindex(out.index)
462
+ out['partner_label'] = second['label'].reindex(out.index)
463
+ same = out['partner'].notna() & (out['partner'] == out['dominant'])
464
+ out.loc[same, 'partner'] = out.loc[same, 'dominant'] + ' x2'
465
+ out.loc[same, 'partner_label'] = out.loc[same, 'dominant_label'] + ' \u00d72'
466
+ out[['partner', 'partner_label']] = out[['partner', 'partner_label']].fillna('alone')
467
+ thr = an.thresholds
468
+ thr = thr[thr['contrast'] == an.contrast.name].drop_duplicates('coord').set_index('coord')
469
+ out['budget'] = thr['signed_budget' if 'signed_budget' in thr else 'budget'].reindex(out.index)
470
+ out['measured'] = measured_difference(an).reindex(out.index)
471
+ out = out.rename_axis('coord').reset_index()
472
+ out['tracks'] = has_tracks(an, out['coord'])
473
+ out['n_jitter'] = out['n'] + np.random.default_rng(0).uniform(-0.3, 0.3, len(out))
474
+ return out
475
+ return an._get(f'view/regions/{level}', load)
476
+
477
+
478
+ def similarity_positions(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
479
+ """
480
+ The motif keys of `level` on one similarity axis, for the browser's colours: the clusters' consensus CWMs are
481
+ compared at their best alignment (1 − correlation, reverse complement allowed), two keys are as far apart as
482
+ their closest clusters, and an average-linkage tree in optimal leaf order gives the order, so neighbours on
483
+ the axis are similar motifs. Columns: key, label, pos (0..1), n_seqlets.
484
+ """
485
+ def load():
486
+ from scipy.cluster.hierarchy import leaves_list, linkage, optimal_leaf_ordering
487
+ from scipy.spatial.distance import squareform
488
+ from ..cluster import compute_distance_matrix
489
+ lab = motif_labels(an, level)
490
+ keys = list(dict.fromkeys(lab['key']))
491
+ n = len(keys)
492
+ pos = np.full(n, 0.5)
493
+ if n > 1:
494
+ try:
495
+ import torch
496
+ device = an.device if torch.cuda.is_available() else 'cpu'
497
+ except ImportError: # pragma: no cover
498
+ device = 'cpu'
499
+ D = compute_distance_matrix([an.consensus[int(c)] for c in lab['cluster']], device=device,
500
+ metric='correlation')[0].astype(float)
501
+ D = np.clip((D + D.T) / 2, 0, None)
502
+ np.fill_diagonal(D, 0)
503
+ members = {k: np.flatnonzero(lab['key'].to_numpy() == k) for k in keys}
504
+ K = np.zeros((n, n))
505
+ for a in range(n):
506
+ for b in range(a + 1, n):
507
+ K[a, b] = K[b, a] = D[np.ix_(members[keys[a]], members[keys[b]])].min()
508
+ cond = squareform(K, checks=False)
509
+ order = leaves_list(optimal_leaf_ordering(linkage(cond, 'average'), cond)) if n > 2 else np.arange(n)
510
+ pos[order] = np.linspace(0, 1, n)
511
+ per = lab.drop_duplicates('key').set_index('key')['label']
512
+ n_seq = lab.groupby('key')['n_seqlets'].sum()
513
+ return pd.DataFrame({'key': keys, 'label': per.reindex(keys).to_numpy(), 'pos': pos,
514
+ 'n_seqlets': n_seq.reindex(keys).to_numpy()})
515
+ return an._get(f'view/similarity/{level}', load)
516
+
517
+
518
+ def _top(frame: pd.DataFrame, col: str, k: int, skip=()) -> list:
519
+ """The k most frequent values of frame[col], most frequent first, without those in skip."""
520
+ return [v for v in frame[col].value_counts().index if v not in skip][:k]
521
+
522
+
523
+ def _partition(frame: pd.DataFrame, col: str, label_col: str, keep: list, first=()) -> list:
524
+ """(key, label, count) for the values in `first` and `keep`, then 'other' for the rest; empty values skipped."""
525
+ counts = frame[col].value_counts()
526
+ labels = frame.drop_duplicates(col).set_index(col)[label_col]
527
+ items = [(k, labels[k], int(counts[k])) for k in list(first) + list(keep) if k in counts and counts[k] > 0]
528
+ rest = int(counts.sum()) - sum(c for _, _, c in items)
529
+ return items + ([('other', 'other', rest)] if rest > 0 else [])
530
+
531
+
532
+ def tree_cells(an: Analysis, level: str = 'subfamily', cls: Optional[str] = None, motif: Optional[str] = None,
533
+ partner: Optional[str] = None, top: int = TOP_MOTIFS, top_partners: int = TOP_PARTNERS) -> pd.DataFrame:
534
+ """
535
+ The browser's tree as rectangles on a 0..1 width, one row per cell: band 0 the classes; band 1 the dominant
536
+ motif of the regions, within the chosen class, or within each class side by side when none is chosen (the `top`
537
+ most frequent keys, then 'other'); band 2, once a motif is chosen, the partner within it ('alone', the
538
+ top_partners most frequent partners, 'other'). Columns: band, set_name, key, label, count, x0, x1, chosen.
539
+ """
540
+ reg = region_table(an, level)
541
+ rows = []
542
+
543
+ def band(items, b, set_name, x0, x1, chosen_key):
544
+ total = sum(c for _, _, c in items) or 1
545
+ x = x0
546
+ for key, label, count in items:
547
+ w = (x1 - x0) * count / total
548
+ rows.append({'band': b, 'set_name': set_name, 'key': key, 'label': label, 'count': count,
549
+ 'x0': x, 'x1': x + w, 'chosen': key == chosen_key})
550
+ x += w
551
+
552
+ sets = [s for s in an.sets if s in set(reg['set_name'])]
553
+ sets += [s for s in reg['set_name'].unique() if s not in sets]
554
+ classes = [(s, s, int((reg['set_name'] == s).sum())) for s in sets]
555
+ band(classes, 0, None, 0.0, 1.0, cls)
556
+ spans = {r['key']: (r['x0'], r['x1']) for r in rows}
557
+ for s in ([cls] if cls else sets):
558
+ sub = reg[reg['set_name'] == s]
559
+ x0, x1 = (0.0, 1.0) if cls else spans[s]
560
+ band(_partition(sub, 'dominant', 'dominant_label', _top(sub, 'dominant', top)), 1, s, x0, x1,
561
+ motif if (cls or len(sets) == 1) or s == cls else None)
562
+ if cls and motif is not None:
563
+ sub = region_pool(an, level, cls, motif)
564
+ band(_partition(sub, 'partner', 'partner_label', _top(sub, 'partner', top_partners, skip=('alone',)),
565
+ first=('alone',)), 2, cls, 0.0, 1.0, partner)
566
+ return pd.DataFrame(rows, columns=['band', 'set_name', 'key', 'label', 'count', 'x0', 'x1', 'chosen'])
567
+
568
+
569
+ def region_pool(an: Analysis, level: str = 'subfamily', cls: Optional[str] = None, motif: Optional[str] = None,
570
+ partner: Optional[str] = None) -> pd.DataFrame:
571
+ """The regions on the browser's path (rows of region_table), strongest first; 'other' means outside the top keys."""
572
+ reg = region_table(an, level)
573
+ if cls is not None:
574
+ reg = reg[reg['set_name'] == cls]
575
+ if motif is not None:
576
+ reg = reg[~reg['dominant'].isin(_top(reg, 'dominant', TOP_MOTIFS))] if motif == 'other' else reg[reg['dominant'] == motif]
577
+ if partner is not None:
578
+ if partner == 'other':
579
+ reg = reg[(reg['partner'] != 'alone') & ~reg['partner'].isin(_top(reg, 'partner', TOP_PARTNERS, skip=('alone',)))]
580
+ else:
581
+ reg = reg[reg['partner'] == partner]
582
+ return reg.sort_values('best', ascending=False, ignore_index=True)
583
+
584
+
585
+ # -- the explorer (the Co-occurrence page): motifs per class, co-occurrence, the graph the network component draws
586
+
587
+ def region_keys(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
588
+ """
589
+ One row per region with a seqlet in one of the report's classes (an.sets): set_name, keys (the motif keys at
590
+ `level` present), best (strongest seqlet).
591
+ """
592
+ def load():
593
+ lab = motif_labels(an, level).set_index('cluster')['key']
594
+ m = seqlet_meta(an)
595
+ m = m[m['set_name'].isin(an.sets)].assign(key=lambda d: d['cluster'].map(lab), strength=lambda d: d['mot_max'].abs().fillna(0.0))
596
+ return (m.groupby('coord').agg(set_name=('set_name', 'first'), keys=('key', lambda v: tuple(dict.fromkeys(v))),
597
+ best=('strength', 'max')).reset_index())
598
+ return an._get(f'view/region_keys/{level}', load)
599
+
600
+
601
+ def motif_usage(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
602
+ """Regions per class carrying each motif key: key, label, set_name, regions, share (of the class's regions with a seqlet)."""
603
+ rk = region_keys(an, level)
604
+ labels = motif_labels(an, level).drop_duplicates('key').set_index('key')['label']
605
+ rows = []
606
+ for s, g in rk.groupby('set_name'):
607
+ counts = pd.Series([k for ks in g['keys'] for k in ks]).value_counts()
608
+ rows += [{'key': k, 'label': labels.get(k, k), 'set_name': s, 'regions': int(n), 'share': n / len(g)} for k, n in counts.items()]
609
+ return pd.DataFrame(rows, columns=['key', 'label', 'set_name', 'regions', 'share'])
610
+
611
+
612
+ REPEAT_SITE = 0.5 # a site is in a repeat when at least this share of its bases is soft-masked in the genome
613
+
614
+
615
+ def _genome(an: Analysis) -> Optional[str]:
616
+ """The run's genome FASTA (from [attribute] or [marginalize]) when the file is there; None in an export."""
617
+ g = an.cfg.get('attribute', {}).get('genome') or an.cfg.get('marginalize', {}).get('genome')
618
+ return g if g and Path(g).exists() else None
619
+
620
+
621
+ def _region_offsets(an: Analysis, coords) -> Dict[str, Tuple[str, int]]:
622
+ """
623
+ coord -> (chrom, genome position of input 0): from the attribute step's candidates (centre - seq_len // 2, as
624
+ attribute.windows cuts the input), else from each region file's metadata (summit and seq_len).
625
+ """
626
+ coords = list(dict.fromkeys(coords))
627
+ out = {}
628
+ L = an.cfg.get('attribute', {}).get('seq_len')
629
+ try:
630
+ c = an.candidates
631
+ if L and {'chrom', 'start', 'end', 'centre'} <= set(c.columns):
632
+ key = c['chrom'].astype(str) + ':' + c['start'].astype(int).astype(str) + '-' + c['end'].astype(int).astype(str)
633
+ cen = pd.Series((c['centre'].astype(int) - int(L) // 2).to_numpy(), index=key).groupby(level=0).first()
634
+ chrom = pd.Series(c['chrom'].astype(str).to_numpy(), index=key).groupby(level=0).first()
635
+ out = {k: (chrom[k], int(cen[k])) for k in coords if k in cen.index}
636
+ except (FileNotFoundError, KeyError, ValueError, OSError):
637
+ pass
638
+ src = an.source
639
+ for k in coords:
640
+ if k in out or not (hasattr(src, 'path_for') and hasattr(src, 'metadata')):
641
+ continue
642
+ try:
643
+ m = src.metadata(src.path_for(k))
644
+ except (KeyError, FileNotFoundError, StopIteration):
645
+ continue
646
+ if {'chrom', 'summit', 'seq_len'} <= set(m):
647
+ out[k] = (str(m['chrom']), int(m['summit']) - int(m['seq_len']) // 2)
648
+ return out
649
+
650
+
651
+ def seqlet_repeat_fraction(an: Analysis) -> Optional[pd.Series]:
652
+ """
653
+ For the seqlets of regions with two seqlets or more (those that can hold a pair), the share of their bases that
654
+ are soft-masked (lower case, repeat) in the run's genome, indexed by seqlet idx (seqlet_meta); None without the
655
+ genome, NaN where a region's place in the genome is not known.
656
+ """
657
+ def load():
658
+ g = _genome(an)
659
+ if g is None:
660
+ return None
661
+ from pyfaidx import Fasta
662
+ m = seqlet_meta(an)
663
+ m = m[m.groupby('coord')['coord'].transform('size') >= 2]
664
+ offs = _region_offsets(an, m['coord'])
665
+ fa = Fasta(g)
666
+ out = {}
667
+ for r in m.itertuples():
668
+ o = offs.get(r.coord)
669
+ if o is None or o[0] not in fa:
670
+ out[r.idx] = np.nan
671
+ continue
672
+ seq = str(fa[o[0]][o[1] + int(r.start):o[1] + int(r.end)])
673
+ out[r.idx] = sum(ch.islower() for ch in seq) / len(seq) if seq else np.nan
674
+ return pd.Series(out, dtype=float)
675
+ return an._get('view/repeat_fraction', load)
676
+
677
+
678
+ GAP_ADJACENT = 10 # bp: two sites this close may be one composite or extended site split into two seqlets
679
+
680
+
681
+ def _absent(N: int, M: np.ndarray, n: int) -> np.ndarray:
682
+ """The chance that n labels drawn without replacement from N, of which M are of one kind, hold none of that kind."""
683
+ out = np.ones(np.shape(M), dtype=float)
684
+ for i in range(int(n)):
685
+ out *= np.clip((N - np.asarray(M, float) - i) / (N - i), 0, None)
686
+ return out
687
+
688
+
689
+ #: [cooccurrence] settings of the run config (see pair_stats); a config sets any of them
690
+ COOC_DEFAULTS = {'min_expected': 1.0, 'alpha': 0.05, 'seed': 0, 'max_permutations': 1_000_000}
691
+ #: [cooccurrence] settings of pair_differential only, kept apart so the saved permutations do not depend on them
692
+ COOC_DIFF_DEFAULTS = {'diff_min_expected': 5.0}
693
+ COOC_COUNT_DEFAULTS = {'counts_min_regions': 50} # cooc_counts: motifs in at least this many regions of one class
694
+ COOC_EXCEED = 20 # a pair's permutations stop at this many draws as extreme as observed (Besag & Clifford 1991)
695
+ COOC_FIRST = 1_000 # permutations of every tested pair before only the rarer ones go on
696
+ COOC_VERSION = 1 # of the cached permutation p-values: raise it when the method changes
697
+ COOC_CACHE = 'view_cache' # under the run directory: the permutation p-values, which take seconds to minutes
698
+ _DENSE = 400_000 # regions x pairs below which shuffles are counted in batches, in a dense presence table
699
+ _BATCH = 4_000_000 # cells of one batch's presence table
700
+ STATUS = ('passes', 'does not pass', 'motifs not selected', 'not tested')
701
+
702
+
703
+ def cooc_settings(an) -> dict:
704
+ """The [cooccurrence] section of the run config over COOC_DEFAULTS, COOC_DIFF_DEFAULTS, COOC_COUNT_DEFAULTS and
705
+ scan.SCAN_DEFAULTS."""
706
+ cfg = getattr(an, 'cfg', None) or {}
707
+ return {**COOC_DEFAULTS, **COOC_DIFF_DEFAULTS, **COOC_COUNT_DEFAULTS, **_scan.SCAN_DEFAULTS,
708
+ **(cfg.get('cooccurrence') or {})}
709
+
710
+
711
+ def _interval_centre(coord: str) -> float:
712
+ """The genome centre of a region named chrom:start-end; NaN for a name without coordinates."""
713
+ m = re.fullmatch(r'[^:]+:(\d+)-(\d+)', str(coord))
714
+ return (int(m.group(1)) + int(m.group(2))) / 2 if m else np.nan
715
+
716
+
717
+ def unique_sites(an: Analysis) -> pd.DataFrame:
718
+ """
719
+ The analysis contrast's seqlets (seqlet_meta), one per genomic site: where the inputs of neighbouring regions
720
+ overlap, a site that several of them saw stays only with the region whose input centre is nearest to it, so one
721
+ region does not count a neighbour's motif; the seqlets of one region are all kept, however much they overlap. Adds
722
+ chrom, g_start, g_end, dist (bp from the centre of its region's input; from the centre of the region's interval
723
+ when the input length cannot be read) and n_windows (how many regions saw the site). Regions the run cannot place
724
+ in the genome keep every seqlet.
725
+ """
726
+ def load():
727
+ m = seqlet_meta(an)
728
+ off = _region_offsets(an, m['coord'].unique())
729
+ placed = m[m['coord'].isin(off)].copy()
730
+ rest = m[~m['coord'].isin(off)]
731
+ if placed.empty:
732
+ return m.assign(n_windows=1)
733
+ base = placed['coord'].map(lambda k: off[k][1])
734
+ placed['chrom'] = placed['coord'].map(lambda k: off[k][0])
735
+ placed['g_start'], placed['g_end'] = base + placed['start'], base + placed['end']
736
+ try:
737
+ half = next(an.source.regions()).onehot.shape[0] / 2 # inputs are centred on their region
738
+ except (StopIteration, AttributeError, OSError, KeyError, ValueError):
739
+ half = None
740
+ placed['dist'] = (((placed['start'] + placed['end']) / 2 - half).abs() if half is not None else
741
+ ((placed['g_start'] + placed['g_end']) / 2 - placed['coord'].map(_interval_centre)).abs())
742
+ placed = placed.sort_values(['chrom', 'g_start'], kind='stable')
743
+ group = np.zeros(len(placed), dtype=np.int64)
744
+ gid, prev_end, prev_chrom = -1, None, None
745
+ for k, (ch, lo, hi) in enumerate(zip(placed['chrom'], placed['g_start'], placed['g_end'])):
746
+ if ch != prev_chrom or prev_end is None or lo >= prev_end:
747
+ gid, prev_end = gid + 1, hi
748
+ else:
749
+ prev_end = max(prev_end, hi)
750
+ group[k], prev_chrom = gid, ch
751
+ placed['site'] = group
752
+ placed['n_windows'] = placed.groupby('site')['coord'].transform('nunique')
753
+ shared = placed[placed['n_windows'] > 1]
754
+ best = shared.sort_values(['site', 'dist'], kind='stable', na_position='last').groupby('site', sort=False).head(1)
755
+ kept = pd.concat([placed[placed['n_windows'] == 1], best]).drop(columns='site')
756
+ return pd.concat([kept, rest.assign(n_windows=1)]).sort_values('idx', ignore_index=True)
757
+ return an._get('view/unique_sites', load)
758
+
759
+
760
+ def cooc_counts(an: Analysis, level: str = 'subfamily', source: str = 'seqlets', min_regions: Optional[float] = None) -> dict:
761
+ """
762
+ Motif co-occurrence as absolute region counts per class, a Fisher test per class and Woolf's test between two
763
+ classes on the same tables (figures.cooc_counts and the Co-occurrence page). source 'seqlets': the seqlets, each
764
+ genomic site once (unique_sites), with two classes sign-matched: each class counts the seqlets that push its way (B:
765
+ stronger in B, A: stronger in A; a site equal in both counts for neither). source 'scan': the sites a scan finds
766
+ (motif_sites), every one: JASPAR matrices at the
767
+ subfamily level, each cluster's own matrix at the cluster level. keys, labels, families: the motifs in at least min_regions regions of one class (default [cooccurrence]
768
+ counts_min_regions), ordered by the JASPAR hierarchy (class, then family, then subfamily number, then regions carried);
769
+ a family is the JASPAR family at the subfamily level, the subfamily at the cluster level. panels, one per class in
770
+ the report's order: set_name, regions (with any site), sign, with (regions carrying each motif) and n x n arrays:
771
+ both (regions carrying both, diagonal 0), expected (under independence), log2_or (0.5 added to every cell), p and q
772
+ (two-sided Fisher test of the pair's 2x2 table over the class's regions, BH over its pairs), sig (+1 or -1 where
773
+ q < [cooccurrence] alpha: more or fewer than independence). woolf, with two classes: sets ([A, B]) and n x n diff
774
+ (log2 odds ratio in B minus A), p, q (Woolf's test, BH over the pairs compared), compared (every cell of both
775
+ tables expected to hold at least [cooccurrence] diff_min_expected regions). Neither test allows for regions that
776
+ carry many motifs, which carry more pairs by chance.
777
+ """
778
+ if level not in LEVELS:
779
+ raise ValueError(f'level is one of {LEVELS}, not {level!r}')
780
+ if source not in SOURCES:
781
+ raise ValueError(f'source is one of {SOURCES}, not {source!r}')
782
+ stt = cooc_settings(an)
783
+ n_min = float(stt['counts_min_regions'] if min_regions is None else min_regions)
784
+
785
+ def load():
786
+ from scipy.stats import fisher_exact, norm
787
+ alpha, e_min = float(stt['alpha']), float(stt['diff_min_expected'])
788
+ pair = differential_sets(an)
789
+ lab = motif_labels(an, level).drop_duplicates('cluster').set_index('cluster')
790
+ if source == 'seqlets':
791
+ sites = unique_sites(an)
792
+ sites = sites[sites['set_name'].isin(an.sets)].assign(key=lambda d: d['cluster'].map(lab['key']))
793
+ want = {pair[1]: 1, pair[0]: -1} if pair else {}
794
+ else:
795
+ sites, want = motif_sites(an, level, 'scan'), {}
796
+ sites = sites.dropna(subset=['key'])
797
+ sets = [s_ for s_ in an.sets if s_ in set(sites['set_name'])]
798
+ per = {}
799
+ for s_ in sets:
800
+ g = sites[sites['set_name'] == s_]
801
+ use = g[g['sign'] == want[s_]] if s_ in want else g
802
+ per[s_] = (int(g['coord'].nunique()), {k: set(v) for k, v in use.groupby('key')['coord']})
803
+ every = set().union(*(per[s_][1] for s_ in sets)) if sets else set()
804
+ most = {k: max(len(per[s_][1].get(k, ())) for s_ in sets) for k in every}
805
+ total = {k: sum(len(per[s_][1].get(k, ())) for s_ in sets) for k in every}
806
+ keys = [k for k in every if most[k] >= n_min]
807
+ if level == 'subfamily':
808
+ fam_of = an.families.drop_duplicates('subfamily').set_index('subfamily')['group'].to_dict()
809
+ sub_of = {k: k for k in keys}
810
+ else:
811
+ fam_of = {f'cl{int(c)}': sf for c, sf in zip(an.families['cluster'], an.families['subfamily'])}
812
+ sub_of = fam_of
813
+ ann = an.annotations.drop_duplicates('subfamily').set_index('subfamily')
814
+ cls_of, grp_of = ann['class'].str.split('; ').str[0].to_dict(), ann['group'].to_dict()
815
+
816
+ def rank(k):
817
+ s = sub_of.get(k)
818
+ base, _, num = str(s).rpartition('.')
819
+ return (cls_of.get(s, '~'), str(grp_of.get(s, s)), (base, int(num)) if num.isdigit() else (str(s), 0))
820
+ keys = sorted(keys, key=lambda k: (*rank(k), -total[k], str(k)))
821
+ n = len(keys)
822
+ labels = lab.drop_duplicates('key').set_index('key')['label']
823
+ upper = [(i, j) for i in range(n) for j in range(i + 1, n)]
824
+ panels, cells = [], {}
825
+ for s_ in sets:
826
+ R, regions = per[s_]
827
+ of = [regions.get(k, set()) for k in keys]
828
+ w = np.array([len(x) for x in of], int)
829
+ both = np.zeros((n, n), int)
830
+ for i, j in upper:
831
+ both[i, j] = both[j, i] = len(of[i] & of[j])
832
+ c = np.zeros((4, len(upper))) # both, i only, j only, neither
833
+ for k, (i, j) in enumerate(upper):
834
+ c[:, k] = both[i, j], w[i] - both[i, j], w[j] - both[i, j], R - w[i] - w[j] + both[i, j]
835
+ cells[s_] = c
836
+ full = lambda v: np.full((n, n), np.nan) if v is None else v # noqa: E731
837
+ expected, lor, pv, qv, sig = full(None), full(None), full(None), full(None), np.zeros((n, n), int)
838
+ tested = [k for k, (i, j) in enumerate(upper) if w[i] and w[j]]
839
+ ps = [fisher_exact(c[:, k].reshape(2, 2), alternative='two-sided')[1] for k in tested]
840
+ qs = _bh(np.asarray(ps, float)) if ps else []
841
+ for k, p_, q_ in zip(tested, ps, qs):
842
+ i, j = upper[k]
843
+ e = w[i] * w[j] / max(R, 1)
844
+ l_ = float(_log2_or(c[:, [k]])[0])
845
+ for a, b in ((i, j), (j, i)):
846
+ expected[a, b], lor[a, b], pv[a, b], qv[a, b] = e, l_, p_, q_
847
+ if q_ < alpha:
848
+ sig[a, b] = 1 if both[i, j] > e else -1
849
+ panels.append({'set_name': s_, 'regions': R, 'sign': want.get(s_, 0), 'with': w.tolist(), 'both': both,
850
+ 'expected': expected, 'log2_or': lor, 'p': pv, 'q': qv, 'sig': sig})
851
+ woolf = None
852
+ if pair and set(pair) <= set(cells) and upper:
853
+ A, B = pair
854
+ ca, cb = cells[A], cells[B]
855
+
856
+ def smallest(c): # the smallest cell expected from the table's margins
857
+ tot = c.sum(axis=0)
858
+ r1, k1 = c[0] + c[1], c[0] + c[2]
859
+ return np.stack([r1 * k1, r1 * (tot - k1), (tot - r1) * k1, (tot - r1) * (tot - k1)]).min(axis=0) / np.maximum(tot, 1)
860
+ comp = (smallest(ca) >= e_min) & (smallest(cb) >= e_min)
861
+ se = np.hypot(np.sqrt((1 / (ca + 0.5)).sum(axis=0)), np.sqrt((1 / (cb + 0.5)).sum(axis=0))) / np.log(2)
862
+ d = _log2_or(cb) - _log2_or(ca)
863
+ p_all = 2 * norm.sf(np.abs(d / se))
864
+ q_all = np.full(len(upper), np.nan)
865
+ if comp.any():
866
+ q_all[comp] = _bh(p_all[comp])
867
+ diff, pw, qw, compared = (np.full((n, n), np.nan), np.full((n, n), np.nan), np.full((n, n), np.nan),
868
+ np.zeros((n, n), bool))
869
+ for k, (i, j) in enumerate(upper):
870
+ for a, b in ((i, j), (j, i)):
871
+ diff[a, b], compared[a, b] = d[k], comp[k]
872
+ if comp[k]:
873
+ pw[a, b], qw[a, b] = p_all[k], q_all[k]
874
+ woolf = {'sets': [A, B], 'diff': diff, 'p': pw, 'q': qw, 'compared': compared}
875
+ return {'keys': keys, 'labels': [k if level == 'subfamily' else labels.get(k, k) for k in keys],
876
+ 'families': [fam_of.get(k, k) for k in keys], 'panels': panels, 'woolf': woolf, 'level': level,
877
+ 'source': source, 'min_regions': n_min, 'alpha': float(stt['alpha']), 'min_expected': e_min}
878
+ return an._get(f'view/cooc_counts/{level}/{source}/{n_min:g}', load)
879
+
880
+
881
+ #: where the co-occurrence tables read which motifs a region carries (motif_sites)
882
+ SOURCES = ('seqlets', 'scan')
883
+
884
+
885
+ def _sequence_reader(an):
886
+ """coord -> the region's input sequence, from the attribution store, for scanning."""
887
+ if not hasattr(an.source, 'sequence'):
888
+ raise ValueError('scanning needs the input sequences, and this attribution store cannot give them')
889
+ return an.source.sequence
890
+
891
+
892
+ def motif_sites(an, level: str = 'subfamily', source: str = 'seqlets') -> pd.DataFrame:
893
+ """
894
+ Where the regions of the report's classes carry each motif key, what the co-occurrence tables count: set_name,
895
+ coord, key, start, end, idx (a row id: for seqlets their index in an.seqlets, which the repeat lookup uses).
896
+ source 'seqlets': the clustered seqlets, at `level`. 'scan': FIMO hits in the central part of every attributed
897
+ region of the classes (diffgrammar.scan; [cooccurrence] scan_threshold, default 1e-4, and scan_window, default
898
+ the whole input) of each key's best JASPAR matrices at the subfamily level (scan.key_matrices),
899
+ and of each cluster's own sequence frequencies at the cluster level, where clusters that share a best match must
900
+ stay apart (scan.cluster_matrices; the frequencies are computed and saved on first use).
901
+ """
902
+ if source not in SOURCES:
903
+ raise ValueError(f'source is one of {SOURCES}, not {source!r}')
904
+ lab = motif_labels(an, level)
905
+ if source == 'seqlets':
906
+ m = seqlet_meta(an)
907
+ return m[m['set_name'].isin(an.sets)].assign(key=lambda d: d['cluster'].map(lab.set_index('cluster')['key']))
908
+ st = cooc_settings(an)
909
+
910
+ def load():
911
+ thr = an.thresholds
912
+ thr = thr[(thr['contrast'] == an.contrast.name) & thr['set_name'].isin(an.sets)]
913
+ matrices = _scan.cluster_matrices(an, lab) if level == 'cluster' else _scan.key_matrices(an, lab)
914
+ hits = _scan.region_hits(thr[['coord', 'set_name']], matrices, _sequence_reader(an),
915
+ st['scan_window'], float(st['scan_threshold']))
916
+ return hits.assign(idx=np.arange(len(hits)))
917
+ return an._get(f"view/scan/{level}/{st['scan_threshold']}/{st['scan_window']}", load)
918
+
919
+
920
+ def unscannable(an: Analysis, level: str = 'subfamily') -> List[str]:
921
+ """
922
+ The motif keys at `level` without a matrix that can reach the scan threshold (diffgrammar.scan.reachable: fewer than
923
+ 7 bp of information at 1e-4, or no JASPAR match), which a scan never finds, by label.
924
+ """
925
+ lab = motif_labels(an, level)
926
+ mats = _scan.cluster_matrices(an, lab) if level == 'cluster' else _scan.key_matrices(an, lab)
927
+ thr = float(cooc_settings(an)['scan_threshold'])
928
+ name = lab.drop_duplicates('key').set_index('key')['label']
929
+ return sorted(name[k] for k in name.index if not _scan.reachable(mats.get(k, {}), thr))
930
+
931
+
932
+ def region_scan(an: Analysis, coord: str) -> pd.DataFrame:
933
+ """
934
+ FIMO hits of every subfamily's best JASPAR matrices (scan.key_matrices) in the central part of one region's input
935
+ sequence, under the co-occurrence scan's settings ([cooccurrence] scan_threshold and scan_window): key (the
936
+ subfamily), family (its family, the key itself for a cluster without one), matrix, start, end (input coordinates,
937
+ as seqlets), strand, score, p. attrs['window'] is the scanned part in input coordinates, attrs['threshold'] the
938
+ p cut.
939
+ """
940
+ st = cooc_settings(an)
941
+
942
+ def load():
943
+ seq = _sequence_reader(an)
944
+ matrices = _scan.key_matrices(an, motif_labels(an, 'subfamily'))
945
+ hits = _scan.region_hits(pd.DataFrame({'coord': [coord], 'set_name': ['']}), matrices, seq,
946
+ st['scan_window'], float(st['scan_threshold']))
947
+ fam = an.families.dropna(subset=['subfamily']).drop_duplicates('subfamily').set_index('subfamily')['group']
948
+ t = hits.drop(columns=['set_name']).assign(family=hits['key'].map(fam).fillna(hits['key']))
949
+ part = _scan.central(coord, len(seq(coord)), st['scan_window'])
950
+ t.attrs['window'] = (part.start, part.stop)
951
+ t.attrs['threshold'] = float(st['scan_threshold'])
952
+ return t
953
+ return an._get(f"view/region_scan/{coord}/{st['scan_threshold']}/{st['scan_window']}", load)
954
+
955
+
956
+ def _log2_or(cells) -> np.ndarray:
957
+ """log2 odds ratio of 2x2 tables given as rows (both, a only, b only, neither), 0.5 added to every cell (Haldane)."""
958
+ c = np.asarray(cells, float) + 0.5
959
+ return np.log2(c[0] * c[3] / (c[1] * c[2]))
960
+
961
+
962
+ def _perm_tails(blocks: list, R: int, K: int, A: np.ndarray, B: np.ndarray, obs: np.ndarray, up: np.ndarray,
963
+ n_max: int, rng: np.random.Generator) -> Tuple[np.ndarray, np.ndarray]:
964
+ """
965
+ Monte Carlo tail probabilities of the shared counts of the pairs (A[i], B[i]) under the shuffle of motif labels
966
+ within each block (one stratum: region index and motif index of each of its seqlets). Sequential as in Besag &
967
+ Clifford (1991): a pair stops at COOC_EXCEED draws as extreme as observed, with tail COOC_EXCEED / draws, else
968
+ goes on to n_max draws, with tail (extreme + 1) / (n_max + 1). Extreme: shared >= observed where `up`, <= elsewhere.
969
+ Every pair takes the first COOC_FIRST draws; later rounds, twice as long each time, shuffle only the labels of
970
+ the motifs of the pairs still going, which is the same shuffle seen through those motifs. Returns (tail, draws).
971
+ """
972
+ import scipy.sparse as sp
973
+ m = len(A)
974
+ hits, draws, done = np.zeros(m, int), np.zeros(m, int), np.zeros(m, bool)
975
+ total, size = 0, COOC_FIRST
976
+ while total < n_max and not done.all():
977
+ act = np.flatnonzero(~done)
978
+ use = np.unique(np.r_[A[act], B[act]])
979
+ u_of = np.full(K, -1)
980
+ u_of[use] = np.arange(len(use))
981
+ parts = []
982
+ for reg, lab in blocks:
983
+ sel = u_of[lab] >= 0
984
+ if sel.any():
985
+ parts.append((reg, u_of[lab[sel]], len(reg), int(sel.sum())))
986
+ au, bu, ob, ua = u_of[A[act]], u_of[B[act]], obs[act], up[act]
987
+ Ku = len(use)
988
+ dense = R * len(act) <= _DENSE # few pairs left: many shuffles at once in a presence table
989
+ batch = max(1, _BATCH // (R * max(Ku, len(act)))) if dense else 1
990
+ h = hits[act].copy()
991
+ fin, fin_at = np.zeros(len(act), bool), np.zeros(len(act), int)
992
+ n_round = min(size, n_max - total)
993
+ i = 0
994
+ while i < n_round:
995
+ nb = min(batch, n_round - i)
996
+ if dense:
997
+ M = np.zeros((nb, R, Ku), bool)
998
+ for reg, labu, N, n in parts:
999
+ pos = np.stack([rng.permutation(N)[:n] if 4 * n > N else rng.choice(N, n, replace=False)
1000
+ for _ in range(nb)])
1001
+ M[np.arange(nb)[:, None], reg[pos], labu[None, :]] = True
1002
+ c = np.count_nonzero(M[:, :, au] & M[:, :, bu], axis=1)
1003
+ else:
1004
+ rs, us = [], []
1005
+ for reg, labu, N, n in parts:
1006
+ pos = rng.permutation(N)[:n] if 4 * n > N else rng.choice(N, n, replace=False)
1007
+ rs.append(reg[pos])
1008
+ us.append(labu)
1009
+ r, u = np.concatenate(rs), np.concatenate(us)
1010
+ P = sp.csr_matrix((np.ones(len(r), np.float32), (r, u)), shape=(R, Ku))
1011
+ P.sum_duplicates()
1012
+ P.data[:] = 1.0
1013
+ c = (P.T @ P).toarray()[au, bu][None, :]
1014
+ ext = np.where(ua, c >= ob, c <= ob) & ~fin
1015
+ cum = h + np.cumsum(ext, axis=0)
1016
+ reach = cum >= COOC_EXCEED
1017
+ new = reach.any(axis=0) & ~fin
1018
+ fin_at[new] = total + i + np.argmax(reach, axis=0)[new] + 1
1019
+ h = np.where(new, COOC_EXCEED, cum[-1])
1020
+ fin |= new
1021
+ i += nb
1022
+ total += n_round
1023
+ hits[act] = h
1024
+ draws[act] = np.where(fin, fin_at, total)
1025
+ done[act[fin]] = True
1026
+ size *= 2
1027
+ return np.where(done, COOC_EXCEED / np.maximum(draws, 1), (hits + 1) / (total + 1)), draws
1028
+
1029
+
1030
+ def _simes(p: np.ndarray) -> float:
1031
+ """Simes' combination of a family's p-values: the smallest m p_(i) / i."""
1032
+ p = np.sort(np.asarray(p, float))
1033
+ return float(min(1.0, np.min(len(p) * p / np.arange(1, len(p) + 1))))
1034
+
1035
+
1036
+ def _stagewise(a: np.ndarray, b: np.ndarray, p: np.ndarray, alpha: float):
1037
+ """
1038
+ The two stages of pair_stats on the tested pairs (a[i], b[i]) of one class. Stage 1: per motif, Simes over its
1039
+ pairs, BH over the motifs; a motif is selected at q <= alpha. Stage 2: within each of the R selected motifs out
1040
+ of K, BH over its pairs, times K / R (the level alpha R / K of Benjamini & Bogomolov 2014). Returns (q_a, q_b: a
1041
+ pair's stage-2 value within the partners of a and of b, NaN where that motif is not selected; the motifs: key,
1042
+ n_tested, p (Simes), q, selected).
1043
+ """
1044
+ keys = np.unique(np.r_[a, b])
1045
+ fams = [np.flatnonzero((a == k) | (b == k)) for k in keys]
1046
+ pf = np.array([_simes(p[i]) for i in fams])
1047
+ qf = _bh(pf)
1048
+ sel = qf <= alpha
1049
+ R, K = int(sel.sum()), len(keys)
1050
+ q_a, q_b = np.full(len(p), np.nan), np.full(len(p), np.nan)
1051
+ for k, idx, s in zip(keys, fams, sel):
1052
+ if s:
1053
+ qw = np.minimum(1.0, _bh(p[idx]) * K / R)
1054
+ first = a[idx] == k
1055
+ q_a[idx[first]], q_b[idx[~first]] = qw[first], qw[~first]
1056
+ motifs = pd.DataFrame({'key': keys, 'n_tested': [len(i) for i in fams], 'p': pf, 'q': qf, 'selected': sel})
1057
+ return q_a, q_b, motifs
1058
+
1059
+
1060
+ def _cooc_fingerprint(m: pd.DataFrame, level: str, max_stratum: int, settings: dict) -> str:
1061
+ """What the cached permutation p-values depend on: every seqlet's class, region and motif, and the settings."""
1062
+ import hashlib
1063
+ h = hashlib.sha1(pd.util.hash_pandas_object(m[['set_name', 'coord', 'key']].astype(str), index=False).to_numpy().tobytes())
1064
+ h.update(json.dumps([COOC_VERSION, COOC_EXCEED, COOC_FIRST, level, max_stratum,
1065
+ {k: settings[k] for k in sorted(COOC_DEFAULTS)}], sort_keys=True).encode())
1066
+ return h.hexdigest()
1067
+
1068
+
1069
+ def _cooc_cache(an, level: str, source: str = 'seqlets') -> Optional[Tuple[Path, Path]]:
1070
+ out = getattr(an, 'out', None)
1071
+ name = f'cooccurrence_{level}' + ('' if source == 'seqlets' else f'_{source}')
1072
+ return None if out is None else (Path(out) / COOC_CACHE / f'{name}.parquet', Path(out) / COOC_CACHE / f'{name}.json')
1073
+
1074
+
1075
+ def _read_cooc_cache(an, level: str, fingerprint: str, source: str = 'seqlets') -> Optional[pd.DataFrame]:
1076
+ f = _cooc_cache(an, level, source)
1077
+ try:
1078
+ if f and f[1].exists() and json.loads(f[1].read_text()).get('fingerprint') == fingerprint:
1079
+ return pd.read_parquet(f[0])
1080
+ except (OSError, ValueError):
1081
+ pass
1082
+ return None
1083
+
1084
+
1085
+ def _write_cooc_cache(an, level: str, fingerprint: str, t: pd.DataFrame, summary: pd.DataFrame,
1086
+ source: str = 'seqlets') -> None:
1087
+ """Saved beside the run, so the next session reads it; a folder that cannot be written is left as it is."""
1088
+ f = _cooc_cache(an, level, source)
1089
+ if f is None:
1090
+ return
1091
+ try:
1092
+ f[0].parent.mkdir(exist_ok=True)
1093
+ tmp = f[0].with_suffix('.tmp')
1094
+ t.to_parquet(tmp, index=False)
1095
+ tmp.replace(f[0])
1096
+ f[1].write_text(json.dumps({'fingerprint': fingerprint, 'version': COOC_VERSION,
1097
+ 'classes': summary.to_dict('records')}, indent=1, default=str))
1098
+ except OSError:
1099
+ pass
1100
+
1101
+
1102
+ def pair_stats(an: Analysis, level: str = 'subfamily', max_stratum: int = 4, source: str = 'seqlets') -> pd.DataFrame:
1103
+ """
1104
+ Every pair of motif keys a < b present in a class of the report (an.sets), one row per pair and class: shared
1105
+ (regions carrying both), expected (the regions expected to carry both by chance, see below), log2_ratio (log2 of
1106
+ shared + 0.5 over expected + 0.5), pct (shared as % of the class's regions with a seqlet), a_regions and b_regions
1107
+ (regions of the class carrying each), n_regions, median_gap (bp between the two nearest sites, median over the
1108
+ regions with both; NaN without one), repeat_share (in the regions with both, the share where both of the two
1109
+ nearest sites lie in soft-masked repeat sequence; NaN without the genome), and the test: tested, p, n_perm,
1110
+ by_chance, q_a, q_b, q and status, below. cooc_motifs gives the motifs' first stage, cooc_summary each class's
1111
+ counts, pair_differential the comparison of two classes.
1112
+
1113
+ Chance: the motif labels shuffled among the seqlets of regions with the same number of seqlets (1, 2, 3, and
1114
+ max_stratum or more). Each motif keeps how often it sits alone, and only which seqlet is which motif moves, so a
1115
+ motif that tends to be a region's single site does not make its partners look rare. The expected count is exact
1116
+ under that shuffle: a region of n seqlets in a stratum of N seqlets, N_a of them motif a, lacks a with chance
1117
+ h(N_a) = prod over i < n of (N - N_a - i) / (N - i), and carries a and b with chance
1118
+ 1 - h(N_a) - h(N_b) + h(N_a + N_b); summed over regions. Both motifs count when called as seqlets above the
1119
+ region's cut; two sites at most GAP_ADJACENT bp apart may be one composite or extended site split into two
1120
+ seqlets, and a pair whose sites mostly sit in repeats may be one repeat element rather than a regulatory
1121
+ arrangement. The shuffle sees neither.
1122
+
1123
+ The test, per class, with the [cooccurrence] settings (cooc_settings):
1124
+ tested expected >= min_expected (default 1). Below it the pair is not tested (p and q NaN, status 'not
1125
+ tested'): too rare to be depleted, and its excess would rest on a region or two. The expected count is
1126
+ fixed by the shuffle, whatever the pair's observed count, so leaving such pairs out before the
1127
+ correction keeps it valid (independent filtering, Bourgon, Gentleman & Huber 2010) and spares the
1128
+ pairs that can be told apart a correction over the many that cannot.
1129
+ p two-sided permutation p-value: twice the tail on the side of the expected count where the observed
1130
+ one lies, the tail estimated by shuffling the labels as above (_perm_tails; seed `seed`, one stream
1131
+ per class and level). A pair stops after COOC_EXCEED shuffles as extreme as observed; the rarer
1132
+ ones go on to n_perm = min(max_permutations, 2 K m / alpha) shuffles (K motifs with a tested pair, m
1133
+ the most tested pairs of one motif), so the smallest reachable p, 2 / (n_perm + 1), can pass both
1134
+ stages even when one motif has one partner. by_chance: p times the class's tested pairs, the number
1135
+ of pairs as extreme that noise alone would give.
1136
+ q stage-wise, matching how the viewer is read (a motif, then its partners). Stage 1: each motif's
1137
+ tested pairs combined by Simes, BH over the motifs; a motif with q <= alpha is selected. Stage 2:
1138
+ within each selected motif, BH over its pairs at level alpha R / K, R the selected motifs
1139
+ (Benjamini & Bogomolov 2014; stageR, Van den Berge et al. 2017, uses Holm here, a stricter error
1140
+ rate). q_a and q_b: the pair's stage-2 value among the partners of a and of b, scaled so that q <= alpha
1141
+ rejects (NaN where that motif is not selected). A pair belongs to both of its motifs, so it is tested
1142
+ in both lists; q = min(q_a, q_b), the pair passes when either list keeps it (status 'passes', 'does
1143
+ not pass', or 'motifs not selected' when neither motif passed stage 1). Error rate: the expected
1144
+ average, over the selected motifs, of the false share of each motif's kept partners is at most alpha,
1145
+ as Benjamini & Bogomolov prove for independent families. Here a pair's two lists overlap and pairs
1146
+ of one motif are mildly dependent, so the bound is expected to hold approximately, not proven, and
1147
+ the pooled list of pairs has no separate guarantee.
1148
+
1149
+ The permutation p-values are saved in <out_dir>/view_cache (COOC_CACHE) with a fingerprint of the seqlets and
1150
+ the settings, and read back while both match. source: where the motifs come from (motif_sites): the seqlets, or
1151
+ 'scan' for the hits of a scan with matrices, each hit then standing for a seqlet throughout.
1152
+ """
1153
+ return _cooc(an, level, max_stratum, source)['pairs']
1154
+
1155
+
1156
+ def cooc_motifs(an: Analysis, level: str = 'subfamily', max_stratum: int = 4, source: str = 'seqlets') -> pd.DataFrame:
1157
+ """Stage 1 of pair_stats per class and motif: set_name, key, label, n_tested, p (Simes), q (BH), selected."""
1158
+ return _cooc(an, level, max_stratum, source)['motifs']
1159
+
1160
+
1161
+ def cooc_summary(an: Analysis, level: str = 'subfamily', max_stratum: int = 4, source: str = 'seqlets') -> pd.DataFrame:
1162
+ """
1163
+ Per class: n_pairs (pairs of motifs present), n_tested, n_left_out (expected below min_expected), n_pass,
1164
+ n_p05 (tested pairs at p < 0.05) and its noise level 0.05 n_tested, n_motifs (with a tested pair), n_selected
1165
+ (passing stage 1), n_perm (the most shuffles a pair took) and p_floor (the smallest p they can give).
1166
+ """
1167
+ return _cooc(an, level, max_stratum, source)['summary']
1168
+
1169
+
1170
+ def _cooc(an: Analysis, level: str, max_stratum: int, source: str = 'seqlets', test: bool = True) -> dict:
1171
+ """pair_stats and its two companions; test=False gives the counts alone (p, q NaN, status 'not tested')."""
1172
+ def load():
1173
+ import itertools
1174
+ import zlib
1175
+ import scipy.sparse as sp
1176
+ st = cooc_settings(an)
1177
+ alpha = float(st['alpha'])
1178
+ lab = motif_labels(an, level)
1179
+ labels = lab.drop_duplicates('key').set_index('key')['label']
1180
+ m = motif_sites(an, level, source)
1181
+ repeat = seqlet_repeat_fraction(an) if source == 'seqlets' and 'idx' in m else None
1182
+ fingerprint = _cooc_fingerprint(m, level, max_stratum, st)
1183
+ cached = _read_cooc_cache(an, level, fingerprint, source) if test else None
1184
+ frames, motif_frames, summary, perm_rows = [], [], [], []
1185
+ for s in [x for x in an.sets if x in set(m['set_name'])]:
1186
+ g = m[m['set_name'] == s]
1187
+ keys = sorted(g['key'].unique())
1188
+ K = len(keys)
1189
+ if K < 2:
1190
+ continue
1191
+ ki = g['key'].map({k: i for i, k in enumerate(keys)}).to_numpy()
1192
+ ri = g['coord'].astype('category').cat.codes.to_numpy()
1193
+ R = int(ri.max()) + 1
1194
+ P = sp.csr_matrix((np.ones(len(ri)), (ri, ki)), shape=(R, K))
1195
+ P.sum_duplicates()
1196
+ P.data[:] = 1.0 # presence of each motif in each region
1197
+ obs = (P.T @ P).toarray()
1198
+ n_r = np.bincount(ri, minlength=R)
1199
+ stratum = np.minimum(n_r, max_stratum)
1200
+ e = np.zeros((K, K))
1201
+ for sv in np.unique(stratum[stratum >= 2]):
1202
+ regs = stratum == sv
1203
+ within = regs[ri]
1204
+ N = int(within.sum())
1205
+ Nk = np.bincount(ki[within], minlength=K).astype(float)
1206
+ sizes, count = np.unique(n_r[regs], return_counts=True)
1207
+ for n, c in zip(sizes, count):
1208
+ h = _absent(N, Nk, n)
1209
+ e += c * (1 - h[:, None] - h[None, :] + _absent(N, Nk[:, None] + Nk[None, :], n))
1210
+ gaps, reps = {}, {}
1211
+ starts, ends = g['start'].to_numpy(), g['end'].to_numpy()
1212
+ rf = repeat.reindex(g['idx']).to_numpy(float) if repeat is not None else np.full(len(g), np.nan)
1213
+ order = np.argsort(ri, kind='stable')
1214
+ for idx in np.split(order, np.flatnonzero(np.diff(ri[order])) + 1):
1215
+ kk = ki[idx]
1216
+ present = sorted(set(kk))
1217
+ for a, b in itertools.combinations(present, 2):
1218
+ ia, ib = idx[kk == a], idx[kk == b]
1219
+ gap, x, y = min((max(0, max(starts[x], starts[y]) - min(ends[x], ends[y])), x, y) for x in ia for y in ib)
1220
+ gaps.setdefault((a, b), []).append(gap)
1221
+ if not (np.isnan(rf[x]) or np.isnan(rf[y])):
1222
+ reps.setdefault((a, b), []).append(rf[x] >= REPEAT_SITE and rf[y] >= REPEAT_SITE)
1223
+ iu = np.triu_indices(K, 1)
1224
+ o, ex = obs[iu], e[iu]
1225
+ ka, kb = np.array(keys, dtype=object)[iu[0]], np.array(keys, dtype=object)[iu[1]]
1226
+ tested = ex >= float(st['min_expected'])
1227
+ ti = np.flatnonzero(tested)
1228
+ pval, n_perm = np.full(len(o), np.nan), np.zeros(len(o), int)
1229
+ q_a, q_b = np.full(len(o), np.nan), np.full(len(o), np.nan)
1230
+ n_max = needed = 0
1231
+ mot = pd.DataFrame(columns=['key', 'n_tested', 'p', 'q', 'selected'])
1232
+ if test and len(ti):
1233
+ per_motif = np.bincount(np.r_[iu[0][ti], iu[1][ti]], minlength=K)
1234
+ needed = int(np.ceil(2 * (per_motif > 0).sum() * per_motif.max() / alpha))
1235
+ n_max = int(min(int(st['max_permutations']), needed))
1236
+ hit = None
1237
+ if cached is not None:
1238
+ c = cached[cached['set_name'] == s].set_index(['a', 'b'])
1239
+ want = pd.MultiIndex.from_arrays([ka[ti], kb[ti]])
1240
+ if len(c) == len(ti) and want.isin(c.index).all():
1241
+ hit = c.reindex(want)
1242
+ if hit is not None:
1243
+ tail, draws = hit['tail'].to_numpy(float), hit['n_perm'].to_numpy(int)
1244
+ else:
1245
+ multi = n_r[ri] >= 2
1246
+ sv = np.minimum(n_r[ri[multi]], max_stratum)
1247
+ blocks = [(ri[multi][sv == v], ki[multi][sv == v]) for v in np.unique(sv)]
1248
+ rng = np.random.default_rng([int(st['seed']), zlib.crc32(f'{level}|{s}'.encode())])
1249
+ tail, draws = _perm_tails(blocks, R, K, iu[0][ti], iu[1][ti], o[ti], o[ti] >= ex[ti], n_max, rng)
1250
+ perm_rows.append(pd.DataFrame({'set_name': s, 'a': ka[ti], 'b': kb[ti], 'tail': tail, 'n_perm': draws}))
1251
+ pval[ti], n_perm[ti] = np.minimum(1.0, 2 * tail), draws
1252
+ q_a[ti], q_b[ti], mot = _stagewise(ka[ti], kb[ti], pval[ti], alpha)
1253
+ q = np.fmin(q_a, q_b)
1254
+ status = np.select([~tested | (not test), q <= alpha, np.isnan(q)],
1255
+ ['not tested', 'passes', 'motifs not selected'], 'does not pass')
1256
+ if len(mot):
1257
+ motif_frames.append(mot.assign(set_name=s, label=mot['key'].map(lambda k: labels.get(k, k))))
1258
+ summary.append({'set_name': s, 'n_pairs': len(o), 'n_tested': len(ti), 'n_left_out': len(o) - len(ti),
1259
+ 'n_pass': int((status == 'passes').sum()), 'n_p05': int((pval[ti] < 0.05).sum()),
1260
+ 'p05_by_chance': 0.05 * len(ti), 'n_motifs': len(mot), 'n_selected': int(mot['selected'].sum()),
1261
+ 'n_perm': n_max, 'n_perm_needed': needed, 'p_floor': 2 / (n_max + 1) if n_max else np.nan,
1262
+ 'min_expected': float(st['min_expected']), 'alpha': alpha})
1263
+ frames.append(pd.DataFrame({
1264
+ 'set_name': s, 'a': ka, 'b': kb, 'a_label': [labels.get(x, x) for x in ka],
1265
+ 'b_label': [labels.get(x, x) for x in kb], 'shared': o.astype(int), 'expected': ex,
1266
+ 'log2_ratio': np.log2((o + 0.5) / (ex + 0.5)), 'pct': 100 * o / R,
1267
+ 'a_regions': np.diag(obs)[iu[0]].astype(int), 'b_regions': np.diag(obs)[iu[1]].astype(int), 'n_regions': R,
1268
+ 'median_gap': [float(np.median(gaps[(a, b)])) if (a, b) in gaps else np.nan for a, b in zip(*iu)],
1269
+ 'repeat_share': [float(np.mean(reps[(a, b)])) if (a, b) in reps else np.nan for a, b in zip(*iu)],
1270
+ 'tested': tested, 'p': pval, 'n_perm': n_perm, 'by_chance': pval * len(ti), 'q_a': q_a, 'q_b': q_b,
1271
+ 'q': q, 'status': status}))
1272
+ cols = ['set_name', 'a', 'b', 'a_label', 'b_label', 'shared', 'expected', 'log2_ratio', 'pct', 'a_regions',
1273
+ 'b_regions', 'n_regions', 'median_gap', 'repeat_share', 'tested', 'p', 'n_perm', 'by_chance', 'q_a', 'q_b',
1274
+ 'q', 'status']
1275
+ summ = pd.DataFrame(summary, columns=['set_name', 'n_pairs', 'n_tested', 'n_left_out', 'n_pass', 'n_p05',
1276
+ 'p05_by_chance', 'n_motifs', 'n_selected', 'n_perm', 'n_perm_needed',
1277
+ 'p_floor', 'min_expected', 'alpha'])
1278
+ if cached is None and perm_rows:
1279
+ _write_cooc_cache(an, level, fingerprint, pd.concat(perm_rows, ignore_index=True), summ, source)
1280
+ motifs = (pd.concat(motif_frames, ignore_index=True) if motif_frames else
1281
+ pd.DataFrame(columns=['key', 'n_tested', 'p', 'q', 'selected', 'set_name', 'label']))
1282
+ return {'pairs': pd.concat(frames, ignore_index=True) if frames else pd.DataFrame(columns=cols),
1283
+ 'motifs': motifs[['set_name', 'key', 'label', 'n_tested', 'p', 'q', 'selected']], 'summary': summ}
1284
+ return an._get(f'view/cooc/{level}/{max_stratum}' + ('' if source == 'seqlets' else f'/{source}') +
1285
+ ('' if test else '/counts'), load)
1286
+
1287
+
1288
+ def pair_counts(an: Analysis, level: str = 'subfamily') -> pd.DataFrame:
1289
+ """
1290
+ The pairs of motif keys that share a region, per class (the rows of pair_stats with shared > 0): set_name, a, b
1291
+ (a < b), shared, expected (see pair_stats), log2_ratio, a_regions, b_regions, p, q, status, median_gap.
1292
+ """
1293
+ ps = pair_stats(an, level)
1294
+ keep = ['set_name', 'a', 'b', 'shared', 'expected', 'log2_ratio', 'a_regions', 'b_regions', 'p', 'q', 'status',
1295
+ 'median_gap', 'repeat_share']
1296
+ return ps.loc[ps['shared'] > 0, keep].reset_index(drop=True)
1297
+
1298
+
1299
+ def significant_pairs(an: Analysis, level: str = 'subfamily', source: str = 'seqlets') -> pd.DataFrame:
1300
+ """
1301
+ Every pair that passes (pair_stats status 'passes'), across the classes: set_name, a, b, a_label, b_label,
1302
+ shared, expected, obs_exp, log2_ratio, p, q, found_by (the motif, or both, whose partner list keeps it),
1303
+ median_gap, repeat_share. By q, then by the size of the effect (|log2 observed / expected|). source: as pair_stats.
1304
+ """
1305
+ ps = pair_stats(an, level, source=source)
1306
+ t = ps[ps['status'] == 'passes'].copy()
1307
+ alpha = float(cooc_settings(an)['alpha'])
1308
+ t['found_by'] = [' and '.join(x for x, v in ((r.a_label, r.q_a), (r.b_label, r.q_b)) if v <= alpha) for r in t.itertuples()]
1309
+ t['obs_exp'] = 2.0 ** t['log2_ratio']
1310
+ t['effect'] = t['log2_ratio'].abs()
1311
+ t = t.sort_values(['q', 'effect'], ascending=[True, False], kind='stable')
1312
+ return t[['set_name', 'a', 'b', 'a_label', 'b_label', 'shared', 'expected', 'obs_exp', 'log2_ratio', 'p', 'q',
1313
+ 'found_by', 'median_gap', 'repeat_share']].reset_index(drop=True)
1314
+
1315
+
1316
+ def pair_wide(an: Analysis, level: str = 'subfamily', source: str = 'seqlets') -> pd.DataFrame:
1317
+ """
1318
+ One row per pair present in any class of the report: a, b, a_label, b_label, per class shared|<set>,
1319
+ expected|<set>, log2_ratio|<set>, pct|<set>, q|<set>, status|<set>, median_gap|<set> (shared 0 and pct 0 where a
1320
+ motif is absent from the class), total_shared, more_in and less_in (the classes where the pair passes, more or
1321
+ less often than chance; see pair_stats). source: as pair_stats.
1322
+ """
1323
+ ps = pair_stats(an, level, source=source)
1324
+ if ps.empty:
1325
+ return pd.DataFrame()
1326
+ sets = [s for s in an.sets if s in set(ps['set_name'])]
1327
+ base = ps.drop_duplicates(['a', 'b'])[['a', 'b', 'a_label', 'b_label']].set_index(['a', 'b'])
1328
+ for s in sets:
1329
+ g = ps[ps['set_name'] == s].set_index(['a', 'b'])
1330
+ for c in ('shared', 'expected', 'log2_ratio', 'pct', 'q', 'status', 'median_gap', 'repeat_share'):
1331
+ base[f'{c}|{s}'] = g[c].reindex(base.index)
1332
+ base[f'shared|{s}'] = base[f'shared|{s}'].fillna(0).astype(int)
1333
+ base[f'pct|{s}'] = base[f'pct|{s}'].fillna(0.0)
1334
+ base['total_shared'] = sum(base[f'shared|{s}'] for s in sets)
1335
+ sig = {s: base[f'status|{s}'] == 'passes' for s in sets}
1336
+ base['more_in'] = [tuple(s for s in sets if sig[s].iat[i] and base[f'shared|{s}'].iat[i] > base[f'expected|{s}'].iat[i])
1337
+ for i in range(len(base))]
1338
+ base['less_in'] = [tuple(s for s in sets if sig[s].iat[i] and base[f'shared|{s}'].iat[i] < base[f'expected|{s}'].iat[i])
1339
+ for i in range(len(base))]
1340
+ return base.reset_index()
1341
+
1342
+
1343
+ def differential_sets(an) -> List[str]:
1344
+ """The report's two classes as [A, B] (summaries.class_sets), the order of every comparison. Empty unless two."""
1345
+ return S.class_sets(an.sets, getattr(an, 'label_a', '') or '', getattr(an, 'label_b', '') or '')
1346
+
1347
+
1348
+ def class_regions(an) -> Dict[str, int]:
1349
+ """
1350
+ The regions of each class under the report's denominator ([report] denominator: by default every attributed
1351
+ region, those without a seqlet too; or only the regions with a seqlet), for the 2x2 tables of pair_differential
1352
+ and pair_contingency. Empty when the run cannot say (then those take the regions with a seqlet).
1353
+ """
1354
+ try:
1355
+ mode = an.cfg['report']['denominator']
1356
+ den = S.denominators(seqlet_meta(an) if mode == 'with_seqlet' else None, an.thresholds, mode)
1357
+ contrast = an.contrast.name
1358
+ except (AttributeError, KeyError, ValueError, FileNotFoundError):
1359
+ return {}
1360
+ return {s: int(n) for (s, c), n in den.items() if c == contrast}
1361
+
1362
+
1363
+ def _cells(t: pd.DataFrame, regions: Optional[Dict[str, int]] = None) -> np.ndarray:
1364
+ """
1365
+ The 2x2 table of each pair_stats row as rows (both, a only, b only, neither), over `regions` of its class (see
1366
+ class_regions) where given, else over the class's regions with a seqlet.
1367
+ """
1368
+ n = t['n_regions'] if not regions else np.maximum(t['set_name'].map(regions).fillna(t['n_regions']), t['n_regions'])
1369
+ return np.stack([t['shared'], t['a_regions'] - t['shared'], t['b_regions'] - t['shared'],
1370
+ n - t['a_regions'] - t['b_regions'] + t['shared']]).astype(float)
1371
+
1372
+
1373
+ def pair_differential(an: Analysis, level: str = 'subfamily', source: str = 'seqlets') -> pd.DataFrame:
1374
+ """
1375
+ Whether two motifs co-occur more in one class than in the other (two-class runs): Woolf's test of the two classes'
1376
+ odds ratios, each read directly off the class's 2x2 table of regions (both motifs, a only, b only, neither, from
1377
+ pair_stats' counts). The regions of a class are those of the report's denominator (class_regions): by default
1378
+ every attributed region, so a region where no motif was called counts as neither. Counting only regions with a
1379
+ seqlet would keep a region because some motif was found in it, which lowers every pair's odds ratio, the more so
1380
+ in the class with more regions without one. One row per pair whose motifs are both present in both classes: a, b,
1381
+ a_label, b_label; per class S of A, B (differential_sets) shared|S, a_only|S, b_only|S, neither|S, n_regions|S
1382
+ (the class's regions), log2_or|S (0.5 added to every cell), or_se|S (its Woolf standard error, log2),
1383
+ median_gap|S, repeat_share|S; then
1384
+ tested in both classes every cell expected under independence (row total x column total / regions) holds at
1385
+ least [cooccurrence] diff_min_expected regions (default 5). Those follow from the margins alone, not from
1386
+ how often the two motifs meet, so leaving the other pairs out before the correction keeps it valid, and
1387
+ the normal approximation of the test holds for the pairs kept.
1388
+ diff log2_or|B - log2_or|A.
1389
+ se, z, p se = sqrt(or_se|A^2 + or_se|B^2), z = diff / se, p two-sided (normal).
1390
+ q BH over the tested pairs, one family; prefers: B or A, the class with the larger odds ratio, at
1391
+ q <= alpha, else ''.
1392
+ Tested pairs first, by p. A pair shares its motifs with other pairs, so the pairs that pass can rest on a few
1393
+ motifs. An odds ratio of regions also follows how many motifs a region holds: regions with more seqlets hold more
1394
+ pairs, and a seqlet of one motif is one its partner does not have, so classes that differ in region complexity
1395
+ differ in their odds ratios without any pairing. On simulated runs without any pairing, 42 to 56% of the pairs
1396
+ compared had p < 0.05 where the two classes differed in region complexity, 4 to 5% where they matched. attrs: sets
1397
+ ([A, B]), n_pairs (present in both classes), n_tested, min_expected, alpha, all_regions (whether the tables count
1398
+ the report's regions, rather than only those with a seqlet), source. source: where the motifs come from
1399
+ (motif_sites), the seqlets or a scan with matrices. Empty unless the report has two classes.
1400
+ """
1401
+ def load():
1402
+ from scipy.stats import norm
1403
+ st = cooc_settings(an)
1404
+ alpha, e_min = float(st['alpha']), float(st['diff_min_expected'])
1405
+ sets = differential_sets(an)
1406
+ ps = _cooc(an, level, 4, source, test=False)['pairs']
1407
+ if len(sets) != 2 or ps.empty or not set(sets) <= set(ps['set_name']):
1408
+ return pd.DataFrame()
1409
+ A, B = sets
1410
+ regions = class_regions(an)
1411
+ parts = []
1412
+ for s in sets:
1413
+ g = ps[ps['set_name'] == s].set_index(['a', 'b'])
1414
+ c = _cells(g, regions)
1415
+ n = c.sum(axis=0)
1416
+ with_a, with_b = c[0] + c[1], c[0] + c[2]
1417
+ smallest = np.stack([with_a * with_b, with_a * (n - with_b), (n - with_a) * with_b,
1418
+ (n - with_a) * (n - with_b)]).min(axis=0) / n
1419
+ parts.append(pd.DataFrame({
1420
+ 'shared': g['shared'], 'a_only': c[1].astype(int), 'b_only': c[2].astype(int), 'neither': c[3].astype(int),
1421
+ 'n_regions': n.astype(int), 'log2_or': _log2_or(c), 'or_se': np.sqrt((1 / (c + 0.5)).sum(axis=0)) / np.log(2),
1422
+ 'smallest': smallest, 'median_gap': g['median_gap'], 'repeat_share': g['repeat_share']},
1423
+ index=g.index).add_suffix(f'|{s}'))
1424
+ names = ps.drop_duplicates(['a', 'b']).set_index(['a', 'b'])[['a_label', 'b_label']]
1425
+ d = names.join(parts[0].join(parts[1], how='inner'), how='inner')
1426
+ t = (d[f'smallest|{A}'] >= e_min) & (d[f'smallest|{B}'] >= e_min)
1427
+ d = d.drop(columns=[f'smallest|{A}', f'smallest|{B}']).assign(tested=t)
1428
+ d['diff'] = d[f'log2_or|{B}'] - d[f'log2_or|{A}']
1429
+ d['se'] = np.hypot(d[f'or_se|{A}'], d[f'or_se|{B}'])
1430
+ d['z'] = np.where(t, d['diff'] / d['se'], np.nan)
1431
+ d['p'] = 2 * norm.sf(np.abs(d['z']))
1432
+ d['q'] = np.nan
1433
+ d.loc[t, 'q'] = _bh(d.loc[t, 'p'].to_numpy())
1434
+ d['prefers'] = np.where(d['q'] <= alpha, np.where(d['diff'] > 0, B, A), '')
1435
+ d = d.assign(effect=d['diff'].abs()).sort_values(['tested', 'p', 'effect'], ascending=[False, True, False],
1436
+ na_position='last', kind='stable')
1437
+ out = d.drop(columns='effect').reset_index()
1438
+ out.attrs.update(sets=sets, n_pairs=len(out), n_tested=int(t.sum()), min_expected=e_min, alpha=alpha,
1439
+ all_regions=bool(regions), source=source)
1440
+ return out
1441
+ return an._get(f'view/cooc_diff/{level}' + ('' if source == 'seqlets' else f'/{source}'), load)
1442
+
1443
+
1444
+ def pair_regression(an, source: str = 'scan') -> pd.DataFrame:
1445
+ """
1446
+ The pair-regression step's pairs from one source of motifs, when the run has them
1447
+ (<out_dir>/pair_regression/<source>/pairs.csv, diffgrammar.pair_regression): every pair of motif families against
1448
+ the measured fold change, B over A; 'scan' over every region of the step's table, 'seqlets' over the attributed
1449
+ ones. By p. attrs: the step's settings.json (regions, blocks, ...), with its settings (alpha, close, block, ...) at
1450
+ the top level too. Empty without that source.
1451
+ """
1452
+ def load():
1453
+ out = getattr(an, 'out', None)
1454
+ f = Path(out) / 'pair_regression' / source / 'pairs.csv' if out is not None else None
1455
+ if f is None or not f.exists():
1456
+ return pd.DataFrame()
1457
+ t = pd.read_csv(f)
1458
+ s = f.parent / 'settings.json'
1459
+ info = json.loads(s.read_text()) if s.exists() else {}
1460
+ t.attrs.update({**info.pop('settings', {}), **info}) # the counts win over a setting of one name
1461
+ return t
1462
+ return an._get(f'view/pair_regression/{source}', load)
1463
+
1464
+
1465
+ def pair_contingency(an: Analysis, level: str, x: str, y: str, source: str = 'seqlets') -> pd.DataFrame:
1466
+ """
1467
+ Motifs x and y in each class where both are present, as the 2x2 table of its regions read from x (the regions of
1468
+ class_regions, as pair_differential): set_name, both, x_only, y_only, neither, n_regions, log2_or (0.5 added to
1469
+ every cell; the same read from either motif). source: as pair_differential. Empty for x == y or a pair present
1470
+ in no class.
1471
+ """
1472
+ if x == y:
1473
+ return pd.DataFrame()
1474
+ ps = _cooc(an, level, 4, source, test=False)['pairs']
1475
+ a, b = sorted((x, y))
1476
+ rows = ps[(ps['a'] == a) & (ps['b'] == b)]
1477
+ c = _cells(rows, class_regions(an))
1478
+ swap = x != a # pair_stats reads the pair from a; the table reads it from x
1479
+ return pd.DataFrame({'set_name': rows['set_name'].to_numpy(), 'both': c[0].astype(int),
1480
+ 'x_only': (c[2] if swap else c[1]).astype(int), 'y_only': (c[1] if swap else c[2]).astype(int),
1481
+ 'neither': c[3].astype(int), 'n_regions': c.sum(axis=0).astype(int), 'log2_or': _log2_or(c)})
1482
+
1483
+
1484
+ def pair_regions(an: Analysis, level: str, set_name: str, a: str, b: str) -> pd.DataFrame:
1485
+ """The regions of a class carrying both keys, strongest first: coord, best."""
1486
+ rk = region_keys(an, level)
1487
+ both = rk[(rk['set_name'] == set_name) & rk['keys'].map(lambda ks: a in ks and b in ks)]
1488
+ return both.sort_values('best', ascending=False)[['coord', 'best']].reset_index(drop=True)
1489
+
1490
+
1491
+ def site_distances(an: Analysis, level: str, set_name: str, a: str, b: str) -> np.ndarray:
1492
+ """Centre of each b site minus centre of each a site, over the regions of the class carrying both (bp)."""
1493
+ lab = motif_labels(an, level).set_index('cluster')['key']
1494
+ m = seqlet_meta(an).assign(key=lambda d: d['cluster'].map(lab), centre=lambda d: (d['start'] + d['end'] - 1) / 2)
1495
+ coords = set(pair_regions(an, level, set_name, a, b)['coord'])
1496
+ m = m[m['coord'].isin(coords)]
1497
+ out = []
1498
+ for _, g in m.groupby('coord'):
1499
+ out += [float(y - x) for x in g.loc[g['key'] == a, 'centre'] for y in g.loc[g['key'] == b, 'centre']]
1500
+ return np.array(out)
1501
+
1502
+
1503
+ def anchor_site(an: Analysis, coord: str, key: str, level: str = 'subfamily') -> Optional[dict]:
1504
+ """The strongest seqlet of motif `key` in a region (a row of seqlet_meta as a dict, with its centre), or None."""
1505
+ lab = motif_labels(an, level).set_index('cluster')['key']
1506
+ m = seqlet_meta(an)
1507
+ m = m[(m['coord'] == coord) & (m['cluster'].map(lab) == key)]
1508
+ if m.empty:
1509
+ return None
1510
+ r = m.loc[m['mot_max'].abs().fillna(0.0).idxmax()].to_dict()
1511
+ r['centre'] = (r['start'] + r['end'] - 1) / 2
1512
+ return r
1513
+
1514
+
1515
+ def key_tfs(an: Analysis, key: str, level: str = 'subfamily') -> List[str]:
1516
+ """The TF names JASPAR gives the clusters of a motif key (best match and runners-up), for naming marginalized motifs."""
1517
+ lab = motif_labels(an, level)
1518
+ clusters = lab.loc[lab['key'] == key, 'cluster']
1519
+ if not has(an, 'families/cluster_families.csv'):
1520
+ return []
1521
+ fam = an.families.set_index('cluster')
1522
+ names = []
1523
+ for c in clusters:
1524
+ if c in fam.index:
1525
+ names += [x.strip() for x in str(fam.loc[c, 'top_tfs']).split(',')] if 'top_tfs' in fam else [str(fam.loc[c, 'tf'])]
1526
+ return list(dict.fromkeys(n for n in names if n and n != 'nan'))
1527
+
1528
+
1529
+ def marginalized_pairs_for(an: Analysis, a: str, b: str, level: str = 'subfamily') -> List[tuple]:
1530
+ """The (anchor, partner) pairs of the marginalize design whose motif names belong to keys a and b, either way round."""
1531
+ if coop_dir(an) is None:
1532
+ return []
1533
+ s = pd.read_csv(coop_dir(an) / 'summary.csv')
1534
+ pairs = s[s['scan'] == 'line'][['anchor', 'partner']].drop_duplicates().itertuples(index=False)
1535
+ ta, tb = {x.upper() for x in key_tfs(an, a, level)}, {x.upper() for x in key_tfs(an, b, level)}
1536
+
1537
+ def of(name, tfs):
1538
+ n = name.upper()
1539
+ return any(n == t or n == t.split('::')[0] or t.startswith(n) for t in tfs)
1540
+ return [(x, y) for x, y in pairs if (of(x, ta) and of(y, tb)) or (of(x, tb) and of(y, ta))]
1541
+
1542
+
1543
+ def partners_of(an: Analysis, level: str, key: str) -> pd.DataFrame:
1544
+ """
1545
+ What co-occurs with motif `key`, per class: partner (a key, or 'alone' for regions carrying nothing else),
1546
+ label, set_name, shared (regions with both), expected and log2_ratio against independence (NaN for 'alone'),
1547
+ x_regions (regions of the class with `key`). Most shared first.
1548
+ """
1549
+ pc = pair_counts(an, level)
1550
+ labels = motif_labels(an, level).drop_duplicates('key').set_index('key')['label']
1551
+ a = pc[pc['a'] == key].rename(columns={'b': 'partner', 'a_regions': 'x_regions'})
1552
+ b = pc[pc['b'] == key].rename(columns={'a': 'partner', 'b_regions': 'x_regions'})
1553
+ out = pd.concat([a, b])[['set_name', 'partner', 'shared', 'expected', 'log2_ratio', 'x_regions']]
1554
+ rk = region_keys(an, level)
1555
+ mine = rk[rk['keys'].map(lambda ks: key in ks)]
1556
+ alone = mine[mine['keys'].map(lambda ks: set(ks) == {key})].groupby('set_name').size()
1557
+ rows = [{'set_name': s, 'partner': 'alone', 'shared': int(n), 'expected': np.nan, 'log2_ratio': np.nan,
1558
+ 'x_regions': int((mine['set_name'] == s).sum())} for s, n in alone.items()]
1559
+ out = pd.concat([out, pd.DataFrame(rows, columns=out.columns)], ignore_index=True)
1560
+ out['label'] = out['partner'].map(lambda k: 'alone' if k == 'alone' else labels.get(k, k))
1561
+ return out.sort_values(['shared'], ascending=False, ignore_index=True)
1562
+
1563
+
1564
+ def _sites(an: Analysis, level: str) -> pd.DataFrame:
1565
+ """Every seqlet with its key at `level`, centre and strength (|mot_max|)."""
1566
+ lab = motif_labels(an, level).set_index('cluster')['key']
1567
+ m = seqlet_meta(an)
1568
+ return m.assign(key=m['cluster'].map(lab), centre=(m['start'] + m['end'] - 1) / 2, strength=m['mot_max'].abs().fillna(0.0))
1569
+
1570
+
1571
+ def pair_region_table(an: Analysis, level: str, set_name: Optional[str], x: str, partner: str,
1572
+ min_dist: Optional[float] = None, max_dist: Optional[float] = None) -> pd.DataFrame:
1573
+ """
1574
+ The regions carrying motif `x` with `partner`, one row each, strongest x site first: coord, set_name, the
1575
+ strongest x site (x_start, x_end, x_centre, x_cluster, x_strength), nearest (signed distance from it to the
1576
+ nearest site of any other motif, NaN without one) and, for a partner key, the partner site nearest to the x
1577
+ site (p_start, p_end, p_centre, p_cluster, p_strength) with distance = p_centre − x_centre; partner == x takes
1578
+ a second x site. partner 'alone': regions where no other motif lies within max_dist of the x site (with
1579
+ max_dist None, regions carrying x and nothing else). For a partner, min_dist / max_dist keep |distance| in a
1580
+ range. set_name None takes every class.
1581
+ """
1582
+ def load():
1583
+ m = _sites(an, level)
1584
+ if set_name is not None:
1585
+ m = m[m['set_name'] == set_name]
1586
+ rk = region_keys(an, level)
1587
+ if partner == 'alone':
1588
+ keep = rk['keys'].map((lambda ks: x in ks) if max_dist is not None else (lambda ks: set(ks) == {x}))
1589
+ else:
1590
+ keep = rk['keys'].map(lambda ks: x in ks and partner in ks)
1591
+ m = m[m['coord'].isin(set(rk.loc[keep, 'coord']))]
1592
+ rows = []
1593
+ for coord, g in m.groupby('coord'):
1594
+ xs = g[g['key'] == x]
1595
+ if xs.empty:
1596
+ continue
1597
+ xi = xs['strength'].idxmax()
1598
+ xr = xs.loc[xi]
1599
+ others = g[g['key'] != x]['centre'] - xr['centre']
1600
+ nearest = float(others.iloc[int(np.argmin(others.abs().to_numpy()))]) if len(others) else np.nan
1601
+ row = {'coord': coord, 'set_name': xr['set_name'], 'x_start': int(xr['start']), 'x_end': int(xr['end']),
1602
+ 'x_centre': float(xr['centre']), 'x_cluster': int(xr['cluster']), 'x_strength': float(xr['strength']),
1603
+ 'nearest': nearest}
1604
+ if partner == 'alone':
1605
+ if max_dist is not None and not np.isnan(nearest) and abs(nearest) <= max_dist:
1606
+ continue
1607
+ else:
1608
+ ps = g[(g['key'] == partner) & (g.index != xi)]
1609
+ if ps.empty:
1610
+ continue
1611
+ pr = ps.loc[(ps['centre'] - xr['centre']).abs().idxmin()]
1612
+ row.update({'p_start': int(pr['start']), 'p_end': int(pr['end']), 'p_centre': float(pr['centre']),
1613
+ 'p_cluster': int(pr['cluster']), 'p_strength': float(pr['strength']),
1614
+ 'distance': float(pr['centre'] - xr['centre'])})
1615
+ rows.append(row)
1616
+ out = pd.DataFrame(rows)
1617
+ if out.empty:
1618
+ return out
1619
+ if partner != 'alone':
1620
+ if min_dist is not None:
1621
+ out = out[out['distance'].abs() >= min_dist]
1622
+ if max_dist is not None:
1623
+ out = out[out['distance'].abs() <= max_dist]
1624
+ return out.sort_values('x_strength', ascending=False, ignore_index=True)
1625
+ return an._get(f'view/pair_regions/{level}/{set_name}/{x}/{partner}/{min_dist}/{max_dist}', load)
1626
+
1627
+
1628
+ def network_graph(an: Analysis, level: str = 'subfamily', min_regions: int = 10, min_shared: int = 3,
1629
+ top_regions: int = 60, start_motifs: int = 6, colors: Optional[dict] = None,
1630
+ labels: Optional[dict] = None) -> dict:
1631
+ """
1632
+ The explorer's graph for the network component: nodes (classes, motifs, regions), edges (usage: class to
1633
+ motif, width by share; co: motif to motif per class, width by shared regions, dashed when fewer than chance;
1634
+ has: motif or pair to region, added as they unfold), and `start`, the ids shown at first. Regions are the
1635
+ top_regions strongest per motif and class, and per pair. colors: set_name -> colour; labels: set_name -> text.
1636
+ """
1637
+ colors, labels = colors or {}, labels or {}
1638
+ rk = region_keys(an, level)
1639
+ use = motif_usage(an, level)
1640
+ sets = [s for s in an.sets if s in set(rk['set_name'])] + [s for s in rk['set_name'].unique() if s not in an.sets]
1641
+ n_cls = rk['set_name'].value_counts()
1642
+ keep = use.groupby('key')['regions'].max()
1643
+ keep = set(keep[keep >= min_regions].index)
1644
+ use = use[use['key'].isin(keep)]
1645
+ tot = use.groupby('key')['regions'].sum()
1646
+ share_b = (use[use['set_name'] == sets[-1]].set_index('key')['regions'].reindex(tot.index).fillna(0) / tot) if len(sets) == 2 else pd.Series(0.5, index=tot.index)
1647
+ label_of = use.drop_duplicates('key').set_index('key')['label']
1648
+ nodes, edges = [], []
1649
+ for s in sets:
1650
+ nodes.append({'id': f'c:{s}', 'kind': 'class', 'label': f"{labels.get(s, s)}\n{n_cls[s]:,}", 'size': 45,
1651
+ 'color': colors.get(s, '#888888'), 'set': s,
1652
+ 'title': f'{labels.get(s, s)}: {n_cls[s]:,} regions with a seqlet'})
1653
+ smax = max(tot.max(), 1)
1654
+ for k in tot.index:
1655
+ sb = float(share_b[k])
1656
+ col = colors.get(sets[-1], '#888888') if sb > 0.65 else colors.get(sets[0], '#888888') if sb < 0.35 else '#9a9a9a'
1657
+ per = '; '.join(f"{labels.get(r.set_name, r.set_name)} {r.regions} ({r.share:.0%})" for r in use[use['key'] == k].itertuples())
1658
+ regions = {}
1659
+ for s in sets:
1660
+ g = rk[(rk['set_name'] == s) & rk['keys'].map(lambda ks: k in ks)].nlargest(top_regions, 'best')
1661
+ regions[s] = g['coord'].tolist()
1662
+ nodes.append({'id': f'm:{k}', 'kind': 'motif', 'key': k, 'label': label_of[k], 'size': float(10 + 30 * np.sqrt(tot[k] / smax)),
1663
+ 'color': col, 'title': f'{label_of[k]} ({k}): {per}', 'regions': regions})
1664
+ for r in use[use['key'] == k].itertuples():
1665
+ if r.regions >= 5:
1666
+ edges.append({'id': f'u:{r.set_name}|{k}', 'from': f'c:{r.set_name}', 'to': f'm:{k}', 'kind': 'usage',
1667
+ 'width': float(1 + 10 * r.share), 'color': colors.get(r.set_name, '#888888'),
1668
+ 'title': f'{r.regions} of the {labels.get(r.set_name, r.set_name)} regions ({r.share:.0%}) carry {label_of[k]}'})
1669
+ pc = pair_counts(an, level)
1670
+ pc = pc[(pc['shared'] >= min_shared) & pc['a'].isin(keep) & pc['b'].isin(keep)]
1671
+ for r in pc.itertuples():
1672
+ regs = pair_regions(an, level, r.set_name, r.a, r.b)['coord'].head(top_regions).tolist()
1673
+ edges.append({'id': f'p:{r.set_name}|{r.a}|{r.b}', 'from': f'm:{r.a}', 'to': f'm:{r.b}', 'kind': 'co', 'set': r.set_name,
1674
+ 'width': float(1 + r.shared / 8), 'color': colors.get(r.set_name, '#888888'),
1675
+ 'dashes': bool(r.shared < r.expected), 'shared': int(r.shared), 'expected': float(r.expected),
1676
+ 'log2_ratio': float(r.log2_ratio), 'a': r.a, 'b': r.b, 'regions': regs,
1677
+ 'title': f'{labels.get(r.set_name, r.set_name)}: {r.shared} regions carry both {label_of[r.a]} and '
1678
+ f'{label_of[r.b]}, {r.expected:.0f} expected (log2 {r.log2_ratio:+.1f})'})
1679
+ rinfo = rk.set_index('coord')
1680
+ for row in rinfo.itertuples():
1681
+ nodes.append({'id': f'r:{row.Index}', 'kind': 'region', 'label': '', 'size': 6, 'set': row.set_name,
1682
+ 'color': colors.get(row.set_name, '#888888'),
1683
+ 'title': f'{row.Index} ({labels.get(row.set_name, row.set_name)}): {", ".join(label_of.get(k, k) for k in row.keys)}; '
1684
+ f'strongest seqlet {row.best:.3f}'})
1685
+ start = [f'c:{s}' for s in sets]
1686
+ for s in sets:
1687
+ top = use[use['set_name'] == s].nlargest(start_motifs, 'regions')['key']
1688
+ start += [f'm:{k}' for k in top]
1689
+ return {'nodes': nodes, 'edges': edges, 'start': list(dict.fromkeys(start)), 'sets': sets,
1690
+ 'set_labels': {s: labels.get(s, s) for s in sets}}
1691
+
1692
+
1693
+ # -- marginalized pairs (the tables of the marginalize step) ------------------------------------------------
1694
+
1695
+ TERMS = {'pair': 'Both motifs', 'additive': 'Additive expectation', 'anchor_alone': 'Anchor alone',
1696
+ 'partner_alone': 'Partner alone', 'baseline': 'Baseline'}
1697
+
1698
+
1699
+ def coop_dir(an: Analysis) -> Optional[Path]:
1700
+ """
1701
+ Where the cooperativity tables of the analysis contrast are: marginalize/<contrast name>/ when the run holds
1702
+ tables per contrast (several contrasts read one store), else marginalize/; None when there are none.
1703
+ """
1704
+ for d in (an.out / 'marginalize' / an.contrast.name, an.out / 'marginalize'):
1705
+ if (d / 'summary.csv').exists():
1706
+ return d
1707
+ return None
1708
+
1709
+
1710
+ def coop_table(an: Analysis, scan: str = 'line') -> pd.DataFrame:
1711
+ """The cooperativity table of a scan for the analysis contrast (Analysis.cooperativity, per contrast)."""
1712
+ return an._get(f'view/coop/{scan}', lambda: pd.read_csv(coop_dir(an) / f'cooperativity_{scan}.csv'))
1713
+
1714
+
1715
+ def coop_conditions(an: Analysis, scan: str = 'line') -> List[str]:
1716
+ """The condition columns of a cooperativity table in order: A, B, then B − A."""
1717
+ return list(dict.fromkeys(coop_table(an, scan)['condition']))
1718
+
1719
+
1720
+ def coop_space(an: Analysis) -> str:
1721
+ """' (logit)' and the like when the tables are in the model's output space, as the step's figures say."""
1722
+ from ..marginalize.cooperativity import settings_of
1723
+ return '' if settings_of(an.cfg)['real_space'] or an.store.space == 'identity' else f' ({an.store.space})'
1724
+
1725
+
1726
+ def pair_table(an: Analysis) -> pd.DataFrame:
1727
+ """
1728
+ One row per marginalized pair: its two motif sequences and, per condition, the peak cooperativity of the
1729
+ line scan (of the heatmap scan when there is no line scan) and the spacing or offsets where it is.
1730
+ """
1731
+ s = pd.read_csv(coop_dir(an) / 'summary.csv')
1732
+ scan = 'line' if (s['scan'] == 'line').any() else 'heatmap'
1733
+ s = s[s['scan'] == scan]
1734
+ at = s['at_spacing'].astype('Int64').astype(str) if scan == 'line' else \
1735
+ s['at_anchor_offset'].astype('Int64').astype(str) + ', ' + s['at_partner_offset'].astype('Int64').astype(str)
1736
+ s = s.assign(at=at)
1737
+ out = s[['anchor', 'partner']].drop_duplicates().reset_index(drop=True)
1738
+ d = an.design
1739
+ out['anchor_seq'], out['partner_seq'] = out['anchor'].map(d.anchors), out['partner'].map(d.partners)
1740
+ for c in dict.fromkeys(s['condition']):
1741
+ sc = s[s['condition'] == c].set_index(['anchor', 'partner'])
1742
+ idx = pd.MultiIndex.from_frame(out[['anchor', 'partner']])
1743
+ out[f'peak|{c}'] = sc['peak_cooperativity'].reindex(idx).to_numpy()
1744
+ out[f'at|{c}'] = sc['at'].reindex(idx).to_numpy()
1745
+ return out
1746
+
1747
+
1748
+ def spacing_terms(an: Analysis, anchor: str, partner: str) -> pd.DataFrame:
1749
+ """The line scan of one pair in long form, every condition: spacing, condition, term, value, sem."""
1750
+ t = coop_table(an, 'line')
1751
+ t = t[(t['anchor'] == anchor) & (t['partner'] == partner)]
1752
+ parts = [t[['spacing', 'condition']].assign(term=label, value=t[k].to_numpy(), sem=t[f'{k}_sem'].to_numpy())
1753
+ for k, label in TERMS.items()]
1754
+ return pd.concat(parts, ignore_index=True)
1755
+
1756
+
1757
+ #: the quantities of a cooperativity table, by column, as the step's figures name them: the cooperativity itself
1758
+ #: and the absolute signals it is built from
1759
+ QUANTITIES = {'cooperativity': 'Cooperativity', 'pair': 'Both motifs', 'additive': 'Additive expectation',
1760
+ 'anchor_alone': 'Anchor alone', 'partner_alone': 'Partner alone', 'baseline': 'Baseline'}
1761
+
1762
+
1763
+ def signed_quantity(value: str, condition: str, conditions: List[str]) -> bool:
1764
+ """Whether a quantity is read around zero: the cooperativity always, any quantity of the difference B - A."""
1765
+ return value == 'cooperativity' or condition in conditions[2:]
1766
+
1767
+
1768
+ def offset_grids(an: Analysis, sigma: Optional[float] = None, value: str = 'cooperativity',
1769
+ vmax_pct: float = 98.0):
1770
+ """
1771
+ The heatmap scan as the step's heatmaps draw it (cooperativity.figures): each pair's mean cooperativity over
1772
+ (anchor offset, partner offset), smoothed by a Gaussian of sigma offset steps ([marginalize] heatmap_sigma,
1773
+ default 1; 0 for none), and the colour limits of those figures: one symmetric limit shared by the two
1774
+ conditions at the vmax_pct percentile of |cooperativity| over every pair, and its own for the difference.
1775
+ value: which quantity of the table to draw (QUANTITIES), the cooperativity by default.
1776
+ Returns (long table: anchor, partner, condition, anchor_offset, partner_offset, value (smoothed),
1777
+ raw (the unsmoothed mean), sem; {condition: (low, high)}), the limits symmetric about zero for a quantity read
1778
+ around zero (signed_quantity) and the percentiles of the values otherwise.
1779
+ """
1780
+ sigma = float(an.cfg.get('marginalize', {}).get('heatmap_sigma', 1.0) if sigma is None else sigma)
1781
+
1782
+ def load():
1783
+ from scipy.ndimage import gaussian_filter
1784
+ t = coop_table(an, 'heatmap')
1785
+ offs = np.unique(np.r_[t['anchor_offset'], t['partner_offset']])
1786
+ x, y = np.meshgrid(offs, offs, indexing='ij')
1787
+ frames = []
1788
+ for (a, p, c), g in t.groupby(['anchor', 'partner', 'condition'], sort=False):
1789
+ grid = lambda v: g.pivot(index='anchor_offset', columns='partner_offset', values=v) \
1790
+ .reindex(index=offs, columns=offs).to_numpy() # noqa: E731
1791
+ raw = grid(value)
1792
+ frames.append(pd.DataFrame({
1793
+ 'anchor': a, 'partner': p, 'condition': c, 'anchor_offset': x.ravel(), 'partner_offset': y.ravel(),
1794
+ 'value': (gaussian_filter(raw, sigma) if sigma else raw).ravel(), 'raw': raw.ravel(),
1795
+ 'sem': grid(f'{value}_sem').ravel()}))
1796
+ out = pd.concat(frames, ignore_index=True).dropna(subset=['value'])
1797
+ conds = coop_conditions(an, 'heatmap')
1798
+
1799
+ def lim(cs):
1800
+ v = out.loc[out['condition'].isin(cs), 'value']
1801
+ if signed_quantity(value, cs[0], conds):
1802
+ return (lambda m: (-m, m))(float(np.nanpercentile(v.abs(), vmax_pct)) or 1.0)
1803
+ lo, hi = (float(x) for x in np.nanpercentile(v, [100 - vmax_pct, vmax_pct]))
1804
+ return (lo, hi) if hi > lo else (lo, lo + 1.0)
1805
+ diff = dict.fromkeys(conds[2:], lim(conds[2:])) if conds[2:] else {} # none in a single-track run
1806
+ return out, {**dict.fromkeys(conds[:2], lim(conds[:2])), **diff}
1807
+ return an._get(('view/offsets', sigma, value, vmax_pct), load)
1808
+
1809
+
1810
+
1811
+ # -- from a gene back to its regions --------------------------------------------------------------
1812
+ COORD = re.compile(r'[^:]+:\d+-\d+')
1813
+ SAME, OPPOSITE, NOT_DIFF = 'changes with the gene', 'changes against the gene', 'not differential'
1814
+ #: the selection's filters on the prediction (selection.from_candidates): a region stopped there is differential in the
1815
+ #: measurement, only not reproduced by the model, so it counts when the question is the measured change
1816
+ MODEL_FILTERS = ('Opposite direction', 'Insufficient magnitude')
1817
+
1818
+
1819
+ def gene_run(an: Analysis) -> bool:
1820
+ """True when each region is one gene's window (an expression model such as Decima): the candidates name a gene."""
1821
+ from .. import selection as SEL
1822
+
1823
+ def load():
1824
+ try:
1825
+ files = SEL.candidate_files(an.cfg)
1826
+ return bool(files) and 'gene' in pd.read_csv(files[0], nrows=0).columns
1827
+ except Exception:
1828
+ return False
1829
+ return an._get('view/gene_run', load)
1830
+
1831
+
1832
+ def all_region_genes(an: Analysis) -> pd.DataFrame:
1833
+ """
1834
+ coord, gene for every candidate region of the run (the region table), not only those with seqlets: going from a gene
1835
+ back to its regions needs the ones the selection left out too. Regions named without coordinates are skipped.
1836
+ """
1837
+ from .. import expression as X
1838
+
1839
+ def load():
1840
+ t = an.region_table
1841
+ coords = (t['coord'] if t is not None else an.seqlets.meta['coord']).astype(str)
1842
+ return X.assign_genes(an.cfg, [c for c in pd.unique(coords) if COORD.fullmatch(c)])
1843
+ return an._get('view/all_region_genes', load)
1844
+
1845
+
1846
+ def gene_expression(an: Analysis, gene: str) -> Optional[pd.Series]:
1847
+ """The gene's row of the expression table (log2fc of B over A, padj), matched without case; None if absent."""
1848
+ de = an.expression_table
1849
+ if de is None:
1850
+ return None
1851
+ hit = de[de['gene'].astype(str).str.upper() == str(gene).upper()]
1852
+ return hit.iloc[0] if len(hit) else None
1853
+
1854
+
1855
+ def gene_ocrs(an: Analysis, gene: str) -> pd.DataFrame:
1856
+ """
1857
+ Every candidate region linked to `gene` under the run's rule ([expression] assign), those the selection left out
1858
+ included. Per region: stage and set_name, measured and predicted B - A, change (measured when known, else
1859
+ predicted), whether it changes with the gene's expression (same sign as its log2FC), against it, or is not
1860
+ differential; attributed, whether it reached seqlet calling. With measured values a region is differential when it
1861
+ passed the selection's measured filters, whether or not the model then reproduced it (MODEL_FILTERS); without them,
1862
+ when it was included. kb: its centre minus the gene's nearest TSS (genomic, when [expression] genes gives TSS
1863
+ positions); motifs and n, the motifs and seqlets of the attributed ones.
1864
+ """
1865
+ from .. import expression as X
1866
+
1867
+ def load():
1868
+ links = all_region_genes(an)
1869
+ coords = links.loc[links['gene'].astype(str).str.upper() == str(gene).upper(), 'coord'].unique()
1870
+ t = an.region_table
1871
+ if t is None:
1872
+ t = pd.DataFrame({'coord': coords, 'stage': 'Included', 'set_name': ''})
1873
+ if 'contrast' in t:
1874
+ t = t[t['contrast'] == an.contrast.name]
1875
+ t = t[t['coord'].isin(coords)].drop_duplicates('coord').copy()
1876
+ for c in ('meas_diff', 'pred_diff'):
1877
+ t[c] = t[c] if c in t else np.nan
1878
+ t['change'] = t['meas_diff'].where(t['meas_diff'].notna(), t['pred_diff'])
1879
+ lfc = gene_expression(an, gene)
1880
+ sign = np.sign(lfc['log2fc']) if lfc is not None and pd.notna(lfc['log2fc']) else 0
1881
+ t['attributed'] = t['stage'] == 'Included'
1882
+ diff = t['attributed'] | (t['stage'].isin(MODEL_FILTERS) & t['meas_diff'].notna())
1883
+ t['concordance'] = np.where(~diff, NOT_DIFF, np.where(np.sign(t['change']) == sign, SAME, OPPOSITE))
1884
+ mid = t['coord'].map(lambda c: (lambda a, b: (a + b) / 2)(*map(int, c.split(':')[1].split('-'))))
1885
+ tss = X.gene_tss(an.cfg)
1886
+ t['kb'] = np.nan
1887
+ if tss is not None:
1888
+ g = tss[tss['gene'].astype(str).str.upper() == str(gene).upper()]
1889
+ chrom = t['coord'].str.split(':').str[0]
1890
+ for i in t.index:
1891
+ pos = g.loc[g['chrom'].astype(str).str.removeprefix('chr') == chrom[i].removeprefix('chr'), 'tss']
1892
+ if len(pos):
1893
+ d = mid[i] - pos.to_numpy(float)
1894
+ t.loc[i, 'kb'] = d[np.argmin(np.abs(d))] / 1000
1895
+ rt = region_table(an, 'subfamily')
1896
+ rt = rt.drop_duplicates('coord').set_index('coord') if 'coord' in rt else rt
1897
+ t['motifs'] = rt['motifs'].reindex(t['coord']).to_numpy() if len(rt) else None
1898
+ t['n'] = rt['n'].reindex(t['coord']).fillna(0).astype(int).to_numpy() if len(rt) else 0
1899
+ keep = ['coord', 'set_name', 'stage', 'attributed', 'meas_diff', 'pred_diff', 'change', 'concordance', 'kb',
1900
+ 'motifs', 'n']
1901
+ return t[keep].sort_values(['kb', 'coord'], na_position='last').reset_index(drop=True)
1902
+ return an._get(('view/gene_ocrs', str(gene).upper()), load)
1903
+
1904
+
1905
+ def gene_motifs(ocrs: pd.DataFrame) -> pd.DataFrame:
1906
+ """motif, and per concordance class the number of the gene's regions carrying it: which motifs recur where."""
1907
+ rows = [(m.strip(), c) for ms, c in zip(ocrs['motifs'], ocrs['concordance']) if isinstance(ms, str)
1908
+ for m in ms.split(',') if m.strip()]
1909
+ if not rows:
1910
+ return pd.DataFrame(columns=['motif', SAME, OPPOSITE, NOT_DIFF])
1911
+ t = pd.DataFrame(rows, columns=['motif', 'concordance']).value_counts().unstack(fill_value=0)
1912
+ for c in (SAME, OPPOSITE, NOT_DIFF):
1913
+ t[c] = t[c] if c in t else 0
1914
+ return t[[SAME, OPPOSITE, NOT_DIFF]].sort_values([SAME, OPPOSITE], ascending=False).reset_index()
1915
+
1916
+
1917
+ def gene_elements(an: Analysis, coord: str) -> Tuple[pd.DataFrame, dict]:
1918
+ """
1919
+ For a gene run (each region one gene's window): every seqlet as an element of that gene, its contribution to the
1920
+ gene's predicted B - A (the contrast contributions summed over its span; all contributions together add up to the
1921
+ predicted change, up to the integration error), a and b (the same sum under each condition), repressive (a + b
1922
+ below zero), effect (the contribution by size, seqlets.by_size: above zero where the element acts more in B, below
1923
+ where more in A, so one that represses in both, more in A, reads negative although it raises B over A) and kb, its
1924
+ centre relative to the TSS in the gene's direction, from the file's `tss_position` or [run] tss_position (Decima:
1925
+ 163840), else from the window start. Also: gene, the contributions' total, the share the seqlets carry, and whether
1926
+ positions are relative to the TSS.
1927
+ """
1928
+ def load():
1929
+ ex = region(an, coord)
1930
+ contrib = np.asarray(ex.record['contributions'], np.float64)
1931
+ mid = np.asarray(ex.record['polarity'], np.float64)
1932
+ meta = {}
1933
+ try:
1934
+ meta = an.source.metadata(an.source.path_for(coord))
1935
+ except Exception:
1936
+ pass
1937
+ tss = meta.get('tss_position', an.cfg.get('run', {}).get('tss_position'))
1938
+ names = motif_names(pd.DataFrame(ex.seqlets)) if ex.seqlets else []
1939
+ rows = []
1940
+ for q, n in zip(ex.seqlets, names):
1941
+ d, m = float(contrib[q['start']:q['end']].sum()), float(mid[q['start']:q['end']].sum())
1942
+ rows.append({'motif': n, 'start': int(q['start']), 'end': int(q['end']), 'contribution': d,
1943
+ 'a': m - d / 2, 'b': m + d / 2, 'repressive': m < 0, 'effect': float(SQ.by_size(d, m)),
1944
+ 'kb': ((q['start'] + q['end']) / 2 - (tss if tss is not None else 0)) / 1000, 'cluster': q.get('cluster')})
1945
+ el = pd.DataFrame(rows, columns=['motif', 'start', 'end', 'contribution', 'a', 'b', 'repressive', 'effect', 'kb', 'cluster'])
1946
+ total = float(contrib.sum())
1947
+ info = {'gene': meta.get('gene', coord), 'total': total, 'relative_to_tss': tss is not None,
1948
+ 'share': float(el['contribution'].sum() / total) if total else float('nan'), 'n': len(el)}
1949
+ return el.sort_values('kb').reset_index(drop=True), info
1950
+ return an._get(('view/gene_elements', coord), load)