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,209 @@
1
+ """
2
+ What to insert where: the motif library, the geometry of the model input, and the layouts.
3
+
4
+ A design holds two motif libraries, anchors and partners (IUPAC strings), and groups that say which
5
+ pairs to run in which geometry:
6
+
7
+ pair_spacing anchor then partner, the PAIR centred in the predicted window, at every
8
+ spacing of the grid (gap between the anchor's end and the partner's start)
9
+ pair_offset_matrix anchor right edge at centre - X, partner left edge at centre + Y, so the
10
+ GAP is centred, on a 2D grid of offsets
11
+
12
+ Each pair comes with each motif alone at the position it holds in the pair, so its cooperativity
13
+ can be read. `Design.from_pairs` builds a design from a list of pairs.
14
+
15
+ A degenerate position (N, R, ...) is filled per background row from a generator seeded by
16
+ (seed, motif string), so the pair, the anchor alone and the partner alone carry the same bases
17
+ in a given row and the cooperativity terms are exactly paired. The draw also depends on how
18
+ many rows are realised (each position draws all rows at once), so a run over a subset of a
19
+ store's backgrounds must realise the full count and index it (run.compute n_fill / fill_rows).
20
+ Mixing independently filled runs gave errors about 7 times the effect in an earlier store, which is
21
+ why this is a pure function.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import zlib
27
+ from dataclasses import asdict, dataclass, field
28
+ from pathlib import Path
29
+ from typing import Dict, List, Optional, Sequence
30
+
31
+ import numpy as np
32
+
33
+ IUPAC = {'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'N': 'ACGT', 'R': 'AG', 'Y': 'CT', 'S': 'GC',
34
+ 'W': 'AT', 'K': 'GT', 'M': 'AC', 'B': 'CGT', 'D': 'AGT', 'H': 'ACT', 'V': 'ACG'}
35
+ _IDX = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
36
+
37
+
38
+ def is_degenerate(seq: str) -> bool:
39
+ return any(len(IUPAC[c]) > 1 for c in seq)
40
+
41
+
42
+ def _onehot(seq: str) -> np.ndarray:
43
+ out = np.zeros((len(seq), 4), np.float32)
44
+ for i, b in enumerate(seq):
45
+ out[i, _IDX[b]] = 1.0
46
+ return out
47
+
48
+
49
+ def realise(seq: str, n_bg: int, seed: int = 42):
50
+ """
51
+ (n_bg, L, 4) one-hot realisation of an IUPAC motif, one per background row, and the chosen
52
+ bases at its degenerate positions (n_bg, n_degenerate) as indices into A, C, G, T.
53
+ """
54
+ deg = [j for j, c in enumerate(seq) if len(IUPAC[c]) > 1]
55
+ base = _onehot(''.join(c if len(IUPAC[c]) == 1 else 'A' for c in seq))
56
+ oh = np.broadcast_to(base, (n_bg,) + base.shape).copy()
57
+ chosen = np.zeros((n_bg, len(deg)), np.uint8)
58
+ if deg:
59
+ rng = np.random.default_rng([seed, zlib.crc32(seq.encode())])
60
+ for k, j in enumerate(deg):
61
+ opts = IUPAC[seq[j]]
62
+ pick = rng.integers(0, len(opts), n_bg)
63
+ oh[:, j, :] = 0
64
+ for b, o in enumerate(opts):
65
+ oh[pick == b, j, _IDX[o]] = 1.0
66
+ chosen[:, k] = [_IDX[opts[p]] for p in pick]
67
+ return oh, chosen
68
+
69
+
70
+ @dataclass
71
+ class Geometry:
72
+ """The model input: its length, the central window whose bins it predicts, and the grids."""
73
+ seq_len: int = 2048
74
+ window: int = 512
75
+ spacings: List[int] = field(default_factory=lambda: list(range(0, 501)))
76
+ offsets: List[int] = field(default_factory=lambda: list(range(0, 257, 8)))
77
+
78
+ @classmethod
79
+ def for_input(cls, seq_len: int, window: Optional[int] = None, **grids) -> 'Geometry':
80
+ """
81
+ Defaults scaled to a model input, the same whatever motifs a design holds (so a store can grow):
82
+ the window is the whole input up to 512 bp; spacings run from 0 to half the window at 1 bp; offsets
83
+ from 0 to a quarter of the window in about 32 steps, which leaves a quarter of the window for each motif.
84
+ """
85
+ window = int(window or min(seq_len, 512))
86
+ grids.setdefault('spacings', list(range(0, window // 2 + 1)))
87
+ grids.setdefault('offsets', list(range(0, window // 4 + 1, max(1, window // 128))))
88
+ return cls(seq_len=int(seq_len), window=window, **grids)
89
+
90
+ @property
91
+ def centre(self) -> int:
92
+ return self.seq_len // 2
93
+
94
+ @property
95
+ def window_start(self) -> int:
96
+ return self.centre - self.window // 2
97
+
98
+ def layout_spacing(self, la: int, lp: int, spacings=None):
99
+ """(anchor start, partner start) per spacing; -1 where the pair does not fit the window."""
100
+ sp = np.asarray(self.spacings if spacings is None else spacings)
101
+ a = np.full(len(sp), -1, np.int32)
102
+ p = np.full(len(sp), -1, np.int32)
103
+ for i, d in enumerate(sp):
104
+ total = la + int(d) + lp
105
+ if total > self.window:
106
+ continue
107
+ pos = self.window_start + (self.window - total) // 2
108
+ a[i], p[i] = pos, pos + la + int(d)
109
+ return a, p
110
+
111
+ def layout_matrix(self, la: int, lp: int):
112
+ """Anchor right edge at centre - X, partner left edge at centre + Y, for every offset."""
113
+ off = np.asarray(self.offsets)
114
+ return (self.centre - off - la).astype(np.int32), (self.centre + off).astype(np.int32)
115
+
116
+ def to_dict(self) -> dict:
117
+ d = asdict(self)
118
+ return {k: ([int(x) for x in v] if isinstance(v, (list, tuple, range)) else v) for k, v in d.items()}
119
+
120
+
121
+ GEOMETRIES = ('pair_spacing', 'pair_offset_matrix')
122
+ #: the scan modes of the run config and the geometry each runs
123
+ SCANS = {'line': 'pair_spacing', 'heatmap': 'pair_offset_matrix'}
124
+
125
+
126
+ @dataclass
127
+ class Design:
128
+ anchors: Dict[str, str]
129
+ partners: Dict[str, str]
130
+ groups: List[dict]
131
+ seed: int = 42
132
+ geometry: Geometry = field(default_factory=Geometry)
133
+
134
+ @classmethod
135
+ def from_dict(cls, d: dict) -> 'Design':
136
+ geo = Geometry(**d['geometry']) if 'geometry' in d else Geometry()
137
+ groups = [{**g, 'anchors': g.get('anchors', []), 'partners': g.get('partners', [])} for g in d['groups']]
138
+ return cls(anchors=d.get('anchors', {}), partners=d['partners'], groups=groups, seed=d.get('seed', 42),
139
+ geometry=geo)
140
+
141
+ @classmethod
142
+ def from_pairs(cls, pairs: Sequence[Sequence[str]], motifs: Dict[str, str], geometry: Geometry,
143
+ scans: Sequence[str] = ('line',), seed: int = 42) -> 'Design':
144
+ """
145
+ One group per (anchor, partner) pair and scan: 'line' (pair_spacing) and / or 'heatmap'
146
+ (pair_offset_matrix). `motifs` maps every name in the pairs to its IUPAC sequence.
147
+ """
148
+ bad = [s for s in scans if s not in SCANS]
149
+ if bad:
150
+ raise ValueError(f'unknown scan {bad}; one of {", ".join(SCANS)}')
151
+ missing = sorted({n for pr in pairs for n in pr} - set(motifs))
152
+ if missing:
153
+ raise ValueError(f'motifs without a sequence: {missing}')
154
+ pairs = [tuple(pr) for pr in pairs]
155
+ if any(len(pr) != 2 for pr in pairs):
156
+ raise ValueError('every pair is [anchor, partner]')
157
+ groups = [{'name': f'{a} + {p}', 'geometry': SCANS[s], 'anchors': [a], 'partners': [p]}
158
+ for s in scans for a, p in pairs]
159
+ return cls(anchors={a: motifs[a].upper() for a, _ in pairs}, partners={p: motifs[p].upper() for _, p in pairs},
160
+ groups=groups, seed=seed, geometry=geometry)
161
+
162
+ @classmethod
163
+ def load(cls, path) -> 'Design':
164
+ return cls.from_dict(json.loads(Path(path).read_text()))
165
+
166
+ def to_dict(self) -> dict:
167
+ return {'seed': self.seed, 'anchors': self.anchors, 'partners': self.partners, 'groups': self.groups,
168
+ 'geometry': self.geometry.to_dict()}
169
+
170
+ def save(self, path):
171
+ Path(path).write_text(json.dumps(self.to_dict(), indent=2) + '\n')
172
+
173
+ def pairs(self, geometry: str = 'pair_spacing') -> List[tuple]:
174
+ """Every (anchor, partner) of the groups of one geometry, in group order, each once."""
175
+ return list(dict.fromkeys((a, p) for g in self.groups if g['geometry'] == geometry
176
+ for a in g['anchors'] for p in g['partners']))
177
+
178
+ def check(self) -> List[str]:
179
+ """Problems that would make a run wrong rather than slow."""
180
+ bad = []
181
+ for lib in (self.anchors, self.partners):
182
+ for k, s in lib.items():
183
+ if set(s) - set(IUPAC):
184
+ bad.append(f'{k}: not IUPAC: {s}')
185
+ geo = self.geometry
186
+ for g in self.groups:
187
+ name, geom = g.get('name'), g.get('geometry')
188
+ if geom not in GEOMETRIES:
189
+ bad.append(f'group {name}: unknown geometry {geom}; one of {", ".join(GEOMETRIES)}')
190
+ continue
191
+ for a in g['anchors']:
192
+ if a not in self.anchors:
193
+ bad.append(f'group {name}: unknown anchor {a}')
194
+ for p in g['partners']:
195
+ if p not in self.partners:
196
+ bad.append(f'group {name}: unknown partner {p}')
197
+ if geom == 'pair_offset_matrix':
198
+ for a in g['anchors']:
199
+ for p in g['partners']:
200
+ sa, sp = geo.layout_matrix(len(self.anchors.get(a, '')), len(self.partners.get(p, '')))
201
+ if sa.min() < geo.window_start or sp.max() + len(self.partners.get(p, '')) > geo.window_start + geo.window:
202
+ bad.append(f'group {name}: offsets up to {max(geo.offsets)} put a motif outside the '
203
+ f'{geo.window} bp window')
204
+ elif not any((geo.layout_spacing(len(self.anchors.get(a, '')), len(self.partners.get(p, '')))[0] >= 0).any()
205
+ for a in g['anchors'] for p in g['partners']):
206
+ bad.append(f'group {name}: no spacing of the grid fits the {geo.window} bp window')
207
+ if geo.window > geo.seq_len:
208
+ bad.append(f'window {geo.window} is longer than the input ({geo.seq_len})')
209
+ return bad