asebind 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 (45) hide show
  1. asebind/__init__.py +3 -0
  2. asebind/__main__.py +4 -0
  3. asebind/ase/__init__.py +1 -0
  4. asebind/ase/betabinom.py +173 -0
  5. asebind/benchmark/__init__.py +1 -0
  6. asebind/benchmark/asbdata.py +107 -0
  7. asebind/benchmark/clean.py +38 -0
  8. asebind/benchmark/features.py +71 -0
  9. asebind/benchmark/metrics.py +69 -0
  10. asebind/benchmark/models.py +151 -0
  11. asebind/benchmark/retest.py +183 -0
  12. asebind/benchmark/splits.py +61 -0
  13. asebind/cli.py +302 -0
  14. asebind/cli_model.py +539 -0
  15. asebind/config.py +340 -0
  16. asebind/data/asebind.example.yaml +56 -0
  17. asebind/finemap.py +86 -0
  18. asebind/haplotype.py +141 -0
  19. asebind/io/__init__.py +1 -0
  20. asebind/io/variants.py +107 -0
  21. asebind/model/__init__.py +1 -0
  22. asebind/model/adastra.py +113 -0
  23. asebind/model/classifier.py +122 -0
  24. asebind/model/context.py +60 -0
  25. asebind/model/features.py +201 -0
  26. asebind/model/other_motifs.py +168 -0
  27. asebind/model/train.py +331 -0
  28. asebind/motifs/__init__.py +1 -0
  29. asebind/motifs/escore.py +112 -0
  30. asebind/motifs/pwm.py +203 -0
  31. asebind/mpra.py +94 -0
  32. asebind/predict.py +163 -0
  33. asebind/resources/__init__.py +1 -0
  34. asebind/resources/ancestral.py +74 -0
  35. asebind/resources/conservation.py +77 -0
  36. asebind/resources/fetch.py +227 -0
  37. asebind/resources/genome.py +93 -0
  38. asebind/resources/registry.py +304 -0
  39. asebind/runrecord.py +108 -0
  40. asebind/tools.py +170 -0
  41. asebind-0.1.0.dist-info/METADATA +138 -0
  42. asebind-0.1.0.dist-info/RECORD +45 -0
  43. asebind-0.1.0.dist-info/WHEEL +4 -0
  44. asebind-0.1.0.dist-info/entry_points.txt +2 -0
  45. asebind-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,168 @@
