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/cluster.py ADDED
@@ -0,0 +1,439 @@
1
+ """
2
+ Seqlet clustering: CWM distances, agglomerative clustering, consensus CWMs, cross-contrast merge.
3
+
4
+ Distance between two CWMs is the correlation p-value at their best alignment (diffgrammar.align:
5
+ reverse complement allowed, minimum overlap 4 bp); lower is more similar. Clusters come from
6
+ complete-linkage agglomerative clustering on that matrix with a p-value cut, so every pair
7
+ inside a cluster is similar. The full matrix is O(N^2) in memory, so large runs cluster a random
8
+ subsample, build the consensus CWMs from it, and then assign every seqlet to its nearest
9
+ consensus (`cluster_run`).
10
+
11
+ The CWMs compared are contributions by default (cwm='contribution': each CWM times the one-hot of
12
+ its own sequence) or the hypothetical CWMs as called (cwm='hypothetical'); the consensus is in the
13
+ same representation.
14
+
15
+ Seqlets are called on several tracks of a region: each condition and their difference under each
16
+ contrast (contrast.TRACKS), so the same motif instance is called once per track it clears the
17
+ threshold on, and once more per contrast when there are several (one per assay, say).
18
+ `merge_overlapping_seqlets` merges seqlets of one region that overlap by at least 30% of the
19
+ shorter one into one site, whatever their tracks, clusters the merged set, and the labels go back
20
+ to every per-track seqlet, so one motif instance gets one label across tracks and contrasts. A
21
+ run with a single track has nothing to merge and is clustered as it is.
22
+
23
+ Downstream, the differential site is the unit: when the run called several tracks, `cluster_run`
24
+ also returns the sites per contrast (the same merge within each contrast, `ClusterResult.merged`),
25
+ one row per site spanning every track's seqlet, with its differential seqlet's values where it has
26
+ one and `sign` 0, "equal in both conditions", where it has none; `diffgrammar cluster` writes it as
27
+ merged_seqlets. The report and the viewer read the sites with a differential seqlet
28
+ (`differential_sites`): the condition tracks widen a site past the bases that differ and shape its
29
+ motif (cluster membership, consensus, sequence frequencies), but a site they alone found makes no
30
+ difference between the conditions and is left out downstream.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import gc
35
+ from dataclasses import dataclass
36
+ from typing import Dict, List, Optional, Sequence, Tuple
37
+
38
+ import numpy as np
39
+ import pandas as pd
40
+
41
+ from .align import compare, consensus_of_clusters
42
+ from .seqlets import SeqletCollection, from_cwms
43
+ from .sequence import one_hot
44
+
45
+ MIN_OVERLAP_FRAC = 0.3
46
+
47
+
48
+ def compute_distance_matrix(cwms: List[np.ndarray], device: str = 'cuda:0', min_overlap: int = 4,
49
+ batchsize: int = 1024, metric: str = 'correlation_pvalue'
50
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
51
+ """
52
+ (distance, offsets, revcomp), each (N, N). offsets / revcomp align row CWM to column CWM.
53
+ metric 'correlation' gives 1 - r at the best alignment instead of the p-value.
54
+ """
55
+ distance, offsets, revcomp = compare(
56
+ cwms, cwms, metric=metric, min_overlap=min_overlap, device=device,
57
+ batchsize=batchsize, return_alignment=True)
58
+ return distance.astype(np.float32), offsets, revcomp
59
+
60
+
61
+ def distance_to(queries: List[np.ndarray], targets: List[np.ndarray], device: str = 'cuda:0',
62
+ min_overlap: int = 4, batchsize: int = 1024, metric: str = 'correlation_pvalue') -> np.ndarray:
63
+ """(n_queries, n_targets) correlation p-value distance (or 1 - r with metric 'correlation'), no alignment."""
64
+ return compare(
65
+ queries, targets, metric=metric, min_overlap=min_overlap, device=device,
66
+ batchsize=batchsize, return_alignment=False)
67
+
68
+
69
+ def cluster_seqlets(distance: np.ndarray, distance_threshold: float = 0.05,
70
+ linkage: str = 'complete') -> np.ndarray:
71
+ """Agglomerative clustering on the precomputed p-value distance; (N,) int32 labels."""
72
+ from sklearn.cluster import AgglomerativeClustering
73
+ np.fill_diagonal(distance, 0.0)
74
+ model = AgglomerativeClustering(n_clusters=None, metric='precomputed', linkage=linkage,
75
+ distance_threshold=distance_threshold)
76
+ model.fit(distance.astype(np.float64))
77
+ return model.labels_.astype(np.int32)
78
+
79
+
80
+ def build_consensus(seqlets: SeqletCollection, labels: np.ndarray, distance: np.ndarray,
81
+ offsets: np.ndarray, revcomp: np.ndarray, remove_low: float = 0.075,
82
+ minlen: int = 3, min_cluster_size: int = 5) -> Tuple[List[int], List[np.ndarray]]:
83
+ """
84
+ One consensus CWM per cluster of at least min_cluster_size seqlets (align.consensus_of_clusters):
85
+ members aligned at their stored offset to the most central member and averaged, low-coverage
86
+ edges trimmed. The most central member is the one most similar to the rest, so it receives 1 - p-value.
87
+ """
88
+ unique, counts = np.unique(labels, return_counts=True)
89
+ keep = {int(u) for u, c in zip(unique, counts) if u >= 0 and c >= min_cluster_size}
90
+ if not keep:
91
+ return [], []
92
+ filtered = np.where(np.isin(labels, list(keep)), labels, -1)
93
+ consensus = consensus_of_clusters(seqlets.cwm_list(), filtered, 1.0 - distance, offsets, revcomp,
94
+ norm='max', remove_low=remove_low, minlen=minlen)
95
+ return sorted(keep), consensus
96
+
97
+
98
+ def merge_cluster_cwms(seqlets: SeqletCollection, labels: np.ndarray, cluster_ids: Sequence[int],
99
+ max_seqlets: int = 3000, seed: int = 0, device: str = 'cuda:0',
100
+ remove_low: float = 0.075) -> np.ndarray:
101
+ """One consensus over the seqlets of several clusters, built like a cluster consensus."""
102
+ idx = np.flatnonzero(np.isin(labels, list(cluster_ids)))
103
+ if len(idx) > max_seqlets:
104
+ idx = np.sort(np.random.default_rng(seed).choice(idx, max_seqlets, replace=False))
105
+ sub = seqlets.take(idx)
106
+ distance, offsets, revcomp = compute_distance_matrix(sub.cwm_list(), device=device)
107
+ _, consensus = build_consensus(sub, np.zeros(len(idx), np.int32), distance, offsets, revcomp,
108
+ remove_low=remove_low, min_cluster_size=1)
109
+ return consensus[0]
110
+
111
+
112
+ def member_consensus(aligned: SeqletCollection, shown: SeqletCollection, labels: np.ndarray,
113
+ cluster_ids: Sequence[int], consensus: Sequence[np.ndarray], device: str = 'cuda:0') -> List[np.ndarray]:
114
+ """
115
+ Per cluster, the mean of its members' CWMs in `shown`, each placed where its CWM in `aligned` (the
116
+ representation the consensus was built from) aligns best to the cluster's consensus: the same members
117
+ in another representation (contributions of a hypothetical consensus, or the reverse), in the consensus
118
+ frame and strand. aligned and shown hold the same seqlets in the same order.
119
+ """
120
+ from .seqlets import reverse_complement_cwm
121
+ labels = np.asarray(labels)
122
+ out = []
123
+ for cl, cons in zip(cluster_ids, consensus):
124
+ idx = np.flatnonzero(labels == cl)
125
+ acc = np.zeros(cons.shape, np.float64)
126
+ if len(idx):
127
+ _, off, rc = compare(
128
+ [aligned.get_cwm(i) for i in idx], [cons], metric='correlation_pvalue', min_overlap=4,
129
+ device=device, batchsize=1024, return_alignment=True)
130
+ for k, i in enumerate(idx):
131
+ c = shown.get_cwm(i)
132
+ c = reverse_complement_cwm(c) if rc[k, 0] else c
133
+ o = int(off[k, 0])
134
+ lo, hi = max(o, 0), min(o + len(c), len(cons))
135
+ if hi > lo:
136
+ acc[lo:hi] += c[lo - o:hi - o]
137
+ acc /= len(idx)
138
+ out.append(acc.astype(np.float32))
139
+ return out
140
+
141
+
142
+ def member_frequencies(aligned: SeqletCollection, sequence_of, cluster_ids: Sequence[int],
143
+ consensus: Sequence[np.ndarray], flank: int = 6, device: str = 'cuda:0') -> List[np.ndarray]:
144
+ """
145
+ Per cluster, its members' bases over the consensus frame widened by `flank` bp on each side, (L + 2 flank, 4):
146
+ each member placed where its CWM in `aligned` aligns best to the consensus (as member_consensus places it), its
147
+ bases read from its region's input (sequence_of: coord -> input sequence; complemented and reversed for a member
148
+ on the other strand), counted and divided by the number of members, so a column sums to the share of members
149
+ whose input reaches it. A member whose region's sequence cannot be read adds nothing.
150
+ """
151
+ meta = aligned.meta
152
+ labels = meta['cluster'].to_numpy()
153
+ seqs: dict = {}
154
+ code = {b: k for k, b in enumerate('ACGT')}
155
+
156
+ def sequence(coord):
157
+ if coord not in seqs:
158
+ try:
159
+ seqs[coord] = str(sequence_of(coord)).upper()
160
+ except (KeyError, FileNotFoundError, StopIteration):
161
+ seqs[coord] = None
162
+ return seqs[coord]
163
+ out = []
164
+ for cl, cons in zip(cluster_ids, consensus):
165
+ idx = np.flatnonzero(labels == cl)
166
+ acc = np.zeros((len(cons) + 2 * flank, 4), np.float64)
167
+ if len(idx):
168
+ _, off, rc = compare(
169
+ [aligned.get_cwm(i) for i in idx], [cons], metric='correlation_pvalue', min_overlap=4,
170
+ device=device, batchsize=1024, return_alignment=True)
171
+ for k, i in enumerate(idx):
172
+ s = sequence(meta['coord'].iat[i])
173
+ if s is None:
174
+ continue
175
+ o, start, end = int(off[k, 0]), int(meta['start'].iat[i]), int(meta['end'].iat[i])
176
+ for j in range(-flank, len(cons) + flank): # frame position j, input position pos
177
+ pos = end - 1 - (j - o) if rc[k, 0] else start + (j - o)
178
+ b = code.get(s[pos]) if 0 <= pos < len(s) else None
179
+ if b is not None:
180
+ acc[j + flank, 3 - b if rc[k, 0] else b] += 1
181
+ acc /= len(idx)
182
+ out.append(acc.astype(np.float32))
183
+ return out
184
+
185
+
186
+ def differential_sites(sites: SeqletCollection) -> SeqletCollection:
187
+ """
188
+ The downstream unit: the sites with a differential seqlet (a 'diff' member, named in `tracks`; sign +1 or -1).
189
+ A site the condition tracks alone found is equal in both conditions and is left out; the condition tracks only
190
+ widen a site and shape its motif. Seqlets as called (a `track` column, no `tracks`) keep their 'diff' rows.
191
+ Every row when nothing was called on 'diff'.
192
+ """
193
+ meta = sites.meta
194
+ if 'tracks' in meta:
195
+ keep = meta['tracks'].str.contains(':diff', regex=False)
196
+ elif 'track' in meta:
197
+ keep = meta['track'] == 'diff'
198
+ else:
199
+ return sites
200
+ return sites.take(np.flatnonzero(keep.to_numpy())) if keep.any() else sites
201
+
202
+
203
+ def cluster_summary(seqlets: SeqletCollection, labels: np.ndarray, cluster_ids: Sequence[int],
204
+ consensus_cwms: Sequence[np.ndarray]) -> pd.DataFrame:
205
+ """
206
+ Per cluster: n_seqlets, its differential seqlets (every row of a per-track collection; of the sites, those with
207
+ a 'diff' member, sign +1 or -1), their records, sign split (n_pos stronger in B, n_neg stronger in A), mot_max
208
+ mean / sd, and n_equal, the sites equal in both conditions that belong to the cluster too (they shape its
209
+ consensus, the downstream leaves them out); consensus length.
210
+ """
211
+ meta = seqlets.meta.assign(cluster=labels)
212
+ rows = []
213
+ for cl, cons in zip(cluster_ids, consensus_cwms):
214
+ sub = meta[meta['cluster'] == cl]
215
+ d = sub[sub['sign'] != 0]
216
+ rows.append({'cluster': int(cl), 'n_seqlets': len(d), 'n_records': d['record'].nunique(),
217
+ 'n_pos': int((d['sign'] == 1).sum()), 'n_neg': int((d['sign'] == -1).sum()),
218
+ 'n_equal': len(sub) - len(d),
219
+ 'mean_mot_max': float(d['mot_max'].mean()), 'std_mot_max': float(d['mot_max'].std(ddof=0)),
220
+ 'consensus_len': int(cons.shape[0])})
221
+ return pd.DataFrame(rows).sort_values('n_seqlets', ascending=False).reset_index(drop=True)
222
+
223
+
224
+ MERGE_MODES = ('signed', 'absolute')
225
+ #: columns a merged seqlet gets of its own, not from a member
226
+ MERGE_COLUMNS = ('record', 'start', 'end', 'seq', 'track', 'contrasts', 'n_contrasts', 'tracks', 'n_tracks', 'n_original')
227
+ #: the differential columns of a seqlet, undefined for a site without a 'diff' member
228
+ DIFF_COLUMNS = ('mot_max', 'mot_sum', 'mot_mean', 'mot_sum_norm')
229
+
230
+
231
+ def track_identity(meta: pd.DataFrame, track_cols: Sequence[str] = ('contrast', 'track')) -> pd.Series:
232
+ """
233
+ What a seqlet was called on, as one string per row: the values of `track_cols` that the table has, joined by ':'
234
+ ('ATAC:diff'; 'ATAC' for seqlets called before tracks were stored). Seqlets of one site with the same identity
235
+ are the same call; different identities are the tracks a merge spans.
236
+ """
237
+ cols = [c for c in track_cols if c in meta]
238
+ if not cols:
239
+ return pd.Series('', index=meta.index)
240
+ return meta[cols].astype(str).agg(':'.join, axis=1)
241
+
242
+
243
+ def merge_overlapping_seqlets(seqlets: SeqletCollection, track_cols: Sequence[str] = ('contrast', 'track'),
244
+ min_overlap_frac: float = MIN_OVERLAP_FRAC, mode: str = 'signed',
245
+ group_cols: Sequence[str] = ('set_name', 'coord')):
246
+ """
247
+ Merge seqlets of one region (group_cols: set_name and coord; with contrast too, one region under one contrast)
248
+ that overlap by >= min_overlap_frac of the shorter one into one site, over every track they were called on
249
+ (track_cols, see track_identity: contrast and track, so a region's conditions, its differential and its other
250
+ contrasts collapse at a shared site). Returns the merged collection and merge_map, the original indices behind
251
+ each merged seqlet.
252
+
253
+ The merged CWM is the signed mean of the members' CWMs at their offsets, renormalized so that its contribution
254
+ peak is 1 like a single seqlet's (mode 'signed'). Every stored CWM is divided by its signed peak, so the tracks of
255
+ one site arrive co-oriented and the mean keeps the within-motif structure the members share; the cluster
256
+ distance is correlation based, so only the pattern matters, not the scale. mode 'absolute' sums |CWM| instead,
257
+ for a site that activates on one track and represses on another, whose signed mean would cancel; it loses the
258
+ sign structure inside each motif, so it is not the default. A site with one member keeps its CWM untouched.
259
+
260
+ A merged row carries every column of its 'diff' member (the one with the largest |mot_max| when there are
261
+ several): mot_max, sign, repressive, mot_max_a / mot_max_b, cluster and the info columns read the differential
262
+ wherever it was called. A site without a 'diff' member was found on a condition track alone, so it has no
263
+ differential: sign is 0 (equal in both conditions), mot_max, mot_sum, mot_mean and mot_sum_norm are NaN,
264
+ repressive says whether its members' contribution sums below zero, mot_max_a / mot_max_b are its 'a' / 'b'
265
+ members' own mot_max (each condition's contribution at its strongest position, the same quantity a 'diff'
266
+ seqlet's columns hold; NaN for a condition it was not found on), and the other columns come from its strongest
267
+ member. Its own columns: record ('<set>||<coord>', with the contrast in the middle when grouped by it), start,
268
+ end and seq, which span the site, contrasts and tracks (the identities that contributed, ',' joined),
269
+ n_contrasts, n_tracks and n_original (its members). `track` is dropped: `tracks` says where it was found.
270
+ """
271
+ if mode not in MERGE_MODES:
272
+ raise ValueError(f'mode is one of {MERGE_MODES}, not {mode!r}')
273
+ meta = seqlets.meta
274
+ has_seq = 'seq' in meta
275
+ ident = track_identity(meta, track_cols)
276
+ strength = meta['mot_max'].abs() if 'mot_max' in meta else pd.Series(0.0, index=meta.index)
277
+ is_diff = meta['track'].eq('diff') if 'track' in meta else pd.Series(True, index=meta.index)
278
+ group_cols = list(group_cols)
279
+ rows, cwms, merge_map = [], [], []
280
+ for key, gidx in meta.groupby(group_cols).groups.items():
281
+ key = dict(zip(group_cols, key if isinstance(key, tuple) else (key,)))
282
+ set_name, coord = key['set_name'], key['coord']
283
+ group = meta.loc[gidx].sort_values('start')
284
+ intervals = []
285
+ for idx in group.index:
286
+ s, e = int(meta.at[idx, 'start']), int(meta.at[idx, 'end'])
287
+ if intervals and s < intervals[-1][1]:
288
+ overlap = intervals[-1][1] - s
289
+ shorter = min(e - s, intervals[-1][1] - intervals[-1][0])
290
+ if overlap / shorter >= min_overlap_frac:
291
+ intervals[-1] = (intervals[-1][0], max(intervals[-1][1], e), intervals[-1][2] + [idx])
292
+ continue
293
+ intervals.append((s, e, [idx]))
294
+ for m_start, m_end, orig in intervals:
295
+ rep = max(orig, key=lambda i: (bool(is_diff[i]), float(strength[i])))
296
+ if len(orig) == 1:
297
+ m_cwm = np.array(seqlets.get_cwm(orig[0]), np.float32)
298
+ m_seq = str(meta.at[orig[0], 'seq']) if has_seq else ''
299
+ else:
300
+ m_cwm = np.zeros((m_end - m_start, 4), np.float32)
301
+ m_seq = ['N'] * (m_end - m_start)
302
+ for idx in orig:
303
+ c = seqlets.get_cwm(idx)
304
+ off = int(meta.at[idx, 'start']) - m_start
305
+ m_cwm[off:off + len(c)] += np.abs(c) if mode == 'absolute' else c
306
+ if has_seq:
307
+ m_seq[off:off + len(c)] = meta.at[idx, 'seq']
308
+ m_seq = ''.join(m_seq)
309
+ m_cwm /= len(orig)
310
+ peak = float(np.abs(m_cwm * one_hot(m_seq)).max()) if has_seq and 'N' not in m_seq else float(np.abs(m_cwm).max())
311
+ if peak > 0:
312
+ m_cwm /= peak
313
+ idents = sorted(set(ident[orig]))
314
+ row = {k: v for k, v in meta.loc[rep].items() if k not in MERGE_COLUMNS}
315
+ if 'track' in meta and not is_diff[rep]: # no differential seqlet here: equal in both conditions
316
+ row['sign'] = 0
317
+ row.update({c: np.nan for c in DIFF_COLUMNS if c in row})
318
+ if 'mot_sum' in meta:
319
+ row['repressive'] = bool(meta.loc[orig, 'mot_sum'].sum() < 0)
320
+ for t, c in (('a', 'mot_max_a'), ('b', 'mot_max_b')):
321
+ members = [i for i in orig if meta.at[i, 'track'] == t]
322
+ row[c] = float(meta.at[max(members, key=lambda i: float(strength[i])), 'mot_max']) if members else np.nan
323
+ record = '||'.join([set_name] + ([str(key['contrast'])] if 'contrast' in key else []) + [coord])
324
+ row.update({'record': record, 'start': m_start, 'end': m_end,
325
+ 'contrasts': ','.join(sorted({str(meta.at[i, 'contrast']) for i in orig})) if 'contrast' in meta else '',
326
+ 'n_contrasts': len({meta.at[i, 'contrast'] for i in orig}) if 'contrast' in meta else 0,
327
+ 'tracks': ','.join(idents), 'n_tracks': len(idents), 'n_original': len(orig),
328
+ **({'seq': m_seq} if has_seq else {})})
329
+ rows.append(row)
330
+ cwms.append(m_cwm)
331
+ merge_map.append(orig)
332
+ return from_cwms(pd.DataFrame(rows), cwms), merge_map
333
+
334
+
335
+ @dataclass
336
+ class ClusterResult:
337
+ labels: np.ndarray # (N,) per original seqlet
338
+ cluster_ids: List[int]
339
+ consensus: List[np.ndarray]
340
+ summary: pd.DataFrame # per cluster, over the sites when there are several tracks
341
+ merged: Optional[SeqletCollection] # the sites: one row per site per contrast, labelled; None with one track
342
+ merge_map: Optional[list] # the original indices behind each site
343
+ n_subsample: int
344
+ merged_clustering: bool = False # whether the clustering ran on the sites merged across tracks and contrasts
345
+
346
+
347
+ def cluster_run(seqlets: SeqletCollection, merge: bool = True, n_subsample: int = 20_000,
348
+ distance_threshold: float = 0.05, min_cluster_size: int = 3, seed: int = 42,
349
+ device: str = 'cuda', cwm: str = 'contribution', merge_mode: str = 'signed', log=print) -> ClusterResult:
350
+ """
351
+ Cluster a collection end to end: with merge, the seqlets of one site are merged across tracks and
352
+ contrasts (merge_overlapping_seqlets, with merge_mode) and the merged set is clustered (skipped
353
+ when the collection was called on a single track, since there is then nothing to merge); random
354
+ subsample of at most n_subsample CWMs for the distance matrix, clustering and consensus on the
355
+ subsample, then every seqlet to its nearest consensus (the subsample keeps its exact labels),
356
+ and labels back to the per-track seqlets. cwm: 'contribution' (needs seq) or 'hypothetical',
357
+ the CWMs compared.
358
+
359
+ When the collection was called on several tracks, the result also holds the sites per contrast
360
+ (`merged`: the same merge within each contrast, labelled, hypothetical CWMs), of which those with
361
+ a differential seqlet are what the downstream reads (differential_sites) and what the summary
362
+ counts; without merge a site's tracks may have landed in different clusters, and the site takes
363
+ its 'diff' member's.
364
+ """
365
+ if cwm not in ('contribution', 'hypothetical'):
366
+ raise ValueError(f"cwm is 'contribution' or 'hypothetical', not {cwm!r}")
367
+ if merge_mode not in MERGE_MODES:
368
+ raise ValueError(f'merge_mode is one of {MERGE_MODES}, not {merge_mode!r}')
369
+ tracks = sorted(track_identity(seqlets.meta).unique())
370
+ multi_track = 'track' in seqlets.meta and seqlets.meta['track'].nunique() > 1
371
+ if merge and len(tracks) <= 1:
372
+ log(f'one track ({tracks[0] if tracks else "none"}): nothing to merge, the seqlets are clustered as they are')
373
+ merge = False
374
+ if merge:
375
+ merged, merge_map = merge_overlapping_seqlets(seqlets, mode=merge_mode)
376
+ shared = int((merged.meta['n_tracks'] > 1).sum())
377
+ log(f'{len(seqlets)} seqlets on {len(tracks)} tracks -> {len(merged)} merged sites, {shared} with more than one '
378
+ f'track ({merge_mode} mean)')
379
+ to_cluster = merged
380
+ else:
381
+ merged, merge_map, to_cluster = None, None, seqlets
382
+ if cwm == 'contribution': # the same as merging contributions: merged members share one sequence
383
+ to_cluster = to_cluster.contributions()
384
+
385
+ n_total = len(to_cluster)
386
+ if n_total > n_subsample:
387
+ sub_idx = np.sort(np.random.default_rng(seed).choice(n_total, n_subsample, replace=False))
388
+ else:
389
+ sub_idx = np.arange(n_total)
390
+ sub = to_cluster.take(sub_idx)
391
+ log(f'distance matrix {len(sub)} x {len(sub)} (~{len(sub) ** 2 * 4 / 1e9:.1f} GB)')
392
+ distance, offsets, revcomp = compute_distance_matrix(sub.cwm_list(), device=device)
393
+ labels_sub = cluster_seqlets(distance, distance_threshold=distance_threshold)
394
+ cluster_ids, consensus = build_consensus(sub, labels_sub, distance, offsets, revcomp,
395
+ min_cluster_size=min_cluster_size)
396
+ log(f'{len(set(labels_sub))} raw clusters, {len(cluster_ids)} with >= {min_cluster_size} seqlets')
397
+ del distance, offsets, revcomp
398
+ gc.collect()
399
+
400
+ d = distance_to(to_cluster.cwm_list(), consensus, device=device)
401
+ labels = np.array([cluster_ids[j] for j in np.argmin(d, axis=1)])
402
+ keep = set(cluster_ids)
403
+ for k, i in enumerate(sub_idx):
404
+ if labels_sub[k] in keep:
405
+ labels[i] = labels_sub[k]
406
+ del d
407
+ gc.collect()
408
+
409
+ if merge:
410
+ original = np.full(len(seqlets), -1, dtype=int)
411
+ for mi, orig in enumerate(merge_map):
412
+ original[orig] = labels[mi]
413
+ else:
414
+ original = labels
415
+ assert (original >= 0).all(), 'some seqlets were not assigned'
416
+ if multi_track: # the sites per contrast: what the downstream reads
417
+ labelled = SeqletCollection(seqlets.meta.assign(cluster=original), seqlets.cwm_buffer, seqlets.cwm_offsets)
418
+ sites, site_map = merge_overlapping_seqlets(labelled, group_cols=('set_name', 'coord', 'contrast'), mode=merge_mode)
419
+ with_diff = int(sites.meta['tracks'].str.contains(':diff').sum())
420
+ mixed = sum(len(set(original[o])) > 1 for o in site_map)
421
+ log(f'{len(seqlets)} seqlets -> {len(sites)} sites per contrast: {with_diff} differential (what the report and '
422
+ f'the viewer read), {len(sites) - with_diff} equal in both conditions (they shape the motifs only)'
423
+ + (f'; {mixed} sites whose tracks fell in different clusters take their differential seqlet\'s' if mixed else ''))
424
+ summary = cluster_summary(sites, sites.meta['cluster'].to_numpy(), cluster_ids, consensus)
425
+ else:
426
+ sites, site_map = None, None
427
+ summary = cluster_summary(seqlets, original, cluster_ids, consensus)
428
+ return ClusterResult(original, cluster_ids, consensus, summary, sites, site_map, len(sub_idx), merge)
429
+
430
+
431
+ def orient_like(cwms: Sequence[np.ndarray], reference: np.ndarray, device: str = 'cuda:0',
432
+ apply_to: Optional[Sequence[np.ndarray]] = None) -> List[np.ndarray]:
433
+ """
434
+ Each CWM on the strand that aligns best to `reference` (reverse-complemented where needed). apply_to:
435
+ matrices in the frames of cwms (the contribution consensus, say) to flip and return instead.
436
+ """
437
+ from .seqlets import reverse_complement_cwm
438
+ _, _, rc = compare(list(cwms), [reference], metric='correlation_pvalue', min_overlap=4, device=device, batchsize=256, return_alignment=True)
439
+ return [reverse_complement_cwm(c) if rc[i, 0] else c for i, c in enumerate(apply_to if apply_to is not None else cwms)]
diffgrammar/config.py ADDED
@@ -0,0 +1,213 @@
1
+ """
2
+ Run configs: one TOML file per analysis, everything a run needs to be repeated.
3
+
4
+ [run] name, out_dir, device
5
+ [attribute] compute the attributions (diffgrammar.attribute): predictor, regions, genome, seq_len,
6
+ a / b (or a_prefixes / b_prefixes), label_a / label_b, transform, bins, holdout_chroms,
7
+ n_steps, selection (lfc, fdr, min_signal, min_pred_frac), out_dir
8
+ [attributions] adapter and its settings (see diffgrammar.adapters); default: what [attribute] writes
9
+ [contrasts.X] a / b track lists (or a_prefixes / b_prefixes), label_a / label_b; default: the two
10
+ conditions of [attribute]
11
+ [seqlets] pct (a share of each record's budget, or "auto": the share at which `coverage` of the regions still
12
+ have a position above the cut), max_gap, min_size, max_len, max_per_record, budget, polarity, tracks (the tracks
13
+ seqlets are called on: any of "a", "b", "diff"; default all three), min_track_budget (a region's
14
+ weaker condition track is called on only when its budget reaches it; "auto": the
15
+ `floor_percentile`-th percentile of the regions' stronger condition budget), min_budget (a region whose stronger condition budget is
16
+ below it is left out; 0 = off, for attributions that arrive without a selection),
17
+ min_track_budget_frac (the same gate as a share of the region's stronger condition track; 0 = off).
18
+ "auto" values are resolved by the seqlets step and kept in <out_dir>/seqlet_settings.json
19
+ (diffgrammar.calibrate)
20
+ [cluster] merge, merge_mode ("signed" or "absolute", see diffgrammar.cluster.merge_overlapping_seqlets),
21
+ n_subsample, distance_threshold, min_cluster_size, seed, cwm
22
+ [jaspar] meme, cache_dir, top_n, group_level, linkage, p_cutoff
23
+ [report] level, denominator, min_cluster_size, sets, set_labels, top_n, n_logos, n_clusters, colours;
24
+ effect_pairs (diffgrammar.effects), value_units (column -> unit, for the labels of colour bars)
25
+ [marginalize] optional: pairs, motifs, scans and their settings (see diffgrammar.marginalize.cooperativity)
26
+ [expression] optional: deseq2, direction, assign ("closest", "table" or "contacts"), genes, assignments
27
+ or contacts (see diffgrammar.expression)
28
+ [cooccurrence] optional, read by the viewer: min_expected, alpha, seed, max_permutations, diff_min_expected,
29
+ scan_threshold, scan_window, counts_min_regions (see diffgrammar.view.data.pair_stats,
30
+ pair_differential and cooc_counts)
31
+ [pair_regression] optional: regions, columns, standard_errors, on, exclude, genome, and the fit's settings
32
+ (see diffgrammar.pair_regression)
33
+
34
+ A config with [attribute] needs neither [attributions] nor [contrasts]: the attribute step writes one attribution
35
+ per condition, named by its label, into `[attribute] out_dir` (default <out_dir>/attributions), and the contrast is
36
+ label_b minus label_a over them.
37
+
38
+ Single-track runs: [attribute] `tracks` instead of a / b analyses each listed track on its own, no comparison. Every
39
+ track becomes its own run, <out_dir>/<track>, with its attributions in <attribute out_dir>/<track> and a config.toml
40
+ written there (for_track, write_track_config), so each opens and exports like any run. The tracks share one
41
+ marginalization store, <out_dir>/marginalize/store, as it holds every model track's predictions. A config whose [attribute]
42
+ (or contrast) has `b` and no `a` is one such run.
43
+ """
44
+ from __future__ import annotations
45
+
46
+ import copy
47
+ import json
48
+ import re
49
+ import subprocess
50
+ import sys
51
+ import time
52
+ from pathlib import Path
53
+
54
+ if sys.version_info >= (3, 11):
55
+ import tomllib
56
+ else: # pragma: no cover
57
+ import tomli as tomllib
58
+
59
+ DEFAULTS = {
60
+ 'run': {'device': 'cuda', 'out_dir': 'results'},
61
+ 'seqlets': {'pct': 'auto', 'coverage': 0.95, # the cut: the share at which 95% of the regions keep a position above it
62
+ 'max_gap': 1, 'min_size': 4, 'max_len': 30, 'max_per_record': 20,
63
+ 'split_frac': 0.3, 'budget': 'auto', 'polarity': True,
64
+ 'tracks': ['a', 'b', 'diff'], # each condition and their difference (contrast.TRACKS)
65
+ 'min_track_budget': 'auto', # a region's weaker condition track is called on only above the
66
+ 'floor_percentile': 5, # 5th percentile of the regions' stronger condition budget
67
+ 'min_budget': 0.0, # regions below it are left out (0 = off)
68
+ 'min_track_budget_frac': 0.0}, # the floor as a share of the stronger track (0 = off; diffgrammar.calibrate)
69
+ 'cluster': {'merge': True, 'merge_mode': 'signed', # or 'absolute'
70
+ 'n_subsample': 20000, 'distance_threshold': 0.05, 'min_cluster_size': 3, 'seed': 42,
71
+ 'cwm': 'contribution'}, # or 'hypothetical'
72
+ 'jaspar': {'top_n': 5, 'group_level': 'family', 'linkage': 'complete', 'p_cutoff': 0.05},
73
+ 'report': {'level': 'subfamily', 'denominator': 'attributed', 'min_cluster_size': 30, 'top_n': 20,
74
+ 'n_logos': 24, 'n_clusters': 26, 'color_by': 'none'},
75
+ }
76
+ #: config keys that hold paths; relative values are resolved against the config file's directory
77
+ PATH_KEYS = {'out_dir', 'root', 'genome', 'budget_table', 'meme', 'cache_dir', 'store', 'design', 'regions',
78
+ 'exclude_beds', 'predictor', 'deseq2', 'assignments', 'genes', 'standard_errors', 'contacts'}
79
+
80
+
81
+ def _resolve(value, base: Path):
82
+ if isinstance(value, list):
83
+ return [_resolve(v, base) for v in value]
84
+ if not isinstance(value, str):
85
+ return value
86
+ if re.fullmatch(r'[A-Za-z_][\w.]*:\w+', value) and not value.split(':')[0].endswith('.py'):
87
+ return value # predictor spec 'package.module:function', not a path
88
+ head, sep, func = value, '', ''
89
+ if value.count('.py:') == 1: # predictor spec 'file.py:function'
90
+ head, func = value.split('.py:')
91
+ head, sep = head + '.py', ':'
92
+ p = Path(head)
93
+ return (str(p if p.is_absolute() else (base / p).resolve())) + (sep + func if sep else '')
94
+
95
+
96
+ def _resolve_paths(node, base: Path):
97
+ for k, v in node.items():
98
+ if isinstance(v, dict):
99
+ _resolve_paths(v, base)
100
+ elif k in PATH_KEYS:
101
+ node[k] = _resolve(v, base)
102
+
103
+
104
+ def load(path) -> dict:
105
+ path = Path(path)
106
+ with open(path, 'rb') as fh:
107
+ cfg = tomllib.load(fh)
108
+ base = path.resolve().parent
109
+ for section, values in DEFAULTS.items():
110
+ cfg.setdefault(section, {})
111
+ for k, v in values.items():
112
+ cfg[section].setdefault(k, v)
113
+ _resolve_paths(cfg, base)
114
+ if 'attribute' in cfg:
115
+ _from_attribute(cfg)
116
+ if 'jaspar' in cfg and 'meme' not in cfg['jaspar']:
117
+ from .jaspar import default_meme
118
+ cfg['jaspar'].setdefault('cache_dir', str(default_meme().parent))
119
+ cfg['jaspar']['meme'] = str(Path(cfg['jaspar']['cache_dir']) / default_meme().name)
120
+ cfg['_path'] = str(path.resolve())
121
+ return cfg
122
+
123
+
124
+ def _from_attribute(cfg: dict) -> None:
125
+ """[attributions] and [contrasts] from [attribute] where the config leaves them out (not for `tracks`, whose
126
+ runs are per track: for_track)."""
127
+ a = cfg['attribute']
128
+ a.setdefault('out_dir', cfg.get('attributions', {}).get('root') or str(Path(cfg['run']['out_dir']) / 'attributions'))
129
+ if 'tracks' in a:
130
+ return
131
+ cfg.setdefault('attributions', {'adapter': 'peak_npz', 'root': a['out_dir'], 'pattern': '*/peaks/*.npz',
132
+ 'set_field': 'class'})
133
+ lb = a.get('label_b', 'B')
134
+ if 'a' not in a and 'a_prefixes' not in a: # one condition: B alone, the contrast named after it
135
+ cfg.setdefault('contrasts', {lb: {'b': [lb], 'label_b': lb}})
136
+ return
137
+ la = a.get('label_a', 'A')
138
+ cfg.setdefault('contrasts', {'conditions': {'a': [la], 'b': [lb], 'label_a': la, 'label_b': lb}})
139
+
140
+
141
+ def tracks_of(cfg: dict) -> list:
142
+ """The tracks of a single-track config ([attribute] tracks), each its own run; [] for any other config."""
143
+ t = cfg.get('attribute', {}).get('tracks')
144
+ return [t] if isinstance(t, str) else list(t or [])
145
+
146
+
147
+ def for_track(cfg: dict, track: str) -> dict:
148
+ """
149
+ The run of one track of a single-track config: [attribute] with `b = [track]` and no A, run.out_dir
150
+ <out_dir>/<track>, its attributions in <attribute out_dir>/<track>, and [attributions] and [contrasts] from that.
151
+ """
152
+ tracks = tracks_of(cfg)
153
+ if track not in tracks:
154
+ raise ValueError(f'{track!r} is not one of [attribute] tracks {tracks}')
155
+ c = copy.deepcopy({k: v for k, v in cfg.items() if k not in ('attributions', 'contrasts')})
156
+ a = c['attribute']
157
+ for k in ('tracks', 'a', 'a_prefixes', 'b_prefixes', 'label_a'):
158
+ a.pop(k, None)
159
+ a['b'], a['label_b'] = [track], track
160
+ a['out_dir'] = str(Path(a['out_dir']) / track)
161
+ run = c['run']
162
+ if 'marginalize' in c: # one store for every track: it holds the predictions of all the model's tracks
163
+ c['marginalize'].setdefault('store', str(Path(run['out_dir']) / 'marginalize' / 'store'))
164
+ run['out_dir'] = str(Path(run['out_dir']) / track)
165
+ run['name'] = f"{run['name']} {track}" if run.get('name') else track
166
+ c['_path'] = str(Path(run['out_dir']) / 'config.toml')
167
+ _from_attribute(c)
168
+ return c
169
+
170
+
171
+ def write_track_config(cfg: dict) -> Path:
172
+ """A single track's run config as <out_dir>/config.toml (paths absolute, the run folder as `.`), so the run opens
173
+ with `diffgrammar view` and Analysis like any other."""
174
+ from .export import write_toml
175
+ out = out_dir(cfg)
176
+ c = {k: copy.deepcopy(v) for k, v in cfg.items() if not k.startswith('_')}
177
+ c['run']['out_dir'] = '.'
178
+ c['jaspar'] = {k: v for k, v in c.get('jaspar', {}).items() if k != 'cache_dir' or v != str(Path(c['jaspar']['meme']).parent)}
179
+ write_toml(c, out / 'config.toml')
180
+ return out / 'config.toml'
181
+
182
+
183
+ def out_dir(cfg) -> Path:
184
+ p = Path(cfg['run']['out_dir'])
185
+ p.mkdir(parents=True, exist_ok=True)
186
+ return p
187
+
188
+
189
+ def resolve_auto(cfg) -> bool:
190
+ """The numbers behind the "auto" thresholds of [seqlets], from the run directory once the seqlets step ran
191
+ (calibrate.apply_settings); True when the config holds numbers only."""
192
+ from .calibrate import apply_settings
193
+ return apply_settings(cfg)
194
+
195
+
196
+ def provenance(cfg, step: str, extra: dict | None = None) -> dict:
197
+ """Appended to run.json in the run directory each time a step finishes."""
198
+ import diffgrammar
199
+ repo = Path(diffgrammar.__file__).resolve().parents[2]
200
+ try:
201
+ commit = subprocess.run(['git', '-C', str(repo), 'rev-parse', 'HEAD'], capture_output=True,
202
+ text=True, timeout=5).stdout.strip() or 'uncommitted'
203
+ dirty = bool(subprocess.run(['git', '-C', str(repo), 'status', '--porcelain'], capture_output=True,
204
+ text=True, timeout=5).stdout.strip())
205
+ except Exception:
206
+ commit, dirty = 'unknown', None
207
+ entry = {'step': step, 'time': time.strftime('%Y-%m-%d %H:%M:%S'), 'diffgrammar_version': diffgrammar.__version__,
208
+ 'diffgrammar_commit': commit, 'diffgrammar_dirty': dirty, 'config': cfg['_path'], **(extra or {})}
209
+ f = out_dir(cfg) / 'run.json'
210
+ log = json.loads(f.read_text()) if f.exists() else []
211
+ log.append(entry)
212
+ f.write_text(json.dumps(log, indent=1))
213
+ return entry