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
asebind/io/variants.py ADDED
@@ -0,0 +1,107 @@
1
+ """Read variants (VCF or TSV) and check their alleles against the reference genome (I-5, I-6).
2
+
3
+ Every variant ends up with ``ref`` = the genome's base and ``alt`` = the other allele, plus flags that say what
4
+ was done: alleles given the other way round, given on the minus strand, strand-ambiguous (A/T, C/G), or not
5
+ matching the genome at all. With a risk/effect allele, ``direction`` says whether the reported change is for the
6
+ risk allele (``risk_vs_other``) so callers can read P(gain) as "the risk allele gains binding".
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 = {"A": "T", "C": "G", "G": "C", "T": "A"}
17
+
18
+
19
+ def read_variants(path: str | Path, risk_allele_column: str | None = None) -> pd.DataFrame:
20
+ """VCF (``#CHROM POS ID REF ALT``; multi-allelic ALT split) or TSV with columns chrom, pos, ref, alt
21
+ (optional id and a risk-allele column). Only single-nucleotide variants are kept."""
22
+ path = Path(path)
23
+ text_head = path.open(encoding="utf-8", errors="replace").readline()
24
+ if text_head.startswith("##fileformat=VCF") or path.suffix in (".vcf",) or path.name.endswith(".vcf.gz"):
25
+ df = _read_vcf(path)
26
+ else:
27
+ df = pd.read_csv(path, sep="\t", dtype=str, comment=None)
28
+ df.columns = [c.strip().lstrip("#").lower() for c in df.columns]
29
+ need = {"chrom", "pos", "ref", "alt"}
30
+ if not need <= set(df.columns):
31
+ raise ValueError(f"{path}: needs columns {sorted(need)} (got {list(df.columns)})")
32
+ if "id" not in df.columns:
33
+ df["id"] = df["chrom"] + ":" + df["pos"] + ":" + df["ref"] + ":" + df["alt"]
34
+ rc = risk_allele_column.lower() if risk_allele_column else None
35
+ if rc and rc not in df.columns:
36
+ raise ValueError(f"{path}: risk allele column {risk_allele_column!r} not found")
37
+ df["risk_allele"] = df[rc].str.upper() if rc else pd.NA
38
+ df = df[["id", "chrom", "pos", "ref", "alt", "risk_allele"]]
39
+ df["pos"] = df["pos"].astype(int)
40
+ df["ref"], df["alt"] = df["ref"].str.upper(), df["alt"].str.upper()
41
+ snv = df["ref"].str.fullmatch("[ACGT]") & df["alt"].str.fullmatch("[ACGT]")
42
+ return df[snv].reset_index(drop=True)
43
+
44
+
45
+ def _read_vcf(path: Path) -> pd.DataFrame:
46
+ rows = []
47
+ opener = __import__("gzip").open if path.name.endswith(".gz") else open
48
+ with opener(path, "rt") as fh:
49
+ for line in fh:
50
+ if line.startswith("#") or not line.strip():
51
+ continue
52
+ f = line.rstrip("\n").split("\t")
53
+ for alt in f[4].split(","):
54
+ vid = f[2] if f[2] not in (".", "") else f"{f[0]}:{f[1]}:{f[3]}:{alt}"
55
+ rows.append((vid, f[0], f[1], f[3], alt))
56
+ df = pd.DataFrame(rows, columns=["id", "chrom", "pos", "ref", "alt"])
57
+ df["risk_allele"] = pd.NA
58
+ return df
59
+
60
+
61
+ def check_alleles(df: pd.DataFrame, genome) -> pd.DataFrame:
62
+ """Orient every variant to the genome's reference base and record what had to be done."""
63
+ out = df.copy()
64
+ gref = np.array([genome.base(c, int(p)) for c, p in zip(out["chrom"], out["pos"], strict=True)])
65
+ ref, alt = out["ref"].to_numpy(), out["alt"].to_numpy()
66
+ comp_ref = np.array([_COMP.get(a, "N") for a in ref])
67
+ comp_alt = np.array([_COMP.get(a, "N") for a in alt])
68
+ ambiguous = np.array([_COMP.get(r) == a for r, a in zip(ref, alt, strict=True)])
69
+ status = np.full(len(out), "ok", dtype=object)
70
+ new_ref, new_alt = ref.copy(), alt.copy()
71
+ swapped = (ref != gref) & (alt == gref)
72
+ status[swapped] = "alleles_swapped"
73
+ new_ref[swapped], new_alt[swapped] = alt[swapped], ref[swapped]
74
+ flip = (ref != gref) & (alt != gref) & ~ambiguous & (comp_ref == gref)
75
+ status[flip] = "strand_flipped"
76
+ new_ref[flip], new_alt[flip] = comp_ref[flip], comp_alt[flip]
77
+ flip_swap = (ref != gref) & (alt != gref) & ~ambiguous & (comp_alt == gref)
78
+ status[flip_swap] = "strand_flipped_and_swapped"
79
+ new_ref[flip_swap], new_alt[flip_swap] = comp_alt[flip_swap], comp_ref[flip_swap]
80
+ bad = new_ref != gref
81
+ status[bad] = "ref_mismatch"
82
+ out["given_ref"], out["given_alt"] = ref, alt
83
+ out["ref"], out["alt"] = new_ref, new_alt
84
+ out["genome_ref"] = gref
85
+ out["allele_check"] = status
86
+ out["strand_ambiguous"] = ambiguous
87
+ risk = out["risk_allele"].astype("string")
88
+ flipped = np.isin(status, ["strand_flipped", "strand_flipped_and_swapped"])
89
+ risk_on_plus = np.where(flipped, risk.map(lambda a: _COMP.get(a, a) if isinstance(a, str) else a), risk)
90
+ out["direction"] = np.where(
91
+ risk.isna(),
92
+ "alt_vs_ref",
93
+ np.where(
94
+ risk_on_plus == out["alt"],
95
+ "risk_vs_other",
96
+ np.where(risk_on_plus == out["ref"], "risk_is_ref", "risk_unmatched"),
97
+ ),
98
+ )
99
+ return out
100
+
101
+
102
+ def build_check(checked: pd.DataFrame) -> dict:
103
+ """Share of variants whose stated alleles include the genome base (I-6). Below 0.9 the build is likely wrong."""
104
+ n = len(checked)
105
+ ok = int((checked["allele_check"] != "ref_mismatch").sum())
106
+ frac = ok / n if n else float("nan")
107
+ return {"variants": n, "matching_genome": ok, "fraction": frac, "build_ok": bool(n == 0 or frac >= 0.9)}
@@ -0,0 +1 @@
1
+ """The ASEbind binding model (Phase 3): features, labels, antisymmetric calibrated classifier."""
@@ -0,0 +1,113 @@
1
+ """Training labels from ADASTRA (release Mabel v6.1, hg38): every tested heterozygous SNV in a TF's ChIP-seq.
2
+
3
+ Labels for the alt allele relative to the ref allele:
4
+ - ``gained``: Alt-ASB (alt allele preferred: ``fdrp_bh_alt`` < fdr, ``fdrp_bh_ref`` >= fdr, ``es_mean_alt`` > 0);
5
+ - ``lost``: Ref-ASB (the mirror image);
6
+ - ``none``: tested, well covered (``total_cover`` >= min_cover) and clearly balanced (both FDR >= none_fdr).
7
+ These are SNPs inside the TF's own peaks with no allelic imbalance: a real "no change" class, unlike
8
+ SNPeBoT's "none" rows (benchmarks/REPORT.md, section 2).
9
+ ADASTRA's motif columns (computed with HOCOMOCO v12) are kept only to cross-check our own features.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+
20
+ KEEP = {
21
+ "#chr": "chrom",
22
+ "end": "pos",
23
+ "ID": "rsid",
24
+ "ref": "ref",
25
+ "alt": "alt",
26
+ "repeat_type": "repeat_type",
27
+ "mean_BAD": "mean_bad",
28
+ "n_aggregated": "n_aggregated",
29
+ "total_cover": "total_cover",
30
+ "es_mean_ref": "es_ref",
31
+ "es_mean_alt": "es_alt",
32
+ "fdrp_bh_ref": "fdr_ref",
33
+ "fdrp_bh_alt": "fdr_alt",
34
+ "motif_fc": "adastra_motif_fc",
35
+ "motif_log_pref": "adastra_motif_lp_ref",
36
+ "motif_log_palt": "adastra_motif_lp_alt",
37
+ }
38
+
39
+
40
+ def tf_symbol(uniprot_entry: str) -> str:
41
+ """``SPI1_HUMAN`` -> ``SPI1`` (UniProt entry names; HOCOMOCO v12 uses the same prefixes)."""
42
+ return uniprot_entry.rsplit("_", 1)[0].upper()
43
+
44
+
45
+ def label_table(d: pd.DataFrame, fdr: float = 0.05, none_fdr: float = 0.5, min_cover: int = 40) -> pd.Series:
46
+ fr, fa = d["fdr_ref"].astype(float), d["fdr_alt"].astype(float)
47
+ er = pd.to_numeric(d["es_ref"], errors="coerce")
48
+ ea = pd.to_numeric(d["es_alt"], errors="coerce")
49
+ lab = pd.Series(pd.NA, index=d.index, dtype="object")
50
+ lab[(fa < fdr) & (fr >= fdr) & (ea > 0)] = "gained"
51
+ lab[(fr < fdr) & (fa >= fdr) & (er > 0)] = "lost"
52
+ lab[(fr >= none_fdr) & (fa >= none_fdr) & (d["total_cover"] >= min_cover)] = "none"
53
+ return lab
54
+
55
+
56
+ def read_tf(path: Path, symbol_of: dict[str, str] | None = None, **kw) -> pd.DataFrame:
57
+ d = pd.read_csv(path, sep="\t", usecols=list(KEEP), dtype={"#chr": str, "ID": str}, low_memory=False)
58
+ d = d.rename(columns=KEEP)
59
+ d = d[d["ref"].str.len().eq(1) & d["alt"].str.len().eq(1)]
60
+ d["label"] = label_table(d, **kw)
61
+ d = d[d["label"].notna()].copy()
62
+ d["uniprot"] = path.stem
63
+ d["tf"] = (symbol_of or {}).get(path.stem.upper(), tf_symbol(path.stem))
64
+ return d
65
+
66
+
67
+ def build_labels(
68
+ tf_dir: str | Path,
69
+ tfs_with_motifs: set[str] | None = None,
70
+ min_asb: int = 20,
71
+ none_per_asb: float = 2.0,
72
+ min_none: int = 200,
73
+ seed: int = 0,
74
+ log: Callable[[str], None] = print,
75
+ symbol_of: dict[str, str] | None = None,
76
+ **kw,
77
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
78
+ """All TFs: labelled rows (``none`` subsampled to at most ``none_per_asb`` x the ASB count, at least
79
+ ``min_none``) and a per-TF count table. TFs without a motif in our collections or with < ``min_asb`` ASBs are
80
+ counted but left out."""
81
+ rng = np.random.default_rng(seed)
82
+ parts, counts = [], []
83
+ files = sorted(Path(tf_dir).glob("*_HUMAN.tsv"))
84
+ for i, f in enumerate(files, 1):
85
+ d = read_tf(f, symbol_of, **kw)
86
+ n = d["label"].value_counts()
87
+ n_asb = int(n.get("gained", 0) + n.get("lost", 0))
88
+ tf = (symbol_of or {}).get(f.stem.upper(), tf_symbol(f.stem))
89
+ has_motif = tfs_with_motifs is None or tf in tfs_with_motifs
90
+ keep = has_motif and n_asb >= min_asb
91
+ row = {
92
+ "tf": tf,
93
+ "uniprot": f.stem,
94
+ "gained": int(n.get("gained", 0)),
95
+ "lost": int(n.get("lost", 0)),
96
+ "none_available": int(n.get("none", 0)),
97
+ "has_motif": has_motif,
98
+ "used": keep,
99
+ }
100
+ if keep:
101
+ none = d[d["label"] == "none"]
102
+ cap = max(min_none, int(none_per_asb * n_asb))
103
+ if len(none) > cap:
104
+ none = none.iloc[np.sort(rng.choice(len(none), cap, replace=False))]
105
+ d = pd.concat([d[d["label"] != "none"], none])
106
+ row["none_used"] = int((d["label"] == "none").sum())
107
+ parts.append(d)
108
+ counts.append(row)
109
+ if i % 100 == 0:
110
+ log(f"labels: {i}/{len(files)} TF files")
111
+ out = pd.concat(parts, ignore_index=True)
112
+ out["snp"] = out["chrom"] + ":" + out["pos"].astype(str) + ":" + out["ref"] + ":" + out["alt"]
113
+ return out, pd.DataFrame(counts)
@@ -0,0 +1,122 @@
1
+ """Antisymmetric, calibrated 3-class model: P(gain), P(loss), P(none) for the alt allele vs the ref allele.
2
+
3
+ - Trained on both allele orders (each row and its swap, with gain/loss exchanged), I-12.
4
+ - Prediction averages p(x) and the class-permuted p(swap x), so P(gain | x) == P(loss | swap x) exactly.
5
+ - Calibration (I-15) on out-of-fold predictions: one isotonic map shared by gain and loss (keeps the symmetry)
6
+ and one for none, then renormalised.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+
15
+ import joblib
16
+ import numpy as np
17
+ import pandas as pd
18
+ from sklearn.ensemble import HistGradientBoostingClassifier
19
+ from sklearn.isotonic import IsotonicRegression
20
+
21
+ from asebind import __version__
22
+ from asebind.model.features import FEATURES, swap
23
+
24
+ LABELS = ("gained", "lost", "none")
25
+ SWAP_CLASSES = [1, 0, 2]
26
+
27
+
28
+ def encode(labels: pd.Series | np.ndarray) -> np.ndarray:
29
+ m = {lab: i for i, lab in enumerate(LABELS)}
30
+ return np.array([m[x] for x in labels])
31
+
32
+
33
+ @dataclass
34
+ class Calibrator:
35
+ change: IsotonicRegression | None = None
36
+ none: IsotonicRegression | None = None
37
+
38
+ def fit(self, p: np.ndarray, y: np.ndarray) -> Calibrator:
39
+ x = np.concatenate([p[:, 0], p[:, 1]])
40
+ t = np.concatenate([y == 0, y == 1]).astype(float)
41
+ self.change = IsotonicRegression(out_of_bounds="clip", y_min=1e-4, y_max=1 - 1e-4).fit(x, t)
42
+ self.none = IsotonicRegression(out_of_bounds="clip", y_min=1e-4, y_max=1 - 1e-4).fit(p[:, 2], y == 2)
43
+ return self
44
+
45
+ def __call__(self, p: np.ndarray) -> np.ndarray:
46
+ if self.change is None or self.none is None:
47
+ return p
48
+ q = np.column_stack(
49
+ [self.change.predict(p[:, 0]), self.change.predict(p[:, 1]), self.none.predict(p[:, 2])]
50
+ )
51
+ return q / q.sum(1, keepdims=True)
52
+
53
+
54
+ @dataclass
55
+ class BindingModel:
56
+ seed: int = 0
57
+ params: dict = field(
58
+ default_factory=lambda: {
59
+ "max_iter": 400,
60
+ "learning_rate": 0.06,
61
+ "max_leaf_nodes": 31,
62
+ "min_samples_leaf": 40,
63
+ "l2_regularization": 1.0,
64
+ "early_stopping": True,
65
+ "validation_fraction": 0.1,
66
+ "n_iter_no_change": 20,
67
+ "class_weight": "balanced",
68
+ }
69
+ )
70
+ features: list[str] = field(default_factory=lambda: list(FEATURES))
71
+ calibrator: Calibrator = field(default_factory=Calibrator)
72
+ est: HistGradientBoostingClassifier | None = None
73
+ info: dict = field(default_factory=dict)
74
+ all_nan: list[str] = field(default_factory=list) # features with no value in training: used as constant 0
75
+
76
+ def _frame(self, X: pd.DataFrame) -> pd.DataFrame:
77
+ X = X[self.features].astype(float)
78
+ if self.all_nan:
79
+ X = X.assign(**{c: 0.0 for c in self.all_nan})
80
+ return X
81
+
82
+ def fit(self, X: pd.DataFrame, y: np.ndarray) -> BindingModel:
83
+ self.all_nan = [c for c in self.features if X[c].isna().all()]
84
+ X = self._frame(X)
85
+ Xa = pd.concat([X, swap(X)], ignore_index=True)
86
+ ya = np.concatenate([y, np.array(SWAP_CLASSES)[y]])
87
+ self.est = HistGradientBoostingClassifier(random_state=self.seed, **self.params).fit(
88
+ Xa.to_numpy(), ya
89
+ )
90
+ return self
91
+
92
+ def predict_raw(self, X: pd.DataFrame) -> np.ndarray:
93
+ assert self.est is not None, "model not fitted"
94
+ X = self._frame(X)
95
+ p = self.est.predict_proba(X.to_numpy())
96
+ ps = self.est.predict_proba(swap(X).to_numpy())
97
+ return (p + ps[:, SWAP_CLASSES]) / 2
98
+
99
+ def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
100
+ return self.calibrator(self.predict_raw(X))
101
+
102
+ def save(self, path: str | Path) -> Path:
103
+ path = Path(path)
104
+ path.parent.mkdir(parents=True, exist_ok=True)
105
+ joblib.dump(self, path)
106
+ meta = {
107
+ "asebind_version": __version__,
108
+ "classes": LABELS,
109
+ "features": self.features,
110
+ "params": self.params,
111
+ "seed": self.seed,
112
+ **self.info,
113
+ }
114
+ path.with_suffix(".json").write_text(json.dumps(meta, indent=2, default=str) + "\n", encoding="utf-8")
115
+ return path
116
+
117
+ @staticmethod
118
+ def load(path: str | Path) -> BindingModel:
119
+ m = joblib.load(path)
120
+ if not isinstance(m, BindingModel):
121
+ raise TypeError(f"{path}: not an ASEbind model")
122
+ return m
@@ -0,0 +1,60 @@
1
+ """Load the fetched resources into a feature ``Context``: PWMs per TF and the E-score table.
2
+
3
+ PWMs: HOCOMOCO v12 for every TF it covers; JASPAR 2024 only for TFs that HOCOMOCO lacks (I-18). E-scores: the
4
+ CIS-BP 3.10 cache when it exists. A TF's evidence tier is ``pbm+pwm`` when it has both, otherwise ``pwm``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from asebind.model.features import Context
12
+ from asebind.motifs.escore import EscoreTable
13
+ from asebind.motifs.pwm import Motif, by_tf, hocomoco_tfs, hocomoco_uniprot_symbols, read_meme
14
+ from asebind.resources.fetch import FetchError, resource_file
15
+
16
+ ESCORE_CACHE = "cisbp_escores_3.10/cache"
17
+
18
+
19
+ def load_motifs(root: Path) -> dict[str, list[Motif]]:
20
+ motifs: dict[str, list[Motif]] = {}
21
+ try:
22
+ meme = resource_file("hocomoco_v12", root, "*.meme")
23
+ ann = resource_file("hocomoco_v12", root, "*annotation.jsonl")
24
+ motifs = by_tf(read_meme(meme, "hocomoco_v12", hocomoco_tfs(ann)))
25
+ except FetchError:
26
+ pass
27
+ try:
28
+ jaspar = by_tf(read_meme(resource_file("jaspar2024", root, "*meme*.txt"), "jaspar2024"))
29
+ for tf, ms in jaspar.items():
30
+ motifs.setdefault(tf, ms)
31
+ except FetchError:
32
+ pass
33
+ if not motifs:
34
+ raise FetchError(f"no motif collection under {root}: run `asebind fetch hocomoco_v12 jaspar2024`")
35
+ return motifs
36
+
37
+
38
+ def uniprot_symbols(root: Path) -> dict[str, str]:
39
+ """UniProt entry name -> gene symbol (HOCOMOCO v12 annotation); empty when HOCOMOCO is not fetched."""
40
+ try:
41
+ return hocomoco_uniprot_symbols(resource_file("hocomoco_v12", Path(root), "*annotation.jsonl"))
42
+ except FetchError:
43
+ return {}
44
+
45
+
46
+ def load_context(root: str | Path, escores: bool = True) -> Context:
47
+ root = Path(root)
48
+ table = None
49
+ if escores and (root / ESCORE_CACHE / "escores.npy").exists():
50
+ table = EscoreTable(root / ESCORE_CACHE)
51
+ return Context(motifs=load_motifs(root), escores=table)
52
+
53
+
54
+ def tier(ctx: Context, tf: str) -> str:
55
+ tf = tf.upper()
56
+ if tf not in ctx.motifs:
57
+ return "none"
58
+ if ctx.escores is not None and tf in ctx.escores.tfs():
59
+ return "pbm+pwm"
60
+ return "pwm"
@@ -0,0 +1,201 @@
1
+ """Features for one (variant, TF) pair, built from the genome, the TF's PWMs and (when present) its PBM E-scores.
2
+
3
+ Every feature is one of three kinds, so swapping the two alleles is an exact operation (I-12, I-13):
4
+ - symmetric (unchanged by a swap): best site strength over both alleles, information content at the SNP, GC;
5
+ - paired ``*_ref`` / ``*_alt`` (exchanged by a swap);
6
+ - antisymmetric (negated by a swap): explicit alt-minus-ref differences.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable, Iterable
12
+ from concurrent.futures import ProcessPoolExecutor
13
+ from dataclasses import dataclass
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ from asebind.motifs.escore import EscoreTable, escore_features
19
+ from asebind.motifs.pwm import Motif, one_hot, scan_snp
20
+
21
+ FLANK = 30 # bases each side of the SNP; longer than any HOCOMOCO/JASPAR motif overlap needs
22
+ SITE_LP = 3.0 # -log10 p for "a site is present"
23
+
24
+ PAIRED = ["lp", "lp_mean", "e_max", "e_mean", "e_nbound"]
25
+ ANTI = ["d_lp", "d_site_bits", "d_lp_mean", "d_lp_maxabs", "d_e_max", "d_e_mean"]
26
+ SYM = ["lp_best", "lp_worse", "ic_snp", "snp_rel_pos", "n_motifs", "n_motifs_site", "has_pbm", "gc"]
27
+ FEATURES = SYM + [f"{p}_{a}" for p in PAIRED for a in ("ref", "alt")] + ANTI
28
+
29
+ # I-35: the other TFs' motifs at the SNP (built by ``other_motifs``; optional columns)
30
+ OTH_SYM = ["oth_lp_best"]
31
+ OTH_PAIRED = ["oth_nsite", "oth_up"]
32
+ OTH_ANTI = ["oth_d_sum"]
33
+ OTHER_FEATURES = OTH_SYM + [f"{p}_{a}" for p in OTH_PAIRED for a in ("ref", "alt")] + OTH_ANTI
34
+
35
+ # I-32: ancestral vs derived allele (built by ``resources.ancestral``; optional columns)
36
+ ANC_SYM = [
37
+ "anc_known"
38
+ ] # 1: high-confidence ancestral base equals ref or alt; 0.5: low confidence; 0: unknown
39
+ ANC_ANTI = [
40
+ "anc_dir"
41
+ ] # +anc_known when the alt allele is derived (ref ancestral), -anc_known when alt is ancestral
42
+ ANCESTRAL_FEATURES = ANC_SYM + ANC_ANTI
43
+
44
+ # I-31: conservation as a weight (built by ``resources.conservation``; optional columns)
45
+ CONS_SYM = [f"{t}_{w}" for t in ("p100", "p241") for w in ("snp", "w7", "w21")]
46
+ CONS_ANTI = ["cons_d_lp"] # d_lp x max(phyloP at the SNP, 0)
47
+ CONSERVATION_FEATURES = CONS_SYM + CONS_ANTI
48
+
49
+
50
+ def swap(X: pd.DataFrame) -> pd.DataFrame:
51
+ """The same rows with the two alleles exchanged (exact for every feature in FEATURES and OTHER_FEATURES)."""
52
+ out = X.copy()
53
+ for p in PAIRED + OTH_PAIRED:
54
+ if f"{p}_ref" in X:
55
+ out[f"{p}_ref"], out[f"{p}_alt"] = X[f"{p}_alt"].to_numpy(), X[f"{p}_ref"].to_numpy()
56
+ for a in ANTI + OTH_ANTI + ANC_ANTI + CONS_ANTI:
57
+ if a in X:
58
+ out[a] = -X[a]
59
+ return out
60
+
61
+
62
+ @dataclass
63
+ class Context:
64
+ """What a worker needs: sequences come from the caller; motifs and E-scores per TF."""
65
+
66
+ motifs: dict[str, list[Motif]]
67
+ escores: EscoreTable | None = None
68
+
69
+
70
+ def flanks(genome, rows: pd.DataFrame, flank: int = FLANK) -> tuple[list[str], np.ndarray]:
71
+ """Reference sequence of +-flank around each 1-based ``pos`` (N-padded at chromosome ends), and whether the
72
+ stated ``ref`` allele matches the genome."""
73
+ seqs, match = [], []
74
+ for chrom, pos, ref in zip(rows["chrom"], rows["pos"], rows["ref"], strict=True):
75
+ start = int(pos) - 1 - flank
76
+ s = genome.fetch(chrom, start, int(pos) + flank)
77
+ if start < 0:
78
+ s = "N" * (-start) + s
79
+ s = s + "N" * (2 * flank + 1 - len(s))
80
+ seqs.append(s)
81
+ match.append(s[flank] == str(ref).upper())
82
+ return seqs, np.array(match)
83
+
84
+
85
+ def with_allele(seqs: Iterable[str], alleles: Iterable[str], centre: int = FLANK) -> list[str]:
86
+ return [s[:centre] + a.upper() + s[centre + 1 :] for s, a in zip(seqs, alleles, strict=True)]
87
+
88
+
89
+ def tf_features(
90
+ tf: str, ref_seqs: list[str], alt_seqs: list[str], ctx: Context, centre: int = FLANK
91
+ ) -> pd.DataFrame:
92
+ n = len(ref_seqs)
93
+ motifs = ctx.motifs.get(tf.upper(), [])
94
+ oh_r, oh_a = one_hot(ref_seqs), one_hot(alt_seqs)
95
+ per = [] # per motif: lp_ref, lp_alt, site delta (bits), ic at snp, relative snp position
96
+ for m in motifs:
97
+ r, a = scan_snp(m, oh_r, centre), scan_snp(m, oh_a, centre)
98
+ lp_r = -np.log10(m.pvalue(r["score"]))
99
+ lp_a = -np.log10(m.pvalue(a["score"]))
100
+ both = np.maximum(r["window_scores"], a["window_scores"])
101
+ b = both.argmax(1)
102
+ idx = np.arange(n)
103
+ d_site = a["window_scores"][idx, b] - r["window_scores"][idx, b]
104
+ snp_i = r["window_snp_index"][b] # SNP position in the joint best window: unchanged by a swap
105
+ per.append((lp_r, lp_a, d_site, m.info[snp_i], snp_i / max(m.length - 1, 1)))
106
+ f: dict[str, np.ndarray] = {}
107
+ if per:
108
+ lp_r = np.stack([p[0] for p in per], 1)
109
+ lp_a = np.stack([p[1] for p in per], 1)
110
+ d_site = np.stack([p[2] for p in per], 1)
111
+ ic = np.stack([p[3] for p in per], 1)
112
+ rel = np.stack([p[4] for p in per], 1)
113
+ best = np.maximum(lp_r, lp_a).argmax(1)
114
+ idx = np.arange(n)
115
+ f["lp_ref"], f["lp_alt"] = lp_r[idx, best], lp_a[idx, best]
116
+ f["lp_mean_ref"], f["lp_mean_alt"] = lp_r.mean(1), lp_a.mean(1)
117
+ f["d_site_bits"] = d_site[idx, best]
118
+ f["ic_snp"] = ic[idx, best]
119
+ # position of the SNP inside the best motif, folded so that a swap or a strand flip leaves it unchanged
120
+ f["snp_rel_pos"] = np.minimum(rel[idx, best], 1 - rel[idx, best])
121
+ d = lp_a - lp_r
122
+ f["d_lp_mean"] = d.mean(1)
123
+ f["d_lp_maxabs"] = d[idx, np.abs(d).argmax(1)]
124
+ f["n_motifs_site"] = (np.maximum(lp_r, lp_a) >= SITE_LP).sum(1).astype(float)
125
+ else:
126
+ nan = np.full(n, np.nan)
127
+ for k in (
128
+ "lp_ref",
129
+ "lp_alt",
130
+ "lp_mean_ref",
131
+ "lp_mean_alt",
132
+ "d_site_bits",
133
+ "ic_snp",
134
+ "snp_rel_pos",
135
+ "d_lp_mean",
136
+ "d_lp_maxabs",
137
+ "n_motifs_site",
138
+ ):
139
+ f[k] = nan
140
+ f["n_motifs"] = np.full(n, float(len(motifs)))
141
+ f["lp_best"] = np.maximum(f["lp_ref"], f["lp_alt"])
142
+ f["lp_worse"] = np.minimum(f["lp_ref"], f["lp_alt"])
143
+ f["d_lp"] = f["lp_alt"] - f["lp_ref"]
144
+ if ctx.escores is not None:
145
+ f.update(escore_features(ctx.escores, tf, ref_seqs, alt_seqs, centre))
146
+ else:
147
+ for k in ("e_max", "e_mean", "e_nbound"):
148
+ f[f"{k}_ref"] = f[f"{k}_alt"] = np.full(n, np.nan)
149
+ f["has_pbm"] = (~np.isnan(f["e_max_ref"])).astype(float)
150
+ f["d_e_max"] = f["e_max_alt"] - f["e_max_ref"]
151
+ f["d_e_mean"] = f["e_mean_alt"] - f["e_mean_ref"]
152
+ flank_only = [s[:centre] + s[centre + 1 :] for s in ref_seqs] # without the SNP: symmetric under a swap
153
+ f["gc"] = np.array([sum(c in "GC" for c in s) / max(sum(c in "ACGT" for c in s), 1) for s in flank_only])
154
+ return pd.DataFrame({k: f[k] for k in FEATURES})
155
+
156
+
157
+ _CTX: Context | None = None
158
+
159
+
160
+ def _init(ctx: Context) -> None:
161
+ global _CTX
162
+ _CTX = ctx
163
+
164
+
165
+ def _work(args: tuple[str, list[str], list[str], np.ndarray]) -> tuple[np.ndarray, pd.DataFrame]:
166
+ tf, ref_s, alt_s, idx = args
167
+ assert _CTX is not None
168
+ return idx, tf_features(tf, ref_s, alt_s, _CTX)
169
+
170
+
171
+ def build(
172
+ rows: pd.DataFrame,
173
+ seqs: list[str],
174
+ ctx: Context,
175
+ workers: int = 1,
176
+ chunk: int = 20000,
177
+ log: Callable[[str], None] = lambda s: None,
178
+ ) -> pd.DataFrame:
179
+ """Features for every row (columns chrom, pos, ref, alt, tf); ``seqs`` are the reference flanks."""
180
+ ref_s = with_allele(seqs, rows["ref"])
181
+ alt_s = with_allele(seqs, rows["alt"])
182
+ jobs = []
183
+ tfs = rows["tf"].str.upper().to_numpy()
184
+ for tf in pd.unique(tfs):
185
+ idx = np.flatnonzero(tfs == tf)
186
+ for i in range(0, len(idx), chunk):
187
+ part = idx[i : i + chunk]
188
+ jobs.append((tf, [ref_s[j] for j in part], [alt_s[j] for j in part], part))
189
+ out = pd.DataFrame(index=np.arange(len(rows)), columns=FEATURES, dtype=float)
190
+ if workers > 1:
191
+ with ProcessPoolExecutor(workers, initializer=_init, initargs=(ctx,)) as ex:
192
+ for n_done, (idx, f) in enumerate(ex.map(_work, jobs), 1):
193
+ out.iloc[idx] = f.to_numpy()
194
+ if n_done % 25 == 0:
195
+ log(f"features: {n_done}/{len(jobs)} TF chunks")
196
+ else:
197
+ _init(ctx)
198
+ for idx, f in map(_work, jobs):
199
+ out.iloc[idx] = f.to_numpy()
200
+ out.index = rows.index
201
+ return out