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
diffgrammar/cli.py ADDED
@@ -0,0 +1,659 @@
1
+ """
2
+ Command line: one subcommand per step, each reading the run config.
3
+
4
+ diffgrammar attribute CONFIG [--max-regions N] [--select-only] differential regions -> attributions (model env)
5
+ diffgrammar seqlets CONFIG [--max-regions N] [--force] attributions -> seqlets + thresholds
6
+ diffgrammar cluster CONFIG seqlets -> clusters + consensus CWMs
7
+ diffgrammar families CONFIG consensus -> JASPAR matches, subfamilies
8
+ diffgrammar report CONFIG tables and figures
9
+ diffgrammar marginalize plan|run CONFIG motif pairs -> cooperativity (model env)
10
+ diffgrammar pipeline CONFIG [--max-regions N] [--force] all of them in order
11
+ diffgrammar view [CONFIG] [--port N] a finished run in the browser (default ./config.toml)
12
+ diffgrammar export CONFIG [--out DIR] [--n-regions 20] [--n-motifs 5] a small folder that opens with view anywhere
13
+
14
+ `pipeline` attributes when the config has [attribute] and the attributions are not finished yet, and
15
+ marginalizes when it has [marginalize]. A run is one directory (run.out_dir); every step appends what it
16
+ did to run.json there.
17
+
18
+ With [attribute] tracks (single-track runs), every command runs once per track, each in <out_dir>/<track> with
19
+ its own config.toml there; `--track NAME` picks one. `view` and `export` open one track's run.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import re
26
+ import sys
27
+ import time
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+ import pandas as pd
32
+
33
+ from . import calibrate as CAL
34
+ from . import config as C
35
+
36
+
37
+ def log(msg):
38
+ print(f'[{time.strftime("%H:%M:%S")}] {msg}', flush=True)
39
+
40
+
41
+ # -- steps --------------------------------------------------------------------------------------
42
+ def step_seqlets(cfg, max_regions=None, force=False):
43
+ from .adapters import make_source
44
+ from .contrast import Contrast, check_tracks, iter_records
45
+ from .seqlets import call_seqlets
46
+
47
+ out = C.out_dir(cfg)
48
+ if (out / 'seqlets').exists() and not force:
49
+ sys.exit(f'{out / "seqlets"} exists; pass --force to replace it (runs are never mixed)')
50
+ acfg = dict(cfg['attributions'])
51
+ if max_regions:
52
+ acfg['max_regions'] = max_regions
53
+ src = make_source(acfg)
54
+ contrasts = [Contrast.from_config(n, c, src.tracks) for n, c in cfg['contrasts'].items()]
55
+ for c in contrasts:
56
+ log(f'contrast {c.name}: ' + (f'{c.label_b} alone ({len(c.b)} tracks), no comparison' if c.single else
57
+ f'{c.label_b} ({len(c.b)} tracks) - {c.label_a} ({len(c.a)} tracks)'))
58
+ s = CAL.requested(cfg['seqlets']) # "auto" is calibrated again on every run of the step
59
+ CAL.check(s)
60
+ tracks = check_tracks(s['tracks'])
61
+ if all(c.single for c in contrasts):
62
+ tracks = ['b']
63
+ log('tracks: b (one condition: its own attribution)')
64
+ else:
65
+ log(f'tracks: {", ".join(tracks)} (a, b: each condition; diff: their difference)')
66
+ surv = CAL.survey(src.regions(), contrasts, budget=s['budget'], tracks=tracks)
67
+ if surv.empty:
68
+ sys.exit(_no_records(cfg, src, contrasts, s['budget'], max_regions))
69
+ settings = CAL.resolve(s, surv)
70
+ _log_thresholds(settings, surv, cfg, max_regions)
71
+ seqlets, thr = call_seqlets(
72
+ iter_records(src.regions(), contrasts, budget=s['budget'], tracks=tracks,
73
+ min_track_budget_frac=settings['min_track_budget_frac'],
74
+ min_track_budget=settings['min_track_budget'], min_budget=settings['min_budget']),
75
+ pct=settings['pct'], polarity=s['polarity'],
76
+ max_gap=s['max_gap'], min_size=s['min_size'], max_len=s['max_len'],
77
+ max_seqlets_per_record=s['max_per_record'], split_frac=s['split_frac'], log_every=500, log=log)
78
+ if thr.empty:
79
+ sys.exit(f'no record passed the gates (min_budget, min_track_budget, tracks {tracks}): nothing was written, '
80
+ f'the run in {out} is as it was')
81
+ for f in (CAL.SETTINGS, CAL.BUDGETS): # until here the run on disk is whole; from here its thresholds would
82
+ (out / f).unlink(missing_ok=True) # sit beside other seqlets, so they go until the new ones are written
83
+ seqlets.save(out / 'seqlets')
84
+ thr.to_csv(out / 'thresholds.csv', index=False)
85
+ (out / 'contrasts.json').write_text(json.dumps([c.__dict__ for c in contrasts], indent=1))
86
+ surv.to_csv(out / CAL.BUDGETS, index=False)
87
+ CAL.write_settings(out, settings)
88
+ by = seqlets.meta.groupby(['set_name', 'contrast', 'track']).size() if len(seqlets) else pd.Series(dtype=int)
89
+ log(f'{len(seqlets)} seqlets from {len(thr)} records ({thr["coord"].nunique()} regions)\n{by.to_string()}')
90
+ per_track = thr.groupby(['contrast', 'track']).agg(records=('record', 'size'), median_budget=('budget', 'median'),
91
+ median_cut=('cut', 'median'), seqlets=('n_seqlets', 'sum'))
92
+ log(f'per track (the cut is pct of each record\'s own budget; a condition\'s budget is its whole predicted signal, '
93
+ f'the contrast\'s a difference):\n{per_track.to_string()}')
94
+ log(f'budget source: {thr.groupby("track")["budget_source"].value_counts().to_dict()}')
95
+ C.provenance(cfg, 'seqlets', {'n_seqlets': len(seqlets), 'n_records': len(thr), 'max_regions': max_regions,
96
+ 'tracks': tracks, 'seqlets_per_track': thr.groupby('track')['n_seqlets'].sum().to_dict(),
97
+ **{k: settings.get(k) for k in (
98
+ 'pct', 'pct_requested', 'coverage', 'pct_calibrated_on', 'pct_interval',
99
+ 'min_track_budget', 'min_track_budget_requested', 'floor_percentile',
100
+ 'min_track_budget_interval', 'min_track_budget_frac', 'min_budget', 'n_regions',
101
+ 'n_regions_admitted')}})
102
+
103
+
104
+ def _no_records(cfg, src, contrasts, budget, max_regions) -> str:
105
+ """Why the survey came out empty: no region read, or regions read that gave no record (contrast_records)."""
106
+ first = next(iter(src.regions()), None)
107
+ if first is None:
108
+ sets = cfg['attributions'].get('sets')
109
+ return (f'no region{" of the sets " + ", ".join(sets) if sets else ""} was read'
110
+ + (f' among the first {max_regions} files (--max-regions counts files before the set filter)'
111
+ if max_regions else '') + ': nothing to calibrate or call seqlets on')
112
+ why = []
113
+ for c in contrasts:
114
+ missing = [t for t in c.a + c.b if t not in first.hypothetical]
115
+ if missing:
116
+ why.append(f'contrast {c.name}: tracks {missing} are not in the attributions (they have {sorted(first.hypothetical)})')
117
+ elif budget == 'stored' and c.name not in first.budgets:
118
+ why.append(f'contrast {c.name}: [seqlets] budget = "stored", but the attributions carry no stored budget for it '
119
+ f'(files written by diffgrammar attribute carry none; "auto" falls back to completeness)')
120
+ return 'regions were read but none gave a record: ' + ('; '.join(why) or 'no region carries every track of a contrast')
121
+
122
+
123
+ def _called(asked: set) -> str:
124
+ """The records called whatever their budget, among the tracks asked for."""
125
+ cond = sorted(asked & {'a', 'b'})
126
+ parts = (["a region's stronger condition track"] if len(cond) == 2 else
127
+ [f"a region's '{cond[0]}' track where it is the stronger condition"] if cond else [])
128
+ if 'diff' in asked:
129
+ parts.append('its diff track' if parts else "a region's diff track")
130
+ return ' and '.join(parts)
131
+
132
+
133
+ def _interval(iv, n, q) -> str:
134
+ """A 95% interval for the log, saying which end the records could not bound."""
135
+ lo, hi = iv
136
+ if lo is None and hi is None:
137
+ return 'no 95% interval'
138
+ if lo is None:
139
+ return f'95% interval: at most {hi:.4g} ({n} records cannot bound it from below; that takes {CAL.records_to_bound(q):.0f})'
140
+ if hi is None:
141
+ return f'95% interval: at least {lo:.4g} ({n} records cannot bound it from above)'
142
+ return f'95% interval {lo:.4g} to {hi:.4g}'
143
+
144
+
145
+ def _log_thresholds(settings: dict, surv, cfg, max_regions=None) -> None:
146
+ """The resolved cut and gates, where each came from, and what they do to the surveyed records."""
147
+ p = settings
148
+ auto = CAL.is_auto
149
+ asked = set(surv['track'])
150
+ contrasts = cfg.get('contrasts', {})
151
+ single = bool(contrasts) and all('a' not in c and 'a_prefixes' not in c for c in contrasts.values())
152
+ gated = bool(asked & {'a', 'b'}) and not single # a single-track run has no weaker condition to gate
153
+ on = ('the track' if single else 'the differential' if p['pct_calibrated_on'] == 'diff' else
154
+ 'the condition tracks (no diff track was asked for)')
155
+ pct = f"pct {p['pct']:.4g}" + (
156
+ f" (auto: the share of each record's budget at which {p['coverage']:.0%} of the regions still have a position "
157
+ f"above the cut on {on}; {_interval(p['pct_interval'], p['n_pct_records'], 1 - p['coverage'])})"
158
+ if auto(p['pct_requested']) else ' (config)')
159
+ called = _called(asked)
160
+ floor = f"min_track_budget {p['min_track_budget']:.4g}" + (
161
+ (' (not applied: one condition)' if single else ' (not applied: no condition track asked for)') if not gated else
162
+ f" (auto: the {p['floor_percentile']:g}th percentile of the regions' stronger condition budget, "
163
+ f"{_interval(p['min_track_budget_interval'], p['n_floor_regions'], p['floor_percentile'] / 100)}; a condition "
164
+ f"track below it is not called on, except {called})"
165
+ if auto(p['min_track_budget_requested']) else f' (config; a condition track below it is not called on, except {called})')
166
+ extra = (f"; min_track_budget_frac {p['min_track_budget_frac']:g}" if p['min_track_budget_frac'] and gated else '') + (
167
+ f"; min_budget {p['min_budget']:g}: {p['n_regions'] - p['n_regions_admitted']} of {p['n_regions']} regions left out"
168
+ if p['min_budget'] else '')
169
+ log(f'thresholds: {pct}; {floor}{extra}')
170
+ log('per set and track (called: records that pass the gates; above_cut: called records with a position above the '
171
+ 'cut, the precondition for a seqlet):\n' + CAL.summary(surv, settings).to_string(index=False))
172
+ if max_regions:
173
+ per_set = surv.groupby('set_name')['coord'].nunique().to_dict()
174
+ log(f'note: --max-regions {max_regions}: the thresholds are calibrated on the regions of the first {max_regions} '
175
+ f'files only ({per_set}), not on the whole run')
176
+ tails = [(name, tail, iv) for name, tail, iv in (('pct', 'pct_tail', 'pct_interval'),
177
+ ('min_track_budget', 'floor_tail', 'min_track_budget_interval'))
178
+ if tail in p and p[tail] < CAL.FEW_TAIL and (name == 'pct' or gated)]
179
+ if any(None in p[iv] for _, _, iv in tails):
180
+ log(f"note: too few records to bound {', '.join(n for n, _, iv in tails if None in p[iv])} at 95% (see the interval): "
181
+ f"calibrate on more regions, or set the number in [seqlets]")
182
+ elif tails:
183
+ log(f"note: few records in the tail ({', '.join(f'{n} on {p[t]:.0f} records' for n, t, _ in tails)}): another draw "
184
+ f"of regions of the same kind could move the value across its interval, so check that a difference between "
185
+ f"sets holds at both ends")
186
+ if 'attribute' not in cfg and not p['min_budget']:
187
+ strong = CAL.strongest(surv)
188
+ log(f"note: the attributions come from an adapter, so diffgrammar's own selection did not admit these regions; "
189
+ f"their stronger condition budget has 1st percentile {strong.quantile(0.01):.4g}, 5th {strong.quantile(0.05):.4g} "
190
+ f"and median {strong.median():.4g}. {called[0].upper() + called[1:]} {'are' if ' and ' in called else 'is'} "
191
+ f"called whatever the budget, so if the set was not filtered for signal upstream, set [seqlets] min_budget to "
192
+ f"leave out the regions without it ({CAL.BUDGETS} has budget_a / budget_b for every region)")
193
+
194
+
195
+ def step_cluster(cfg):
196
+ from .cluster import cluster_run
197
+ from .seqlets import SeqletCollection
198
+
199
+ out = C.out_dir(cfg)
200
+ seqlets = _with_sequences(cfg, SeqletCollection.load(out / 'seqlets'))
201
+ k = cfg['cluster']
202
+ res = cluster_run(seqlets, merge=k['merge'], n_subsample=k['n_subsample'],
203
+ distance_threshold=k['distance_threshold'], min_cluster_size=k['min_cluster_size'],
204
+ seed=k['seed'], device=cfg['run']['device'], cwm=k['cwm'], merge_mode=k['merge_mode'], log=log)
205
+ seqlets.meta['cluster'] = res.labels
206
+ seqlets.save(out / 'seqlets')
207
+ np.save(out / 'labels.npy', res.labels)
208
+ if res.merged is not None: # the sites per contrast, what the report and the viewer read
209
+ res.merged.save(out / 'merged_seqlets')
210
+ site_map = np.empty(len(res.merge_map), dtype=object) # one list per site, whatever their lengths
211
+ for i, m in enumerate(res.merge_map):
212
+ site_map[i] = list(m)
213
+ np.save(out / 'merge_map.npy', site_map, allow_pickle=True)
214
+ else: # an earlier clustering's sites, which this run has no need of
215
+ import shutil
216
+ shutil.rmtree(out / 'merged_seqlets', ignore_errors=True)
217
+ (out / 'merge_map.npy').unlink(missing_ok=True)
218
+ res.summary.to_csv(out / 'cluster_summary.csv', index=False)
219
+ cdir = out / 'cluster_consensus'
220
+ cdir.mkdir(exist_ok=True)
221
+ for f in cdir.glob('*_cl[0-9]*.npy'): # a previous clustering's matrices, in any representation
222
+ f.unlink()
223
+ for cid, m in zip(res.cluster_ids, res.consensus):
224
+ np.save(cdir / f'consensus_cl{cid:03d}.npy', m)
225
+ (cdir / 'cwm.txt').write_text(k['cwm'])
226
+ _consensus_as(cfg, out, res.cluster_ids, res.consensus, # the other representation, in the same frame
227
+ 'hypothetical' if k['cwm'] == 'contribution' else 'contribution')
228
+ log(f'{len(res.cluster_ids)} clusters; largest:\n{res.summary.head(10).to_string(index=False)}')
229
+ C.provenance(cfg, 'cluster', {'n_clusters': len(res.cluster_ids), 'n_subsample': res.n_subsample, 'cwm': k['cwm'],
230
+ 'merge': res.merged_clustering, 'merge_mode': k['merge_mode'] if res.merged_clustering else None,
231
+ 'n_sites': None if res.merged is None else len(res.merged)})
232
+
233
+
234
+ def _consensus(out):
235
+ summary = pd.read_csv(out / 'cluster_summary.csv')
236
+ ids = summary['cluster'].tolist()
237
+ return summary, ids, [np.load(out / 'cluster_consensus' / f'consensus_cl{c:03d}.npy') for c in ids]
238
+
239
+
240
+ def _with_sequences(cfg, seqlets):
241
+ """seqlets with their seq column; runs called before seqlets stored it read it from the attribution source."""
242
+ if 'seq' not in seqlets.meta:
243
+ from .adapters import make_source
244
+ from .seqlets import attach_sequences
245
+ attach_sequences(seqlets, make_source(cfg['attributions']).sequence)
246
+ return seqlets
247
+
248
+
249
+ def _clustered(cfg, out) -> Path:
250
+ """
251
+ The collection the labels and the consensus rest on: merged_seqlets, one row per site per contrast, every site,
252
+ once `cluster` ran on seqlets called on several tracks (cluster.cluster_run), else seqlets as called. The report
253
+ and the viewer read its differential sites (cluster.differential_sites, Analysis.seqlets).
254
+ """
255
+ return out / ('merged_seqlets' if (out / 'merged_seqlets').exists() else 'seqlets')
256
+
257
+
258
+ def _run_cwm(out) -> str:
259
+ """The CWMs a run was clustered on (cluster_consensus/cwm.txt); runs clustered before it existed used hypothetical ones."""
260
+ f = out / 'cluster_consensus' / 'cwm.txt'
261
+ return f.read_text().strip() if f.exists() else 'hypothetical'
262
+
263
+
264
+ def _consensus_as(cfg, out, ids, consensus, kind):
265
+ """
266
+ The run's consensus as `kind` CWMs ('contribution' or 'hypothetical'): the consensus itself when the run was
267
+ clustered on kind, else each cluster's members in kind averaged in its frame (cluster_consensus/{kind}_clNNN.npy;
268
+ `cluster` writes it, and for a run clustered before that it is computed and saved here on first use). Logos
269
+ show contributions; JASPAR is matched on hypothetical CWMs.
270
+ """
271
+ run = _run_cwm(out)
272
+ if run == kind:
273
+ return list(consensus)
274
+ from .cluster import member_consensus
275
+ from .seqlets import SeqletCollection
276
+ paths = [out / 'cluster_consensus' / f'{kind}_cl{c:03d}.npy' for c in ids]
277
+ if not all(p.exists() for p in paths):
278
+ log(f'{kind} consensus of {len(ids)} clusters, from their members')
279
+ clustered = _with_sequences(cfg, SeqletCollection.load(_clustered(cfg, out)))
280
+ contrib = clustered.contributions()
281
+ aligned, shown = (contrib, clustered) if run == 'contribution' else (clustered, contrib)
282
+ for p, m in zip(paths, member_consensus(aligned, shown, clustered.meta['cluster'], ids, consensus,
283
+ device=cfg['run']['device'])):
284
+ np.save(p, m)
285
+ return [np.load(p) for p in paths]
286
+
287
+
288
+ PFM_FLANK = 6 # bp of input read beyond each side of a cluster's consensus for its sequence frequencies
289
+
290
+
291
+ def _consensus_pfm(cfg, out, ids, consensus):
292
+ """
293
+ Each cluster's sequence frequencies, what a scan for the cluster uses: its members placed where their CWMs align to
294
+ the consensus (as _consensus_as places them) and their bases read from their regions' inputs over the consensus
295
+ frame and PFM_FLANK bp on each side (cluster.member_frequencies), so flank preferences the short seqlets leave out
296
+ count too. Saved as cluster_consensus/sequence_clNNN.npy on first use.
297
+ """
298
+ paths = [out / 'cluster_consensus' / f'sequence_cl{c:03d}.npy' for c in ids]
299
+ if not all(p.exists() for p in paths):
300
+ from .adapters import make_source
301
+ from .cluster import member_frequencies
302
+ from .seqlets import SeqletCollection
303
+ log(f'sequence frequencies of {len(ids)} clusters, from their members and {PFM_FLANK} bp around them')
304
+ clustered = _with_sequences(cfg, SeqletCollection.load(_clustered(cfg, out)))
305
+ aligned = clustered.contributions() if _run_cwm(out) == 'contribution' else clustered
306
+ for p, m in zip(paths, member_frequencies(aligned, make_source(cfg['attributions']).sequence, ids, consensus,
307
+ flank=PFM_FLANK, device=cfg['run']['device'])):
308
+ np.save(p, m)
309
+ return [np.load(p) for p in paths]
310
+
311
+
312
+ def _logos(cfg, out, ids, consensus):
313
+ """Cluster logos show contributions."""
314
+ return _consensus_as(cfg, out, ids, consensus, 'contribution')
315
+
316
+
317
+ def _cluster_report(cfg, meta, thr, ids, logos, hits, contrasts, clusters=None, targets=None, target_ref=None,
318
+ target_label='Gene log2FC'):
319
+ """
320
+ The per-cluster report figure, or None for a run whose seqlets predate mot_max_a / mot_max_b. clusters: draw these
321
+ instead of the [report] n_clusters largest (every one with a seqlet in the report's sets, ordered the same way).
322
+ targets, target_ref, target_label: the genes' panel of plotting.plot_cluster_report.
323
+ """
324
+ from . import plotting as P
325
+ from . import summaries as S
326
+ from .cluster import compute_distance_matrix
327
+ c0 = contrasts[0]
328
+ single = not c0.get('a')
329
+ if single: # one condition: its seqlets by direction, and their own contribution
330
+ meta = meta.assign(mot_max_a=np.nan, mot_max_b=meta['mot_max'])
331
+ if not {'mot_max_a', 'mot_max_b'} <= set(meta.columns):
332
+ log('cluster report skipped: rerun `seqlets` to store each condition\'s contribution (mot_max_a, mot_max_b)')
333
+ return None
334
+ r = cfg['report']
335
+ sets = r.get('sets') or sorted(meta['set_name'].unique())
336
+ logo_of = dict(zip(ids, logos))
337
+ if clusters is None:
338
+ in_b, in_a = S.report_clusters(meta, sets, n=r['n_clusters'], min_seqlets=r['min_cluster_size'])
339
+ else:
340
+ in_b, in_a = S.report_clusters(meta[meta['cluster'].isin(list(clusters))], sets, n=len(clusters), min_seqlets=1)
341
+ order = []
342
+ for grp in (in_b, in_a): # similar motifs together, within each direction
343
+ if len(grp) >= 3:
344
+ sim = 1.0 - compute_distance_matrix([logo_of[c] for c in grp], device=cfg['run']['device'],
345
+ metric='correlation')[0]
346
+ order += S.order_by_similarity(grp, sim)
347
+ else:
348
+ order += list(grp)
349
+ names = {c: f"cl{c}\n{hits[c][0]['tf']}" if hits.get(c) else f'cl{c}' for c in order}
350
+ la, lb = (f"lowers {c0['label_b']}", f"raises {c0['label_b']}") if single else (c0['label_a'], c0['label_b'])
351
+ return P.plot_cluster_report(meta, order, logo_of, names, sets, [c['name'] for c in contrasts],
352
+ thr.groupby(['set_name', 'contrast'])['coord'].nunique().to_dict(),
353
+ set_labels=r.get('set_labels', {}), color_a=r.get('color_a', P.DEFAULT_A),
354
+ color_b=r.get('color_b', P.DEFAULT_B), label_a=la, label_b=lb,
355
+ split=len(in_b), targets=targets, target_ref=target_ref, target_label=target_label)
356
+
357
+
358
+ def step_families(cfg):
359
+ from . import jaspar as J
360
+
361
+ out = C.out_dir(cfg)
362
+ j = cfg['jaspar']
363
+ summary, ids_cl, consensus = _consensus(out)
364
+ ids, names, pwms = J.load_meme(J.ensure_meme(j['meme'], log=log))
365
+ hits = J.match(_consensus_as(cfg, out, ids_cl, consensus, 'hypothetical'), ids_cl, ids, names, pwms,
366
+ device=cfg['run']['device'], top_n=j['top_n'])
367
+ (out / 'jaspar_matches.json').write_text(json.dumps({str(k): v for k, v in hits.items()}))
368
+ cache = Path(j.get('cache_dir') or Path(j['meme']).parent)
369
+ stem = Path(j['meme']).name.removesuffix('.txt').removesuffix('_meme').removesuffix('_pfms')
370
+ ann = J.fetch_annotations(ids, names, cache / f'{stem}_annotations.json', log=log)
371
+ dist = J.pwm_distance(pwms, ids, cache=cache / f'{stem}_pwm_distance.npz', device=cfg['run']['device'])
372
+ ann = J.subfamilies(ann, dist, group_level=j['group_level'], linkage=j['linkage'], p_cutoff=j['p_cutoff'])
373
+ fdir = out / 'families'
374
+ fdir.mkdir(exist_ok=True)
375
+ ann.to_csv(fdir / 'jaspar_subfamilies.csv', index=False)
376
+ fam = J.cluster_families(hits, ann).merge(summary[['cluster', 'n_seqlets']], on='cluster')
377
+ fam.to_csv(fdir / 'cluster_families.csv', index=False)
378
+ log(f'{ann["group"].nunique()} JASPAR {j["group_level"]} groups -> {ann["subfamily"].nunique()} subfamilies; '
379
+ f'{fam["subfamily"].nunique()} subfamilies among {len(fam)} clusters')
380
+ C.provenance(cfg, 'families', {'n_subfamilies': int(ann['subfamily'].nunique()), 'matched_on': 'hypothetical'})
381
+
382
+
383
+ def fdir_annotations(out):
384
+ return out / 'families' / 'jaspar_subfamilies.csv'
385
+
386
+
387
+ def step_report(cfg):
388
+ import matplotlib.pyplot as plt
389
+ from . import plotting as P
390
+ from . import summaries as S
391
+ from .seqlets import SeqletCollection
392
+
393
+ out = C.out_dir(cfg)
394
+ if CAL.needs_settings(cfg):
395
+ sys.exit(CAL.missing_message(cfg, Path(cfg.get('_path', 'CONFIG')).name))
396
+ r = cfg['report']
397
+ rdir = out / 'report'
398
+ rdir.mkdir(exist_ok=True)
399
+ P.style()
400
+ from .cluster import differential_sites
401
+ from .selection import contrast_thresholds
402
+ meta = differential_sites(SeqletCollection.load(_clustered(cfg, out))).meta # the differential sites, one row each
403
+ thr = contrast_thresholds(pd.read_csv(out / 'thresholds.csv')) # the contrast's record of each region
404
+ fam = pd.read_csv(out / 'families' / 'cluster_families.csv')
405
+ contrasts = json.loads((out / 'contrasts.json').read_text())
406
+ summary, ids_cl, consensus = _consensus(out)
407
+ hits = {int(k): v for k, v in json.loads((out / 'jaspar_matches.json').read_text()).items()}
408
+
409
+ lab = S.label_seqlets(meta, fam, min_cluster_size=r['min_cluster_size'])
410
+ den = S.denominators(meta, thr, r['denominator'])
411
+ level = r['level']
412
+ table = S.motif_table(lab, level=level, den=den)
413
+ table.to_csv(rdir / f'motif_table_{level}.csv', index=False)
414
+ group_table = S.motif_table(lab, level='group', den=den)
415
+ group_table.to_csv(rdir / 'motif_table_group.csv', index=False)
416
+ S.motif_table(lab.assign(cluster_label=lab['cluster'].map(lambda c: f'cl{c}')),
417
+ level='cluster_label', den=den).to_csv(rdir / 'motif_table_cluster.csv', index=False)
418
+
419
+ shown = _logos(cfg, out, ids_cl, consensus)
420
+ fig = P.plot_cluster_logos(ids_cl, shown, summary, hits=hits, n_show=r['n_logos'])
421
+ for ext in ('pdf', 'png'):
422
+ fig.savefig(rdir / f'cluster_logos.{ext}', bbox_inches='tight')
423
+ plt.close(fig)
424
+
425
+ logo_of = dict(zip(ids_cl, shown))
426
+ largest = fam.sort_values('n_seqlets', ascending=False).drop_duplicates(level)
427
+ logos = {row[level]: logo_of[row['cluster']] for _, row in largest.iterrows() if row['cluster'] in logo_of}
428
+ c0 = contrasts[0]
429
+ names = [c['name'] for c in contrasts]
430
+ sets = r.get('sets') or sorted(meta['set_name'].unique())
431
+ set_labels = r.get('set_labels', {})
432
+ motifs = list(dict.fromkeys(m for s in sets for m in S.top_motifs(table, level, s, n=r['top_n'])))
433
+ cols = [(s, c) for s in sets for c in names]
434
+ col_labels = [f'{set_labels.get(s, s)}' + (f'\n{c}' if len(names) > 1 else '') + f'\nn={int(den.get((s, c), 0))}'
435
+ for s, c in cols]
436
+ classes = S.class_sets(sets, c0['label_a'], c0['label_b']) # [A, B]: the ratio is B over A, as the contrast
437
+ ratio = S.prevalence_ratio(table, level, classes[1], classes[0]) if classes else None
438
+ ratio_label = (f'log2 prevalence, {set_labels.get(classes[1], classes[1])} / '
439
+ f'{set_labels.get(classes[0], classes[0])}') if classes else ''
440
+ color_a, color_b = r.get('color_a', P.DEFAULT_A), r.get('color_b', P.DEFAULT_B)
441
+ from . import expression as X
442
+ de = X.de_table(cfg)
443
+ candidates = None if de is None else X.tf_members(de, pd.read_csv(fdir_annotations(out)), fam, hits, level, motifs)
444
+ fig = P.plot_motif_bubbles(table, motifs, cols, level=level, logos=logos, column_labels=col_labels,
445
+ color_a=color_a, color_b=color_b, label_a=c0['label_a'], label_b=c0['label_b'],
446
+ color_by=r['color_by'], ratio=ratio, ratio_label=ratio_label, de=candidates,
447
+ de_label=f"TF log2FC ({c0['label_b']} / {c0['label_a']})")
448
+ for ext in ('pdf', 'png'):
449
+ fig.savefig(rdir / f'motif_bubbles.{ext}', bbox_inches='tight')
450
+ plt.close(fig)
451
+
452
+ fig = _cluster_report(cfg, meta, thr, ids_cl, shown, hits, contrasts)
453
+ if fig is not None:
454
+ for ext in ('pdf', 'png'):
455
+ fig.savefig(rdir / f'cluster_report.{ext}', bbox_inches='tight')
456
+ plt.close(fig)
457
+
458
+ from .analysis import Analysis
459
+ an = Analysis(cfg['_path'])
460
+ plots = [('selection_funnel', an.plot_selection_funnel), ('predicted_signal', an.plot_predicted_signal),
461
+ ('motif_targets', an.plot_motif_targets)]
462
+ if an.expression_table is not None and an.region_genes is not None:
463
+ an.motif_targets()[0].to_csv(rdir / 'motif_targets.csv', index=False, float_format='%.6g')
464
+ for c in contrasts:
465
+ one = Analysis(cfg['_path'], contrast=c['name'])
466
+ tag = f"_{c['name']}" if len(contrasts) > 1 else ''
467
+ plots += [(f'seqlet_threshold{tag}', one.plot_seqlet_threshold), (f'measured_predicted{tag}', one.plot_measured_predicted)]
468
+ for name, plot in plots:
469
+ fig = plot()
470
+ if fig is not None:
471
+ for ext in ('pdf', 'png'):
472
+ fig.savefig(rdir / f'{name}.{ext}', bbox_inches='tight')
473
+ from .view import figures as VF # co-occurrence as absolute region counts, sign-matched
474
+ fig = VF.cooc_counts(an, level if level in ('subfamily', 'cluster') else 'subfamily')
475
+ if fig is not None:
476
+ for ext in ('pdf', 'png'):
477
+ fig.savefig(rdir / f'cooccurrence_counts.{ext}', bbox_inches='tight', facecolor='white')
478
+ from . import effects as E
479
+ E.write_pairs(lambda c: Analysis(cfg['_path'], contrast=c), rdir, log=log)
480
+ log(f'report written to {rdir}')
481
+ C.provenance(cfg, 'report', {'level': level, 'denominator': r['denominator']})
482
+
483
+
484
+ def step_attribute(cfg, max_regions=None, select_only=False, predictor=None):
485
+ from . import attribute
486
+ C.provenance(cfg, 'attribute', attribute.run(cfg, max_regions=max_regions, select_only=select_only,
487
+ predictor=predictor, log=log))
488
+
489
+
490
+ def step_pair_regression(cfg):
491
+ """The [pair_regression] step (diffgrammar.pair_regression): every pair of motif families against the measured fold
492
+ change of every region of a table, written to <out_dir>/pair_regression/<source>/."""
493
+ from . import pair_regression
494
+ infos = pair_regression.run(cfg, log=log)
495
+ C.provenance(cfg, 'pair_regression', {src: {k: i[k] for k in ('regions', 'pairs_tested', 'blocks', 'weighted')}
496
+ for src, i in infos.items()})
497
+
498
+
499
+ def step_marginalize(cfg, action='run', predictor=None):
500
+ from .marginalize import cooperativity
501
+ info = cooperativity.run(cfg, predictor=predictor, plan_only=action == 'plan', log=log)
502
+ if action == 'run':
503
+ C.provenance(cfg, 'marginalize', info)
504
+
505
+
506
+ def pipeline(cfg, max_regions=None, force=False, predictor=None):
507
+ """Every step the config asks for, in order: attribute, seqlets, cluster, families, report, pair_regression,
508
+ marginalize."""
509
+ from . import attribute
510
+ if 'attribute' in cfg:
511
+ if attribute.finished(cfg) and not force:
512
+ log(f'attributions in {cfg["attributions"]["root"]} are complete; not recomputed (--force recomputes '
513
+ 'the selection, and attributes regions not written yet)')
514
+ else:
515
+ step_attribute(cfg, max_regions, predictor=predictor)
516
+ step_seqlets(cfg, max_regions, force)
517
+ step_cluster(cfg)
518
+ step_families(cfg)
519
+ step_report(cfg)
520
+ if 'pair_regression' in cfg:
521
+ step_pair_regression(cfg)
522
+ if 'marginalize' in cfg:
523
+ step_marginalize(cfg, 'run', predictor=predictor)
524
+
525
+
526
+ VIEW_NEEDS = {'seqlets': 'seqlets/meta.parquet', 'cluster': 'cluster_summary.csv', 'families': 'jaspar_matches.json'}
527
+
528
+
529
+ def _free_port(start=8501):
530
+ """The first port from start with nothing listening, so several runs can be open side by side."""
531
+ import socket
532
+ for port in range(start, start + 100):
533
+ with socket.socket() as s:
534
+ if s.connect_ex(('localhost', port)) != 0:
535
+ return port
536
+ sys.exit(f'no free port from {start} to {start + 99}; give one with --port')
537
+
538
+
539
+ def view(config='config.toml', port=None):
540
+ """
541
+ `diffgrammar view`: the run of a config in the browser (diffgrammar.view.app, served by streamlit). It listens on
542
+ localhost only, since it has no login and runs are often unpublished; VS Code and ssh -L forward from there.
543
+ """
544
+ import importlib.util
545
+ import os
546
+ if importlib.util.find_spec('streamlit') is None:
547
+ sys.exit(f'{sys.executable} has no streamlit: activate the diffgrammar environment, or pip install -e ".[view]"')
548
+ path = Path(config).resolve()
549
+ if not path.is_file():
550
+ sys.exit(f"no config at {path}: run this in the folder of the run's config.toml, or give its path")
551
+ cfg = C.load(path)
552
+ out = Path(cfg['run']['out_dir'])
553
+ missing = [step for step, f in VIEW_NEEDS.items() if not (out / f).exists()]
554
+ if missing:
555
+ sys.exit(f"{out} has no output of: {', '.join(missing)}. Run the pipeline first: diffgrammar pipeline {config}")
556
+ if CAL.needs_settings(cfg):
557
+ sys.exit(CAL.missing_message(cfg, config))
558
+ port = port or _free_port()
559
+ src = str(Path(__file__).resolve().parents[1]) # the app imports this checkout of the package
560
+ env = {**os.environ, 'PYTHONPATH': os.pathsep.join(p for p in (src, os.environ.get('PYTHONPATH')) if p)}
561
+ print(f'{path}\nOpen http://localhost:{port} (Ctrl+C stops it)', flush=True)
562
+ os.execve(sys.executable, [sys.executable, '-m', 'streamlit', 'run', str(Path(__file__).parent / 'view' / 'app.py'),
563
+ '--server.port', str(port), '--server.address', 'localhost',
564
+ '--server.headless', 'true',
565
+ '--browser.gatherUsageStats', 'false', '--', str(path)], env)
566
+
567
+
568
+ # -- entry point --------------------------------------------------------------------------------
569
+ def main(argv=None):
570
+ ap = argparse.ArgumentParser(prog='diffgrammar', description=__doc__,
571
+ formatter_class=argparse.RawDescriptionHelpFormatter)
572
+ sub = ap.add_subparsers(dest='cmd', required=True)
573
+ for name in ('seqlets', 'pipeline'):
574
+ p = sub.add_parser(name)
575
+ p.add_argument('config')
576
+ p.add_argument('--max-regions', type=int, default=None, help='first N regions only, for a quick check')
577
+ p.add_argument('--force', action='store_true', help='replace the seqlets of an earlier run')
578
+ for name in ('cluster', 'families', 'report'):
579
+ sub.add_parser(name).add_argument('config')
580
+ sub.add_parser('pair-regression', help='every pair of motif families against the measured fold change of every '
581
+ 'region of a table ([pair_regression], diffgrammar.pair_regression)').add_argument('config')
582
+ p = sub.add_parser('attribute', help='attributions of the [attribute] conditions, in the layout the pipeline reads')
583
+ p.add_argument('config')
584
+ p.add_argument('--max-regions', type=int, default=None, help='first N kept regions only, for a quick check')
585
+ p.add_argument('--select-only', action='store_true', help='write candidates.csv and stop before attributing')
586
+ p = sub.add_parser('marginalize', help='the [marginalize] pairs: what is missing (plan), or compute and read (run)')
587
+ p.add_argument('action', choices=['plan', 'run'])
588
+ p.add_argument('config')
589
+ p = sub.add_parser('view', help='a finished run in the browser (needs the view extra: pip install -e ".[view]")')
590
+ p.add_argument('config', nargs='?', default='config.toml', help='default: config.toml in this folder')
591
+ p.add_argument('--port', type=int, default=None, help='default: the first free port from 8501')
592
+ p = sub.add_parser('export', help='a finished run as one small folder for `view` elsewhere (diffgrammar.export)')
593
+ p.add_argument('config')
594
+ p.add_argument('--out', default=None, help='default: export_<run name> beside the config')
595
+ p.add_argument('--n-regions', type=int, default=20, help='regions with attributions per motif and set')
596
+ p.add_argument('--n-motifs', type=int, default=5, help='motifs per set whose regions keep their attributions')
597
+ for p in sub.choices.values():
598
+ p.add_argument('--track', default=None, help='with [attribute] tracks: this track only (default: every track; '
599
+ 'view and export need one when there are several)')
600
+ a = ap.parse_args(argv)
601
+ if C.tracks_of(C.load(a.config) if Path(a.config).is_file() else {}):
602
+ return _per_track(a)
603
+ if a.track:
604
+ sys.exit(f'--track needs a config with [attribute] tracks; {a.config} has none')
605
+ if a.cmd == 'view':
606
+ return view(a.config, a.port)
607
+ if a.cmd == 'export':
608
+ from . import export
609
+ export.run(C.load(a.config), a.out, a.n_regions, a.n_motifs, log=log)
610
+ return 0
611
+ _run_step(a, C.load(a.config))
612
+
613
+
614
+ def _per_track(a):
615
+ """A command on a single-track config: once per track (or the one --track names), each in its own run folder."""
616
+ cfg = C.load(a.config)
617
+ tracks = C.tracks_of(cfg)
618
+ if a.track and a.track not in tracks:
619
+ sys.exit(f'--track {a.track}: not one of [attribute] tracks {tracks}')
620
+ if a.cmd in ('view', 'export'):
621
+ if not a.track and len(tracks) > 1:
622
+ sys.exit(f'{a.config} has one run per track: name one with --track ({", ".join(tracks)}), '
623
+ f'or open its run config directly ({Path(C.for_track(cfg, tracks[0])["_path"])})')
624
+ tcfg = C.for_track(cfg, a.track or tracks[0])
625
+ if not Path(tcfg['_path']).is_file():
626
+ sys.exit(f"no run of track {a.track or tracks[0]} at {tcfg['run']['out_dir']}: run the pipeline first")
627
+ if a.cmd == 'view':
628
+ return view(tcfg['_path'], a.port)
629
+ from . import export
630
+ export.run(C.load(tcfg['_path']), a.out, a.n_regions, a.n_motifs, log=log)
631
+ return 0
632
+ for t in [a.track] if a.track else tracks:
633
+ tcfg = C.for_track(cfg, t)
634
+ log(f'== track {t}: {tcfg["run"]["out_dir"]}')
635
+ C.write_track_config(tcfg)
636
+ _run_step(a, C.load(tcfg['_path']))
637
+ return 0
638
+
639
+
640
+ def _run_step(a, cfg):
641
+ """One step command (not view or export) on one run's config."""
642
+ import matplotlib
643
+ matplotlib.use('Agg') # the command line only writes files; notebooks keep their backend
644
+ if a.cmd == 'pipeline':
645
+ pipeline(cfg, a.max_regions, a.force)
646
+ elif a.cmd == 'attribute':
647
+ step_attribute(cfg, a.max_regions, a.select_only)
648
+ elif a.cmd == 'seqlets':
649
+ step_seqlets(cfg, a.max_regions, a.force)
650
+ elif a.cmd == 'marginalize':
651
+ step_marginalize(cfg, a.action)
652
+ elif a.cmd == 'pair-regression':
653
+ step_pair_regression(cfg)
654
+ else:
655
+ {'cluster': step_cluster, 'families': step_families, 'report': step_report}[a.cmd](cfg)
656
+
657
+
658
+ if __name__ == '__main__':
659
+ main()