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/seqlets.py ADDED
@@ -0,0 +1,376 @@
1
+ """
2
+ Seqlet detection on the contributions of a record.
3
+
4
+ A seqlet is a short window whose per-position contribution exceeds a fraction of the record's
5
+ attribution budget:
6
+
7
+ cut = pct * budget, budget = |dF(x) - dF(reference)|
8
+
9
+ where dF is the record's track: the predicted B - A difference on the 'diff' track, one condition's
10
+ prediction on the 'a' or 'b' track (contrast.contrast_records). Integrated gradients is complete,
11
+ so the contributions of a record sum to dF(x) - dF(reference) and the threshold means "this
12
+ position carries at least pct of the record's total". Records with a larger budget get a
13
+ proportionally higher absolute bar, so a condition track, whose budget is a whole predicted
14
+ signal, has a higher cut than the differential, whose budget is a difference of two.
15
+
16
+ Detection is sign-aware with smooth gap bridging (after find_motifs in drg_tools.motif_analysis
17
+ .find_motifs): runs split where the contribution sign flips, a below-threshold position only
18
+ counts as a gap when the local average is also below the cut, and runs longer than max_len are
19
+ split at their deepest internal valley instead of being discarded.
20
+
21
+ CWMs are the hypothetical attributions of the window divided by mot_max, the signed
22
+ contribution at the strongest position, so every CWM has peak magnitude 1 and repressive and
23
+ activating instances of one motif share an orientation for clustering. The sign is kept in the
24
+ `sign` column. On a 'diff' record the polarity correction (call_seqlets, apply_polarity) makes it
25
+ read +1 = the motif's effect is stronger in B, -1 = stronger in A; on a condition record it is
26
+ the raw sign of mot_max, +1 = the motif activates in that condition, -1 = it represses there.
27
+ `repressive` is true where the seqlet's contribution summed over its span is below zero, in the
28
+ mean of both conditions on 'diff', in the condition itself on 'a' or 'b'. mot_max_a / mot_max_b,
29
+ the decomposition of a differential seqlet into each condition's contribution, exist on 'diff'
30
+ records only.
31
+
32
+ The contribution of a seqlet is its CWM times the one-hot of its own sequence (the `seq` column):
33
+ only the bases actually present, each with its signed share of the contrast. Clustering compares
34
+ contributions by default (cluster.cwm) and logos always show them.
35
+ """
36
+ from __future__ import annotations
37
+
38
+ from dataclasses import dataclass
39
+ from pathlib import Path
40
+ from typing import Callable, Iterable, List, Optional, Sequence, Tuple
41
+
42
+ import numpy as np
43
+ import pandas as pd
44
+
45
+ from .sequence import decode, one_hot
46
+
47
+ #: columns of older SCLC runs and their names here
48
+ LEGACY_COLUMNS = {'gene_name': 'record', 'assay': 'contrast'}
49
+
50
+ META_COLUMNS = ['record', 'pred', 'baseline', 'cut', 'start', 'end',
51
+ 'mot_max', 'mot_mean', 'mot_sum', 'mot_sum_norm', 'sign']
52
+
53
+
54
+ @dataclass
55
+ class SeqletCollection:
56
+ """
57
+ Detected seqlets: scalar metadata plus variable-length CWMs in one flat buffer.
58
+
59
+ meta : one row per seqlet (see META_COLUMNS, plus whatever the records carried, and seq,
60
+ the input sequence under the seqlet, when the records carried their one-hot)
61
+ cwm_buffer : (total_bp, 4) float32, all CWMs end to end
62
+ cwm_offsets : (N + 1,) int32, CWM i is cwm_buffer[cwm_offsets[i]:cwm_offsets[i + 1]]
63
+ """
64
+ meta: pd.DataFrame
65
+ cwm_buffer: np.ndarray
66
+ cwm_offsets: np.ndarray
67
+
68
+ def __len__(self) -> int:
69
+ return len(self.meta)
70
+
71
+ def get_cwm(self, i: int) -> np.ndarray:
72
+ return self.cwm_buffer[self.cwm_offsets[i]:self.cwm_offsets[i + 1], :]
73
+
74
+ def get_contribution(self, i: int) -> np.ndarray:
75
+ """CWM i times the one-hot of its sequence: the contribution of the bases present (needs seq)."""
76
+ return self.get_cwm(i) * one_hot(self.meta['seq'].iat[i])
77
+
78
+ def contributions(self) -> 'SeqletCollection':
79
+ """The same seqlets with every CWM replaced by its contribution (get_contribution); meta is shared."""
80
+ onehot = one_hot(''.join(self.meta['seq']))
81
+ if len(onehot) != len(self.cwm_buffer):
82
+ raise ValueError('seq lengths do not match the CWMs')
83
+ return SeqletCollection(meta=self.meta, cwm_buffer=self.cwm_buffer * onehot, cwm_offsets=self.cwm_offsets)
84
+
85
+ def cwm_list(self) -> List[np.ndarray]:
86
+ return [self.get_cwm(i) for i in range(len(self.meta))]
87
+
88
+ def take(self, idx: Sequence[int]) -> 'SeqletCollection':
89
+ """A new collection with the seqlets at idx, in that order."""
90
+ idx = np.asarray(idx, dtype=np.int64)
91
+ return from_cwms(self.meta.iloc[idx].reset_index(drop=True), [self.get_cwm(i) for i in idx])
92
+
93
+ def save(self, path: str | Path) -> None:
94
+ """Write meta.parquet and arrays.npz into the directory path."""
95
+ path = Path(path)
96
+ path.mkdir(parents=True, exist_ok=True)
97
+ self.meta.to_parquet(path / 'meta.parquet')
98
+ np.savez(path / 'arrays.npz', cwm_buffer=self.cwm_buffer, cwm_offsets=self.cwm_offsets)
99
+
100
+ @classmethod
101
+ def load(cls, path: str | Path) -> 'SeqletCollection':
102
+ """Read a collection written by save(), including older SCLC runs (legacy column names)."""
103
+ path = Path(path)
104
+ meta = pd.read_parquet(path / 'meta.parquet').rename(columns=LEGACY_COLUMNS)
105
+ arrs = np.load(path / 'arrays.npz')
106
+ return cls(meta=meta, cwm_buffer=arrs['cwm_buffer'], cwm_offsets=arrs['cwm_offsets'])
107
+
108
+
109
+ def from_cwms(meta: pd.DataFrame, cwms: Sequence[np.ndarray]) -> SeqletCollection:
110
+ """Bundle a metadata table and its CWMs (same order) into a collection."""
111
+ offsets = np.zeros(len(cwms) + 1, dtype=np.int32)
112
+ np.cumsum([len(c) for c in cwms], out=offsets[1:])
113
+ buf = np.concatenate(cwms, axis=0).astype(np.float32) if len(cwms) else np.empty((0, 4), np.float32)
114
+ return SeqletCollection(meta=meta.reset_index(drop=True), cwm_buffer=buf, cwm_offsets=offsets)
115
+
116
+
117
+ def attach_sequences(seqlets: SeqletCollection, sequence_of: Callable[[str], str]) -> SeqletCollection:
118
+ """
119
+ Adds the column seq to a collection called without it. sequence_of maps a region id (coord) to its
120
+ model input sequence, such as an adapter's `sequence`; each region is read once.
121
+ """
122
+ meta = seqlets.meta
123
+ seqs = {c: sequence_of(c) for c in meta['coord'].unique()}
124
+ meta['seq'] = [seqs[c][int(s):int(e)] for c, s, e in zip(meta['coord'], meta['start'], meta['end'])]
125
+ return seqlets
126
+
127
+
128
+ def reverse_complement_cwm(cwm: np.ndarray) -> np.ndarray:
129
+ """Reverse complement of an (L, 4) matrix, columns A, C, G, T."""
130
+ return cwm[::-1, :][:, [3, 2, 1, 0]]
131
+
132
+
133
+ def contributions_from_attributions(attributions: np.ndarray, onehot: np.ndarray) -> np.ndarray:
134
+ """(L,) contribution per position: attribution times the one-hot input, summed over bases."""
135
+ attributions = np.asarray(attributions, dtype=np.float64)
136
+ onehot = np.asarray(onehot, dtype=np.float64)
137
+ if onehot.shape[0] == 4 and onehot.shape != attributions.shape:
138
+ onehot = onehot.T
139
+ return (attributions * onehot).sum(axis=-1)
140
+
141
+
142
+ # -- detection --------------------------------------------------------------------------------
143
+ def _find_runs(contribs: np.ndarray, cut: float, max_gap: int = 1, min_size: int = 4,
144
+ smooth_gap: bool = True) -> List[Tuple[int, int]]:
145
+ """Sign-aware runs of |contribution| > cut with smooth gap bridging; half-open intervals."""
146
+ aloc = np.abs(contribs) > cut
147
+ sign = np.sign(contribs)
148
+ lra = len(contribs)
149
+
150
+ def _gap_call(i, msi, avgwindow=0):
151
+ lo = max(0, i - avgwindow)
152
+ hi = min(lra, i + avgwindow + 1)
153
+ return msi * np.mean(contribs[lo:hi]) < cut
154
+
155
+ runs: List[Tuple[int, int]] = []
156
+ gap = max_gap + 1
157
+ msi = 1
158
+ potloc: List[int] = []
159
+ i = 0
160
+ while i < lra:
161
+ if aloc[i]:
162
+ if len(potloc) == 0:
163
+ msi = sign[i]
164
+ if sign[i] == msi:
165
+ potloc.append(i)
166
+ gap = 0
167
+ elif _gap_call(i, msi, avgwindow=max_gap * int(smooth_gap)):
168
+ gap += 1
169
+ if gap > max_gap:
170
+ if len(potloc) >= min_size:
171
+ runs.append((potloc[0], potloc[-1] + 1))
172
+ if len(potloc) > 0:
173
+ i -= gap
174
+ gap = max_gap + 1
175
+ potloc = []
176
+ elif _gap_call(i, msi, avgwindow=max_gap * int(smooth_gap)):
177
+ gap += 1
178
+ if gap > max_gap:
179
+ if len(potloc) >= min_size:
180
+ runs.append((potloc[0], potloc[-1] + 1))
181
+ if len(potloc) > 0:
182
+ i -= gap
183
+ gap = max_gap + 1
184
+ potloc = []
185
+ i += 1
186
+ if len(potloc) >= min_size:
187
+ runs.append((potloc[0], potloc[-1] + 1))
188
+ return runs
189
+
190
+
191
+ def _split_at_valleys(contribs: np.ndarray, start: int, end: int, max_len: int = 30,
192
+ min_size: int = 4, split_frac: float = 0.3) -> List[Tuple[int, int]]:
193
+ """Split a run longer than max_len at its deepest valley (|c| < split_frac * peak), recursively."""
194
+ length = end - start
195
+ span = np.abs(contribs[start:end])
196
+ peak = span.max()
197
+ if peak == 0:
198
+ return []
199
+ if length <= max_len:
200
+ return [(start, end)]
201
+ valley_mask = span < split_frac * peak
202
+ if not valley_mask.any():
203
+ return [(start, end)]
204
+ split_pos = int(np.argmin(np.where(valley_mask, span, np.inf)))
205
+ left_end, right_start = start + split_pos, start + split_pos + 1
206
+ result = []
207
+ if left_end - start >= min_size:
208
+ result.extend(_split_at_valleys(contribs, start, left_end, max_len, min_size, split_frac))
209
+ if end - right_start >= min_size:
210
+ result.extend(_split_at_valleys(contribs, right_start, end, max_len, min_size, split_frac))
211
+ return result
212
+
213
+
214
+ KEEP = ('set_name', 'contrast', 'track', 'coord') # record columns copied to every seqlet and threshold row
215
+
216
+
217
+ def record_seqlets(rec: dict, pct: float = 0.05, max_gap: int = 1, min_size: int = 4, max_len: int = 30,
218
+ smooth_gap: bool = True, max_seqlets_per_record: Optional[int] = None,
219
+ split_frac: float = 0.3, keep: Sequence[str] = KEEP):
220
+ """The seqlet rows and CWMs of one record (see collect_seqlets); ([], []) when its budget is <= 0."""
221
+ pred, baseline = float(rec['pred']), float(rec['baseline'])
222
+ budget = pred - baseline
223
+ if budget <= 0:
224
+ return [], []
225
+ cut = pct * budget
226
+ contribs = np.asarray(rec['contributions'], dtype=np.float64)
227
+ attrs = np.asarray(rec['attributions'], dtype=np.float64)
228
+
229
+ final_runs = []
230
+ for start, end in _find_runs(contribs, cut, max_gap=max_gap, min_size=min_size, smooth_gap=smooth_gap):
231
+ if end - start <= max_len:
232
+ final_runs.append((start, end))
233
+ else:
234
+ final_runs.extend(_split_at_valleys(contribs, start, end, max_len=max_len,
235
+ min_size=min_size, split_frac=split_frac))
236
+ rows, cwms = [], []
237
+ extra = {k: rec[k] for k in keep if k in rec}
238
+ onehot = rec.get('onehot')
239
+ mean_ab = rec.get('polarity') if rec.get('track', 'diff') == 'diff' else None # a decomposition of the differential
240
+ for start, end in final_runs:
241
+ span = contribs[start:end]
242
+ mot_max = float(span[int(np.argmax(np.abs(span)))])
243
+ if mot_max == 0:
244
+ continue
245
+ mot_sum = float(span.sum())
246
+ row = {'record': rec['record'], 'pred': pred, 'baseline': baseline, 'cut': cut,
247
+ 'start': start, 'end': end, 'mot_max': mot_max, 'mot_mean': float(span.mean()),
248
+ 'mot_sum': mot_sum, 'mot_sum_norm': mot_sum / abs(mot_max),
249
+ 'sign': int(np.sign(mot_max)), **extra}
250
+ if onehot is not None:
251
+ row['seq'] = decode(onehot[start:end])
252
+ if mean_ab is not None: # each condition's own contribution: the mean of both -/+ half the difference
253
+ for col, c in (('mot_max_a', mean_ab[start:end] - span / 2), ('mot_max_b', mean_ab[start:end] + span / 2)):
254
+ row[col] = float(c[int(np.argmax(np.abs(c)))])
255
+ rows.append(row)
256
+ cwms.append(attrs[start:end, :] / mot_max)
257
+ if max_seqlets_per_record is not None and len(rows) > max_seqlets_per_record:
258
+ order = sorted(range(len(rows)), key=lambda i: abs(rows[i]['mot_max']), reverse=True)
259
+ rows = [rows[i] for i in order[:max_seqlets_per_record]]
260
+ cwms = [cwms[i] for i in order[:max_seqlets_per_record]]
261
+ return rows, cwms
262
+
263
+
264
+ def collect_seqlets(records: Iterable[dict], pct: float = 0.05, max_gap: int = 1, min_size: int = 4,
265
+ max_len: int = 30, smooth_gap: bool = True,
266
+ max_seqlets_per_record: Optional[int] = None, split_frac: float = 0.3,
267
+ keep: Sequence[str] = KEEP) -> SeqletCollection:
268
+ """
269
+ Detect seqlets in every record.
270
+
271
+ Each record is a dict with
272
+ record : str, unique id of the (region, contrast, track)
273
+ contributions : (L,) contribution per position
274
+ attributions : (L, 4) hypothetical attributions, the CWM source
275
+ pred, baseline: the budget is pred - baseline; records with budget <= 0 are skipped
276
+ and optionally track ('a', 'b' or 'diff'; a record without one is a 'diff' record); onehot, the
277
+ (L, 4) input, which gives every seqlet its seq; polarity, the (L,) contributions averaged over
278
+ both conditions, which on a 'diff' record gives mot_max_a / mot_max_b, each condition's
279
+ contribution at its own strongest position in the seqlet (signed, never flipped by the polarity
280
+ correction); and the columns named in `keep`, which are copied to every row.
281
+
282
+ max_seqlets_per_record keeps the strongest seqlets of a record by |mot_max|.
283
+ """
284
+ kw = dict(pct=pct, max_gap=max_gap, min_size=min_size, max_len=max_len, smooth_gap=smooth_gap,
285
+ max_seqlets_per_record=max_seqlets_per_record, split_frac=split_frac, keep=keep)
286
+ meta_rows, cwm_list = [], []
287
+ for rec in records:
288
+ rows, cwms = record_seqlets(rec, **kw)
289
+ meta_rows.extend(rows)
290
+ cwm_list.extend(cwms)
291
+ return _bundle(meta_rows, cwm_list, keep)
292
+
293
+
294
+ def _bundle(meta_rows, cwm_list, keep):
295
+ if not meta_rows:
296
+ return SeqletCollection(meta=pd.DataFrame(columns=META_COLUMNS + list(keep)),
297
+ cwm_buffer=np.empty((0, 4), np.float32),
298
+ cwm_offsets=np.zeros(1, np.int32))
299
+ return from_cwms(pd.DataFrame(meta_rows), cwm_list)
300
+
301
+
302
+ def call_seqlets(records: Iterable[dict], pct: float, polarity: bool = True, log_every: int = 0, log=print,
303
+ **kw):
304
+ """
305
+ Streaming seqlet calling: one record at a time, so attributions are never all in memory.
306
+ With polarity, every seqlet gets `repressive`, and a 'diff' record's seqlets the polarity
307
+ correction (as apply_polarity does) when the record has a 'polarity' array: a differential
308
+ seqlet that represses in both conditions has its sign flipped, so +1 reads "stronger in B". A
309
+ condition record's seqlets keep the raw sign of their contribution, and are repressive where that
310
+ contribution, summed over the seqlet, is below zero. Returns (SeqletCollection, threshold table).
311
+ """
312
+ meta_rows, cwm_list, thr = [], [], []
313
+ keep = kw.get('keep', KEEP)
314
+ for k, rec in enumerate(records, 1):
315
+ rows, cwms = record_seqlets(rec, pct=pct, **kw)
316
+ if polarity and rows:
317
+ diff = rec.get('track', 'diff') == 'diff'
318
+ pol = rec.get('polarity') if diff else None
319
+ for r in rows:
320
+ if diff:
321
+ rep = pol is not None and pol[int(r['start']):int(r['end'])].sum() < 0
322
+ if rep:
323
+ for c in ('mot_sum_norm', 'mot_max', 'mot_sum'):
324
+ r[c] = -r[c]
325
+ else:
326
+ rep = r['mot_sum'] < 0
327
+ r['repressive'] = bool(rep)
328
+ r['sign'] = int(np.sign(r['mot_max']))
329
+ meta_rows.extend(rows)
330
+ cwm_list.extend(cwms)
331
+ c = np.asarray(rec['contributions'])
332
+ budget = float(rec['pred']) - float(rec['baseline'])
333
+ thr.append({'record': rec['record'], **{x: rec[x] for x in keep if x in rec},
334
+ 'signed_budget': rec.get('signed_budget', budget), 'budget': budget,
335
+ 'budget_source': rec.get('budget_source', ''), 'cut': pct * budget,
336
+ 'sum_contributions': float(c.sum()), 'max_abs_contribution': float(np.abs(c).max()),
337
+ 'n_above_cut': int((np.abs(c) > pct * budget).sum()), 'n_seqlets': len(rows)})
338
+ if log_every and k % log_every == 0:
339
+ log(f' {k} records, {len(meta_rows)} seqlets')
340
+ return _bundle(meta_rows, cwm_list, keep), pd.DataFrame(thr)
341
+
342
+
343
+ def apply_polarity(seqlets: SeqletCollection, polarity: dict) -> SeqletCollection:
344
+ """
345
+ Orient each differential seqlet by what the motif does, not by the sign of the difference.
346
+
347
+ polarity maps record id -> (L,) contributions averaged over both conditions. A seqlet whose
348
+ averaged contribution sums below zero is repressive in both conditions; its difference sign is
349
+ flipped so that `sign` always reads +1 = |effect| stronger in B, -1 = stronger in A. The CWM is
350
+ left as it is. Adds the column `repressive`. Seqlets of a condition track (`track` 'a' or 'b')
351
+ are left alone: their sign is that of their own contribution.
352
+ """
353
+ meta = seqlets.meta
354
+ repressive = np.zeros(len(meta), dtype=bool)
355
+ tracks = meta['track'] if 'track' in meta else ['diff'] * len(meta)
356
+ for i, (rec, s, e, t) in enumerate(zip(meta['record'], meta['start'], meta['end'], tracks)):
357
+ ca = polarity.get(rec) if t == 'diff' else None
358
+ if ca is not None:
359
+ repressive[i] = ca[int(s):int(e)].sum() < 0
360
+ meta['repressive'] = repressive
361
+ for c in ('mot_sum_norm', 'mot_max', 'mot_sum'):
362
+ meta[c] = np.where(repressive, -meta[c], meta[c])
363
+ meta['sign'] = np.sign(meta['mot_max']).astype(int)
364
+ return seqlets
365
+
366
+
367
+ def by_size(diff, mean):
368
+ """
369
+ B − A oriented as apply_polarity orients a seqlet: flipped where the mean of A and B is below zero (the sequence
370
+ represses), so it is above zero where |B| > |A| and below where |A| > |B|, whatever the sign of either. A base or
371
+ site that represses in both, more in A, has B − A > 0 and would otherwise read as acting in B. Works per base
372
+ (arrays) or per site (sums over its span).
373
+ """
374
+ diff, mean = np.asarray(diff, np.float64), np.asarray(mean, np.float64)
375
+ return np.where(mean < 0, -diff, diff)
376
+
@@ -0,0 +1,22 @@
1
+ """DNA one-hot helpers. Column / channel order A, C, G, T; unknown bases (N, ...) are all zeros."""
2
+ import numpy as np
3
+
4
+ _IDX = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
5
+
6
+
7
+ def one_hot(seq: str) -> np.ndarray:
8
+ """(L, 4) float32."""
9
+ out = np.zeros((len(seq), 4), np.float32)
10
+ for i, b in enumerate(seq.upper()):
11
+ j = _IDX.get(b)
12
+ if j is not None:
13
+ out[i, j] = 1.0
14
+ return out
15
+
16
+
17
+ def decode(onehot: np.ndarray) -> str:
18
+ """(L, 4) or (4, L) one-hot to a string; all-zero positions become N."""
19
+ x = onehot if onehot.shape[-1] == 4 else onehot.T
20
+ s = np.array(list('ACGT'))[x.argmax(-1)]
21
+ s[x.sum(-1) == 0] = 'N'
22
+ return ''.join(s)
@@ -0,0 +1,140 @@
1
+ """
2
+ Report tables: how often each motif (cluster, subfamily or family) occurs in each region set and
3
+ contrast, and in which direction it acts.
4
+
5
+ Prevalence is the share of regions carrying the motif. Its denominator is stated explicitly
6
+ because it changes the numbers: 'with_seqlet' counts regions with at least one seqlet in that
7
+ set and contrast, 'attributed' counts every region that was
8
+ attributed and passed into seqlet calling, whether or not a seqlet was found there.
9
+
10
+ Direction uses the polarity-corrected sign: share_b is the fraction of a motif's seqlets whose
11
+ effect is stronger in condition B, share_equal the fraction equal in both (sites found on a
12
+ condition track alone, sign 0; the rest are stronger in A). The median mot_max is the signed
13
+ contribution at the seqlet's strongest position, so it also carries magnitude; sites equal in
14
+ both have none and are left out of it.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from typing import Optional, Sequence
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+
25
+ def denominators(meta: pd.DataFrame, thresholds: Optional[pd.DataFrame] = None,
26
+ mode: str = 'with_seqlet') -> pd.Series:
27
+ """(set_name, contrast) -> number of regions."""
28
+ if mode == 'with_seqlet':
29
+ return meta.groupby(['set_name', 'contrast'])['coord'].nunique()
30
+ if mode == 'attributed':
31
+ if thresholds is None:
32
+ raise ValueError("mode 'attributed' needs the threshold table of the seqlet run")
33
+ return thresholds.groupby(['set_name', 'contrast'])['coord'].nunique()
34
+ raise ValueError(f'unknown denominator mode {mode!r}')
35
+
36
+
37
+ def class_sets(sets: Sequence[str], label_a: str, label_b: str) -> list:
38
+ """
39
+ Two region classes as [A, B], so that every comparison between them runs the contrast's way, B over A: B is the
40
+ set named after label_b when exactly one is, else A is the set named after label_a when exactly one is, else the
41
+ order given. A set is named after a label that is a word of its name (`Treg_high`, `seed_Treg`), else that its
42
+ name contains. Empty unless there are two sets.
43
+ """
44
+ sets = list(sets)
45
+ if len(sets) != 2:
46
+ return []
47
+ for whole in (True, False):
48
+ for label, is_b in ((label_b, True), (label_a, False)):
49
+ if not label:
50
+ continue
51
+ word = re.compile(rf'(?<![A-Za-z0-9]){re.escape(str(label))}(?![A-Za-z0-9])')
52
+ named = [s for s in sets if (word.search(str(s)) if whole else str(label) in str(s))]
53
+ if len(named) == 1:
54
+ other = next(s for s in sets if s != named[0])
55
+ return [other, named[0]] if is_b else [named[0], other]
56
+ return sets
57
+
58
+
59
+ def label_seqlets(meta: pd.DataFrame, families: pd.DataFrame, min_cluster_size: int = 1) -> pd.DataFrame:
60
+ """Seqlet table joined to its cluster's tf / group / subfamily; small clusters dropped."""
61
+ sizes = meta.groupby('cluster').size()
62
+ keep = families[families['cluster'].map(sizes).fillna(0) >= min_cluster_size]
63
+ return meta.merge(keep[['cluster', 'tf', 'group', 'subfamily']], on='cluster', how='inner')
64
+
65
+
66
+ def motif_table(meta: pd.DataFrame, level: str = 'subfamily', den: Optional[pd.Series] = None,
67
+ effect: str = 'mot_max') -> pd.DataFrame:
68
+ """
69
+ One row per (motif, set_name, contrast): regions, prevalence %, seqlets, median effect,
70
+ share stronger in B, and the TFs whose matrices best match the motif's clusters.
71
+ """
72
+ den = denominators(meta) if den is None else den
73
+ rows = []
74
+ for (m, s, c), g in meta.groupby([level, 'set_name', 'contrast']):
75
+ n_reg = g['coord'].nunique()
76
+ tfs = g.groupby('tf').size().sort_values(ascending=False).index[:3] if 'tf' in g else []
77
+ with_effect = g[effect].dropna() # sites equal in both conditions have none
78
+ rows.append({level: m, 'set_name': s, 'contrast': c, 'regions': n_reg,
79
+ 'prevalence_pct': 100 * n_reg / den.get((s, c), np.nan), 'seqlets': len(g),
80
+ 'clusters': g['cluster'].nunique(),
81
+ 'median_effect': float(with_effect.median()) if len(with_effect) else np.nan,
82
+ 'share_b': float((g['sign'] > 0).mean()), 'share_equal': float((g['sign'] == 0).mean()),
83
+ 'top_tfs': ', '.join(tfs)})
84
+ return pd.DataFrame(rows)
85
+
86
+
87
+ def top_motifs(table: pd.DataFrame, level: str, set_name: str, n: int = 20,
88
+ contrasts: Optional[Sequence[str]] = None) -> list:
89
+ """The n motifs with the most regions in set_name, summed over the given contrasts."""
90
+ t = table[table['set_name'] == set_name]
91
+ if contrasts is not None:
92
+ t = t[t['contrast'].isin(contrasts)]
93
+ return t.groupby(level)['regions'].sum().nlargest(n).index.tolist()
94
+
95
+
96
+ def prevalence_ratio(table: pd.DataFrame, level: str, numerator: str, denominator: str) -> pd.Series:
97
+ """
98
+ log2 of a motif's prevalence in one region class over another, averaged over contrasts, with one
99
+ pseudo-region in each class so that a motif absent from one class stays finite.
100
+ """
101
+ t = table.assign(n_class=table['regions'] * 100 / table['prevalence_pct'])
102
+ out = {}
103
+ for m, g in t.groupby(level):
104
+ vals = []
105
+ for c, gc in g.groupby('contrast'):
106
+ a, b = gc[gc['set_name'] == numerator], gc[gc['set_name'] == denominator]
107
+ if a.empty and b.empty:
108
+ continue
109
+ na = float(a['n_class'].iloc[0]) if len(a) else float(t.loc[t['set_name'] == numerator, 'n_class'].max())
110
+ nb = float(b['n_class'].iloc[0]) if len(b) else float(t.loc[t['set_name'] == denominator, 'n_class'].max())
111
+ ra = float(a['regions'].iloc[0]) if len(a) else 0.0
112
+ rb = float(b['regions'].iloc[0]) if len(b) else 0.0
113
+ vals.append(np.log2(((ra + 1) / (na + 1)) / ((rb + 1) / (nb + 1))))
114
+ if vals:
115
+ out[m] = float(np.mean(vals))
116
+ return pd.Series(out)
117
+
118
+
119
+ def report_clusters(meta: pd.DataFrame, sets: Sequence[str], n: int = 26, min_seqlets: int = 30) -> tuple:
120
+ """
121
+ The n largest clusters with at least min_seqlets seqlets in `sets`, split by the sign of their mean
122
+ mot_max: (stronger in B, stronger in A), each largest first. A cluster whose seqlets are all equal in
123
+ both conditions (no mot_max) goes last, with those stronger in A.
124
+ """
125
+ m = meta[meta['set_name'].isin(sets)]
126
+ size = m.groupby('cluster').size()
127
+ top = size[size >= min_seqlets].nlargest(n).index
128
+ mean = m[m['cluster'].isin(top)].groupby('cluster')['mot_max'].mean()
129
+ return [int(c) for c in top if mean[c] >= 0], [int(c) for c in top if not mean[c] >= 0]
130
+
131
+
132
+ def order_by_similarity(ids: Sequence[int], r: np.ndarray) -> list:
133
+ """ids reordered so similar motifs sit together: average linkage on 1 - r, r an (n, n) similarity."""
134
+ if len(ids) < 3:
135
+ return list(ids)
136
+ from scipy.cluster.hierarchy import leaves_list, linkage
137
+ from scipy.spatial.distance import squareform
138
+ d = np.clip(1.0 - np.nan_to_num(np.maximum(r, r.T)), 0.0, None)
139
+ np.fill_diagonal(d, 0.0)
140
+ return [ids[i] for i in leaves_list(linkage(squareform(d, checks=False), method='average'))]
diffgrammar/toy.py ADDED
@@ -0,0 +1,129 @@
1
+ """
2
+ A toy model with a known grammar, and data to run the pipeline on it: the tutorial in tutorials/toy and a check
3
+ that every step returns what was planted. CPU, seconds.
4
+
5
+ The model reads four motifs, each the consensus of a JASPAR 2024 matrix, on both strands. A site's activation is
6
+ about 1 for an exact match, 0.2 with one mismatch and nearly 0 otherwise. Two output tracks, one per condition:
7
+
8
+ A = GATA_W x GATA + EBOX_W x EBOX
9
+ B = SINGLE_W x (FOXA + HNF4) + EBOX_W x EBOX + COOP_W x sum over FOXA, HNF4 site pairs of K(distance)
10
+
11
+ K(d) = 1 - d / COOP_RANGE for start-to-start distances d below COOP_RANGE, else 0. So the planted truth:
12
+ GATA acts in A only; FOXA and HNF4 act in B only; the E-box acts equally in both, so it drops out of the B - A
13
+ contrast; and FOXA with HNF4 cooperate in B, more the closer they are, while in A no pair cooperates.
14
+
15
+ `make_data` writes a genome of 300 bp windows, each a random sequence with motifs planted in its centre, and the
16
+ region table with a measured value per condition (the model's output with noise).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ #: name -> (consensus, JASPAR matrix it comes from)
26
+ MOTIFS = {'GATA': ('CTTATCT', 'MA0036.4 GATA2'), 'FOXA': ('GTAAACAT', 'MA0148.5 FOXA1'),
27
+ 'HNF4': ('CAAAGTCCA', 'MA0114.5 HNF4A'), 'EBOX': ('GTCACGTGAC', 'MA0526.5 USF2')}
28
+ GATA_W, SINGLE_W, EBOX_W, COOP_W, COOP_RANGE = 3.0, 2.0, 1.0, 3.0, 40
29
+ TRACKS = ['A', 'B']
30
+ SEQ_LEN, WINDOW, CORE = 200, 300, 150
31
+ #: region kinds and how often each is drawn
32
+ KINDS = {'gata': 0.3, 'foxa_hnf4': 0.3, 'foxa_or_hnf4': 0.15, 'ebox': 0.15, 'none': 0.1}
33
+
34
+
35
+ def _model():
36
+ import torch
37
+
38
+ class Toy(torch.nn.Module):
39
+ def __init__(self):
40
+ super().__init__()
41
+ from .sequence import one_hot
42
+ self.names = list(MOTIFS)
43
+ self.filters = torch.nn.ParameterList(
44
+ [torch.nn.Parameter(torch.tensor(one_hot(s).T.copy()), requires_grad=False) for s, _ in MOTIFS.values()])
45
+ k = 1 - np.abs(np.arange(-COOP_RANGE + 1, COOP_RANGE)) / COOP_RANGE
46
+ self.register_buffer('kernel', torch.tensor(k, dtype=torch.float32).view(1, 1, -1))
47
+
48
+ def activation(self, x, w):
49
+ """(N, L) per start position, both strands, an exact match about 1."""
50
+ import torch.nn.functional as F
51
+ n = w.shape[1]
52
+ out = 0
53
+ for f in (w, w.flip(0, 1)): # the motif and its reverse complement
54
+ s = F.conv1d(x, f.unsqueeze(0))[:, 0]
55
+ out = out + F.softplus(3 * (s - (n - 1))) / 3
56
+ return F.pad(out, (0, n - 1))
57
+
58
+ def forward(self, x):
59
+ import torch
60
+ import torch.nn.functional as F
61
+ act = {n: self.activation(x, w) for n, w in zip(self.names, self.filters)}
62
+ near = F.conv1d(act['HNF4'].unsqueeze(1), self.kernel, padding=COOP_RANGE - 1)[:, 0]
63
+ coop = (act['FOXA'] * near).sum(-1)
64
+ a = GATA_W * act['GATA'].sum(-1) + EBOX_W * act['EBOX'].sum(-1)
65
+ b = SINGLE_W * (act['FOXA'].sum(-1) + act['HNF4'].sum(-1)) + EBOX_W * act['EBOX'].sum(-1) + COOP_W * coop
66
+ return torch.stack([a, b], 1)
67
+
68
+ return Toy().eval()
69
+
70
+
71
+ def make_predictor(device: str = 'cpu', batch_size: int = 512):
72
+ """The toy model as a predictor, the form every step takes a model in."""
73
+ from .marginalize import TorchEnsemble
74
+ return TorchEnsemble([_model()], member_names=['toy'], all_tracks=TRACKS, batch_size=batch_size, device=device)
75
+
76
+
77
+ def _plant(seq: list, rng, kind: str) -> None:
78
+ from .sequence import decode, one_hot
79
+ rc = lambda s: decode(one_hot(s)[::-1, ::-1])
80
+ lo = (WINDOW - CORE) // 2
81
+ sites = {'gata': ['GATA'] * int(rng.integers(1, 3)), 'foxa_hnf4': ['FOXA', 'HNF4'],
82
+ 'foxa_or_hnf4': [str(rng.choice(['FOXA', 'HNF4']))], 'ebox': ['EBOX'], 'none': []}[kind]
83
+ if kind != 'ebox' and rng.random() < 0.3:
84
+ sites = sites + ['EBOX'] # the shared motif, here and there
85
+ if kind == 'foxa_hnf4': # the pair at a random gap, either order
86
+ a, b = (MOTIFS[m][0] for m in rng.permutation(['FOXA', 'HNF4']))
87
+ gap = int(rng.integers(0, 60))
88
+ start = lo + int(rng.integers(0, CORE - len(a) - gap - len(b)))
89
+ for s, pos in ((a, start), (b, start + len(a) + gap)):
90
+ seq[pos:pos + len(s)] = list(s if rng.random() < 0.5 else rc(s))
91
+ sites = sites[2:]
92
+ for m in sites:
93
+ s = MOTIFS[m][0]
94
+ pos = lo + int(rng.integers(0, CORE - len(s)))
95
+ seq[pos:pos + len(s)] = list(s if rng.random() < 0.5 else rc(s))
96
+
97
+
98
+ def make_data(out_dir, n_regions: int = 1600, n_chroms: int = 4, noise: float = 0.3, seed: int = 0) -> pd.DataFrame:
99
+ """
100
+ Writes genome.fa and regions.csv (chrom, start, end, kind, and the measured A and B) into out_dir and returns
101
+ the region table. Each region is the central SEQ_LEN bp of its own window.
102
+ """
103
+ import torch
104
+ from .sequence import one_hot
105
+ out = Path(out_dir)
106
+ out.mkdir(parents=True, exist_ok=True)
107
+ rng = np.random.default_rng(seed)
108
+ per = n_regions // n_chroms
109
+ rows, fasta, genomes = [], [], {}
110
+ for c in range(1, n_chroms + 1):
111
+ chrom = f'chr{c}'
112
+ parts = []
113
+ for k in range(per):
114
+ seq = list(rng.choice(list('ACGT'), WINDOW))
115
+ kind = str(rng.choice(list(KINDS), p=list(KINDS.values())))
116
+ _plant(seq, rng, kind)
117
+ parts.append(''.join(seq))
118
+ centre = k * WINDOW + WINDOW // 2
119
+ rows.append({'chrom': chrom, 'start': centre - SEQ_LEN // 2, 'end': centre + SEQ_LEN // 2, 'kind': kind})
120
+ genome = genomes[chrom] = ''.join(parts)
121
+ fasta.append(f'>{chrom}\n' + '\n'.join(genome[i:i + 80] for i in range(0, len(genome), 80)))
122
+ (out / 'genome.fa').write_text('\n'.join(fasta) + '\n')
123
+ regions = pd.DataFrame(rows)
124
+ x = np.stack([one_hot(genomes[r.chrom][r.start:r.end]).T for r in regions.itertuples()]).astype(np.float32)
125
+ with torch.no_grad():
126
+ y = _model()(torch.tensor(x)).numpy()
127
+ regions[TRACKS] = np.clip(y * np.exp(rng.normal(0, noise, y.shape)), 0, None).round(4)
128
+ regions.to_csv(out / 'regions.csv', index=False)
129
+ return regions
File without changes