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,6 @@
1
+ """diffgrammar: differential motif grammar from sequence-to-function models."""
2
+ __version__ = '0.1.0'
3
+
4
+ from .contrast import Contrast, RegionAttributions, contrast_record, iter_records
5
+ from .seqlets import SeqletCollection, collect_seqlets, apply_polarity
6
+ from .analysis import Analysis, Example
@@ -0,0 +1,21 @@
1
+ """
2
+ Adapters read stored attributions and yield `RegionAttributions`.
3
+
4
+ Every adapter takes its settings from the `[attributions]` table of a run config and exposes
5
+ tracks : the track names it can deliver
6
+ regions() : an iterator of RegionAttributions
7
+ `diffgrammar attribute` writes the `peak_npz` layout; attributions computed elsewhere can be saved in it, or
8
+ read by a new adapter. Everything downstream is shared.
9
+ """
10
+ from .peak_npz import PeakNpzSource
11
+
12
+ ADAPTERS = {
13
+ 'peak_npz': PeakNpzSource, # one file per peak, (K, L, 4) over K tracks with metadata
14
+ }
15
+
16
+
17
+ def make_source(cfg: dict):
18
+ kind = cfg.get('adapter')
19
+ if kind not in ADAPTERS:
20
+ raise ValueError(f'unknown adapter {kind!r}; available: {sorted(ADAPTERS)}')
21
+ return ADAPTERS[kind](**{k: v for k, v in cfg.items() if k != 'adapter'})
@@ -0,0 +1,114 @@
1
+ """
2
+ One npz per peak holding every track at once (what `diffgrammar attribute` writes).
3
+
4
+ <root>/<fold dir>/peaks/<chrom>_<summit>.npz
5
+ hypothetical (K, L, 4) sequence (4, L) uint8 celltypes (K,) metadata (JSON string)
6
+
7
+ The region set of a peak is a metadata field (`set_field`, default 'class', e.g. HepG2_high /
8
+ K562_high). A `budgets` metadata field, contrast name -> signed dF(x) - dF(reference), carries stored
9
+ budgets for `[seqlets] budget = "stored"` (attributions made outside the attribute step). The region id is '<chrom>:<start>-<end>' of the peak when the metadata gives the
10
+ coordinates, else the peak id. Seqlet positions are always in input coordinates (0..L).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from pathlib import Path
17
+ from typing import Iterator, List, Optional, Sequence
18
+
19
+ import numpy as np
20
+
21
+ from ..contrast import RegionAttributions
22
+
23
+
24
+ class PeakNpzSource:
25
+ def __init__(self, root: str, pattern: str = '*/peaks/*.npz', set_field: str = 'class',
26
+ sets: Optional[Sequence[str]] = None, tracks: Optional[Sequence[str]] = None,
27
+ info_fields: Sequence[str] = ('fold', 'peak_id'), max_regions: Optional[int] = None):
28
+ self.root = Path(root)
29
+ self.pattern = pattern
30
+ self.set_field = set_field
31
+ self.sets = set(sets) if sets else None
32
+ self._tracks = list(tracks) if tracks else None
33
+ self.info_fields = list(info_fields)
34
+ self.max_regions = max_regions
35
+
36
+ def files(self) -> List[Path]:
37
+ f = sorted(self.root.glob(self.pattern))
38
+ return f[:self.max_regions] if self.max_regions else f
39
+
40
+ @property
41
+ def tracks(self) -> List[str]:
42
+ if self._tracks is None:
43
+ self._tracks = [str(t) for t in np.load(self.files()[0])['celltypes']]
44
+ return self._tracks
45
+
46
+ def metadata(self, path) -> dict:
47
+ return json.loads(str(np.load(path, allow_pickle=True)['metadata']))
48
+
49
+ def region(self, path) -> Optional[RegionAttributions]:
50
+ """One peak file as RegionAttributions; None when its set is filtered out."""
51
+ d = np.load(path, allow_pickle=True)
52
+ meta = json.loads(str(d['metadata']))
53
+ set_name = str(meta.get(self.set_field, ''))
54
+ if self.sets is not None and set_name not in self.sets:
55
+ return None
56
+ names = [str(t) for t in d['celltypes']]
57
+ keep = self._tracks or names
58
+ hyp_all = d['hypothetical']
59
+ hyp = {t: hyp_all[i] for i, t in enumerate(names) if t in keep}
60
+ region = (f"{meta['chrom']}:{meta['start']}-{meta['end']}"
61
+ if {'chrom', 'start', 'end'} <= set(meta) else meta.get('peak_id', Path(path).stem))
62
+ return RegionAttributions(region=region, set_name=set_name,
63
+ onehot=np.asarray(d['sequence'], np.float32).T, hypothetical=hyp,
64
+ budgets={k: float(v) for k, v in meta.get('budgets', {}).items()},
65
+ info={k: meta[k] for k in self.info_fields if k in meta})
66
+
67
+ def _region_of(self, path) -> str:
68
+ m = self.metadata(path)
69
+ return f"{m['chrom']}:{m['start']}-{m['end']}" if {'chrom', 'start', 'end'} <= set(m) else m.get('peak_id', Path(path).stem)
70
+
71
+ def paths_for(self, coord: str) -> List[Path]:
72
+ """
73
+ Every file of the peak 'chrom:start-end', or of the peak id when the metadata gives no coordinates: a peak in
74
+ several region sets has one per set. Files named <chrom>_<summit> are found by name from an index built once, and
75
+ checked, since a neighbouring peak's summit can fall inside the window too; any other naming, and every peak id,
76
+ falls back to an index of every file's metadata, built once.
77
+ """
78
+ m = re.fullmatch(r'(.+):(\d+)-(\d+)', coord)
79
+ if m:
80
+ chrom, start, end = m[1], int(m[2]), int(m[3])
81
+ if not hasattr(self, '_name_index'):
82
+ index: dict = {}
83
+ for f in self.files():
84
+ c, _, tail = f.stem.rpartition('_')
85
+ if tail.isdigit():
86
+ index.setdefault(c, []).append((int(tail), f))
87
+ self._name_index = index
88
+ near = [(abs(summit - (start + end) // 2), str(f), f) for summit, f in self._name_index.get(chrom, []) if start <= summit <= end]
89
+ found = [f for _, _, f in sorted(near) if self._region_of(f) == coord]
90
+ if found:
91
+ return found
92
+ if not hasattr(self, '_coord_index'):
93
+ self._coord_index = {}
94
+ for f in self.files():
95
+ self._coord_index.setdefault(self._region_of(f), []).append(f)
96
+ return list(self._coord_index.get(coord, []))
97
+
98
+ def sequence(self, coord: str) -> str:
99
+ """The input sequence of a peak as a string, read without loading its attributions."""
100
+ from ..sequence import decode
101
+ return decode(np.load(self.path_for(coord))['sequence'])
102
+
103
+ def path_for(self, coord: str) -> Path:
104
+ """The file of the peak 'chrom:start-end' (the first, when it is in several region sets)."""
105
+ found = self.paths_for(coord)
106
+ if not found:
107
+ raise KeyError(coord)
108
+ return found[0]
109
+
110
+ def regions(self) -> Iterator[RegionAttributions]:
111
+ for path in self.files():
112
+ r = self.region(path)
113
+ if r is not None:
114
+ yield r
diffgrammar/align.py ADDED
@@ -0,0 +1,195 @@
1
+ """
2
+ Motif alignment and distance: how two matrices are compared at their best offset and strand, and how a cluster's
3
+ members are averaged into one consensus. Used to cluster seqlets, to match clusters to JASPAR and to split JASPAR
4
+ families into subfamilies.
5
+
6
+ A matrix is (L, 4), columns A, C, G, T: a CWM, a hypothetical attribution or a JASPAR PWM. `compare` puts every query
7
+ against every target at every offset where the two overlap by at least `min_overlap` positions, on both strands when
8
+ `reverse_complement` is set. At each offset the two are laid in one window covering both, the positions one matrix
9
+ does not reach filled with zeros, and the Pearson correlation r of the two windows (all 4 x window length values) is
10
+ taken. The offset and strand with the largest r are kept. With zero padding every term of r but the cross product
11
+ is a property of one matrix alone, so one cross-correlation gives r at every offset at once.
12
+
13
+ metric = "correlation" 1 - r at the best alignment
14
+ metric = "correlation_pvalue" the two-sided p-value of r on n = 4 x window length values (t-test); for r < 0 the
15
+ reciprocal, so anti-correlated matrices are far apart. The pipeline clusters on
16
+ this distance (complete linkage, cut at 0.05).
17
+
18
+ The offset of a query against a target is the target position at which the query's first position sits, after the
19
+ query is reverse-complemented where `revcomp` says so. `consensus_of_clusters` uses those offsets to stack a
20
+ cluster's members on its most central member.
21
+
22
+ This is a rewrite of torch_compute_similarity_motifs(exact=True, padding=0) and combine_pwms in
23
+ drg_tools.motif_analysis (Alexander Sasse, BSD 3-clause), kept so that the distances and offsets of runs made with
24
+ drg_tools still hold: the same windows, the same r, the same tie rules (the first of equal offsets, the other strand
25
+ only when strictly better). Differences: r is kept in float64 (drg_tools stored it in float32, which moves the
26
+ p-value of near-identical matrices, r close to 1, by up to a factor of about three, all of them far below any cut);
27
+ exact ties between two alignments, common among palindromic JASPAR matrices, can fall to the other alignment through
28
+ rounding; r = -1 gives a finite distance (drg_tools returns NaN there, its guard covering only r = +1); and only the
29
+ two correlation metrics exist. drg_tools computed on the CPU whatever device it was given;
30
+ `device` here is where the arithmetic runs, in float64 either way.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ from typing import List, Optional, Sequence, Tuple, Union
35
+
36
+ import numpy as np
37
+ import torch
38
+ import torch.nn.functional as F
39
+ from scipy.stats import t as t_dist
40
+
41
+ METRICS = ('correlation', 'correlation_pvalue')
42
+
43
+
44
+ def reverse_complement(m: np.ndarray) -> np.ndarray:
45
+ """The other strand of an (L, 4) matrix, columns A, C, G, T."""
46
+ return m[::-1, ::-1]
47
+
48
+
49
+ def compare(queries: Sequence[np.ndarray], targets: Sequence[np.ndarray], metric: str = 'correlation_pvalue',
50
+ min_overlap: int = 4, reverse_complement: bool = True, device: str = 'cpu', batchsize: int = 1024,
51
+ return_alignment: bool = False, min_p: float = 1e-127
52
+ ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray, np.ndarray]]:
53
+ """
54
+ Distance of every query to every target at their best alignment: (n_queries, n_targets) float64. With
55
+ return_alignment also offsets (int32: where the query's first position sits on the target) and revcomp (int8: 1
56
+ where the query is reverse-complemented in that alignment). `batchsize` caps the targets compared at once; the
57
+ chunk shrinks further when queries x targets x offsets would pass 25 million values (about 200 MB each).
58
+ """
59
+ if metric not in METRICS:
60
+ raise ValueError(f'metric is one of {METRICS}, not {metric!r}')
61
+ queries = [np.asarray(q, dtype=np.float64) for q in queries]
62
+ targets = [np.asarray(t, dtype=np.float64) for t in targets]
63
+ nq, nt = len(queries), len(targets)
64
+ r = np.zeros((nq, nt), np.float64)
65
+ n = np.zeros((nq, nt), np.int64)
66
+ offsets = np.zeros((nq, nt), np.int32)
67
+ revcomp = np.zeros((nq, nt), np.int8)
68
+ if nq and nt:
69
+ q_groups = _by_length(queries)
70
+ t_groups = _by_length(targets)
71
+ with torch.no_grad():
72
+ for lq, qi in q_groups:
73
+ q = torch.tensor(np.stack([queries[i] for i in qi]), device=device).transpose(-1, -2) # (n, 4, L)
74
+ q_rc = q.flip([-1, -2]) if reverse_complement else None
75
+ for lt, ti in t_groups:
76
+ n_off = lt + lq - 2 * min_overlap + 1
77
+ chunk = max(1, min(batchsize, int(2.5e7 // (len(qi) * n_off))))
78
+ for b in range(0, len(ti), chunk):
79
+ tb = ti[b:b + chunk]
80
+ t = torch.tensor(np.stack([targets[i] for i in tb]), device=device).transpose(-1, -2)
81
+ best, off = _best_alignment(q, t, min_overlap)
82
+ rc = np.zeros(best.shape, bool)
83
+ if q_rc is not None:
84
+ best_rc, off_rc = _best_alignment(q_rc, t, min_overlap)
85
+ rc = best_rc > best
86
+ best, off = np.where(rc, best_rc, best), np.where(rc, off_rc, off)
87
+ rows, cols = np.ix_(qi, tb)
88
+ r[rows, cols] = best
89
+ offsets[rows, cols] = off
90
+ revcomp[rows, cols] = rc
91
+ n[rows, cols] = 4 * (np.maximum(lq + off, lt) - np.minimum(off, 0))
92
+ if metric == 'correlation':
93
+ distance = 1.0 - r
94
+ else:
95
+ distance = correlation_pvalue(r, n, min_p)
96
+ if return_alignment:
97
+ return distance, offsets, revcomp
98
+ return distance
99
+
100
+
101
+ def correlation_pvalue(r: np.ndarray, n: np.ndarray, min_p: float = 1e-127, eps: float = 1e-7) -> np.ndarray:
102
+ """
103
+ Two-sided p-value of a Pearson r on n values (t with n - 1 degrees of freedom), floored at min_p; for r < 0 its
104
+ reciprocal, so the result orders matrices from identical (near 0) through unrelated (near 1) to opposite (large).
105
+ """
106
+ r = np.clip(np.asarray(r, np.float64), -1.0, 1.0)
107
+ n = np.asarray(n, np.float64)
108
+ tt = r * np.sqrt(n - 2) / np.sqrt(1.0 - (np.abs(r) - eps) ** 2) # eps keeps |r| = 1 finite
109
+ p = 2.0 * t_dist.sf(np.abs(tt), n - 1) + min_p
110
+ return np.where(r >= 0, p, 1.0 / p)
111
+
112
+
113
+ def _by_length(mats: Sequence[np.ndarray]) -> List[Tuple[int, np.ndarray]]:
114
+ lengths = np.array([len(m) for m in mats])
115
+ return [(int(L), np.flatnonzero(lengths == L)) for L in np.unique(lengths)]
116
+
117
+
118
+ def _best_alignment(q: torch.Tensor, t: torch.Tensor, min_overlap: int) -> Tuple[np.ndarray, np.ndarray]:
119
+ """
120
+ Pearson r of every query (nq, 4, lq) with every target (nt, 4, lt) at the best offset: (nq, nt) r and (nq, nt)
121
+ offset of the query's first position on the target. Offsets run from -(lq - min_overlap) to lt - min_overlap; the
122
+ first of equal maxima is kept.
123
+
124
+ At an offset the window covering both matrices has w positions, n = 4 w values, and each matrix is zero outside
125
+ itself, so with S1 = sum, S2 = sum of squares over a matrix and XY the cross product over the overlap:
126
+ r = (XY - S1q S1t / n) / sqrt((S2q - S1q^2 / n) (S2t - S1t^2 / n)). XY at every offset is one cross-correlation.
127
+ """
128
+ lq, lt = q.shape[-1], t.shape[-1]
129
+ pad = lq - min_overlap # the query may hang over by all but min_overlap
130
+ xy = F.conv1d(F.pad(t, (pad, pad)), q).transpose(0, 1) # (nq, nt, n_off): the query at offset k - pad
131
+ offsets = torch.arange(xy.shape[-1], device=q.device) - pad
132
+ n = 4 * (torch.maximum(offsets + lq, torch.tensor(lt, device=q.device)) - torch.clamp(offsets, max=0))
133
+ n = n.to(q.dtype)
134
+ s1q, s2q = q.sum(dim=(-1, -2))[:, None, None], (q ** 2).sum(dim=(-1, -2))[:, None, None]
135
+ s1t, s2t = t.sum(dim=(-1, -2))[None, :, None], (t ** 2).sum(dim=(-1, -2))[None, :, None]
136
+ var = (s2q - s1q ** 2 / n) * (s2t - s1t ** 2 / n)
137
+ r = (xy - s1q * s1t / n) / torch.sqrt(torch.clamp(var, min=0))
138
+ r = torch.nan_to_num(r, nan=0.0, posinf=0.0, neginf=0.0) # a flat window has no correlation
139
+ best, arg = torch.max(r, dim=-1)
140
+ return best.cpu().numpy(), (arg - pad).cpu().numpy().astype(np.int32)
141
+
142
+
143
+ def consensus_of_clusters(mats: Sequence[np.ndarray], labels: np.ndarray, similarity: np.ndarray,
144
+ offsets: np.ndarray, revcomp: np.ndarray, norm: str = 'max', remove_low: float = 0.075,
145
+ minlen: int = 3) -> List[np.ndarray]:
146
+ """
147
+ One consensus per cluster label (labels >= 0, in increasing order): the members stacked on the most central one
148
+ (the largest row sum of `similarity`), each at its offset to it and reverse-complemented where `revcomp` says
149
+ so, summed, and divided by the number of members (norm 'max') or by the members covering each position
150
+ ('mean'). Positions whose summed magnitude is below `remove_low` of the largest are trimmed from both ends; a
151
+ consensus shorter than `minlen` after that is all zeros.
152
+ """
153
+ labels = np.asarray(labels)
154
+ lengths = np.array([len(m) for m in mats])
155
+ out = []
156
+ for u in np.unique(labels[labels >= 0]):
157
+ members = np.flatnonzero(labels == u)
158
+ order = members[np.argsort(-similarity[members][:, members].sum(axis=1))]
159
+ centre = order[0]
160
+ out.append(_stack(
161
+ [mats[m] for m in order], lengths[order], offsets[order, centre], revcomp[order, centre],
162
+ norm=norm, remove_low=remove_low, minlen=minlen))
163
+ return out
164
+
165
+
166
+ def _stack(mats: List[np.ndarray], lengths: np.ndarray, offsets: np.ndarray, revcomp: np.ndarray, norm: str,
167
+ remove_low: float, minlen: int) -> np.ndarray:
168
+ centre_len = len(mats[0])
169
+ if len(mats) > 1:
170
+ start = -min(0, int(offsets.min()))
171
+ total = centre_len + max(0, int((offsets + lengths - centre_len).max())) + start
172
+ seed = np.zeros((total, mats[0].shape[1]), np.float64)
173
+ count = np.zeros(total, np.float64)
174
+ for m, off, rc in zip(mats, offsets, revcomp):
175
+ m = reverse_complement(m) if rc else m
176
+ lo = start + int(off)
177
+ seed[lo:lo + len(m)] += np.asarray(m, np.float64)
178
+ count[lo:lo + len(m)] += 1
179
+ if norm == 'mean':
180
+ seed = seed / count[:, None]
181
+ else:
182
+ seed = np.asarray(mats[0], np.float64)
183
+ count = np.ones(len(seed))
184
+ if norm == 'max':
185
+ seed = seed / count.max()
186
+ elif norm != 'mean':
187
+ raise ValueError(f"norm is 'max' or 'mean', not {norm!r}")
188
+ if remove_low > 0:
189
+ mass = np.abs(seed).sum(axis=1)
190
+ kept = np.flatnonzero(mass / mass.max() > remove_low) if mass.max() > 0 else np.array([], int)
191
+ if len(kept) and kept[-1] + 1 - kept[0] >= minlen:
192
+ seed = seed[kept[0]:kept[-1] + 1]
193
+ else:
194
+ seed = np.zeros_like(seed)
195
+ return seed