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,445 @@
1
+ """
2
+ Attributions of a two-condition contrast, written where the pipeline reads them.
3
+
4
+ `diffgrammar attribute CONFIG` (or `run(cfg)`) picks the regions a model separates between two conditions, attributes
5
+ each condition and writes one npz per region in the layout of the `peak_npz` adapter, so `diffgrammar pipeline` runs on
6
+ the output unchanged.
7
+
8
+ Conditions
9
+ A condition is a group of the model's output tracks, given in [attribute] the way a contrast is: `a`, `b` (track
10
+ lists) or `a_prefixes`, `b_prefixes`, and `label_a`, `label_b`. Its target is the model's signal summed over the
11
+ readout bins in signal space and averaged over the condition's tracks,
12
+
13
+ F_c(x) = mean over tracks t of c of sum over bins of transform(model(x)[t, bin])
14
+
15
+ `transform` undoes the model's output transform so the target is in signal space: 'pow2m1' (2^y - 1) for a model
16
+ of log2(x + 1) coverage, such as a Borzoi-type model; 'sigmoid' for a classifier's logits; 'exp' for natural-log
17
+ outputs; 'identity' for none.
18
+
19
+ Attributions (`integrated_gradients`)
20
+ Integrated gradients from a uniform 0.25 reference at `n_steps` points of [0, 1] with captum's riemann_trapezoid
21
+ weights (1 / n_steps each, the first and last halved), raw gradients (multiply_by_inputs=False): the same numbers
22
+ as captum's IntegratedGradients with those settings (tests/test_attribute.py checks it against captum), computed
23
+ here so one pass serves both conditions. At each position the mean over the four bases is subtracted: the hypothetical
24
+ attributions, every base scored. Times the one-hot input they are the contributions, and a condition's
25
+ contributions sum to F_c(x) - F_c(reference) up to the integration error (`completeness` in the metadata).
26
+ IG is linear in its target, so attributing F_c gives exactly the mean of the per-track attributions of c's
27
+ tracks, so one pass serves both conditions.
28
+
29
+ How many steps are enough depends on the model: 100 suffice for a Borzoi-based coverage model, while the 200 bp
30
+ Enformer-trunk classifier of the HepG2 vs K562 tutorial needs 2,000 (at 200 its contrast attributions are 19% off
31
+ a 4,000-step reference). So every run first checks its own step count (`convergence`): on `check_regions`
32
+ regions it compares n_steps with 2 n_steps and records the difference in config.json, with a warning when the
33
+ median relative L1 of the contrast attributions is above `check_tolerance`.
34
+
35
+ Regions (`select_regions`)
36
+ Chosen from a table of candidate regions (chrom, start, end, optionally summit) with an
37
+ optional measured value per track (columns named by track):
38
+ - held-out chromosomes only (`holdout_chroms`), so no region is attributed by a model that trained on it;
39
+ - the measured effect, log2((m_b + pseudocount) / (m_a + pseudocount)) of each condition's mean measured signal,
40
+ at least `lfc` in size;
41
+ - consistency: Welch's t-test across each condition's member tracks, BH over regions, q at most `fdr`. Only when
42
+ both conditions have two tracks or more; with one track each there is nothing to test;
43
+ - a signal floor: the stronger condition's measured signal at least `min_signal`;
44
+ - the model reproduces the difference: the predicted F_b - F_a has the measured sign and at least `min_pred_frac`
45
+ of its size, so the attributions explain a difference the model gets right.
46
+ Without measured values the regions are chosen on the predicted effect alone, which the metadata records. A kept
47
+ region is `<label>_high` for the condition it favours.
48
+
49
+ One condition (`tracks`, or `b` without `a`)
50
+ Each track on its own, no comparison: the target is F_b alone, one attribution per region, and a region is kept
51
+ when the track's measured signal (where the table has it) is at least `min_signal` and its predicted signal at
52
+ least `min_pred`, as `<label>_active`. `lfc`, `fdr` and `min_pred_frac` do not apply. With `tracks` listing
53
+ several, the pipeline runs each as its own run (config.for_track).
54
+
55
+ Output, under `out_dir` (default: the [attributions] root, so the pipeline reads it as is)
56
+ candidates.csv every candidate on the held-out chromosomes, its statistics and whether it was kept
57
+ config.json conditions, selection, IG settings and model
58
+ <group>/peaks/<chrom>_<centre>.npz
59
+ hypothetical, attributions (2, L, 4) condition a then b; hypothetical, and the contributions
60
+ sequence (4, L) uint8
61
+ predicted, reference, measured (2,) F_c(x), F_c(reference), each condition's mean measured signal
62
+ celltypes (2,) label_a, label_b: the track names a downstream contrast uses
63
+ metadata JSON: region, class, statistics, completeness, settings
64
+ Regions already written are skipped, so a run can be resumed.
65
+ """
66
+ from __future__ import annotations
67
+
68
+ import json
69
+ import time
70
+ from pathlib import Path
71
+ from typing import Callable, Optional, Sequence
72
+
73
+ import numpy as np
74
+ import pandas as pd
75
+
76
+ DEFAULTS = {'n_steps': 200, 'chunk': 50, 'batch_regions': 8, 'transform': 'pow2m1', 'bins': None,
77
+ 'lfc': 1.0, 'fdr': 0.05, 'min_signal': 0.0, 'min_pred_frac': 0.4, 'min_pred': 0.0, 'pseudocount': 1.0,
78
+ 'n_max': None, 'seed': 0, 'member': 0, 'group': 'heldout', 'holdout_chroms': None,
79
+ 'check_regions': 32, 'check_tolerance': 0.03}
80
+ TRANSFORMS = ('identity', 'pow2m1', 'sigmoid', 'exp')
81
+
82
+
83
+ # -- the target -------------------------------------------------------------------------------------
84
+
85
+ def signal(y, transform: str):
86
+ """Model output to signal space; works on torch tensors and numpy arrays."""
87
+ if transform == 'identity':
88
+ return y
89
+ is_np = isinstance(y, np.ndarray)
90
+ if transform == 'pow2m1':
91
+ return np.exp2(y) - 1.0 if is_np else y.exp2() - 1.0
92
+ if transform == 'exp':
93
+ return np.exp(y) if is_np else y.exp()
94
+ if transform == 'sigmoid':
95
+ return 1.0 / (1.0 + np.exp(-y)) if is_np else y.sigmoid()
96
+ raise ValueError(f'transform must be one of {TRANSFORMS}, not {transform!r}')
97
+
98
+
99
+ class Target:
100
+ """F_a and F_b from a model output (N, tracks, bins) or (N, tracks): (N, 2); F_b alone, (N, 1), without A columns."""
101
+
102
+ def __init__(self, cols_a: Sequence[int], cols_b: Sequence[int], transform: str = 'pow2m1', bins=None):
103
+ if transform not in TRANSFORMS:
104
+ raise ValueError(f'transform must be one of {TRANSFORMS}, not {transform!r}')
105
+ self.cols = [list(cols_a), list(cols_b)] if len(cols_a) else [list(cols_b)]
106
+ self.transform = transform
107
+ self.bins = slice(*bins) if bins is not None else slice(None)
108
+
109
+ def __call__(self, out):
110
+ if out.ndim == 2:
111
+ out = out[..., None]
112
+ y = signal(out[..., self.bins], self.transform).sum(-1) # (N, tracks)
113
+ cols = [y[:, c].mean(1) for c in self.cols]
114
+ if isinstance(y, np.ndarray):
115
+ return np.stack(cols, 1)
116
+ import torch
117
+ return torch.stack(cols, 1)
118
+
119
+
120
+ # -- integrated gradients ---------------------------------------------------------------------------
121
+
122
+ def integrated_gradients(forward: Callable, x: np.ndarray, target: Target, n_steps: int = 200, chunk: int = 50,
123
+ device: str = 'cpu'):
124
+ """
125
+ Hypothetical attributions of both conditions (of the one, for a single target) for one-hot inputs x (N, 4, L).
126
+
127
+ Returns hypothetical (N, K, L, 4), F(x) (N, K) and F(reference) (K,), K the target's conditions (2, or 1). `forward` maps (M, 4, L) to the model's full
128
+ output (M, tracks, bins); the interpolation is batched over regions and `chunk` steps at a time.
129
+ """
130
+ import torch
131
+ xt = torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float32, device=device)
132
+ n, _, L = xt.shape
133
+ base = torch.full((1, 4, L), 0.25, device=device)
134
+ alphas = torch.linspace(0, 1, n_steps, device=device)
135
+ deltas = torch.full((n_steps,), 1.0 / n_steps, device=device)
136
+ deltas[0] /= 2
137
+ deltas[-1] /= 2
138
+ k_out = len(target.cols)
139
+ acc = torch.zeros(k_out, n, 4, L, device=device)
140
+ for s0 in range(0, n_steps, chunk):
141
+ a, w = alphas[s0:s0 + chunk], deltas[s0:s0 + chunk]
142
+ s = len(a)
143
+ inp = (base.unsqueeze(1) + a.view(1, s, 1, 1) * (xt.unsqueeze(1) - base.unsqueeze(1)))
144
+ inp = inp.reshape(n * s, 4, L).requires_grad_(True)
145
+ out = target(forward(inp)) # (n s, K)
146
+ for c in range(k_out):
147
+ g, = torch.autograd.grad(out[:, c].sum(), inp, retain_graph=c < k_out - 1)
148
+ acc[c] += (g.view(n, s, 4, L) * w.view(1, s, 1, 1)).sum(1)
149
+ del inp, out
150
+ with torch.no_grad():
151
+ fx = target(forward(xt)).double().cpu().numpy()
152
+ fr = target(forward(base)).double().cpu().numpy()[0]
153
+ hyp = acc - acc.mean(dim=2, keepdim=True) # mean over the four bases
154
+ return hyp.permute(1, 0, 3, 2).double().cpu().numpy(), fx, fr
155
+
156
+
157
+ def predict_targets(forward: Callable, x: np.ndarray, target: Target, batch: int = 512, device: str = 'cpu'):
158
+ """F_a and F_b (N, 2) without gradients."""
159
+ import torch
160
+ out = []
161
+ with torch.no_grad():
162
+ for k in range(0, len(x), batch):
163
+ xt = torch.as_tensor(np.ascontiguousarray(x[k:k + batch]), dtype=torch.float32, device=device)
164
+ out.append(target(forward(xt)).double().cpu().numpy())
165
+ return np.concatenate(out) if out else np.zeros((0, len(target.cols)))
166
+
167
+
168
+ def convergence(forward: Callable, x: np.ndarray, target: Target, n_steps: int, chunk: int = 50,
169
+ batch: int = 8, device: str = 'cpu') -> dict:
170
+ """
171
+ How far n_steps is from 2 n_steps on these inputs, for the contrast (b minus a) contributions, or B's own for a
172
+ single target: the median and 90th percentile of the per-region relative L1 difference, the median per-region
173
+ correlation, and the share of regions whose contributions sum to within 5% of F_b - F_a (F_b) at each step count.
174
+ """
175
+ single = len(target.cols) == 1
176
+
177
+ def contrast(n):
178
+ cs, ds = [], []
179
+ for k in range(0, len(x), batch):
180
+ h, fx, fr = integrated_gradients(forward, x[k:k + batch], target, n, chunk, device)
181
+ c = h * x[k:k + batch].transpose(0, 2, 1)[:, None]
182
+ cs.append(c[:, 0] if single else c[:, 1] - c[:, 0])
183
+ ds.append((fx - fr)[:, 0] if single else (fx - fr) @ np.array([-1.0, 1.0]))
184
+ return np.concatenate(cs), np.concatenate(ds)
185
+ lo, d = contrast(n_steps)
186
+ hi, _ = contrast(2 * n_steps)
187
+ l1 = np.abs(lo - hi).sum(axis=(1, 2)) / np.maximum(np.abs(hi).sum(axis=(1, 2)), 1e-12)
188
+ r = [np.corrcoef(a.ravel(), b.ravel())[0, 1] for a, b in zip(lo, hi)]
189
+ ok = np.abs(d) > 1e-9
190
+ within = lambda c: float(np.mean(np.abs(c.sum(axis=(1, 2))[ok] / d[ok] - 1) <= 0.05)) if ok.any() else None
191
+ return {'n_steps': n_steps, 'against': 2 * n_steps, 'n_regions': len(x),
192
+ 'relative_l1_median': float(np.median(l1)), 'relative_l1_p90': float(np.percentile(l1, 90)),
193
+ 'r_median': float(np.median(r)), 'complete_5pct': within(lo), 'complete_5pct_at_2n': within(hi)}
194
+
195
+
196
+ def model_from_predictor(pred, member: int = 0):
197
+ """(forward, output column per track, device) of one member of a TorchEnsemble-like predictor."""
198
+ m = pred.models[member]
199
+ transform = getattr(pred, 'transform', None)
200
+
201
+ def forward(x):
202
+ y = m(x)
203
+ return transform(y) if transform is not None else y
204
+
205
+ cols = dict(zip(pred.tracks, pred.idx))
206
+ return forward, cols, pred.device
207
+
208
+
209
+ # -- regions ----------------------------------------------------------------------------------------
210
+
211
+ def _bh(p: np.ndarray) -> np.ndarray:
212
+ p = np.asarray(p, float)
213
+ q = np.full(len(p), np.nan)
214
+ ok = np.isfinite(p)
215
+ if ok.any():
216
+ from scipy.stats import false_discovery_control
217
+ q[ok] = false_discovery_control(p[ok])
218
+ return q
219
+
220
+
221
+ def select_regions(regions: pd.DataFrame, predicted: np.ndarray, contrast, settings: dict) -> pd.DataFrame:
222
+ """
223
+ The candidates with their statistics, `selected` and `class` (see the module docstring). `predicted` holds F_a
224
+ and F_b per region (N, 2); measured columns are the contrast's track names, where present.
225
+ """
226
+ s = {**DEFAULTS, **settings}
227
+ if not list(contrast.a): # one condition (Contrast.single)
228
+ return _select_single(regions, predicted, contrast, s)
229
+ out = regions.copy()
230
+ out['pred_a'], out['pred_b'] = predicted[:, 0], predicted[:, 1]
231
+ out['pred_diff'] = out['pred_b'] - out['pred_a']
232
+ has_meas = all(t in regions.columns for t in list(contrast.a) + list(contrast.b))
233
+ if has_meas:
234
+ A, B = regions[list(contrast.a)].to_numpy(float), regions[list(contrast.b)].to_numpy(float)
235
+ out['meas_a'], out['meas_b'] = A.mean(1), B.mean(1)
236
+ out['meas_diff'] = out['meas_b'] - out['meas_a']
237
+ pc = s['pseudocount']
238
+ out['log2fc'] = np.log2((out['meas_b'] + pc) / (out['meas_a'] + pc))
239
+ if A.shape[1] >= 2 and B.shape[1] >= 2:
240
+ from scipy.stats import ttest_ind
241
+ p = ttest_ind(B, A, axis=1, equal_var=False).pvalue
242
+ out['q'] = _bh(np.where(np.isfinite(p), p, 1.0))
243
+ consistent = out['q'] <= s['fdr']
244
+ else:
245
+ out['q'] = np.nan
246
+ consistent = pd.Series(True, index=out.index)
247
+ keep = ((out['log2fc'].abs() >= s['lfc']) & consistent
248
+ & (out[['meas_a', 'meas_b']].max(axis=1) >= s['min_signal'])
249
+ & (np.sign(out['pred_diff']) == np.sign(out['meas_diff']))
250
+ & (out['pred_diff'].abs() >= s['min_pred_frac'] * out['meas_diff'].abs()))
251
+ direction = np.sign(out['log2fc'])
252
+ out['selection'] = 'measured'
253
+ else:
254
+ pc = s['pseudocount']
255
+ out['log2fc'] = np.log2((out['pred_b'].clip(lower=0) + pc) / (out['pred_a'].clip(lower=0) + pc))
256
+ keep = (out['log2fc'].abs() >= s['lfc']) & (out[['pred_a', 'pred_b']].max(axis=1) >= s['min_signal'])
257
+ direction = np.sign(out['log2fc'])
258
+ out['selection'] = 'predicted'
259
+ out['class'] = np.select([direction > 0, direction < 0], [f'{contrast.label_b}_high', f'{contrast.label_a}_high'],
260
+ 'none')
261
+ out['selected'] = keep.to_numpy()
262
+ if s['n_max']:
263
+ rng = np.random.default_rng(s['seed'])
264
+ for cls in out.loc[out['selected'], 'class'].unique():
265
+ ix = out.index[out['selected'] & (out['class'] == cls)]
266
+ if len(ix) > s['n_max']:
267
+ out.loc[rng.permutation(ix)[s['n_max']:], 'selected'] = False
268
+ return out
269
+
270
+
271
+ def _select_single(regions: pd.DataFrame, predicted: np.ndarray, contrast, s: dict) -> pd.DataFrame:
272
+ """
273
+ One condition: kept where the measured signal (the mean of B's measured columns, where the table has them) is at
274
+ least min_signal and the predicted signal F_b at least min_pred; at most n_max of them, drawn at random.
275
+ """
276
+ out = regions.copy()
277
+ out['pred_b'] = predicted[:, 0]
278
+ keep = out['pred_b'] >= s['min_pred']
279
+ if all(t in regions.columns for t in contrast.b):
280
+ out['meas_b'] = regions[list(contrast.b)].to_numpy(float).mean(1)
281
+ keep &= out['meas_b'] >= s['min_signal']
282
+ out['selection'] = 'measured'
283
+ else:
284
+ out['selection'] = 'predicted'
285
+ out['class'] = np.where(keep, f'{contrast.label_b}_active', 'none')
286
+ out['selected'] = keep.to_numpy()
287
+ if s['n_max'] and keep.sum() > s['n_max']:
288
+ rng = np.random.default_rng(s['seed'])
289
+ out.loc[rng.permutation(out.index[out['selected']])[s['n_max']:], 'selected'] = False
290
+ return out
291
+
292
+
293
+ def windows(regions: pd.DataFrame, genome: str, seq_len: int) -> tuple:
294
+ """One-hot (N, 4, seq_len) centred on each region's summit (or centre); and which regions fit their chromosome."""
295
+ from pyfaidx import Fasta
296
+ from .sequence import one_hot
297
+ fa = Fasta(genome)
298
+ centre = (regions['summit'] if 'summit' in regions else (regions['start'] + regions['end']) // 2).to_numpy(int)
299
+ x = np.zeros((len(regions), 4, seq_len), np.float32)
300
+ ok = np.ones(len(regions), bool)
301
+ for k, (c, m) in enumerate(zip(regions['chrom'], centre)):
302
+ lo = m - seq_len // 2
303
+ if lo < 0 or lo + seq_len > len(fa[c]):
304
+ ok[k] = False
305
+ continue
306
+ x[k] = one_hot(str(fa[c][lo:lo + seq_len])).T
307
+ return x, ok, centre
308
+
309
+
310
+ # -- the step ---------------------------------------------------------------------------------------
311
+
312
+ def settings_of(cfg: dict, need_predictor: bool = True) -> dict:
313
+ a = dict(cfg.get('attribute', {}))
314
+ m = cfg.get('marginalize', {})
315
+ a.setdefault('predictor', m.get('predictor'))
316
+ a.setdefault('predictor_kwargs', m.get('predictor_kwargs', {}))
317
+ a.setdefault('out_dir', cfg.get('attributions', {}).get('root'))
318
+ for k in ('predictor', 'regions', 'genome', 'seq_len', 'out_dir'):
319
+ if not a.get(k) and (k != 'predictor' or need_predictor):
320
+ raise ValueError(f'[attribute] needs `{k}`')
321
+ return {**DEFAULTS, **a}
322
+
323
+
324
+ def finished(cfg: dict) -> bool:
325
+ """True when the attribution directory holds a completed run (its config.json records the completeness)."""
326
+ f = Path(settings_of(cfg, need_predictor=False)['out_dir']) / 'config.json'
327
+ return f.exists() and 'completeness' in json.loads(f.read_text())
328
+
329
+
330
+ def run(cfg: dict, max_regions: Optional[int] = None, select_only: bool = False, predictor=None, log=print) -> dict:
331
+ """
332
+ The attribute step. `predictor` (a TorchEnsemble-like object: `models`, `tracks`, `idx`, `device`) replaces the
333
+ config's predictor factory, so a model built in Python needs no factory file.
334
+ """
335
+ from .contrast import Contrast
336
+ from .marginalize import load_predictor
337
+ s = settings_of(cfg, need_predictor=predictor is None)
338
+ out = Path(s['out_dir'])
339
+ peaks_dir = out / s['group'] / 'peaks'
340
+ peaks_dir.mkdir(parents=True, exist_ok=True)
341
+ pred = predictor if predictor is not None else load_predictor(s['predictor'], **(s['predictor_kwargs'] or {}))
342
+ forward, cols, device = model_from_predictor(pred, s['member'])
343
+ contrast = Contrast.from_config('attribute', s, tracks=list(cols))
344
+ missing = [t for t in list(contrast.a) + list(contrast.b) if t not in cols]
345
+ if missing:
346
+ raise ValueError(f'[attribute] tracks not in the model: {missing}; it has {list(cols)}')
347
+ target = Target([cols[t] for t in contrast.a], [cols[t] for t in contrast.b], s['transform'], s['bins'])
348
+
349
+ regions = pd.read_csv(s['regions'])
350
+ if s['holdout_chroms']:
351
+ regions = regions[regions['chrom'].isin(s['holdout_chroms'])]
352
+ else:
353
+ log('[attribute] no holdout_chroms: regions may include ones the model trained on')
354
+ regions = regions.reset_index(drop=True)
355
+ x, ok, centre = windows(regions, s['genome'], int(s['seq_len']))
356
+ regions, x, centre = regions[ok].reset_index(drop=True), x[ok], centre[ok]
357
+ t0 = time.time()
358
+ predicted = predict_targets(forward, x, target, device=device)
359
+ cand = select_regions(regions, predicted, contrast, s)
360
+ cand['centre'] = centre
361
+ cand.to_csv(out / 'candidates.csv', index=False, float_format='%.6g')
362
+ sel = cand.index[cand['selected']]
363
+ if max_regions:
364
+ sel = sel[:max_regions]
365
+ counts = cand.loc[sel, 'class'].value_counts().to_dict()
366
+ log(f'[attribute] {len(cand)} candidates on {s["holdout_chroms"] or "all chromosomes"} '
367
+ f'({cand["selection"].iloc[0] if len(cand) else "-"} selection), kept {counts}, '
368
+ f'predicted in {time.time() - t0:.0f} s')
369
+ conditions = {'b': {'label': contrast.label_b, 'tracks': list(contrast.b)}}
370
+ if not contrast.single:
371
+ conditions = {'a': {'label': contrast.label_a, 'tracks': list(contrast.a)}, **conditions}
372
+ labels = [contrast.label_b] if contrast.single else [contrast.label_a, contrast.label_b]
373
+ keys = ('min_signal', 'min_pred', 'n_max') if contrast.single else (
374
+ 'lfc', 'fdr', 'min_signal', 'min_pred_frac', 'pseudocount', 'n_max')
375
+ info = {'conditions': conditions,
376
+ 'ig_target': f'mean over a condition\'s tracks of sum over bins of {s["transform"]}(model output)',
377
+ 'transform': s['transform'], 'bins': s['bins'], 'baseline': 'uniform 0.25', 'n_steps': s['n_steps'],
378
+ 'integration': 'riemann_trapezoid, captum step sizes (1/n, first and last halved)',
379
+ 'multiply_by_inputs': False, 'hypothetical': 'path-averaged gradient minus its mean over the 4 bases',
380
+ 'predictor': s['predictor'] if predictor is None else type(predictor).__name__,
381
+ 'predictor_kwargs': s['predictor_kwargs'] if predictor is None else {}, 'member': s['member'],
382
+ 'holdout_chroms': s['holdout_chroms'], 'seq_len': int(s['seq_len']), 'genome': s['genome'],
383
+ 'selection': {k: s[k] for k in keys},
384
+ 'regions': s['regions'], 'n_candidates': len(cand), 'kept': counts}
385
+ (out / 'config.json').write_text(json.dumps(info, indent=2, default=str) + '\n')
386
+ if select_only:
387
+ return info
388
+
389
+ if s['check_regions'] and len(sel):
390
+ rng = np.random.default_rng(s['seed'])
391
+ pick = rng.choice(np.asarray(sel), min(int(s['check_regions']), len(sel)), replace=False)
392
+ conv = convergence(forward, x[pick], target, int(s['n_steps']), int(s['chunk']), device=device)
393
+ info['convergence'] = conv
394
+ (out / 'config.json').write_text(json.dumps(info, indent=2, default=str) + '\n')
395
+ warn = conv['relative_l1_median'] > s['check_tolerance']
396
+ log(f'[attribute] {"WARNING: " if warn else ""}{conv["n_steps"]} vs {conv["against"]} steps on '
397
+ f'{conv["n_regions"]} regions: relative L1 median {conv["relative_l1_median"]:.3f} '
398
+ f'(90th {conv["relative_l1_p90"]:.3f}), r {conv["r_median"]:.4f}, complete within 5% '
399
+ f'{conv["complete_5pct"]:.2f}' + ('; raise n_steps' if warn else ''))
400
+ todo = [i for i in sel if not (peaks_dir / f'{cand.at[i, "chrom"]}_{int(cand.at[i, "centre"])}.npz').exists()]
401
+ log(f'[attribute] integrated gradients for {len(todo)} regions ({len(sel) - len(todo)} already written), '
402
+ f'{s["n_steps"]} steps, ' + ('one condition' if contrast.single else 'both conditions per pass'))
403
+ ratios, t0 = [], time.time()
404
+ for b0 in range(0, len(todo), int(s['batch_regions'])):
405
+ ix = todo[b0:b0 + int(s['batch_regions'])]
406
+ xb = x[ix]
407
+ hyp, fx, fr = integrated_gradients(forward, xb, target, int(s['n_steps']), int(s['chunk']), device)
408
+ for k, i in enumerate(ix):
409
+ row = cand.loc[i]
410
+ contrib = hyp[k] * xb[k].T[None]
411
+ sums = contrib.sum(axis=(1, 2))
412
+ delta = fx[k] - fr
413
+ ratio = [float(sm / d) if abs(d) > 1e-9 else float('nan') for sm, d in zip(sums, delta)]
414
+ ratios.extend(ratio)
415
+ stem = f'{row.chrom}_{int(row.centre)}'
416
+ meta = {'peak_id': stem, 'chrom': row.chrom, 'start': int(row.start), 'end': int(row.end),
417
+ 'summit': int(row.centre), 'fold': s['group'], 'class': row['class'],
418
+ **({'pred_b': float(row.pred_b), 'meas_b': float(row.meas_b) if 'meas_b' in cand else None}
419
+ if contrast.single else
420
+ {'log2fc': float(row.log2fc), 'q': None if pd.isna(row.get('q', np.nan)) else float(row.q),
421
+ 'pred_diff': float(row.pred_diff),
422
+ 'meas_diff': float(row.meas_diff) if 'meas_diff' in cand else None}),
423
+ 'completeness': ratio, 'celltypes': labels, **info}
424
+ meta.pop('kept', None)
425
+ np.savez_compressed(
426
+ peaks_dir / f'{stem}.npz',
427
+ hypothetical=hyp[k].astype(np.float32), attributions=contrib.astype(np.float32),
428
+ sequence=xb[k].astype(np.uint8), predicted=fx[k].astype(np.float32),
429
+ reference=fr.astype(np.float32),
430
+ measured=np.array([row.get('meas_b', np.nan)] if contrast.single else
431
+ [row.get('meas_a', np.nan), row.get('meas_b', np.nan)], np.float32),
432
+ celltypes=np.array(labels),
433
+ metadata=np.array(json.dumps(meta, default=str)))
434
+ done = min(b0 + len(ix), len(todo))
435
+ if done == len(ix) or done % 500 < len(ix) or done == len(todo):
436
+ rate = (time.time() - t0) / done
437
+ log(f'[attribute] {done}/{len(todo)} {rate:.2f} s/region eta {(len(todo) - done) * rate / 60:.0f} min')
438
+ r = np.asarray(ratios, float)
439
+ r = r[np.isfinite(r)]
440
+ info['completeness'] = {'median': float(np.median(r)) if len(r) else None,
441
+ 'within_10pct': float(np.mean(np.abs(r - 1) <= 0.1)) if len(r) else None}
442
+ (out / 'config.json').write_text(json.dumps(info, indent=2, default=str) + '\n')
443
+ log(f'[attribute] done; completeness ratio median {info["completeness"]["median"]}, '
444
+ f'within 10% for {info["completeness"]["within_10pct"]}')
445
+ return info