1
+ """I-35: the other TFs' motifs at the SNP.
2
+
3
+ Most allele-specific binding in ADASTRA sits where the TF's own motif is weak (PHASE3_REPORT.md section 2), which
4
+ points to indirect binding through partner TFs. This module scans every SNP with every TF in the motif collection
5
+ and summarises, for each (SNP, TF) row, how the *other* TFs' sites change (the row's own TF is left out).
6
+
7
+ Per TF the motif with the strongest hit over both alleles is used (as in ``features.tf_features``). Features keep
8
+ the swap rules of ``features``:
9
+ - symmetric: oth_lp_best (best other site over both alleles);
10
+ - paired: oth_nsite_ref/alt (other TFs with a site, -log10 p >= SITE_LP, in that allele),
11
+ oth_up_ref/alt (largest -log10 p increase of an other TF's site towards that allele);
12
+ - antisymmetric: oth_d_sum (sum of alt-minus-ref -log10 p over other TFs with a site).
13
+
14
+ Scanning is one matrix product per motif length: every window overlapping the SNP, both strands, all motifs of
15
+ that length at once. Scores equal ``pwm.scan_snp`` (same rounded matrices, N scored as the column minimum).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Callable
21
+ from concurrent.futures import ProcessPoolExecutor
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+ from numpy.lib.stride_tricks import sliding_window_view
26
+
27
+ from asebind.model.features import FLANK, OTHER_FEATURES, SITE_LP, with_allele
28
+ from asebind.motifs.pwm import Motif, one_hot
29
+
30
+
31
+ class Scanner:
32
+ """All motifs grouped by length, as matrices ready for one product per length."""
33
+
34
+ def __init__(self, motifs: dict[str, list[Motif]]) -> None:
35
+ self.tfs = sorted(motifs)
36
+ col = {tf: i for i, tf in enumerate(self.tfs)}
37
+ groups: dict[int, list[Motif]] = {}
38
+ for tf in self.tfs:
39
+ for m in motifs[tf]:
40
+ groups.setdefault(m.length, []).append(m)
41
+ self.groups = []
42
+ for L, ms in sorted(groups.items()):
43
+ fwd = np.stack([m.scan_matrix for m in ms]) # k x L x 4
44
+ rev = np.stack([m.reverse_complement() for m in ms])
45
+ W = np.concatenate([fwd, rev]).reshape(2 * len(ms), L * 4).T # (L*4) x 2k
46
+ floor = np.concatenate([fwd.min(2), rev.min(2)]).T # L x 2k
47
+ self.groups.append((L, ms, W, floor, np.array([col[m.tf] for m in ms])))
48
+
49
+ def best_lp(self, seqs: list[str], centre: int = FLANK) -> np.ndarray:
50
+ """n x n_TFs: -log10 p of each TF's best motif hit overlapping ``centre`` (max over its motifs)."""
51
+ oh = one_hot(seqs)
52
+ n, length, _ = oh.shape
53
+ unknown = 1.0 - oh.sum(2)
54
+ out = np.zeros((n, len(self.tfs)))
55
+ for L, ms, W, floor, cols in self.groups:
56
+ lo, hi = max(centre - L + 1, 0), min(centre, length - L)
57
+ if hi < lo:
58
+ continue
59
+ # windows starting at lo..hi: n x w x L x 4 -> (n*w) x (L*4)
60
+ win = sliding_window_view(oh, (L, 4), axis=(1, 2))[:, lo : hi + 1, 0]
61
+ w = win.shape[1]
62
+ s = win.reshape(n * w, L * 4) @ W
63
+ unk = sliding_window_view(unknown, L, axis=1)[:, lo : hi + 1]
64
+ if unk.any():
65
+ s = s + unk.reshape(n * w, L) @ floor
66
+ s = s.reshape(n, w, -1).max(1) # best window per motif and strand
67
+ k = len(ms)
68
+ best = np.maximum(s[:, :k], s[:, k:])
69
+ for j, m in enumerate(ms):
70
+ lp = -np.log10(m.pvalue(best[:, j]))
71
+ np.maximum(out[:, cols[j]], lp, out=out[:, cols[j]])
72
+ return out
73
+
74
+
75
+ _SC: Scanner | None = None
76
+
77
+
78
+ def _init(sc: Scanner) -> None:
79
+ global _SC
80
+ _SC = sc
81
+
82
+
83
+ def _scan(args: tuple[list[str], list[str]]) -> tuple[np.ndarray, np.ndarray]:
84
+ assert _SC is not None
85
+ r, a = args
86
+ return _SC.best_lp(r).astype(np.float32), _SC.best_lp(a).astype(np.float32)
87
+
88
+
89
+ def scan_snps(
90
+ ref_seqs: list[str],
91
+ alt_seqs: list[str],
92
+ motifs: dict[str, list[Motif]],
93
+ workers: int = 1,
94
+ chunk: int = 5000,
95
+ log: Callable[[str], None] = lambda s: None,
96
+ ) -> tuple[list[str], np.ndarray, np.ndarray]:
97
+ """TF names and two n x n_TFs float32 matrices (-log10 p, ref and alt allele)."""
98
+ sc = Scanner(motifs)
99
+ jobs = [(ref_seqs[i : i + chunk], alt_seqs[i : i + chunk]) for i in range(0, len(ref_seqs), chunk)]
100
+ parts: list[tuple[np.ndarray, np.ndarray]] = []
101
+ if workers > 1:
102
+ with ProcessPoolExecutor(workers, initializer=_init, initargs=(sc,)) as ex:
103
+ for i, p in enumerate(ex.map(_scan, jobs), 1):
104
+ parts.append(p)
105
+ if i % 10 == 0:
106
+ log(f"other motifs: {i}/{len(jobs)} SNP chunks")
107
+ else:
108
+ _init(sc)
109
+ parts = [_scan(j) for j in jobs]
110
+ if not parts:
111
+ z = np.zeros((0, len(sc.tfs)), np.float32)
112
+ return sc.tfs, z, z
113
+ return sc.tfs, np.concatenate([p[0] for p in parts]), np.concatenate([p[1] for p in parts])
114
+
115
+
116
+ def row_features(
117
+ tfs: list[str],
118
+ LR: np.ndarray,
119
+ LA: np.ndarray,
120
+ snp_index: np.ndarray,
121
+ row_tf: np.ndarray,
122
+ chunk: int = 50000,
123
+ ) -> pd.DataFrame:
124
+ """OTHER_FEATURES for rows pointing at SNP ``snp_index`` (rows of LR/LA), leaving out each row's own TF."""
125
+ col = {tf: i for i, tf in enumerate(tfs)}
126
+ own = np.array([col.get(str(t).upper(), -1) for t in row_tf])
127
+ n = len(snp_index)
128
+ f = {k: np.zeros(n) for k in OTHER_FEATURES}
129
+ for s in range(0, n, chunk):
130
+ sl = slice(s, s + chunk)
131
+ r = LR[snp_index[sl]].astype(float)
132
+ a = LA[snp_index[sl]].astype(float)
133
+ keep = np.ones_like(r, bool)
134
+ o = own[sl]
135
+ has = o >= 0
136
+ keep[np.flatnonzero(has), o[has]] = False
137
+ site = keep & (np.maximum(r, a) >= SITE_LP)
138
+ d = a - r
139
+ f["oth_lp_best"][sl] = np.where(keep, np.maximum(r, a), 0).max(1)
140
+ f["oth_nsite_ref"][sl] = (keep & (r >= SITE_LP)).sum(1)
141
+ f["oth_nsite_alt"][sl] = (keep & (a >= SITE_LP)).sum(1)
142
+ f["oth_up_alt"][sl] = np.where(site, np.clip(d, 0, None), 0).max(1)
143
+ f["oth_up_ref"][sl] = np.where(site, np.clip(-d, 0, None), 0).max(1)
144
+ f["oth_d_sum"][sl] = np.where(site, d, 0).sum(1)
145
+ return pd.DataFrame(f)
146
+
147
+
148
+ def build(
149
+ rows: pd.DataFrame,
150
+ seqs: list[str],
151
+ motifs: dict[str, list[Motif]],
152
+ workers: int = 1,
153
+ log: Callable[[str], None] = lambda s: None,
154
+ ) -> pd.DataFrame:
155
+ """OTHER_FEATURES for every row (columns chrom, pos, ref, alt, tf); ``seqs`` are the reference flanks.
156
+
157
+ Each distinct (chrom, pos, ref, alt) is scanned once."""
158
+ key = rows["chrom"].astype(str) + ":" + rows["pos"].astype(str) + ":" + rows["ref"] + ":" + rows["alt"]
159
+ codes, uniq = pd.factorize(key)
160
+ first = pd.Series(np.arange(len(rows))).groupby(codes).first().to_numpy()
161
+ u_seqs = [seqs[i] for i in first]
162
+ ref_s = with_allele(u_seqs, rows["ref"].to_numpy()[first])
163
+ alt_s = with_allele(u_seqs, rows["alt"].to_numpy()[first])
164
+ log(f"other motifs: {len(uniq)} distinct SNPs x {len(motifs)} TFs")
165
+ tfs, LR, LA = scan_snps(ref_s, alt_s, motifs, workers=workers, log=log)
166
+ out = row_features(tfs, LR, LA, codes, rows["tf"].to_numpy())
167
+ out.index = rows.index
168
+ return out
asebind/model/train.py ADDED
@@ -0,0 +1,331 @@
1
+ """Phase 3 evaluation and final training on ADASTRA labels.
2
+
3
+ Models compared on the same grouped folds (by SNP, chromosome, TF):
4
+ - ``pwm_delta_lr``: logistic regression on the PWM change and site strength only (the plain PWM rule);
5
+ - ``hgb``: gradient boosting on all features, one allele order, uncalibrated;
6
+ - ``asebind``: the ASEbind model (both orders, exactly antisymmetric, calibrated inside the training fold);
7
+ - ``asebind_pwm_only``: the same without E-score features (the PWM-only tier, I-18).
8
+ Calibration is fitted on out-of-fold predictions *within the training fold* (I-16), never on test rows.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import time
15
+ from collections.abc import Callable, Sequence
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ from sklearn.linear_model import LogisticRegression
21
+ from sklearn.model_selection import GroupKFold
22
+ from sklearn.pipeline import make_pipeline
23
+ from sklearn.preprocessing import StandardScaler
24
+
25
+ from asebind.benchmark import metrics, splits
26
+ from asebind.model.classifier import SWAP_CLASSES, BindingModel, encode
27
+ from asebind.model.features import (
28
+ ANCESTRAL_FEATURES,
29
+ CONSERVATION_FEATURES,
30
+ FEATURES,
31
+ OTHER_FEATURES,
32
+ swap,
33
+ )
34
+
35
+ ESCORE_FEATURES = [f for f in FEATURES if f.startswith(("e_", "d_e_")) or f == "has_pbm"]
36
+ PWM_FEATURES = [f for f in FEATURES if f not in ESCORE_FEATURES]
37
+ # optional feature sets added to the base model by name: model "asebind+oth" = FEATURES + OTHER_FEATURES
38
+ FEATURE_SETS: dict[str, list[str]] = {
39
+ "oth": OTHER_FEATURES,
40
+ "anc": ANCESTRAL_FEATURES,
41
+ "cons": CONSERVATION_FEATURES,
42
+ }
43
+ ALL_FEATURES = FEATURES + [f for s in FEATURE_SETS.values() for f in s]
44
+ MODELS = ("pwm_delta_lr", "hgb", "asebind", "asebind_pwm_only")
45
+ SPLITS = ("by_snp", "by_chrom", "by_tf")
46
+ BINS = [-np.inf, 2.0, 3.0, 4.0, np.inf]
47
+ BIN_LABELS = ["<2", "2-3", "3-4", ">=4"]
48
+
49
+
50
+ def oof_calibrated(
51
+ X: pd.DataFrame, y: np.ndarray, groups: np.ndarray, features: list[str], seed: int, inner: int = 3
52
+ ) -> BindingModel:
53
+ """Fit on all rows; calibrate on out-of-fold raw predictions (grouped by ``groups``)."""
54
+ raw = np.zeros((len(y), 3))
55
+ for tr, te in GroupKFold(n_splits=inner).split(X, groups=groups):
56
+ m = BindingModel(seed=seed, features=features).fit(X.iloc[tr], y[tr])
57
+ raw[te] = m.predict_raw(X.iloc[te])
58
+ final = BindingModel(seed=seed, features=features).fit(X, y)
59
+ final.calibrator.fit(raw, y)
60
+ return final
61
+
62
+
63
+ class _Sk:
64
+ """Plain one-order sklearn model on a feature subset (NaN -> 0 for the linear model)."""
65
+
66
+ def __init__(self, est, features: list[str], fill: bool) -> None:
67
+ self.est, self.features, self.fill = est, features, fill
68
+
69
+ def _x(self, X: pd.DataFrame) -> np.ndarray:
70
+ a = X[self.features].to_numpy(float)
71
+ if self.fill:
72
+ return np.nan_to_num(a)
73
+ return np.where(np.isnan(a).all(0), 0.0, a) if len(a) else a
74
+
75
+ def fit(self, X: pd.DataFrame, y: np.ndarray) -> _Sk:
76
+ self.est.fit(self._x(X), y)
77
+ return self
78
+
79
+ def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
80
+ return self.est.predict_proba(self._x(X))
81
+
82
+
83
+ def fit_model(name: str, X: pd.DataFrame, y: np.ndarray, snp: np.ndarray, seed: int):
84
+ if name == "pwm_delta_lr":
85
+ est = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000, class_weight="balanced"))
86
+ return _Sk(est, ["d_lp", "lp_best", "d_site_bits"], fill=True).fit(X, y)
87
+ if name == "hgb":
88
+ from sklearn.ensemble import HistGradientBoostingClassifier
89
+
90
+ est = HistGradientBoostingClassifier(random_state=seed, **BindingModel().params)
91
+ return _Sk(est, list(FEATURES), fill=False).fit(X, y)
92
+ if name == "asebind":
93
+ return oof_calibrated(X, y, snp, list(FEATURES), seed)
94
+ if name == "asebind_pwm_only":
95
+ return oof_calibrated(X, y, snp, PWM_FEATURES, seed)
96
+ if name.startswith("asebind+"):
97
+ return oof_calibrated(X, y, snp, model_features(name), seed)
98
+ raise ValueError(f"unknown model {name!r}")
99
+
100
+
101
+ def model_features(name: str) -> list[str]:
102
+ """Features of model ``asebind+<set>[+<set>...]`` (sets from FEATURE_SETS)."""
103
+ feats = list(FEATURES)
104
+ for s in name.split("+")[1:]:
105
+ if s not in FEATURE_SETS:
106
+ raise ValueError(f"unknown feature set {s!r} in {name!r}; choose from {sorted(FEATURE_SETS)}")
107
+ feats += FEATURE_SETS[s]
108
+ return feats
109
+
110
+
111
+ def ece(y: np.ndarray, p: np.ndarray, bins: int = 10) -> float:
112
+ """Expected calibration error, averaged over the three one-vs-rest probabilities."""
113
+ out = []
114
+ for c in range(3):
115
+ q, t = p[:, c], (y == c).astype(float)
116
+ edges = np.linspace(0, 1, bins + 1)
117
+ b = np.clip(np.digitize(q, edges) - 1, 0, bins - 1)
118
+ e = sum(
119
+ abs(q[b == i].mean() - t[b == i].mean()) * (b == i).mean() for i in range(bins) if (b == i).any()
120
+ )
121
+ out.append(e)
122
+ return float(np.mean(out))
123
+
124
+
125
+ def reliability(y: np.ndarray, p: np.ndarray, bins: int = 10) -> pd.DataFrame:
126
+ rows = []
127
+ edges = np.linspace(0, 1, bins + 1)
128
+ for c, lab in enumerate(("gained", "lost", "none")):
129
+ b = np.clip(np.digitize(p[:, c], edges) - 1, 0, bins - 1)
130
+ for i in range(bins):
131
+ m = b == i
132
+ if m.any():
133
+ rows.append(
134
+ {
135
+ "class": lab,
136
+ "bin": i,
137
+ "n": int(m.sum()),
138
+ "mean_p": p[m, c].mean(),
139
+ "observed": (y[m] == c).mean(),
140
+ }
141
+ )
142
+ return pd.DataFrame(rows)
143
+
144
+
145
+ def eval_units(
146
+ data: pd.DataFrame,
147
+ model_names: Sequence[str] = MODELS,
148
+ split_names: Sequence[str] = SPLITS,
149
+ seeds: Sequence[int] = (0,),
150
+ k: int = 5,
151
+ ) -> list[tuple[str, int, np.ndarray, np.ndarray, str]]:
152
+ """Every (split, fold, model) unit in a fixed order; unit i is array task i on the cluster."""
153
+ return [
154
+ (split, fold, tr, te, name)
155
+ for split, fold, tr, te in splits.make_splits(data, split_names, k=k, seeds=seeds)
156
+ for name in model_names
157
+ ]
158
+
159
+
160
+ def _part(out: Path, split: str, fold: int, name: str) -> tuple[Path, Path]:
161
+ stem = out / "parts" / f"{split}__{fold}__{name}"
162
+ return stem.with_name(stem.name + ".folds.tsv"), stem.with_name(stem.name + ".pred.tsv.gz")
163
+
164
+
165
+ def _run_unit(data, X, Xs, y, snp, strength, unit, out: Path, log) -> None:
166
+ split, fold, tr, te, name = unit
167
+ fpath, ppath = _part(out, split, fold, name)
168
+ fpath.parent.mkdir(parents=True, exist_ok=True)
169
+ t0 = time.time()
170
+ m = fit_model(name, X.iloc[tr], y[tr], snp[tr], seed=fold)
171
+ p = m.predict_proba(X.iloc[te])
172
+ ps = m.predict_proba(Xs.iloc[te])
173
+ s = metrics.scores(y[te], p)
174
+ s["flip_rate"] = metrics.flip_rate(p, ps)
175
+ s["antisym_max_err"] = float(np.abs(p - ps[:, SWAP_CLASSES]).max())
176
+ s["ece"] = ece(y[te], p)
177
+ secs = round(time.time() - t0, 1)
178
+ log(
179
+ f"{split:9} fold {fold:<4} {name:17} bal {s['balanced_accuracy']:.3f} macroAUC "
180
+ f"{s['macro_auc']:.3f} gain/loss AUC {s['gain_vs_loss_auc']:.3f} flip {s['flip_rate']:.3f} "
181
+ f"ECE {s['ece']:.3f} ({secs}s)"
182
+ )
183
+ pred = pd.DataFrame(
184
+ {
185
+ "split": split,
186
+ "fold": fold,
187
+ "model": name,
188
+ "row": data.index[te],
189
+ "tf": data["tf"].to_numpy()[te],
190
+ "strength": strength[te],
191
+ "has_pbm": X["has_pbm"].to_numpy()[te],
192
+ "y": y[te],
193
+ "p_gained": p[:, 0],
194
+ "p_lost": p[:, 1],
195
+ "p_none": p[:, 2],
196
+ }
197
+ )
198
+ # predictions first, the one-row fold table last: its presence marks the unit as done
199
+ tmp = ppath.with_name(ppath.name + ".tmp")
200
+ pred.to_csv(tmp, sep="\t", index=False, float_format="%.4g", compression="gzip")
201
+ tmp.replace(ppath)
202
+ tmp = fpath.with_name(fpath.name + ".tmp")
203
+ pd.DataFrame([{"model": name, "split": split, "fold": fold, **s, "seconds": secs}]).to_csv(
204
+ tmp, sep="\t", index=False, float_format="%.6g"
205
+ )
206
+ tmp.replace(fpath)
207
+
208
+
209
+ def evaluate(
210
+ data: pd.DataFrame,
211
+ out: Path,
212
+ model_names: Sequence[str] = MODELS,
213
+ split_names: Sequence[str] = SPLITS,
214
+ seeds: Sequence[int] = (0,),
215
+ k: int = 5,
216
+ log: Callable[[str], None] = print,
217
+ task: int | None = None,
218
+ merge_only: bool = False,
219
+ ) -> dict[str, Path]:
220
+ """Run the units not yet in ``out/parts`` (only unit ``task`` when given), then merge them.
221
+
222
+ With ``task`` set nothing is merged; with ``merge_only`` nothing is run and a missing unit is an error.
223
+ """
224
+ out.mkdir(parents=True, exist_ok=True)
225
+ X = data[[f for f in ALL_FEATURES if f in data]].astype(float)
226
+ Xs = swap(X)
227
+ y = encode(data["label"])
228
+ snp = data["snp"].to_numpy()
229
+ strength = pd.cut(X["lp_best"].fillna(0), BINS, labels=BIN_LABELS, right=False).astype(str).to_numpy()
230
+ units = eval_units(data, model_names, split_names, seeds, k)
231
+ if task is not None and not 0 <= task < len(units):
232
+ raise ValueError(f"task {task} out of range: {len(units)} units")
233
+ todo = units if task is None else [units[task]]
234
+ if not merge_only:
235
+ for u in todo:
236
+ if _part(out, u[0], u[1], u[4])[0].exists():
237
+ log(f"{u[0]:9} fold {u[1]:<4} {u[4]:17} done earlier")
238
+ continue
239
+ _run_unit(data, X, Xs, y, snp, strength, u, out, log)
240
+ if task is not None:
241
+ return {}
242
+ missing = [f"{u[0]}/{u[1]}/{u[4]}" for u in units if not _part(out, u[0], u[1], u[4])[0].exists()]
243
+ if missing:
244
+ raise FileNotFoundError(f"{len(missing)} of {len(units)} units not run yet: {', '.join(missing[:5])}")
245
+ folds = pd.concat(
246
+ [pd.read_csv(_part(out, u[0], u[1], u[4])[0], sep="\t") for u in units], ignore_index=True
247
+ )
248
+ pred = pd.concat(
249
+ [pd.read_csv(_part(out, u[0], u[1], u[4])[1], sep="\t") for u in units], ignore_index=True
250
+ )
251
+ g = folds.groupby(["split", "model"], sort=False)
252
+ mcols = [c for c in folds.columns if c not in ("model", "split", "fold", "seconds")]
253
+ summary = pd.concat(
254
+ [
255
+ g.size().rename("folds"),
256
+ g[mcols].mean().add_suffix("_mean"),
257
+ g[mcols].std(ddof=1).add_suffix("_sd"),
258
+ ],
259
+ axis=1,
260
+ ).reset_index()
261
+ strat = _grouped_scores(pred, ["split", "model", "strength"])
262
+ tier = _grouped_scores(pred, ["split", "model", "has_pbm"])
263
+ per_tf = _grouped_scores(pred, ["split", "model", "tf"], min_n=100)
264
+ rel = pd.concat(
265
+ [
266
+ reliability(d["y"].to_numpy(), d[["p_gained", "p_lost", "p_none"]].to_numpy()).assign(
267
+ split=s, model=m
268
+ )
269
+ for (s, m), d in pred.groupby(["split", "model"], sort=False)
270
+ ]
271
+ )
272
+ paths = {
273
+ "folds": out / "phase3_folds.tsv",
274
+ "summary": out / "phase3_summary.tsv",
275
+ "by_site_strength": out / "phase3_by_site_strength.tsv",
276
+ "by_tier": out / "phase3_by_tier.tsv",
277
+ "per_tf": out / "phase3_per_tf.tsv",
278
+ "reliability": out / "phase3_reliability.tsv",
279
+ "predictions": out / "phase3_predictions.tsv.gz",
280
+ }
281
+ for key, df in (
282
+ ("folds", folds),
283
+ ("summary", summary),
284
+ ("by_site_strength", strat),
285
+ ("by_tier", tier),
286
+ ("per_tf", per_tf),
287
+ ("reliability", rel),
288
+ ):
289
+ df.to_csv(paths[key], sep="\t", index=False, float_format="%.5g")
290
+ pred.to_csv(paths["predictions"], sep="\t", index=False, float_format="%.4g")
291
+ return paths
292
+
293
+
294
+ def _grouped_scores(pred: pd.DataFrame, by: list[str], min_n: int = 0) -> pd.DataFrame:
295
+ rows = []
296
+ for key, d in pred.groupby(by, sort=False):
297
+ if len(d) < min_n:
298
+ continue
299
+ y = d["y"].to_numpy()
300
+ p = d[["p_gained", "p_lost", "p_none"]].to_numpy()
301
+ cnt = np.bincount(y, minlength=3)
302
+ rows.append(
303
+ {
304
+ **dict(zip(by, key, strict=True)),
305
+ "n_gained": cnt[0],
306
+ "n_lost": cnt[1],
307
+ "n_none": cnt[2],
308
+ **metrics.scores(y, p),
309
+ "ece": ece(y, p),
310
+ }
311
+ )
312
+ return pd.DataFrame(rows)
313
+
314
+
315
+ def train_final(
316
+ data: pd.DataFrame, path: Path, seed: int = 0, info: dict | None = None, model: str = "asebind"
317
+ ) -> Path:
318
+ feats = list(FEATURES) if model == "asebind" else model_features(model)
319
+ X = data[feats].astype(float)
320
+ y = encode(data["label"])
321
+ m = oof_calibrated(X, y, data["snp"].to_numpy(), feats, seed, inner=5)
322
+ m.info = {
323
+ "trained_rows": len(y),
324
+ "class_counts": {lab: int((y == i).sum()) for i, lab in enumerate(("gained", "lost", "none"))},
325
+ "tfs": sorted(data["tf"].unique().tolist()),
326
+ "model": model,
327
+ **(info or {}),
328
+ }
329
+ p = m.save(path)
330
+ (path.parent / "training_info.json").write_text(json.dumps(m.info, indent=2, default=str) + "\n")
331
+ return p
@@ -0,0 +1 @@
1
+ """Motif resources and scanning: MEME-format PWMs (HOCOMOCO, JASPAR), exact p-values, CIS-BP 8-mer E-scores."""
@@ -0,0 +1,112 @@
1
+ """CIS-BP PBM 8-mer E-scores (I-13/I-18 PBM tier).
2
+
3
+ The CIS-BP table (one row per 8-mer, one column per PBM experiment, ~3 GB of text) is converted once to a
4
+ float16 matrix (``escores.npy``) plus ``columns.tsv`` and ``kmers.txt``, then memory-mapped.
5
+ Column names look like ``M00056_3.10:Badis08:ABF1_4505.2_ArrayA``; the TF symbol is the third field up to the
6
+ first underscore, upper-cased (mouse/human orthologue symbols then coincide, I-34).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ _COMP = str.maketrans("ACGT", "TGCA")
17
+
18
+
19
+ def revcomp(s: str) -> str:
20
+ return s.translate(_COMP)[::-1]
21
+
22
+
23
+ def column_tf(col: str) -> str:
24
+ """TF symbol of an experiment column; "" for PBMs of mutant proteins (Barrera 2016 arrays other than _REF_)."""
25
+ parts = col.split(":")
26
+ name = parts[2] if len(parts) >= 3 else col
27
+ if len(parts) >= 2 and parts[1].startswith("Barrera") and "_REF_" not in name:
28
+ return ""
29
+ return name.split("_")[0].upper()
30
+
31
+
32
+ def build_cache(table: str | Path, outdir: str | Path, chunksize: int = 2000) -> Path:
33
+ outdir = Path(outdir)
34
+ outdir.mkdir(parents=True, exist_ok=True)
35
+ header = pd.read_csv(table, sep="\t", nrows=0).columns.tolist()
36
+ cols = header[1:]
37
+ kmers: list[str] = []
38
+ blocks = []
39
+ for chunk in pd.read_csv(table, sep="\t", chunksize=chunksize, dtype={header[0]: str}, low_memory=False):
40
+ km = chunk.iloc[:, 0].fillna("").str.upper()
41
+ # CIS-BP lists each 8-mer / reverse-complement pair once; rows without a valid 8-mer (the unlabelled
42
+ # reverse-complement half of some exports) are dropped: lookups try both orientations.
43
+ ok = km.str.fullmatch("[ACGT]{8}").to_numpy()
44
+ kmers.extend(km[ok].tolist())
45
+ vals = chunk.loc[ok, chunk.columns[1:]].apply(pd.to_numeric, errors="coerce")
46
+ blocks.append(vals.to_numpy(np.float16))
47
+ if not kmers:
48
+ raise ValueError(f"{table}: no 8-mer rows")
49
+ mat = np.vstack(blocks)
50
+ (outdir / "kmers.txt").write_text("\n".join(kmers) + "\n")
51
+ pd.DataFrame({"column": cols, "tf": [column_tf(c) for c in cols]}).to_csv(
52
+ outdir / "columns.tsv", sep="\t", index=False
53
+ )
54
+ tmp = outdir / "escores.tmp.npy"
55
+ np.save(tmp, mat)
56
+ tmp.replace(
57
+ outdir / "escores.npy"
58
+ ) # written last: its presence (with kmers.txt) means the cache is complete
59
+ return outdir
60
+
61
+
62
+ class EscoreTable:
63
+ def __init__(self, cache_dir: str | Path) -> None:
64
+ d = Path(cache_dir)
65
+ self.mat = np.load(d / "escores.npy", mmap_mode="r")
66
+ self.columns = pd.read_csv(d / "columns.tsv", sep="\t")
67
+ kmers = (d / "kmers.txt").read_text().split()
68
+ self.row = {}
69
+ for i, k in enumerate(kmers):
70
+ self.row[k] = i
71
+ self.row.setdefault(revcomp(k), i)
72
+ self._tf_cols = {k: v for k, v in self.columns.fillna("").groupby("tf").indices.items() if k}
73
+
74
+ def tfs(self) -> set[str]:
75
+ return set(self._tf_cols)
76
+
77
+ def tf_matrix(self, tf: str) -> np.ndarray | None:
78
+ """32896-ish x n_experiments float32 matrix for one TF, or None when the TF has no PBM data."""
79
+ idx = self._tf_cols.get(tf.upper())
80
+ if idx is None:
81
+ return None
82
+ return np.asarray(self.mat[:, idx], dtype=np.float32)
83
+
84
+ def kmer_rows(self, seqs: list[str], centre: int, k: int = 8) -> np.ndarray:
85
+ """n x k row indices of the k 8-mers that contain the centre base (-1 where the 8-mer has an N)."""
86
+ out = np.full((len(seqs), k), -1, dtype=np.int64)
87
+ for i, s in enumerate(seqs):
88
+ for j, st in enumerate(range(centre - k + 1, centre + 1)):
89
+ out[i, j] = self.row.get(s[st : st + k], -1)
90
+ return out
91
+
92
+
93
+ def escore_features(
94
+ table: EscoreTable, tf: str, ref_seqs: list[str], alt_seqs: list[str], centre: int
95
+ ) -> dict:
96
+ """Per sequence: max E-score over the 8 overlapping 8-mers (max over the TF's experiments), mean over
97
+ experiments of that max, and the number of 8-mers above 0.35 (a common 'bound' cut-off)."""
98
+ m = table.tf_matrix(tf)
99
+ n = len(ref_seqs)
100
+ if m is None:
101
+ nan = np.full(n, np.nan)
102
+ return {f"{f}_{a}": nan for f in ("e_max", "e_mean", "e_nbound") for a in ("ref", "alt")}
103
+ out = {}
104
+ for allele, seqs in (("ref", ref_seqs), ("alt", alt_seqs)):
105
+ rows = table.kmer_rows(seqs, centre)
106
+ vals = np.where(rows[..., None] >= 0, m[np.clip(rows, 0, None)], np.nan) # n x 8 x experiments
107
+ with np.errstate(all="ignore"):
108
+ per_exp = np.nanmax(vals, axis=1) # n x experiments
109
+ out[f"e_max_{allele}"] = np.nanmax(per_exp, axis=1)
110
+ out[f"e_mean_{allele}"] = np.nanmean(per_exp, axis=1)
111
+ out[f"e_nbound_{allele}"] = np.nansum(np.nanmax(vals, axis=2) > 0.35, axis=1).astype(float)
112
+ return out