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,744 @@
1
+ """
2
+ A run as one object: the steps of the command line as methods, the outputs of every step as attributes
3
+ read back from the run directory, and the tables and figures of a walkthrough.
4
+
5
+ from diffgrammar import Analysis
6
+ an = Analysis('config.toml', seqlets={'pct': 0.05}) # keyword arguments override config sections
7
+ an.run_pipeline() # or the steps one by one: an.run_seqlets(), ...
8
+ an.top_motifs()
9
+
10
+ Every run_* method calls the command-line step of the same name (diffgrammar.cli), so a notebook and
11
+ `diffgrammar pipeline` write the same files and the same run.json entries. A model built in Python is
12
+ passed as `predictor` (a TorchEnsemble, see diffgrammar.marginalize.predictor) and replaces the config's
13
+ predictor factory in the attribute and marginalize steps. Outputs are read lazily from
14
+ the run directory, so a new session can tabulate and plot a finished run without recomputing it.
15
+
16
+ Figures come back closed, so a notebook shows each once; pass save='name' to any plot_* method to write
17
+ name.pdf and name.png into <run>/figures. Paths given as overrides are taken relative to the working
18
+ directory; paths in the config file stay relative to the config file.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import copy
23
+ import json
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import Dict, List, Optional, Sequence, Tuple
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+
31
+ from . import cli
32
+ from . import config as C
33
+ from . import plotting as P
34
+ from . import summaries as S
35
+ from .contrast import Contrast, contrast_record
36
+ from .seqlets import by_size
37
+ from .sequence import decode
38
+
39
+
40
+
41
+ def _merge(base: dict, extra: dict) -> dict:
42
+ for k, v in extra.items():
43
+ if isinstance(v, dict) and isinstance(base.get(k), dict):
44
+ _merge(base[k], v)
45
+ else:
46
+ base[k] = v
47
+ return base
48
+
49
+
50
+ @dataclass
51
+ class Example:
52
+ """One region under the run's contrast: its seqlet-calling record, its input and its seqlets with their CWMs."""
53
+ record: dict
54
+ onehot: np.ndarray
55
+ seqlets: List[dict]
56
+ cwms: List[np.ndarray]
57
+ labels: Tuple[str, str] = ('A', 'B')
58
+
59
+ @property
60
+ def single(self) -> bool:
61
+ """A single-track run's record: B's own contributions, no difference (contrast._single_record)."""
62
+ return 'polarity' not in self.record
63
+
64
+ @property
65
+ def diff_name(self) -> str:
66
+ """The name of the difference track: up where a base contributes more in B, down where more in A; the track's
67
+ own name in a single-track run."""
68
+ la, lb = self.labels
69
+ return lb if self.single else f'{lb} ↑ {la} ↓'
70
+
71
+ @property
72
+ def tracks(self) -> Dict[str, np.ndarray]:
73
+ """
74
+ Per-position contributions of the mean A attribution, the mean B attribution and their difference by size
75
+ (seqlets.by_size): B − A, flipped where the base represses on average, so a base that represses in both, more
76
+ in A, points to A as its seqlet does. record['contributions'] keeps the plain B − A.
77
+ """
78
+ la, lb = self.labels
79
+ if self.single:
80
+ return {lb: np.asarray(self.record['contributions'])}
81
+ c, mid = self.record['contributions'], self.record['polarity'] # polarity: mean of A and B
82
+ return {f'{la} mean': mid - c / 2, f'{lb} mean': mid + c / 2, self.diff_name: by_size(c, mid)}
83
+
84
+ @property
85
+ def table(self) -> pd.DataFrame:
86
+ return pd.DataFrame([{'start': r['start'], 'end': r['end'], 'sequence': decode(self.onehot[r['start']:r['end']]),
87
+ 'mot_max': r['mot_max'], 'mot_sum': r['mot_sum'], 'sign': r['sign']}
88
+ for r in self.seqlets]).round(2)
89
+
90
+
91
+ class Analysis:
92
+ def __init__(self, config, contrast: Optional[str] = None, predictor=None, **overrides):
93
+ """
94
+ config: a run config (TOML). contrast: the contrast the tables and figures read (default the first;
95
+ the steps always run every contrast of the config). predictor: a model object for the attribute and
96
+ marginalize steps, in place of the config's factory. overrides: config sections to update, such as
97
+ seqlets={'pct': 0.05} or run={'out_dir': 'results_pct05'}.
98
+ """
99
+ self.cfg = C.load(config)
100
+ tracks = C.tracks_of(self.cfg)
101
+ if tracks:
102
+ raise ValueError(f'{config} has one run per track ({", ".join(tracks)}): open them with '
103
+ f'Analysis.per_track(config), or one with Analysis(<out_dir>/<track>/config.toml)')
104
+ self.predictor = predictor
105
+ if overrides:
106
+ extra = copy.deepcopy(overrides)
107
+ C._resolve_paths(extra, Path.cwd())
108
+ _merge(self.cfg, extra)
109
+ self.out = C.out_dir(self.cfg)
110
+ C.resolve_auto(self.cfg) # the numbers behind "auto" thresholds, once the seqlets step ran
111
+ self.device = self.cfg['run']['device']
112
+ self._static: dict = {}
113
+ self._cache: dict = {}
114
+ name = contrast or next(iter(self.cfg['contrasts']))
115
+ ccfg = self.cfg['contrasts'][name]
116
+ explicit = 'b' in ccfg and ('a' in ccfg or 'a_prefixes' not in ccfg) # track lists, no prefixes to resolve
117
+ self.contrast = Contrast.from_config(name, ccfg, None if explicit else self.source.tracks)
118
+ r = self.cfg.get('report', {})
119
+ self.single = self.contrast.single # one condition, no comparison (a single-track run)
120
+ self.label_a, self.label_b = self.contrast.label_a, self.contrast.label_b
121
+ if self.single:
122
+ self.label_a = ''
123
+ self.colors = {self.label_a: r.get('color_a', P.DEFAULT_A), self.label_b: r.get('color_b', P.DEFAULT_B)}
124
+ self.set_labels = r.get('set_labels', {})
125
+ P.style()
126
+
127
+ @classmethod
128
+ def per_track(cls, config, predictor=None, **kw) -> Dict[str, 'Analysis']:
129
+ """
130
+ track -> Analysis of each run of a single-track config ([attribute] tracks): every track in its own folder,
131
+ <out_dir>/<track>, with its config.toml written there. Each runs and reads like any Analysis
132
+ (run_pipeline, tables, figures), and `diffgrammar view <out_dir>/<track>/config.toml` opens it.
133
+ """
134
+ cfg = C.load(config)
135
+ if not C.tracks_of(cfg):
136
+ raise ValueError(f'{config} has no [attribute] tracks: open it with Analysis(config)')
137
+ return {t: cls(C.write_track_config(C.for_track(cfg, t)), predictor=predictor, **kw) for t in C.tracks_of(cfg)}
138
+
139
+ def __repr__(self):
140
+ c = self.contrast
141
+ what = (f'{c.label_b} alone ({len(c.b)} tracks), no comparison' if self.single else
142
+ f'{c.label_b} ({len(c.b)} tracks) minus {c.label_a} ({len(c.a)} tracks)')
143
+ return (f"Analysis '{self.cfg['run'].get('name', '')}': {what}, {self.cfg['attributions']['adapter']} attributions, "
144
+ f"outputs in {self.out}")
145
+
146
+ @property
147
+ def directions(self) -> Tuple[str, str]:
148
+ """How a seqlet of sign -1 and of sign +1 reads: stronger in A and in B, or, for one condition, lowers and
149
+ raises it."""
150
+ if self.single:
151
+ return f'lowers {self.label_b}', f'raises {self.label_b}'
152
+ return f'stronger in {self.label_a}', f'stronger in {self.label_b}'
153
+
154
+ # -- plumbing ------------------------------------------------------------------------------
155
+ def _get(self, key, load, static=False):
156
+ cache = self._static if static else self._cache
157
+ if key not in cache:
158
+ cache[key] = load()
159
+ return cache[key]
160
+
161
+ def _finish(self, fig, save: Optional[str] = None):
162
+ import matplotlib.pyplot as plt
163
+ if save:
164
+ d = self.out / 'figures'
165
+ d.mkdir(exist_ok=True)
166
+ for ext in ('pdf', 'png'):
167
+ fig.savefig(d / f'{save}.{ext}', bbox_inches='tight')
168
+ plt.close(fig)
169
+ return fig
170
+
171
+ def _step(self, fn, *args, **kw):
172
+ fn(self.cfg, *args, **kw)
173
+ C.resolve_auto(self.cfg)
174
+ self._cache.clear()
175
+
176
+ @property
177
+ def pct(self) -> float:
178
+ """The seqlet cut as a share of each record's budget: the config's number, or the one the seqlets step
179
+ resolved for "auto" (seqlet_settings.json in the run directory)."""
180
+ v = self.cfg['seqlets']['pct']
181
+ if isinstance(v, str):
182
+ from .calibrate import missing_message
183
+ raise RuntimeError(missing_message(self.cfg, Path(self.cfg['_path']).name))
184
+ return float(v)
185
+
186
+ def _seqlet_kw(self, pct: Optional[float] = None) -> dict:
187
+ s = self.cfg['seqlets']
188
+ return dict(pct=self.pct if pct is None else pct, max_gap=s['max_gap'], min_size=s['min_size'],
189
+ max_len=s['max_len'], max_seqlets_per_record=s['max_per_record'], split_frac=s['split_frac'])
190
+
191
+ def show(self, path, width: Optional[int] = None):
192
+ """A figure a step wrote, by its path inside the run directory (such as 'report/motif_bubbles.png')."""
193
+ from IPython.display import Image
194
+ return Image(filename=str(self.out / path), width=width)
195
+
196
+ # -- inputs --------------------------------------------------------------------------------
197
+ @property
198
+ def source(self):
199
+ from .adapters import make_source
200
+ return self._get('source', lambda: make_source(self.cfg['attributions']), static=True)
201
+
202
+ @property
203
+ def sets(self) -> List[str]:
204
+ return self.cfg.get('report', {}).get('sets') or sorted(self.thresholds['set_name'].unique())
205
+
206
+ @property
207
+ def set_colors(self) -> Dict[str, str]:
208
+ r = self.cfg.get('report', {})
209
+ if r.get('set_colors'):
210
+ return r['set_colors']
211
+ if len(self.sets) == 2:
212
+ A, B = S.class_sets(self.sets, self.label_a, self.label_b)
213
+ return {A: self.colors[self.label_a], B: self.colors[self.label_b]}
214
+ return {s: f'C{k}' for k, s in enumerate(self.sets)}
215
+
216
+ def describe(self) -> pd.DataFrame:
217
+ """What the run reads: regions, tracks, input length, the contrast and how its budget is set."""
218
+ src, c = self.source, self.contrast
219
+ r = next(src.regions())
220
+ return pd.Series({'regions': len(src.files()), 'tracks per region': len(src.tracks),
221
+ 'input length (bp)': r.onehot.shape[0],
222
+ 'contrast': (f'{c.label_b} alone ({len(c.b)} tracks)' if self.single else
223
+ f'{c.label_b} ({len(c.b)} tracks) minus {c.label_a} ({len(c.a)} tracks)'),
224
+ 'budget': self.cfg['seqlets']['budget'], 'first region': f'{r.region} ({r.set_name})'}).to_frame('')
225
+
226
+ def sample(self, n_regions: int = 300) -> List[Tuple[dict, np.ndarray]]:
227
+ """(record, onehot) of the first n_regions regions under the contrast, kept for the session."""
228
+ def load():
229
+ from .adapters import make_source
230
+ src = make_source({**self.cfg['attributions'], 'max_regions': n_regions})
231
+ out = []
232
+ for r in src.regions():
233
+ rec = contrast_record(r, self.contrast, self.cfg['seqlets']['budget'])
234
+ if rec is not None:
235
+ out.append((rec, np.asarray(r.onehot, np.float32)))
236
+ return out
237
+ return self._get(('sample', n_regions), load, static=True)
238
+
239
+ # -- one region ----------------------------------------------------------------------------
240
+ def example(self, set_name: Optional[str] = None, n_regions: int = 300, quantile: float = 0.75,
241
+ region: Optional[str] = None) -> Example:
242
+ """
243
+ One region to look at, by id (region) or chosen among the first n_regions of set_name: the one whose
244
+ number of positions above the seqlet cut sits at that quantile (0.75 gives a region with a few seqlets).
245
+ """
246
+ from .seqlets import record_seqlets
247
+ recs = self.sample(n_regions)
248
+ if region is not None:
249
+ rec, oh = next((r, o) for r, o in recs if r['coord'] == region)
250
+ else:
251
+ pct = self.pct
252
+ cand = [(r, o) for r, o in recs if set_name is None or r['set_name'] == set_name]
253
+ above = np.array([(np.abs(r['contributions']) > pct * r['pred']).sum() for r, _ in cand])
254
+ rec, oh = cand[int(np.argmin(np.abs(above - np.quantile(above, quantile))))]
255
+ rows, cwms = record_seqlets(rec, **self._seqlet_kw())
256
+ g = self.genomic_offset(rec['coord'], len(rec['contributions']))
257
+ if g:
258
+ rec['genomic_chrom'], rec['genomic_start'] = g
259
+ return Example(rec, oh, rows, cwms, labels=(self.label_a, self.label_b))
260
+
261
+ def genomic_offset(self, coord: str, length: int) -> Optional[Tuple[str, int]]:
262
+ """
263
+ (chrom, genome position of input 0) of a region whose file carries the attribute step's metadata (summit and
264
+ seq_len, the input being centred on the summit as attribute.windows cuts it); None otherwise, and the
265
+ figures then label input positions.
266
+ """
267
+ src = self.source
268
+ if not (hasattr(src, 'path_for') and hasattr(src, 'metadata')):
269
+ return None
270
+ try:
271
+ m = src.metadata(src.path_for(coord))
272
+ except (KeyError, FileNotFoundError, StopIteration):
273
+ return None
274
+ if {'chrom', 'summit', 'seq_len'} <= set(m) and int(m['seq_len']) == length:
275
+ return str(m['chrom']), int(m['summit']) - length // 2
276
+ return None
277
+
278
+ def plot_example_tracks(self, ex: Example, save=None):
279
+ la, lb = self.label_a, self.label_b
280
+ r = ex.record
281
+ fig = P.plot_tracks(ex.tracks, colors={ex.diff_name: (self.colors[la], self.colors[lb])},
282
+ title=f"{r['coord']} ({r['set_name']}): budget {r['pred']:.1f} from {r['budget_source']}")
283
+ return self._finish(fig, save)
284
+
285
+ def plot_example_seqlets(self, ex: Example, pad: int = 40, save=None):
286
+ r, rows, n = ex.record, ex.seqlets, len(ex.record['contributions'])
287
+ window = (max(0, min(s['start'] for s in rows) - pad), min(n, max(s['end'] for s in rows) + pad)) if rows else None
288
+ cut = self.pct * r['pred']
289
+ fig = P.plot_seqlet_window(ex.tracks[ex.diff_name], rows, window, color_a=self.colors[self.label_a],
290
+ color_b=self.colors[self.label_b], label=f'Contribution, {ex.diff_name}',
291
+ title=f"{r['coord']}: {len(rows)} seqlets above the cut {cut:.2f} "
292
+ f"({self.pct:.0%} of the budget {r['pred']:.1f})")
293
+ return self._finish(fig, save)
294
+
295
+ def plot_example_cwms(self, ex: Example, save=None):
296
+ """The region's seqlets as contribution logos (CWM times the one-hot of the input)."""
297
+ fig = P.plot_logo_grid([[(cwm * ex.onehot[s['start']:s['end']], f"{s['start']}-{s['end']} {'+' if s['sign'] > 0 else '−'}")
298
+ for s, cwm in zip(ex.seqlets, ex.cwms)]])
299
+ return self._finish(fig, save)
300
+
301
+ def plot_example_logos(self, ex: Example, window: Optional[tuple] = None, pad: int = 40, max_bp: int = 1000,
302
+ names: Optional[Sequence[str]] = None, highlight=None,
303
+ share_y: bool = True, ymax: Optional[float] = None, save=None):
304
+ """
305
+ The region as attribution logos (plotting.plot_tracks_logos): each condition's mean contribution and B − A by size,
306
+ every base drawn at its contribution, the seqlets shaded and the cut dotted. window: (lo, hi) in input
307
+ coordinates; default the whole input up to max_bp bases, else the seqlets' span plus pad, centred on the
308
+ strongest seqlet when that is still wider. names label the seqlets (one per seqlet), highlight colours the
309
+ seqlets of that cluster. The axis is in genome coordinates when the record says where input 0 lies
310
+ (genomic_chrom, genomic_start; the viewer reads them from the attribute step's metadata).
311
+ """
312
+ r, rows, L = ex.record, ex.seqlets, len(ex.record['contributions'])
313
+ if window is None:
314
+ if L <= max_bp or not rows:
315
+ window = (0, min(L, max_bp))
316
+ else:
317
+ lo, hi = max(0, min(s['start'] for s in rows) - pad), min(L, max(s['end'] for s in rows) + pad)
318
+ if hi - lo > max_bp:
319
+ best = max(rows, key=lambda s: np.nan_to_num(abs(s['mot_max']))) # a site equal in both: weakest
320
+ lo = max(0, min((best['start'] + best['end']) // 2 - max_bp // 2, L - max_bp))
321
+ hi = lo + max_bp
322
+ window = (lo, hi)
323
+ la, lb = self.label_a, self.label_b
324
+ cut = self.pct * r['pred']
325
+ genomic = (r['genomic_chrom'], r['genomic_start']) if r.get('genomic_start') is not None else None
326
+ shown = sum(1 for s in rows if s['end'] > window[0] and s['start'] < window[1])
327
+ unit = 'seqlet' if len(rows) == 1 else 'seqlets'
328
+ n = f'{len(rows)} {unit}' if shown == len(rows) else f'{shown} of {len(rows)} {unit}'
329
+ fig = P.plot_tracks_logos(ex.onehot, ex.tracks, rows, window=window, cut=cut, names=names, highlight=highlight,
330
+ row_colors={f'{la} mean': self.colors[la], f'{lb} mean': self.colors[lb]},
331
+ share_y=share_y, genomic=genomic, ymax=ymax,
332
+ title=f"{r['coord']} ({r['set_name']}): {n} above the cut {cut:.2f} "
333
+ f"({self.pct:.0%} of the budget {r['pred']:.1f})")
334
+ return self._finish(fig, save)
335
+
336
+ def threshold_sweep(self, pcts: Sequence[float], n_regions: int = 300) -> pd.DataFrame:
337
+ """Seqlets per region, regions with a seqlet and median seqlet length at each pct, on the sample."""
338
+ from .seqlets import collect_seqlets
339
+ recs = [r for r, _ in self.sample(n_regions)]
340
+ ids = [r['record'] for r in recs]
341
+ rows = []
342
+ for pct in pcts:
343
+ s = collect_seqlets(recs, **self._seqlet_kw(pct))
344
+ per = s.meta.groupby('record').size().reindex(ids, fill_value=0)
345
+ rows.append({'pct': pct, 'Seqlets per region': per.mean(), 'Regions with a seqlet (%)': 100 * (per > 0).mean(),
346
+ 'Median seqlet length (bp)': (s.meta['end'] - s.meta['start']).median()})
347
+ return pd.DataFrame(rows)
348
+
349
+ def plot_threshold_sweep(self, pcts: Sequence[float], n_regions: int = 300, save=None):
350
+ fig = P.plot_threshold_sweep(self.threshold_sweep(pcts, n_regions), current=self.pct)
351
+ return self._finish(fig, save)
352
+
353
+ # -- the whole run ---------------------------------------------------------------------------
354
+ def run_pipeline(self, max_regions: Optional[int] = None, force: bool = False):
355
+ """`diffgrammar pipeline`: every step the config asks for, attributions to marginalization."""
356
+ self._step(cli.pipeline, max_regions=max_regions, force=force, predictor=self.predictor)
357
+ self._static.pop('source', None)
358
+
359
+ # -- attributions ---------------------------------------------------------------------------
360
+ def run_attribute(self, max_regions: Optional[int] = None, select_only: bool = False) -> pd.DataFrame:
361
+ """`diffgrammar attribute`: choose the regions of the [attribute] conditions and attribute them; the kept ones per class."""
362
+ self._step(cli.step_attribute, max_regions=max_regions, select_only=select_only, predictor=self.predictor)
363
+ self._static.pop('source', None)
364
+ c = self.candidates
365
+ return c[c['selected']].groupby('class').size().to_frame('regions')
366
+
367
+ def _attribution_dir(self) -> Path:
368
+ from . import attribute
369
+ return Path(attribute.settings_of(self.cfg, need_predictor=False)['out_dir'])
370
+
371
+ @property
372
+ def candidates(self) -> pd.DataFrame:
373
+ """Every candidate region of the attribute step, its statistics and whether it was kept."""
374
+ return self._get('candidates', lambda: pd.read_csv(self._attribution_dir() / 'candidates.csv'))
375
+
376
+ @property
377
+ def attribution_info(self) -> dict:
378
+ """The attribute step's record: conditions, IG settings, the step-count check (`convergence`), completeness."""
379
+ return self._get('attribution_info', lambda: json.loads((self._attribution_dir() / 'config.json').read_text()))
380
+
381
+ def plot_region_selection(self, save=None):
382
+ """Measured against predicted difference of every candidate, the kept regions coloured by class."""
383
+ fig = P.plot_region_selection(self.candidates, self.label_a, self.label_b, self.colors[self.label_a],
384
+ self.colors[self.label_b])
385
+ return self._finish(fig, save)
386
+
387
+ @property
388
+ def region_table(self) -> Optional[pd.DataFrame]:
389
+ """Which regions were kept and why not, with their measured and predicted values (diffgrammar.selection); None if unknown."""
390
+ from . import selection as SEL
391
+ return self._get('region_table', lambda: SEL.region_table(self.cfg, self.thresholds, self.contrast))
392
+
393
+ @property
394
+ def expression_table(self) -> Optional[pd.DataFrame]:
395
+ """gene, log2fc (B over A), padj, base_mean from [expression] (diffgrammar.expression); None without one."""
396
+ from . import expression as X
397
+ return self._get('expression_table', lambda: X.de_table(self.cfg))
398
+
399
+ @property
400
+ def region_genes(self) -> Optional[pd.DataFrame]:
401
+ """coord, gene: the genes of the run's regions under [expression] assign (diffgrammar.expression); None without one."""
402
+ from . import expression as X
403
+ if X.settings(self.cfg) is None:
404
+ return None
405
+ return self._get('region_genes', lambda: X.assign_genes(self.cfg, self.seqlets.meta['coord'].unique().tolist()))
406
+
407
+ def motif_targets(self, level: Optional[str] = None, motifs: Optional[Sequence[str]] = None, sets: Optional[Sequence[str]] = None, n: int = 8) -> tuple:
408
+ """Fold changes of the genes of the regions carrying each motif: (table, values), see expression.motif_targets."""
409
+ from . import expression as X
410
+ from . import summaries as S
411
+ level = level or self.cfg['report']['level']
412
+ sets = list(sets or self.sets)
413
+ if motifs is None:
414
+ lab = S.label_seqlets(self.seqlets.meta, self.families, min_cluster_size=self.cfg['report']['min_cluster_size'])
415
+ size = lab[lab['set_name'].isin(sets)].groupby(['set_name', level])['coord'].nunique().rename('n').reset_index()
416
+ motifs = list(dict.fromkeys(m for s in sets for m in size[size['set_name'] == s].nlargest(n, 'n')[level]))
417
+ return X.motif_targets(self, level, list(motifs), sets)
418
+
419
+ def plot_motif_targets(self, level: Optional[str] = None, motifs: Optional[Sequence[str]] = None, sets: Optional[Sequence[str]] = None, n: int = 8, save=None):
420
+ """Per motif and set, the fold change of the genes assigned to the regions carrying it; None without [expression]."""
421
+ if self.expression_table is None or self.region_genes is None:
422
+ return None
423
+ from . import expression as X
424
+ level = level or self.cfg['report']['level']
425
+ sets = list(sets or self.sets)
426
+ table, values = self.motif_targets(level, motifs, sets, n)
427
+ names = [m for m in dict.fromkeys(table['motif']) if m != X.ALL_REGIONS]
428
+ fam = self.families.sort_values('n_seqlets', ascending=False).drop_duplicates(level)
429
+ logos = {r[level]: self.logos[r['cluster']] for _, r in fam.iterrows() if r[level] in names and r['cluster'] in self.logos}
430
+ fig = P.plot_motif_targets(table, values, names, sets, X.ALL_REGIONS, logos, self.set_labels,
431
+ f'log2FC of the assigned genes ({self.label_b} / {self.label_a})')
432
+ return self._finish(fig, save)
433
+
434
+ def _all_sets(self, table: pd.DataFrame) -> List[str]:
435
+ """The sets of a table, the report's first; 'none' is the class of candidates without a direction."""
436
+ return self.sets + [s for s in dict.fromkeys(table['set_name']) if s not in self.sets and s != 'none']
437
+
438
+ def plot_selection_funnel(self, save=None):
439
+ """Per contrast and set, the share of regions each filter removed and the number kept; None without a region table."""
440
+ from . import selection as SEL
441
+ if self.region_table is None or 'stage' not in self.region_table:
442
+ return None
443
+ counts = SEL.stage_counts(self.region_table)
444
+ fig = P.plot_selection_funnel(counts, SEL.stage_order(counts), self._all_sets(counts), list(self.cfg['contrasts']), self.set_labels)
445
+ return self._finish(fig, save)
446
+
447
+ def plot_predicted_signal(self, save=None):
448
+ """Predicted signal of the kept regions of each set against shuffled sequences, or all candidates; None if unknown."""
449
+ from . import selection as SEL
450
+ t = self.region_table
451
+ if t is None or not {'pred_a', 'pred_b'} <= set(t.columns):
452
+ return None
453
+ fig = P.plot_predicted_signal(t, SEL.null_table(self.cfg), self.sets, list(self.cfg['contrasts']), self.label_a,
454
+ self.label_b, self.set_labels, self.set_colors)
455
+ return self._finish(fig, save)
456
+
457
+ def plot_measured_predicted(self, save=None):
458
+ """Measured against predicted difference of each set under the contrast, coloured by the filter; None if not measured."""
459
+ t = self.region_table
460
+ if t is None or not {'meas_diff', 'pred_diff', 'stage'} <= set(t.columns):
461
+ return None
462
+ from . import selection as SEL
463
+ t = t[t['contrast'] == self.contrast.name]
464
+ t = t[t['set_name'] != 'none']
465
+ fig = P.plot_measured_predicted(t, self._all_sets(t), SEL.stage_order(SEL.stage_counts(t)), self.label_a, self.label_b, self.set_labels)
466
+ return self._finish(fig, save)
467
+
468
+ def plot_seqlet_threshold(self, save=None):
469
+ """Per set, each region's strongest contribution against its seqlet cut, by whether a seqlet was called."""
470
+ from . import selection as SEL
471
+ thr = self.thresholds[self.thresholds['contrast'] == self.contrast.name]
472
+ fig = P.plot_seqlet_threshold(thr.assign(outcome=SEL.seqlet_outcomes(thr)), self._all_sets(thr), self.pct,
473
+ self.cfg['seqlets']['min_size'], self.set_labels)
474
+ return self._finish(fig, save)
475
+
476
+ def pair_effects(self, x, y, sets=None, max_dist=None, value='diff') -> pd.DataFrame:
477
+ """One motif's effect against another's per region, with what can colour it (diffgrammar.effects)."""
478
+ from . import effects as E
479
+ out = E.pair_effects(self, x, y, sets, max_dist, value)
480
+ missing = out.attrs.get('missing', 0)
481
+ out = E.add_region_values(out, self)
482
+ out.attrs['missing'] = missing
483
+ return out
484
+
485
+ def plot_effect_scatter(self, x, y, color_by=('x_variant',), sets=None, max_dist=None, value='diff', save=None):
486
+ """pair_effects as a figure: one panel per set, one row per entry of color_by (a column of the table)."""
487
+ from . import effects as E
488
+ t = self.pair_effects(x, y, sets, max_dist, value)
489
+ return self._finish(P.plot_effect_scatter(*E.scatter_args(self, t, x, y, color_by, sets, value)), save)
490
+
491
+ # -- seqlets -------------------------------------------------------------------------------
492
+ def run_seqlets(self, max_regions: Optional[int] = None) -> pd.DataFrame:
493
+ """`diffgrammar seqlets --force`: seqlets on every region, then the counts per set and direction."""
494
+ self._step(cli.step_seqlets, max_regions=max_regions, force=True)
495
+ return self.seqlet_counts()
496
+
497
+ @property
498
+ def seqlets(self):
499
+ """
500
+ The differential seqlets the tables and figures read, one row per site: once `cluster` ran on seqlets called
501
+ on several tracks, the sites with a differential seqlet (cluster.differential_sites over `sites`), each
502
+ spanning every track's seqlet there with its differential seqlet's values; else the seqlets as called, on
503
+ the 'diff' track. The condition tracks' own seqlets widen the sites and shape the motifs and are read nowhere
504
+ else; `diffgrammar seqlets` output as such is seqlets/ in the run directory.
505
+ """
506
+ from .cluster import differential_sites
507
+ return self._get('seqlets', lambda: differential_sites(self.sites))
508
+
509
+ @property
510
+ def sites(self):
511
+ """
512
+ Every site of the run, the ones equal in both conditions included (merged_seqlets, one row per site per
513
+ contrast, sign 0 where no differential seqlet was called; cluster.merge_overlapping_seqlets), or the seqlets
514
+ as called when the run has one track.
515
+ """
516
+ from .seqlets import SeqletCollection
517
+ return self._get('sites', lambda: SeqletCollection.load(cli._clustered(self.cfg, self.out)))
518
+
519
+ @property
520
+ def thresholds(self) -> pd.DataFrame:
521
+ """One row per region and contrast: the contrast's record (selection.contrast_thresholds); thresholds.csv has one per track."""
522
+ from . import selection as SEL
523
+ return self._get('thresholds', lambda: SEL.contrast_thresholds(pd.read_csv(self.out / 'thresholds.csv')))
524
+
525
+ def seqlet_counts(self) -> pd.DataFrame:
526
+ meta, thr = self.seqlets.meta, self.thresholds
527
+ meta = meta[meta['contrast'] == self.contrast.name]
528
+ thr = thr[thr['contrast'] == self.contrast.name]
529
+ t = (meta.groupby(['set_name', 'sign']).size().unstack(fill_value=0)
530
+ .rename(columns={-1: self.directions[0], 1: self.directions[1], 0: 'equal in both'}))
531
+ t['regions'] = thr.groupby('set_name')['coord'].nunique()
532
+ t['regions with a seqlet'] = meta.groupby('set_name')['coord'].nunique()
533
+ return t
534
+
535
+ def plot_seqlet_overview(self, save=None):
536
+ meta = self.seqlets.meta
537
+ fig = P.plot_seqlet_overview(meta[meta['contrast'] == self.contrast.name], self.sets, self.set_labels,
538
+ self.set_colors, self.colors[self.label_a], self.colors[self.label_b],
539
+ self.label_a, self.label_b, directions=self.directions)
540
+ return self._finish(fig, save)
541
+
542
+ def budget_diagnostics(self, bins: int = 5) -> pd.DataFrame:
543
+ """Regions binned by budget over their strongest single contribution: seqlets and positions above the cut."""
544
+ thr = self.thresholds.assign(budget_ratio=lambda t: t['budget'] / t['max_abs_contribution'])
545
+ cap = self.cfg['seqlets']['max_per_record']
546
+ low = thr['budget_ratio'] < 1
547
+ print(f"budget below the strongest contribution: {low.sum()} regions ({low.mean():.1%}), "
548
+ f"{thr.loc[low, 'n_seqlets'].sum() / thr['n_seqlets'].sum():.1%} of seqlets; "
549
+ f"regions at the {cap}-seqlet cap: {(thr['n_seqlets'] >= cap).sum()}")
550
+ return thr.groupby(pd.qcut(thr['budget_ratio'], bins), observed=True).agg(
551
+ regions=('record', 'size'), seqlets_per_region=('n_seqlets', 'mean'),
552
+ positions_above_cut=('n_above_cut', 'mean')).round(1)
553
+
554
+ # -- clusters ------------------------------------------------------------------------------
555
+ def run_cluster(self, n: int = 12) -> pd.DataFrame:
556
+ """`diffgrammar cluster`: seqlets clustered into motifs; the n largest clusters."""
557
+ self._step(cli.step_cluster)
558
+ return self.clusters.head(n)
559
+
560
+ @property
561
+ def clusters(self) -> pd.DataFrame:
562
+ return self._get('clusters', lambda: pd.read_csv(self.out / 'cluster_summary.csv'))
563
+
564
+ @property
565
+ def consensus(self) -> Dict[int, np.ndarray]:
566
+ return self._get('consensus', lambda: {int(c): np.load(self.out / 'cluster_consensus' / f'consensus_cl{c:03d}.npy')
567
+ for c in self.clusters['cluster']})
568
+
569
+ @property
570
+ def logos(self) -> Dict[int, np.ndarray]:
571
+ """The contribution consensus of each cluster, what logos show (`consensus` itself for a run clustered on contributions)."""
572
+ def load():
573
+ ids = self.clusters['cluster'].astype(int).tolist()
574
+ return dict(zip(ids, cli._logos(self.cfg, self.out, ids, [self.consensus[c] for c in ids])))
575
+ return self._get('logos', load)
576
+
577
+ @property
578
+ def pfms(self) -> Dict[int, np.ndarray]:
579
+ """Each cluster's sequence frequencies over its consensus frame and cli.PFM_FLANK bp on each side, (L, 4)
580
+ (cli._consensus_pfm), saved on first use."""
581
+ def load():
582
+ ids = self.clusters['cluster'].astype(int).tolist()
583
+ return dict(zip(ids, cli._consensus_pfm(self.cfg, self.out, ids, [self.consensus[c] for c in ids])))
584
+ return self._get('pfms', load)
585
+
586
+ def plot_cluster_sizes(self, n: int = 30, save=None):
587
+ fig = P.plot_cluster_sizes(self.clusters, n, self.colors[self.label_a], self.colors[self.label_b], self.label_a,
588
+ self.label_b, title=f'{len(self.clusters)} clusters; the {n} largest',
589
+ directions=self.directions)
590
+ return self._finish(fig, save)
591
+
592
+ def plot_cluster_members(self, cluster: Optional[int] = None, n: int = 5, save=None):
593
+ """A cluster's consensus (default the largest) beside n of its seqlets, each on the strand it was called."""
594
+ cluster = int(self.clusters['cluster'].iloc[0]) if cluster is None else int(cluster)
595
+ meta = self.seqlets.meta
596
+ sub = cli._with_sequences(self.cfg, self.seqlets.take(np.flatnonzero(meta['cluster'].to_numpy() == cluster)[:n]))
597
+ fig = P.plot_logo_grid([[(self.logos[cluster], f'cl{cluster} consensus')] +
598
+ [(sub.get_contribution(k), sub.meta['coord'].iat[k]) for k in range(len(sub))]],
599
+ width=7.0, title_size=5.5)
600
+ return self._finish(fig, save)
601
+
602
+ # -- JASPAR ----------------------------------------------------------------------------------
603
+ def run_families(self, n: int = 10) -> pd.DataFrame:
604
+ """`diffgrammar families`: JASPAR matches and subfamilies; the n largest clusters with their match."""
605
+ self._step(cli.step_families)
606
+ ann = self.annotations
607
+ print(f'{len(ann)} JASPAR matrices in {ann["group"].nunique()} families and {ann["subfamily"].nunique()} '
608
+ f'subfamilies; {self.families["subfamily"].nunique()} subfamilies among {len(self.families)} clusters')
609
+ return self.families.sort_values('n_seqlets', ascending=False)[
610
+ ['cluster', 'n_seqlets', 'tf', 'match_p', 'group', 'subfamily', 'top_tfs']].head(n)
611
+
612
+ @property
613
+ def families(self) -> pd.DataFrame:
614
+ return self._get('families', lambda: pd.read_csv(self.out / 'families' / 'cluster_families.csv'))
615
+
616
+ @property
617
+ def annotations(self) -> pd.DataFrame:
618
+ return self._get('annotations', lambda: pd.read_csv(self.out / 'families' / 'jaspar_subfamilies.csv'))
619
+
620
+ @property
621
+ def hits(self) -> Dict[int, list]:
622
+ return self._get('hits', lambda: {int(k): v for k, v in
623
+ json.loads((self.out / 'jaspar_matches.json').read_text()).items()})
624
+
625
+ @property
626
+ def jaspar(self):
627
+ """(ids, names, pwms) of the JASPAR file in the config."""
628
+ from .jaspar import load_meme
629
+ return self._get('jaspar', lambda: load_meme(self.cfg['jaspar']['meme']), static=True)
630
+
631
+ def plot_jaspar_matches(self, n: int = 6, save=None):
632
+ """The n largest clusters above their best JASPAR matrix, in bits, on the strand of the consensus."""
633
+ from .cluster import orient_like
634
+ from .jaspar import information_content
635
+ pwm = dict(zip(self.jaspar[0], self.jaspar[2]))
636
+ top, bottom = [], []
637
+ for c in self.clusters['cluster'].head(n).astype(int):
638
+ best = self.hits[c][0]
639
+ ic = orient_like([information_content(pwm[best['id']])], self.consensus[c], device=self.device)[0]
640
+ top.append((self.logos[c], f'cl{c}'))
641
+ bottom.append((ic, f"{best['tf']} p = {best['pval']:.0e}"))
642
+ fig = P.plot_logo_grid([top, bottom], row_labels=['consensus', 'best JASPAR'], width=7.0)
643
+ return self._finish(fig, save)
644
+
645
+ def plot_cluster_report(self, clusters: Optional[Sequence[int]] = None, targets: bool = False, save=None):
646
+ """
647
+ Per cluster and region set: its logo, its seqlets stronger in each condition, and each condition's contribution.
648
+ clusters: these instead of the report's largest. targets: with [expression], a panel per set of the fold changes
649
+ of the genes of the regions where each cluster has a seqlet (each gene once), the set's median dashed.
650
+ """
651
+ ids = self.clusters['cluster'].astype(int).tolist()
652
+ kw = {}
653
+ de, links = (self.expression_table, self.region_genes) if targets else (None, None)
654
+ if de is not None and links is not None and len(links):
655
+ from . import expression as X
656
+ m = self.seqlets.meta
657
+ m = m[m['contrast'] == self.contrast.name]
658
+ shown = clusters if clusters is not None else m['cluster'].unique()
659
+ kw = dict(targets={(int(c), s): X.target_values(de, links, m.loc[(m['cluster'] == c) & (m['set_name'] == s), 'coord'].unique())
660
+ for c in shown for s in self.sets},
661
+ target_ref={s: float(np.median(v)) if len(v) else np.nan for s in self.sets
662
+ for v in [X.target_values(de, links, m.loc[m['set_name'] == s, 'coord'].unique())]},
663
+ target_label=f'Nearby genes\nlog2FC {self.label_b}/{self.label_a}')
664
+ fig = cli._cluster_report(self.cfg, self.seqlets.meta, self.thresholds, ids, [self.logos[c] for c in ids], self.hits,
665
+ json.loads((self.out / 'contrasts.json').read_text()), clusters=clusters, **kw)
666
+ return self._finish(fig, save) if fig is not None else None
667
+
668
+ def plot_cluster_logos(self, n: int = 24, save=None):
669
+ ids = self.clusters['cluster'].astype(int).tolist()
670
+ fig = P.plot_cluster_logos(ids, [self.logos[c] for c in ids], self.clusters, hits=self.hits, n_show=n)
671
+ return self._finish(fig, save)
672
+
673
+ def family_matrices(self, family: str) -> pd.DataFrame:
674
+ """The JASPAR matrices of each subfamily of a family."""
675
+ ann = self.annotations
676
+ return ann[ann['group'] == family].groupby('subfamily')['name'].agg(', '.join).to_frame('JASPAR matrices')
677
+
678
+ def family_clusters(self, family: str) -> pd.DataFrame:
679
+ """The clusters whose best match is in a family, with their subfamily."""
680
+ f = self.families
681
+ return f[f['group'] == family][['cluster', 'n_seqlets', 'tf', 'subfamily', 'match_p']].sort_values(
682
+ 'n_seqlets', ascending=False)
683
+
684
+ # -- report --------------------------------------------------------------------------------
685
+ def run_report(self, n: int = 8) -> pd.DataFrame:
686
+ """`diffgrammar report`: motif tables and figures; the n motifs in most regions of each set."""
687
+ self._step(cli.step_report)
688
+ return self.top_motifs(n)
689
+
690
+ def top_motifs(self, n: int = 8) -> pd.DataFrame:
691
+ """The n motifs in most regions of each set, from the report's motif table."""
692
+ level = self.cfg['report']['level']
693
+ t = pd.read_csv(self.out / 'report' / f'motif_table_{level}.csv')
694
+ t = t[t['contrast'] == self.contrast.name]
695
+ cols = [level, 'regions', 'prevalence_pct', 'median_effect', 'share_b', 'top_tfs']
696
+ out = pd.concat({self.set_labels.get(s, s): t[t['set_name'] == s].nlargest(n, 'regions')[cols].reset_index(drop=True)
697
+ for s in self.sets}).round(2)
698
+ return out.rename(columns={'share_b': 'share_raising'}) if self.single else out
699
+
700
+ # -- marginalization -----------------------------------------------------------------------
701
+ def run_marginalize(self, action: str = 'run') -> pd.DataFrame:
702
+ """
703
+ `diffgrammar marginalize`: the [marginalize] pairs, computed where the store lacks them (action 'run'),
704
+ then the cooperativity tables and figures; 'plan' only says what is missing. The summary per pair.
705
+ """
706
+ self._step(cli.step_marginalize, action, predictor=self.predictor)
707
+ return self.cooperativity_summary() if action == 'run' else None
708
+
709
+ @property
710
+ def store(self):
711
+ from .marginalize import Store
712
+ from .marginalize.cooperativity import settings_of
713
+ return self._get('store', lambda: Store(settings_of(self.cfg)['store']))
714
+
715
+ @property
716
+ def design(self):
717
+ from .marginalize.cooperativity import design_of
718
+ return self._get('design', lambda: design_of(self.cfg))
719
+
720
+ def cooperativity(self, scan: str = 'line') -> pd.DataFrame:
721
+ """The cooperativity table of a scan ('line' or 'heatmap'): every quantity per position and condition."""
722
+ return self._get(f'coop/{scan}', lambda: pd.read_csv(self.out / 'marginalize' / f'cooperativity_{scan}.csv'))
723
+
724
+ def cooperativity_summary(self) -> pd.DataFrame:
725
+ """Per pair, scan and condition: the largest cooperativity in magnitude, where it is and its SEM."""
726
+ return pd.read_csv(self.out / 'marginalize' / 'summary.csv').round(3)
727
+
728
+ def plot_marginalization(self, save: bool = False) -> dict:
729
+ """Every marginalization figure of the step, by name; save writes them to <run>/figures."""
730
+ from .marginalize.cooperativity import _readout, conditions, figures, settings_of
731
+ m = settings_of(self.cfg)
732
+ figs = figures(self.store, self.design, conditions(self.cfg, self.store.meta.get('tracks')),
733
+ colors={'a': self.colors[self.label_a], 'b': self.colors[self.label_b]},
734
+ sigma=float(m.get('heatmap_sigma', 1.0)), **_readout(m))
735
+ return {k: self._finish(f, k if save else None) for k, f in figs.items()}
736
+
737
+ # -- provenance ----------------------------------------------------------------------------
738
+ def provenance(self, n: int = 6) -> pd.DataFrame:
739
+ """The last n entries of run.json."""
740
+ log = pd.DataFrame(json.loads((self.out / 'run.json').read_text()))
741
+ for old, new in (('seqlet_scan_version', 'diffgrammar_version'), ('seqlet_scan_commit', 'diffgrammar_commit')):
742
+ if old in log: # entries written when the package was still called seqlet-scan
743
+ log[new] = log[new].fillna(log.pop(old)) if new in log else log.pop(old)
744
+ return log[['step', 'time', 'diffgrammar_version', 'diffgrammar_commit']].tail(n)