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.
- diffgrammar/__init__.py +6 -0
- diffgrammar/adapters/__init__.py +21 -0
- diffgrammar/adapters/peak_npz.py +114 -0
- diffgrammar/align.py +195 -0
- diffgrammar/analysis.py +744 -0
- diffgrammar/attribute.py +445 -0
- diffgrammar/calibrate.py +279 -0
- diffgrammar/cli.py +659 -0
- diffgrammar/cluster.py +439 -0
- diffgrammar/config.py +213 -0
- diffgrammar/contrast.py +223 -0
- diffgrammar/effects.py +317 -0
- diffgrammar/export.py +185 -0
- diffgrammar/expression.py +399 -0
- diffgrammar/jaspar.py +185 -0
- diffgrammar/marginalize/__init__.py +4 -0
- diffgrammar/marginalize/backgrounds.py +107 -0
- diffgrammar/marginalize/cooperativity.py +344 -0
- diffgrammar/marginalize/design.py +209 -0
- diffgrammar/marginalize/plots.py +546 -0
- diffgrammar/marginalize/predictor.py +109 -0
- diffgrammar/marginalize/readout.py +86 -0
- diffgrammar/marginalize/run.py +223 -0
- diffgrammar/marginalize/store.py +191 -0
- diffgrammar/pair_regression.py +323 -0
- diffgrammar/plotting.py +1186 -0
- diffgrammar/scan.py +151 -0
- diffgrammar/selection.py +174 -0
- diffgrammar/seqlets.py +376 -0
- diffgrammar/sequence.py +22 -0
- diffgrammar/summaries.py +140 -0
- diffgrammar/toy.py +129 -0
- diffgrammar/view/__init__.py +0 -0
- diffgrammar/view/app.py +1942 -0
- diffgrammar/view/data.py +1950 -0
- diffgrammar/view/figures.py +400 -0
- diffgrammar/view/network/index.html +232 -0
- diffgrammar/view/network.py +21 -0
- diffgrammar/view/pages.py +257 -0
- diffgrammar/view/tracks/index.html +459 -0
- diffgrammar/view/tracks.py +153 -0
- diffgrammar-0.1.0.dist-info/METADATA +204 -0
- diffgrammar-0.1.0.dist-info/RECORD +47 -0
- diffgrammar-0.1.0.dist-info/WHEEL +5 -0
- diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
- diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
- diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Contrast-level readouts of the store: cooperativity and single-motif effects averaged over the
|
|
3
|
+
tracks of each condition, with the B - A difference taken per background (paired), so its error
|
|
4
|
+
reflects the background-to-background spread of the difference itself.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Optional, Sequence
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from .store import Store
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _mean_sem(x: np.ndarray):
|
|
17
|
+
"""(D, n_bg) -> mean and SEM over backgrounds."""
|
|
18
|
+
n = np.sum(np.isfinite(x), axis=1)
|
|
19
|
+
return np.nanmean(x, axis=1), np.nanstd(x, axis=1, ddof=1) / np.sqrt(np.maximum(n, 1))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def contrast_cooperativity(store: Store, anchor: str, partner: str, tracks_a: Sequence[str],
|
|
23
|
+
tracks_b: Sequence[str], bg: Optional[np.ndarray] = None, real_space: bool = False,
|
|
24
|
+
bins=None, labels=('A', 'B')) -> pd.DataFrame:
|
|
25
|
+
"""
|
|
26
|
+
Per spacing: cooperativity averaged over the tracks of A and of B (mean and SEM over
|
|
27
|
+
backgrounds), and the paired difference B - A.
|
|
28
|
+
"""
|
|
29
|
+
kw = dict(bg=bg, real_space=real_space, bins=bins)
|
|
30
|
+
dist, ca = store.cooperativity(anchor, partner, tracks=list(tracks_a), **kw)
|
|
31
|
+
_, cb = store.cooperativity(anchor, partner, tracks=list(tracks_b), **kw)
|
|
32
|
+
ga, gb = np.nanmean(ca, axis=2), np.nanmean(cb, axis=2)
|
|
33
|
+
la, lb = labels
|
|
34
|
+
out = {'spacing': dist}
|
|
35
|
+
for name, g in ((la, ga), (lb, gb), (f'{lb} - {la}', gb - ga)):
|
|
36
|
+
out[name], out[f'{name} sem'] = _mean_sem(g)
|
|
37
|
+
return pd.DataFrame(out).dropna(subset=[la])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def single_effects(store: Store, anchor: str, partner: str, tracks: Sequence[str],
|
|
41
|
+
bg: Optional[np.ndarray] = None, real_space: bool = False, bins=None) -> pd.DataFrame:
|
|
42
|
+
"""Per spacing: anchor alone, partner alone, pair and their additive sum, each minus background."""
|
|
43
|
+
dist, c = store.components(anchor, partner, tracks=list(tracks), bg=bg, real_space=real_space, bins=bins)
|
|
44
|
+
b = c['background'][None]
|
|
45
|
+
eff = {k: np.nanmean(np.nanmean(c[k] - b, axis=2), axis=1) for k in ('anchor', 'partner', 'pair')}
|
|
46
|
+
df = pd.DataFrame({'spacing': dist, 'anchor alone': eff['anchor'], 'partner alone': eff['partner'],
|
|
47
|
+
'pair': eff['pair']})
|
|
48
|
+
df['additive'] = df['anchor alone'] + df['partner alone']
|
|
49
|
+
df['cooperativity'] = df['pair'] - df['additive']
|
|
50
|
+
return df.dropna()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def by_condition(terms: dict, tracks: Sequence[str], contrasts: Sequence, diff: bool = False):
|
|
54
|
+
"""
|
|
55
|
+
The track axis (last) of every array in `terms` reduced to condition columns: for each contrast the
|
|
56
|
+
mean over its A tracks and over its B tracks, or with diff=True the B - A difference, taken within each
|
|
57
|
+
background so its spread is paired. `tracks` names the last axis; contrasts carry name, a, b, label_a
|
|
58
|
+
and label_b (diffgrammar.Contrast). Returns the reduced dict and the columns as (contrast, label). A single
|
|
59
|
+
contrast (B alone) gives its B column, and nothing with diff=True.
|
|
60
|
+
"""
|
|
61
|
+
idx = {t: i for i, t in enumerate(tracks)}
|
|
62
|
+
cols, labels = [], []
|
|
63
|
+
for c in contrasts:
|
|
64
|
+
ia, ib = [idx[t] for t in c.a], [idx[t] for t in c.b]
|
|
65
|
+
if not ia:
|
|
66
|
+
if not diff:
|
|
67
|
+
cols.append((ib, None))
|
|
68
|
+
labels.append((c.name, c.label_b))
|
|
69
|
+
continue
|
|
70
|
+
if diff:
|
|
71
|
+
cols.append((ia, ib))
|
|
72
|
+
labels.append((c.name, f'{c.label_b} − {c.label_a}'))
|
|
73
|
+
else:
|
|
74
|
+
cols += [(ia, None), (ib, None)]
|
|
75
|
+
labels += [(c.name, c.label_a), (c.name, c.label_b)]
|
|
76
|
+
|
|
77
|
+
def reduce(x):
|
|
78
|
+
x = np.asarray(x, np.float64)
|
|
79
|
+
out = [x[..., i].mean(-1) if j is None else x[..., j].mean(-1) - x[..., i].mean(-1) for i, j in cols]
|
|
80
|
+
return np.stack(out, -1) if out else np.zeros(x.shape[:-1] + (0,))
|
|
81
|
+
return {k: reduce(v) for k, v in terms.items()}, labels
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def contrast_tracks(contrasts: Sequence) -> list:
|
|
85
|
+
"""Every track the contrasts use, each once, in order."""
|
|
86
|
+
return list(dict.fromkeys(t for c in contrasts for t in list(c.a) + list(c.b)))
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Inference half of the marginalization store: design -> plan() -> compute() -> files.
|
|
3
|
+
|
|
4
|
+
Deterministic throughout. An experiment already in the store is never recomputed; plan()
|
|
5
|
+
returns only what is missing, so adding a motif to the design and rerunning appends it.
|
|
6
|
+
Files are written atomically (temporary name, then rename), so an interrupted run never
|
|
7
|
+
leaves a partial file that looks finished.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import List, Optional
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
from .design import Design, realise
|
|
20
|
+
from .store import SUBDIR, Store, length_tag, stem
|
|
21
|
+
|
|
22
|
+
SCHEMA = 'diffgrammar-1'
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def insert(backgrounds: np.ndarray, rows: np.ndarray, slots) -> np.ndarray:
|
|
26
|
+
"""
|
|
27
|
+
Inputs (N, 4, L) for background rows `rows` with motifs set in. slots is a list of
|
|
28
|
+
(starts (N,), one-hot (N, Lm, 4)); every slot is written at its start in its row.
|
|
29
|
+
"""
|
|
30
|
+
x = backgrounds[rows] # fancy indexing copies, the backgrounds stay intact
|
|
31
|
+
xt = x.transpose(0, 2, 1)
|
|
32
|
+
r = np.arange(len(x))[:, None]
|
|
33
|
+
for start, oh in slots:
|
|
34
|
+
pos = start[:, None] + np.arange(oh.shape[1])[None, :]
|
|
35
|
+
xt[r, pos] = oh
|
|
36
|
+
return x
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _predict(predictor, backgrounds, rows, slots, batch_rows: int = 4096) -> np.ndarray:
|
|
40
|
+
out = None
|
|
41
|
+
for b0 in range(0, len(rows), batch_rows):
|
|
42
|
+
b = slice(b0, min(b0 + batch_rows, len(rows)))
|
|
43
|
+
y = predictor.predict(insert(backgrounds, rows[b], [(s[b], o[b]) for s, o in slots]))
|
|
44
|
+
if out is None:
|
|
45
|
+
out = np.zeros((y.shape[0], len(rows)) + y.shape[2:], np.float32)
|
|
46
|
+
out[:, b] = y
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _scatter(shape, valid_idx, values):
|
|
51
|
+
out = np.full((values.shape[0],) + shape + values.shape[2:], np.nan, np.float32)
|
|
52
|
+
out[(slice(None),) + valid_idx] = values
|
|
53
|
+
return out
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def compute_background(predictor, backgrounds: np.ndarray) -> dict:
|
|
57
|
+
y = predictor.predict(backgrounds)
|
|
58
|
+
return dict(perbin_by_fold=y, tracks=np.array(predictor.tracks), members=np.array(predictor.members),
|
|
59
|
+
kind='background', schema=SCHEMA)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _realise_rows(seq, n_bg, seed, n_fill, fill_rows):
|
|
63
|
+
if n_fill is None:
|
|
64
|
+
return realise(seq, n_bg, seed)
|
|
65
|
+
oh, chosen = realise(seq, n_fill, seed)
|
|
66
|
+
return oh[fill_rows], chosen[fill_rows]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def compute(design: Design, kind: str, anchor: Optional[str], partner: Optional[str], predictor,
|
|
70
|
+
backgrounds: np.ndarray, n_fill: Optional[int] = None, fill_rows=None) -> dict:
|
|
71
|
+
"""
|
|
72
|
+
One experiment over every background row; returns the arrays of its file.
|
|
73
|
+
|
|
74
|
+
Degenerate motifs are realised for n_fill rows (default: the number of backgrounds) and
|
|
75
|
+
fill_rows of them are used. The draw for a row depends on how many rows are realised, so a
|
|
76
|
+
check on a subset of a store's backgrounds passes the store's full row count as n_fill and
|
|
77
|
+
the subset's positions as fill_rows to get the same bases the store run used.
|
|
78
|
+
"""
|
|
79
|
+
geo = design.geometry
|
|
80
|
+
n_bg = len(backgrounds)
|
|
81
|
+
if n_fill is not None and (fill_rows is None or len(fill_rows) != n_bg):
|
|
82
|
+
raise ValueError('n_fill needs fill_rows, one per background')
|
|
83
|
+
a_seq = design.anchors[anchor] if anchor and anchor in design.anchors else None
|
|
84
|
+
p_seq = design.partners[partner] if partner else None
|
|
85
|
+
a_oh = _realise_rows(a_seq, n_bg, design.seed, n_fill, fill_rows)[0] if a_seq else None
|
|
86
|
+
p_oh, p_fill = _realise_rows(p_seq, n_bg, design.seed, n_fill, fill_rows) if p_seq \
|
|
87
|
+
else (None, np.zeros((n_bg, 0), np.uint8))
|
|
88
|
+
geom = SUBDIR[kind]
|
|
89
|
+
|
|
90
|
+
if geom == 'pair_spacing':
|
|
91
|
+
# partner_single is shared by every anchor of one length; its anchor slot is the length tag
|
|
92
|
+
if kind == 'partner_single':
|
|
93
|
+
la = int(anchor[3:]) if anchor and anchor.startswith('len') else len(next(iter(design.anchors.values())))
|
|
94
|
+
a_seq = None
|
|
95
|
+
else:
|
|
96
|
+
la = len(a_seq)
|
|
97
|
+
lp = len(p_seq)
|
|
98
|
+
a_st, p_st = geo.layout_spacing(la, lp)
|
|
99
|
+
grid, axis = np.asarray(geo.spacings), 'distances'
|
|
100
|
+
ok = a_st >= 0
|
|
101
|
+
di, si = [v.ravel() for v in np.meshgrid(np.flatnonzero(ok), np.arange(n_bg), indexing='ij')]
|
|
102
|
+
slots = []
|
|
103
|
+
if kind in ('pairwise', 'anchor_single'):
|
|
104
|
+
slots.append((a_st[di], a_oh[si]))
|
|
105
|
+
if kind in ('pairwise', 'partner_single'):
|
|
106
|
+
slots.append((p_st[di], p_oh[si]))
|
|
107
|
+
shape, vidx = (len(grid), n_bg), (di, si)
|
|
108
|
+
starts = {'starts_anchor': np.where(kind in ('pairwise', 'anchor_single'), a_st, -1).astype(np.int32),
|
|
109
|
+
'starts_partner': np.where(kind in ('pairwise', 'partner_single'), p_st, -1).astype(np.int32)}
|
|
110
|
+
extra = {'anchor_len': la} if kind == 'partner_single' else {}
|
|
111
|
+
elif geom == 'pair_offset_matrix':
|
|
112
|
+
grid, axis = np.asarray(geo.offsets), 'scan_offsets'
|
|
113
|
+
n = len(grid)
|
|
114
|
+
a_st, _ = geo.layout_matrix(len(a_seq) if a_seq else 0, 0)
|
|
115
|
+
_, p_st = geo.layout_matrix(0, len(p_seq) if p_seq else 0)
|
|
116
|
+
if kind == 'pairwise_2d':
|
|
117
|
+
xi, yi, si = [v.ravel() for v in np.meshgrid(np.arange(n), np.arange(n), np.arange(n_bg), indexing='ij')]
|
|
118
|
+
slots = [(a_st[xi], a_oh[si]), (p_st[yi], p_oh[si])]
|
|
119
|
+
shape, vidx = (n, n, n_bg), (xi, yi, si)
|
|
120
|
+
else:
|
|
121
|
+
oi, si = [v.ravel() for v in np.meshgrid(np.arange(n), np.arange(n_bg), indexing='ij')]
|
|
122
|
+
slots = [(a_st[oi], a_oh[si])] if kind == 'anchor_only' else [(p_st[oi], p_oh[si])]
|
|
123
|
+
shape, vidx = (n, n_bg), (oi, si)
|
|
124
|
+
starts = {'starts_anchor': a_st, 'starts_partner': p_st}
|
|
125
|
+
extra = {}
|
|
126
|
+
else:
|
|
127
|
+
raise NotImplementedError(geom)
|
|
128
|
+
|
|
129
|
+
if any(np.any(s < 0) or np.any(s + o.shape[1] > geo.seq_len) for s, o in slots):
|
|
130
|
+
raise ValueError(f'{kind} {anchor} {partner}: a motif falls outside the input')
|
|
131
|
+
pred = _predict(predictor, backgrounds, si, slots)
|
|
132
|
+
valid = np.zeros(shape, bool)
|
|
133
|
+
valid[vidx] = True
|
|
134
|
+
inserted_a = kind in ('pairwise', 'anchor_single', 'pairwise_2d', 'anchor_only')
|
|
135
|
+
inserted_p = kind in ('pairwise', 'partner_single', 'pairwise_2d', 'partner_only')
|
|
136
|
+
return dict(perbin_by_fold=_scatter(shape, vidx, pred), valid=valid, tracks=np.array(predictor.tracks),
|
|
137
|
+
members=np.array(predictor.members), **{axis: grid.astype(np.int64)},
|
|
138
|
+
partner_fill=p_fill if inserted_p else np.zeros((n_bg, 0), np.uint8), **starts,
|
|
139
|
+
anchor=a_seq if inserted_a else '', motif=p_seq if inserted_p else '',
|
|
140
|
+
anchor_name=anchor or '', partner_name=partner or '', kind=kind, geometry=geom,
|
|
141
|
+
seed=design.seed, schema=SCHEMA, **extra)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def write(store: Store, kind, anchor, partner, arrays) -> Path:
|
|
145
|
+
path = store.path / SUBDIR[kind] / f'{stem(kind, anchor, partner)}.npz'
|
|
146
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
tmp = path.with_name(path.stem + '.tmp.npz')
|
|
148
|
+
np.savez_compressed(tmp, **arrays)
|
|
149
|
+
os.replace(tmp, path)
|
|
150
|
+
return path
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _items(design: Design, g: dict) -> List[tuple]:
|
|
154
|
+
"""The (kind, anchor, partner) experiments of one design group."""
|
|
155
|
+
geom, A, P = g['geometry'], g.get('anchors', []), g.get('partners', [])
|
|
156
|
+
if geom == 'pair_spacing':
|
|
157
|
+
return [it for a in A for p in P for it in (('pairwise', a, p), ('anchor_single', a, p),
|
|
158
|
+
('partner_single', length_tag(len(design.anchors[a])), p))]
|
|
159
|
+
if geom == 'pair_offset_matrix':
|
|
160
|
+
return [it for a in A for p in P for it in (('pairwise_2d', a, p), ('anchor_only', a, None),
|
|
161
|
+
('partner_only', None, p))]
|
|
162
|
+
raise NotImplementedError(geom)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def wanted(design: Design) -> List[tuple]:
|
|
166
|
+
"""Every (kind, anchor, partner) the design asks for, in group order, without duplicates."""
|
|
167
|
+
seen, out = set(), []
|
|
168
|
+
for g in design.groups:
|
|
169
|
+
for it in _items(design, g):
|
|
170
|
+
if it not in seen:
|
|
171
|
+
seen.add(it)
|
|
172
|
+
out.append(it)
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def status(store: Store, design: Design, kind, anchor, partner) -> str:
|
|
177
|
+
"""'current' or 'missing'; a file written for other motif sequences is 'stale' and is recomputed."""
|
|
178
|
+
f = store.file(kind, anchor, partner)
|
|
179
|
+
if not f.exists():
|
|
180
|
+
return 'missing'
|
|
181
|
+
d = np.load(f, allow_pickle=True)
|
|
182
|
+
want = {'anchor': design.anchors.get(anchor, '') if kind in ('pairwise', 'anchor_single', 'pairwise_2d', 'anchor_only')
|
|
183
|
+
else '', 'motif': design.partners.get(partner, '') if kind != 'anchor_single' and partner else ''}
|
|
184
|
+
if any(k in d.files and str(d[k]) != v for k, v in want.items() if v):
|
|
185
|
+
return 'stale'
|
|
186
|
+
return 'current'
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def plan(store: Store, design: Design) -> List[tuple]:
|
|
190
|
+
return [(*w, st) for w in wanted(design) if (st := status(store, design, *w)) in ('missing', 'stale')]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def passes(design: Design, kind, anchor, partner, n_bg: int, n_members: int) -> int:
|
|
194
|
+
"""Forward passes an experiment costs, for the dry-run estimate."""
|
|
195
|
+
geo, geom = design.geometry, SUBDIR[kind]
|
|
196
|
+
if geom == 'pair_spacing':
|
|
197
|
+
la = int(anchor[3:]) if kind == 'partner_single' else len(design.anchors[anchor])
|
|
198
|
+
rows = int((geo.layout_spacing(la, len(design.partners[partner]))[0] >= 0).sum())
|
|
199
|
+
else:
|
|
200
|
+
rows = len(geo.offsets) ** (2 if kind == 'pairwise_2d' else 1)
|
|
201
|
+
return rows * n_bg * n_members
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def init_store(path, design: Design, predictor, backgrounds_npz, metadata_csv, background_types,
|
|
205
|
+
prediction_space: str, figure_background: Optional[str] = None,
|
|
206
|
+
readout: Optional[dict] = None) -> Store:
|
|
207
|
+
"""Create a store: copy the backgrounds in, predict them once, write store.json."""
|
|
208
|
+
path = Path(path)
|
|
209
|
+
(path / 'backgrounds').mkdir(parents=True, exist_ok=True)
|
|
210
|
+
seqs = np.load(backgrounds_npz)['sequences'].astype(np.float32)
|
|
211
|
+
meta = pd.read_csv(metadata_csv)
|
|
212
|
+
np.savez_compressed(path / 'backgrounds' / 'sequences.npz', sequences=seqs)
|
|
213
|
+
meta.to_csv(path / 'backgrounds' / 'sequence_metadata.csv', index=False)
|
|
214
|
+
rows = meta.index[meta['type'].isin(background_types)].tolist()
|
|
215
|
+
store_json = {'description': 'In silico marginalization store written by diffgrammar.',
|
|
216
|
+
'prediction_space': prediction_space, 'tracks': list(predictor.tracks),
|
|
217
|
+
'members': list(predictor.members), 'background_rows': rows,
|
|
218
|
+
'figure_background': figure_background, 'readout': readout or {},
|
|
219
|
+
'design': design.to_dict(), 'schema': SCHEMA}
|
|
220
|
+
(path / 'store.json').write_text(json.dumps(store_json, indent=2) + '\n')
|
|
221
|
+
(path / 'pair_spacing').mkdir(exist_ok=True)
|
|
222
|
+
np.savez_compressed(path / 'pair_spacing' / 'background.npz', **compute_background(predictor, seqs[rows]))
|
|
223
|
+
return Store(path)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The marginalization store on disk: one npz per experiment, conventions once in store.json.
|
|
3
|
+
|
|
4
|
+
<store>/store.json tracks, model members, prediction space, backgrounds
|
|
5
|
+
<store>/design.json the motifs and pairs it was made for
|
|
6
|
+
<store>/backgrounds/sequences.npz (n, 4, L) one-hot backgrounds
|
|
7
|
+
<store>/backgrounds/sequence_metadata.csv type and origin of each background row
|
|
8
|
+
<store>/pair_spacing/<kind>__<anchor>__<partner>.npz
|
|
9
|
+
<store>/pair_offset_matrix/<kind>__...npz
|
|
10
|
+
|
|
11
|
+
Each geometry has a reader that returns the same five quantities, every one at the position its motifs
|
|
12
|
+
hold in the combined construct: `pair` (both motifs), `first` (the anchor alone), `second` (the partner
|
|
13
|
+
alone), `baseline` (nothing inserted), `additive` = first + second - baseline and `cooperativity` =
|
|
14
|
+
pair - additive.
|
|
15
|
+
|
|
16
|
+
Every prediction array is `perbin_by_fold`, (member, *grid, background, track, bin), in the
|
|
17
|
+
model's output space. Reductions (tracks, bins, members, real space) happen at read time in
|
|
18
|
+
float64, because a cooperativity effect is a difference of similar magnitudes.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Optional
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pandas as pd
|
|
28
|
+
|
|
29
|
+
KINDS = {
|
|
30
|
+
'pairwise': ('anchor', 'partner'), 'anchor_single': ('anchor', 'partner'), 'partner_single': ('partner',),
|
|
31
|
+
'pairwise_2d': ('anchor', 'partner'), 'anchor_only': ('anchor',), 'partner_only': ('partner',),
|
|
32
|
+
}
|
|
33
|
+
SUBDIR = {'pairwise': 'pair_spacing', 'anchor_single': 'pair_spacing', 'partner_single': 'pair_spacing',
|
|
34
|
+
'pairwise_2d': 'pair_offset_matrix', 'anchor_only': 'pair_offset_matrix',
|
|
35
|
+
'partner_only': 'pair_offset_matrix'}
|
|
36
|
+
|
|
37
|
+
#: output space -> inverse transform to real signal
|
|
38
|
+
TO_REAL = {'log1p': np.expm1, 'log2p1': lambda x: np.exp2(x) - 1.0, 'logit': lambda x: 1.0 / (1.0 + np.exp(-x)),
|
|
39
|
+
'identity': lambda x: x}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def stem(kind: str, anchor: Optional[str] = None, partner: Optional[str] = None) -> str:
|
|
43
|
+
"""
|
|
44
|
+
File stem of an experiment. partner_single is laid out for the length of the anchor it pairs
|
|
45
|
+
with, so it is shared by every anchor of that length: its anchor slot carries a length tag
|
|
46
|
+
'len<n>' that is appended to the name ('partner_single__AP1__len9').
|
|
47
|
+
"""
|
|
48
|
+
got = {'anchor': anchor, 'partner': partner}
|
|
49
|
+
missing = [k for k in KINDS[kind] if got[k] is None]
|
|
50
|
+
if missing:
|
|
51
|
+
raise ValueError(f'{kind} needs {", ".join(KINDS[kind])}; missing {", ".join(missing)}')
|
|
52
|
+
parts = [kind] + [got[k] for k in KINDS[kind]]
|
|
53
|
+
if kind == 'partner_single' and anchor and anchor.startswith('len'):
|
|
54
|
+
parts.append(anchor)
|
|
55
|
+
return '__'.join(parts)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def length_tag(n: int) -> str:
|
|
59
|
+
return f'len{int(n)}'
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Store:
|
|
63
|
+
def __init__(self, path):
|
|
64
|
+
self.path = Path(path)
|
|
65
|
+
f = self.path / 'store.json'
|
|
66
|
+
self.meta = json.loads(f.read_text()) if f.exists() else {}
|
|
67
|
+
space = str(self.meta.get('prediction_space', 'identity')).split()[0].rstrip(';,')
|
|
68
|
+
self.space = space if space in TO_REAL else 'identity'
|
|
69
|
+
ro = self.meta.get('readout', {})
|
|
70
|
+
self.default_tracks = ro.get('tracks') or self.meta.get('tracks')
|
|
71
|
+
self.default_bins = slice(*ro['bins']) if 'bins' in ro else slice(None)
|
|
72
|
+
|
|
73
|
+
# -- files ---------------------------------------------------------------------------------
|
|
74
|
+
def file(self, kind, anchor=None, partner=None) -> Path:
|
|
75
|
+
return self.path / SUBDIR[kind] / f'{stem(kind, anchor, partner)}.npz'
|
|
76
|
+
|
|
77
|
+
def have(self, kind, anchor=None, partner=None) -> bool:
|
|
78
|
+
return self.file(kind, anchor, partner).exists()
|
|
79
|
+
|
|
80
|
+
def load(self, kind, anchor=None, partner=None) -> dict:
|
|
81
|
+
d = np.load(self.file(kind, anchor, partner), allow_pickle=True)
|
|
82
|
+
out = {k: d[k] for k in d.files}
|
|
83
|
+
out.setdefault('tracks', np.array(self.meta.get('tracks', [])))
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
def experiments(self) -> pd.DataFrame:
|
|
87
|
+
"""What is on disk, from the file names."""
|
|
88
|
+
rows = []
|
|
89
|
+
for sub in sorted(set(SUBDIR.values())):
|
|
90
|
+
for f in sorted((self.path / sub).glob('*__*.npz')):
|
|
91
|
+
kind, *names = f.stem.split('__')
|
|
92
|
+
if kind in KINDS:
|
|
93
|
+
rows.append({'geometry': sub, 'kind': kind, **dict(zip(KINDS[kind], names)),
|
|
94
|
+
'file': str(f.relative_to(self.path))})
|
|
95
|
+
return pd.DataFrame(rows)
|
|
96
|
+
|
|
97
|
+
# -- reading -------------------------------------------------------------------------------
|
|
98
|
+
def _reduce(self, perbin, file_tracks, tracks, bins, real_space):
|
|
99
|
+
tracks = tracks or self.default_tracks
|
|
100
|
+
bins = self.default_bins if bins is None else bins
|
|
101
|
+
idx = [list(map(str, file_tracks)).index(t) for t in tracks]
|
|
102
|
+
x = perbin[..., idx, bins].astype(np.float64)
|
|
103
|
+
if real_space:
|
|
104
|
+
x = TO_REAL[self.space](x)
|
|
105
|
+
return x.sum(-1).mean(0)
|
|
106
|
+
|
|
107
|
+
def readout(self, kind, anchor=None, partner=None, tracks=None, bins=None, real_space=False):
|
|
108
|
+
"""(*grid, n_background, track): tracks picked, bins summed, model members averaged."""
|
|
109
|
+
d = self.load(kind, anchor, partner)
|
|
110
|
+
return self._reduce(d['perbin_by_fold'], d['tracks'], tracks, bins, real_space)
|
|
111
|
+
|
|
112
|
+
def background(self, tracks=None, bins=None, real_space=False):
|
|
113
|
+
"""The backgrounds with nothing inserted, (n_background, track)."""
|
|
114
|
+
d = np.load(self.path / 'pair_spacing' / 'background.npz', allow_pickle=True)
|
|
115
|
+
return self._reduce(d['perbin_by_fold'], d['tracks'], tracks, bins, real_space)
|
|
116
|
+
|
|
117
|
+
def backgrounds_table(self) -> pd.DataFrame:
|
|
118
|
+
m = pd.read_csv(self.path / 'backgrounds' / 'sequence_metadata.csv')
|
|
119
|
+
rows = self.meta.get('background_rows')
|
|
120
|
+
return m.iloc[rows].reset_index(drop=True) if rows else m
|
|
121
|
+
|
|
122
|
+
def bg_mask(self, kind: Optional[str] = None) -> np.ndarray:
|
|
123
|
+
"""Boolean mask over prediction rows by background type; default the figure set."""
|
|
124
|
+
kind = kind or self.meta.get('figure_background')
|
|
125
|
+
t = self.backgrounds_table()
|
|
126
|
+
return np.ones(len(t), bool) if kind is None else (t['type'] == kind).to_numpy()
|
|
127
|
+
|
|
128
|
+
# -- cooperativity -------------------------------------------------------------------------
|
|
129
|
+
def components(self, anchor, partner, tracks=None, bins=None, real_space=False, step=None, bg=None):
|
|
130
|
+
"""pair, anchor alone and partner alone where they sit in the pair, and background; (D, n_bg, T)."""
|
|
131
|
+
kw = dict(tracks=tracks, bins=bins, real_space=real_space)
|
|
132
|
+
f = self.load('pairwise', anchor, partner)
|
|
133
|
+
dist = f['distances']
|
|
134
|
+
keep = np.arange(len(dist)) if step in (None, 1) else np.where(dist % step == 0)[0]
|
|
135
|
+
pick = (lambda a: a[keep]) if bg is None else (lambda a: a[keep][:, bg])
|
|
136
|
+
tag = length_tag(len(str(f['anchor']))) if 'anchor' in f and str(f['anchor']) else None
|
|
137
|
+
comp = {'pair': pick(self._reduce(f['perbin_by_fold'], f['tracks'], tracks, bins, real_space)),
|
|
138
|
+
'anchor': pick(self.readout('anchor_single', anchor, partner, **kw)),
|
|
139
|
+
'partner': pick(self.readout('partner_single', tag, partner, **kw)),
|
|
140
|
+
'background': self.background(**kw)[slice(None) if bg is None else bg]}
|
|
141
|
+
return dist[keep], comp
|
|
142
|
+
|
|
143
|
+
def cooperativity(self, anchor, partner, **kw):
|
|
144
|
+
"""pair - anchor alone - partner alone + background; 0 additive, > 0 super-additive."""
|
|
145
|
+
dist, c = self.components(anchor, partner, **kw)
|
|
146
|
+
return dist, c['pair'] - c['anchor'] - c['partner'] + c['background'][None]
|
|
147
|
+
|
|
148
|
+
def cooperativity_matrix(self, anchor, partner, tracks=None, bins=None, real_space=False):
|
|
149
|
+
"""2D scan, (X, Y, n_bg, T): pair - anchor at X - partner at Y + background."""
|
|
150
|
+
off, t = self.matrix_terms(anchor, partner, tracks=tracks, bins=bins, real_space=real_space)
|
|
151
|
+
return off, t['cooperativity']
|
|
152
|
+
|
|
153
|
+
# -- the five quantities, per geometry -------------------------------------------------------
|
|
154
|
+
@staticmethod
|
|
155
|
+
def _five(pair, first, second, baseline, bg=None, axis=-2) -> dict:
|
|
156
|
+
"""pair, first, second and baseline broadcast to one shape, plus additive and cooperativity;
|
|
157
|
+
bg masks the background axis (second to last)."""
|
|
158
|
+
first, second, baseline = (np.broadcast_to(x, pair.shape) for x in (first, second, baseline))
|
|
159
|
+
out = {'pair': pair, 'first': first, 'second': second, 'baseline': baseline,
|
|
160
|
+
'additive': first + second - baseline}
|
|
161
|
+
out['cooperativity'] = pair - out['additive']
|
|
162
|
+
if bg is not None:
|
|
163
|
+
out = {k: np.compress(bg, v, axis=axis) for k, v in out.items()}
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
def terms(self, anchor, partner, tracks=None, bins=None, real_space=False, step=None, bg=None):
|
|
167
|
+
"""pair_spacing: spacings and the five quantities, each (D, n_bg, track)."""
|
|
168
|
+
dist, c = self.components(anchor, partner, tracks=tracks, bins=bins, real_space=real_space, step=step)
|
|
169
|
+
return dist, self._five(c['pair'], c['anchor'], c['partner'], c['background'][None], bg)
|
|
170
|
+
|
|
171
|
+
def has_terms(self, anchor, partner) -> bool:
|
|
172
|
+
"""True when the spacing scan of this pair and both of its singles are on disk."""
|
|
173
|
+
f = self.file('pairwise', anchor, partner)
|
|
174
|
+
if not f.exists():
|
|
175
|
+
return False
|
|
176
|
+
la = len(str(np.load(f, allow_pickle=True)['anchor']))
|
|
177
|
+
return self.have('anchor_single', anchor, partner) and self.have('partner_single', length_tag(la), partner)
|
|
178
|
+
|
|
179
|
+
def has_matrix(self, anchor, partner) -> bool:
|
|
180
|
+
"""True when the 2D scan of this pair and both of its singles are on disk."""
|
|
181
|
+
return all(self.have(*k) for k in [('pairwise_2d', anchor, partner), ('anchor_only', anchor, None),
|
|
182
|
+
('partner_only', None, partner)])
|
|
183
|
+
|
|
184
|
+
def matrix_terms(self, anchor, partner, tracks=None, bins=None, real_space=False, bg=None):
|
|
185
|
+
"""pair_offset_matrix: offsets and the five quantities, each (X, Y, n_bg, track), X the anchor's offset."""
|
|
186
|
+
kw = dict(tracks=tracks, bins=bins, real_space=real_space)
|
|
187
|
+
f = self.load('pairwise_2d', anchor, partner)
|
|
188
|
+
pair = self._reduce(f['perbin_by_fold'], f['tracks'], tracks, bins, real_space)
|
|
189
|
+
a, p, b = self.readout('anchor_only', anchor, None, **kw), self.readout('partner_only', None, partner, **kw), \
|
|
190
|
+
self.background(**kw)
|
|
191
|
+
return f['scan_offsets'], self._five(pair, a[:, None], p[None, :], b[None, None], bg)
|