diffgrammar 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffgrammar/__init__.py +6 -0
- diffgrammar/adapters/__init__.py +21 -0
- diffgrammar/adapters/peak_npz.py +114 -0
- diffgrammar/align.py +195 -0
- diffgrammar/analysis.py +744 -0
- diffgrammar/attribute.py +445 -0
- diffgrammar/calibrate.py +279 -0
- diffgrammar/cli.py +659 -0
- diffgrammar/cluster.py +439 -0
- diffgrammar/config.py +213 -0
- diffgrammar/contrast.py +223 -0
- diffgrammar/effects.py +317 -0
- diffgrammar/export.py +185 -0
- diffgrammar/expression.py +399 -0
- diffgrammar/jaspar.py +185 -0
- diffgrammar/marginalize/__init__.py +4 -0
- diffgrammar/marginalize/backgrounds.py +107 -0
- diffgrammar/marginalize/cooperativity.py +344 -0
- diffgrammar/marginalize/design.py +209 -0
- diffgrammar/marginalize/plots.py +546 -0
- diffgrammar/marginalize/predictor.py +109 -0
- diffgrammar/marginalize/readout.py +86 -0
- diffgrammar/marginalize/run.py +223 -0
- diffgrammar/marginalize/store.py +191 -0
- diffgrammar/pair_regression.py +323 -0
- diffgrammar/plotting.py +1186 -0
- diffgrammar/scan.py +151 -0
- diffgrammar/selection.py +174 -0
- diffgrammar/seqlets.py +376 -0
- diffgrammar/sequence.py +22 -0
- diffgrammar/summaries.py +140 -0
- diffgrammar/toy.py +129 -0
- diffgrammar/view/__init__.py +0 -0
- diffgrammar/view/app.py +1942 -0
- diffgrammar/view/data.py +1950 -0
- diffgrammar/view/figures.py +400 -0
- diffgrammar/view/network/index.html +232 -0
- diffgrammar/view/network.py +21 -0
- diffgrammar/view/pages.py +257 -0
- diffgrammar/view/tracks/index.html +459 -0
- diffgrammar/view/tracks.py +153 -0
- diffgrammar-0.1.0.dist-info/METADATA +204 -0
- diffgrammar-0.1.0.dist-info/RECORD +47 -0
- diffgrammar-0.1.0.dist-info/WHEEL +5 -0
- diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
- diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
- diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
diffgrammar/calibrate.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Seqlet thresholds calibrated on the run's own budgets.
|
|
3
|
+
|
|
4
|
+
`[seqlets] pct`, the cut as a share of each record's budget, and `[seqlets] min_track_budget`, the budget
|
|
5
|
+
below which a region's weaker condition track is not called on, are each a number or "auto". The seqlets step
|
|
6
|
+
first surveys the run (`survey`: one row per record with its budget, its largest contribution and the region's
|
|
7
|
+
two condition budgets, no seqlet called yet; a pass over the attributions of its own), then `resolve` turns
|
|
8
|
+
"auto" into numbers:
|
|
9
|
+
|
|
10
|
+
pct = "auto" the largest share at which `coverage` (default 0.95) of the regions still have
|
|
11
|
+
a position above the cut on the differential: the (1 - coverage) quantile of
|
|
12
|
+
max|contribution| / budget over the 'diff' records. A position above the cut
|
|
13
|
+
is the precondition for a seqlet, not a seqlet (that also takes min_size
|
|
14
|
+
positions in a run), so fewer regions yield one. One share for every record
|
|
15
|
+
and every set, so the sets of a run are compared at one cut; a flat
|
|
16
|
+
differential (a long window, a designed insert) gets a smaller share than a
|
|
17
|
+
peaked one, where a share tuned by hand on one run would not carry over.
|
|
18
|
+
min_track_budget = "auto" the `floor_percentile`-th (default 5) percentile of the regions' stronger
|
|
19
|
+
condition budget: a region's weaker condition track is called on only where
|
|
20
|
+
it carries at least as much budget as the weakest admitted regions' stronger
|
|
21
|
+
tracks do, that is, where it alone would have qualified the region as one
|
|
22
|
+
with signal. pct is a share of each record's own budget, so on a track with
|
|
23
|
+
almost no signal the absolute cut is near zero and its seqlets are noise,
|
|
24
|
+
and their CWMs, peak normalized, would shape the motifs as much as real
|
|
25
|
+
ones. The stronger condition track is always called on (of the tracks asked
|
|
26
|
+
for), as the region's own signal, and so is 'diff', what the downstream reads: whether a region has
|
|
27
|
+
signal at all is the selection's question (the attribute step, or
|
|
28
|
+
min_budget), and by construction floor_percentile percent of the regions
|
|
29
|
+
have even their stronger track under the floor.
|
|
30
|
+
min_budget a number, 0 = off: a region whose stronger condition budget is below it is
|
|
31
|
+
left out. The attribute step's selection admits only regions with signal;
|
|
32
|
+
attributions from an adapter arrive unselected, so this is their guard, and
|
|
33
|
+
budgets.csv (the survey) gives the scale to set it by.
|
|
34
|
+
min_track_budget_frac a number, 0 = off: the same gate as min_track_budget, as a share of the
|
|
35
|
+
region's stronger condition budget; where both are set the higher floor holds.
|
|
36
|
+
|
|
37
|
+
Both automatic values are percentiles of the run's own distributions, so they carry over between models and
|
|
38
|
+
units; the free numbers are the coverage and the percentile, not a cut in model units. Each comes with a
|
|
39
|
+
distribution-free 95% interval (`quantile_interval`): the quantile of a small run rests on a few records (pct on
|
|
40
|
+
n x (1 - coverage) of them), and the interval says how far another draw of regions of the same kind could move it.
|
|
41
|
+
The resolved values go to <out_dir>/seqlet_settings.json (`write_settings`). `apply_settings` puts them into a
|
|
42
|
+
config in place of "auto" wherever a later step or the viewer needs the number and records what it put there, so
|
|
43
|
+
the seqlets step calibrates again whenever it runs (`requested`) unless the number was changed since.
|
|
44
|
+
"""
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import json
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
from typing import Iterable, Optional, Sequence
|
|
50
|
+
|
|
51
|
+
import numpy as np
|
|
52
|
+
import pandas as pd
|
|
53
|
+
|
|
54
|
+
from .contrast import Contrast, RegionAttributions, TRACKS, check_tracks, contrast_records
|
|
55
|
+
|
|
56
|
+
#: the resolved thresholds of a run, beside its seqlets
|
|
57
|
+
SETTINGS = 'seqlet_settings.json'
|
|
58
|
+
#: the survey of a run, one row per record
|
|
59
|
+
BUDGETS = 'budgets.csv'
|
|
60
|
+
#: the [seqlets] keys that take "auto"
|
|
61
|
+
AUTO_KEYS = ('pct', 'min_track_budget')
|
|
62
|
+
#: where apply_settings records the numbers it put in place of "auto"
|
|
63
|
+
RESOLVED = '_resolved'
|
|
64
|
+
#: one region under one contrast
|
|
65
|
+
REGION = ['contrast', 'set_name', 'coord']
|
|
66
|
+
#: below this many records in the tail a quantile is set by a handful of regions, and the step says so
|
|
67
|
+
FEW_TAIL = 30
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def is_auto(value) -> bool:
|
|
71
|
+
"""Whether a [seqlets] value asks for calibration; any other string is an error."""
|
|
72
|
+
if isinstance(value, str):
|
|
73
|
+
if value != 'auto':
|
|
74
|
+
raise ValueError(f'a [seqlets] threshold is a number or "auto", not {value!r}')
|
|
75
|
+
return True
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def requested(seqlets_cfg: dict) -> dict:
|
|
80
|
+
"""The [seqlets] section as the config asks for it now: "auto" wherever the number in place is still the one
|
|
81
|
+
apply_settings put there; a value changed since then is the new request."""
|
|
82
|
+
resolved = seqlets_cfg.get(RESOLVED, {})
|
|
83
|
+
return {k: 'auto' if k in resolved and v == resolved[k] else v for k, v in seqlets_cfg.items() if k != RESOLVED}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def check(seqlets_cfg: dict) -> dict:
|
|
87
|
+
"""The calibration settings of a [seqlets] section (as requested), validated before any attribution is read:
|
|
88
|
+
coverage, floor_percentile, min_budget and min_track_budget_frac as numbers; pct and min_track_budget are each a
|
|
89
|
+
number or "auto" (is_auto raises on any other string)."""
|
|
90
|
+
out = {'coverage': float(seqlets_cfg.get('coverage', 0.95)),
|
|
91
|
+
'floor_percentile': float(seqlets_cfg.get('floor_percentile', 5)),
|
|
92
|
+
'min_budget': float(seqlets_cfg.get('min_budget') or 0),
|
|
93
|
+
'min_track_budget_frac': float(seqlets_cfg.get('min_track_budget_frac') or 0)}
|
|
94
|
+
if not 0 < out['coverage'] <= 1:
|
|
95
|
+
raise ValueError(f"[seqlets] coverage is a share of the regions in (0, 1], not {out['coverage']}")
|
|
96
|
+
if not 0 <= out['floor_percentile'] <= 100:
|
|
97
|
+
raise ValueError(f"[seqlets] floor_percentile is a percentile in [0, 100], not {out['floor_percentile']}")
|
|
98
|
+
for k in AUTO_KEYS:
|
|
99
|
+
is_auto(seqlets_cfg.get(k, 'auto'))
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def quantile_interval(values, q: float, level: float = 0.95):
|
|
104
|
+
"""
|
|
105
|
+
A distribution-free `level` interval for the q-quantile of the population `values` were drawn from: the order
|
|
106
|
+
statistics X_(r) and X_(s) with r the lower and s - 1 the upper (1 - level) / 2 bound of a Binomial(n, q) count,
|
|
107
|
+
so that P(X_(r) <= quantile <= X_(s)) >= level whatever the distribution. An end the sample is too small to
|
|
108
|
+
bound is infinite: the lower one below records_to_bound(q, level) values (72 for q = 0.05). (nan, nan) for no
|
|
109
|
+
values.
|
|
110
|
+
"""
|
|
111
|
+
from scipy.stats import binom
|
|
112
|
+
x = np.sort(np.asarray(values, float))
|
|
113
|
+
n = len(x)
|
|
114
|
+
if n == 0:
|
|
115
|
+
return float('nan'), float('nan')
|
|
116
|
+
a = (1 - level) / 2
|
|
117
|
+
r, s = int(binom.ppf(a, n, q)), int(binom.ppf(1 - a, n, q)) + 1
|
|
118
|
+
return (float(x[r - 1]) if r >= 1 else -np.inf), (float(x[s - 1]) if s <= n else np.inf)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def records_to_bound(q: float, level: float = 0.95) -> float:
|
|
122
|
+
"""The fewest values whose quantile_interval for the q-quantile has a lower end: (1 - q)^n below (1 - level) / 2."""
|
|
123
|
+
if q <= 0:
|
|
124
|
+
return np.inf
|
|
125
|
+
if q >= 1:
|
|
126
|
+
return 1
|
|
127
|
+
return float(np.floor(np.log((1 - level) / 2) / np.log(1 - q)) + 1)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _ends(lo: float, hi: float) -> list:
|
|
131
|
+
"""An interval as JSON can hold it: None for an end the sample could not bound."""
|
|
132
|
+
return [v if np.isfinite(v) else None for v in (lo, hi)]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def survey(regions: Iterable[RegionAttributions], contrasts: Sequence[Contrast], budget: str = 'auto',
|
|
136
|
+
tracks: Sequence[str] = TRACKS) -> pd.DataFrame:
|
|
137
|
+
"""
|
|
138
|
+
Every record of every region (contrast_records, no gate) as one row: record (the id thresholds.csv uses), set_name,
|
|
139
|
+
contrast, coord, track, budget, signed_budget, budget_source, max_abs (its largest |contribution|), max_share
|
|
140
|
+
(max_abs / budget, the largest pct at which the record still has a position above the cut; NaN at a zero budget),
|
|
141
|
+
and budget_a / budget_b, the region's two condition budgets, whichever tracks are surveyed.
|
|
142
|
+
"""
|
|
143
|
+
tracks = check_tracks(tracks)
|
|
144
|
+
rows = []
|
|
145
|
+
for r in regions:
|
|
146
|
+
for c in contrasts:
|
|
147
|
+
for rec in contrast_records(r, c, budget, tracks):
|
|
148
|
+
contrib = np.asarray(rec['contributions'])
|
|
149
|
+
cond = rec['condition_budgets']
|
|
150
|
+
rows.append({'record': rec['record'], 'set_name': rec['set_name'], 'contrast': rec['contrast'],
|
|
151
|
+
'coord': rec['coord'], 'track': rec['track'], 'budget': float(rec['pred']),
|
|
152
|
+
'signed_budget': float(rec['signed_budget']), 'budget_source': rec['budget_source'],
|
|
153
|
+
'max_abs': float(np.abs(contrib).max()), 'budget_a': cond.get('a', np.nan),
|
|
154
|
+
'budget_b': cond.get('b', np.nan)})
|
|
155
|
+
s = pd.DataFrame(rows, columns=['record', 'set_name', 'contrast', 'coord', 'track', 'budget', 'signed_budget',
|
|
156
|
+
'budget_source', 'max_abs', 'budget_a', 'budget_b'])
|
|
157
|
+
s['max_share'] = s['max_abs'] / s['budget'].where(s['budget'] > 0)
|
|
158
|
+
return s
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def strongest(s: pd.DataFrame) -> pd.Series:
|
|
162
|
+
"""The stronger condition budget per region (contrast, set_name, coord), from both conditions."""
|
|
163
|
+
return s.groupby(REGION)[['budget_a', 'budget_b']].first().max(axis=1)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def resolve(seqlets_cfg: dict, s: pd.DataFrame) -> dict:
|
|
167
|
+
"""
|
|
168
|
+
The thresholds of a run from its [seqlets] section (as requested, see `requested`) and its survey: pct and
|
|
169
|
+
min_track_budget as numbers (the config's, or calibrated from the survey when "auto"), min_budget and
|
|
170
|
+
min_track_budget_frac as given, with what they were resolved from: pct_requested, coverage, pct_calibrated_on
|
|
171
|
+
('diff', or 'condition tracks' when no diff track was surveyed; None for a number), min_track_budget_requested,
|
|
172
|
+
floor_percentile, the counts n_regions and n_regions_admitted (those whose stronger condition budget reaches
|
|
173
|
+
min_budget; the calibration reads the admitted regions only), and for each "auto" value the records it was taken
|
|
174
|
+
over (n_pct_records, n_floor_regions), how many of them sit in its tail (pct_tail, floor_tail) and its
|
|
175
|
+
distribution-free 95% interval (pct_interval, min_track_budget_interval; see quantile_interval; None for an end
|
|
176
|
+
the records cannot bound).
|
|
177
|
+
"""
|
|
178
|
+
out = check(seqlets_cfg)
|
|
179
|
+
regions = strongest(s)
|
|
180
|
+
admitted = regions[regions >= out['min_budget']]
|
|
181
|
+
if len(regions) and not len(admitted):
|
|
182
|
+
raise ValueError(f"[seqlets] min_budget {out['min_budget']:g} leaves out all {len(regions)} regions: their stronger "
|
|
183
|
+
f"condition budget is at most {regions.max():.4g} (median {regions.median():.4g}); lower it, or "
|
|
184
|
+
f"set 0 to turn it off")
|
|
185
|
+
out['n_regions'], out['n_regions_admitted'] = int(len(regions)), int(len(admitted))
|
|
186
|
+
s = s[s.set_index(REGION).index.isin(admitted.index)]
|
|
187
|
+
|
|
188
|
+
pct = seqlets_cfg.get('pct', 'auto')
|
|
189
|
+
out['pct_requested'], out['pct_calibrated_on'] = pct, None
|
|
190
|
+
if is_auto(pct):
|
|
191
|
+
diff = s['track'] == 'diff'
|
|
192
|
+
out['pct_calibrated_on'] = 'diff' if diff.any() else 'condition tracks'
|
|
193
|
+
shares = s.loc[diff if diff.any() else s.index, 'max_share'].dropna()
|
|
194
|
+
if shares.empty:
|
|
195
|
+
raise ValueError('pct = "auto" needs records with a positive budget to calibrate on')
|
|
196
|
+
q = 1 - out['coverage']
|
|
197
|
+
pct = float(np.quantile(shares, q))
|
|
198
|
+
out.update(n_pct_records=int(len(shares)), pct_tail=float(len(shares) * q),
|
|
199
|
+
pct_interval=_ends(*quantile_interval(shares, q)))
|
|
200
|
+
out['pct'] = float(pct)
|
|
201
|
+
|
|
202
|
+
floor = seqlets_cfg.get('min_track_budget', 'auto')
|
|
203
|
+
out['min_track_budget_requested'] = floor
|
|
204
|
+
if is_auto(floor):
|
|
205
|
+
q = out['floor_percentile'] / 100
|
|
206
|
+
floor = float(np.quantile(admitted, q)) if len(admitted) else 0.0
|
|
207
|
+
out.update(n_floor_regions=int(len(admitted)), floor_tail=float(len(admitted) * q),
|
|
208
|
+
min_track_budget_interval=_ends(*quantile_interval(admitted, q)))
|
|
209
|
+
out['min_track_budget'] = float(floor)
|
|
210
|
+
return out
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def summary(s: pd.DataFrame, settings: dict) -> pd.DataFrame:
|
|
214
|
+
"""
|
|
215
|
+
What the resolved thresholds do to the survey, per set and track: regions, called (records that pass the gates:
|
|
216
|
+
'diff' and the stronger condition track of an admitted region always, the weaker one where it reaches the floor),
|
|
217
|
+
and above_cut (called records with a position above the cut, the precondition for a seqlet).
|
|
218
|
+
"""
|
|
219
|
+
strongest_ = strongest(s)
|
|
220
|
+
rows = []
|
|
221
|
+
for (contrast, set_name, track), g in s.groupby(['contrast', 'set_name', 'track']):
|
|
222
|
+
strong = strongest_.reindex(pd.MultiIndex.from_arrays([g[c] for c in REGION])).to_numpy()
|
|
223
|
+
admitted = strong >= settings['min_budget']
|
|
224
|
+
floor = np.maximum(settings['min_track_budget'], settings['min_track_budget_frac'] * strong)
|
|
225
|
+
budget = g['budget'].to_numpy()
|
|
226
|
+
called = admitted & ((track == 'diff') | (budget >= strong) | (budget >= floor))
|
|
227
|
+
above = called & (g['max_share'].fillna(0).to_numpy() > settings['pct'])
|
|
228
|
+
rows.append({'contrast': contrast, 'set_name': set_name, 'track': track, 'regions': len(g),
|
|
229
|
+
'called': int(called.sum()), 'above_cut': int(above.sum())})
|
|
230
|
+
return pd.DataFrame(rows)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def write_settings(out_dir, settings: dict) -> Path:
|
|
234
|
+
p = Path(out_dir) / SETTINGS
|
|
235
|
+
p.write_text(json.dumps(settings, indent=1))
|
|
236
|
+
return p
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def read_settings(out_dir) -> Optional[dict]:
|
|
240
|
+
p = Path(out_dir) / SETTINGS
|
|
241
|
+
return json.loads(p.read_text()) if p.exists() else None
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def apply_settings(cfg: dict) -> bool:
|
|
245
|
+
"""
|
|
246
|
+
Put the numbers the seqlets step resolved (seqlet_settings.json in the run directory) into cfg['seqlets'] in
|
|
247
|
+
place of "auto", and record them under RESOLVED (see `requested`). True when every "auto" now has its number,
|
|
248
|
+
False when the run has no settings for it yet (the values stay "auto"); a config that asks for no "auto" is
|
|
249
|
+
left alone and is True.
|
|
250
|
+
"""
|
|
251
|
+
s = cfg['seqlets']
|
|
252
|
+
req = requested(s)
|
|
253
|
+
s.pop(RESOLVED, None)
|
|
254
|
+
auto = [k for k in AUTO_KEYS if is_auto(req.get(k))]
|
|
255
|
+
if not auto:
|
|
256
|
+
return True
|
|
257
|
+
saved = read_settings(cfg['run']['out_dir'])
|
|
258
|
+
if saved is None or any(k not in saved for k in auto):
|
|
259
|
+
for k in auto:
|
|
260
|
+
s[k] = 'auto'
|
|
261
|
+
return False
|
|
262
|
+
s[RESOLVED] = {}
|
|
263
|
+
for k in auto:
|
|
264
|
+
s[k] = s[RESOLVED][k] = float(saved[k])
|
|
265
|
+
return True
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def needs_settings(cfg: dict) -> bool:
|
|
269
|
+
"""Whether the run's seqlets lack the settings its config asks for: pct is "auto" and the run directory has no
|
|
270
|
+
seqlet_settings.json (the seqlets step did not finish, or called its seqlets before calibration)."""
|
|
271
|
+
return is_auto(requested(cfg['seqlets']).get('pct')) and read_settings(cfg['run']['out_dir']) is None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def missing_message(cfg: dict, config: str = 'CONFIG') -> str:
|
|
275
|
+
"""What to do about a run that needs_settings: the steps that rebuild it, in order."""
|
|
276
|
+
return (f'[seqlets] pct is "auto" and {cfg["run"]["out_dir"]} has no {SETTINGS}: the seqlets step did not finish '
|
|
277
|
+
f'there, or called its seqlets before the cut was calibrated. Run diffgrammar seqlets {config} --force, then '
|
|
278
|
+
f'cluster, families and report; or, for seqlets called before calibration, write the pct they were called '
|
|
279
|
+
f'with into [seqlets] (cut / budget in thresholds.csv; the default was 0.05)')
|