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/motifs/pwm.py ADDED
@@ -0,0 +1,203 @@
1
+ """Position weight matrices: MEME-format reader, log-odds scoring, exact p-values, scanning around a SNP (I-14).
2
+
3
+ Scores use a uniform background; p-values come from the exact score distribution of the discretised matrix
4
+ (as in FIMO / PERFECTOS-APE), so they do not depend on any external tool. Every hit that overlaps the SNP is
5
+ scanned, on both strands.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from functools import cached_property
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ BASES = "ACGT"
17
+ _IDX = {b: i for i, b in enumerate(BASES)}
18
+ SCALE = 100 # score units per bit when discretising for p-values
19
+ PSEUDO = 0.01
20
+
21
+
22
+ @dataclass
23
+ class Motif:
24
+ name: str
25
+ tf: str # upper-case gene symbol of the TF the motif belongs to
26
+ source: str
27
+ probs: np.ndarray # L x 4 letter probabilities (A, C, G, T)
28
+ alt_name: str = ""
29
+ meta: dict = field(default_factory=dict)
30
+
31
+ @property
32
+ def length(self) -> int:
33
+ return self.probs.shape[0]
34
+
35
+ @cached_property
36
+ def logodds(self) -> np.ndarray:
37
+ p = (self.probs + PSEUDO) / (self.probs + PSEUDO).sum(1, keepdims=True)
38
+ return np.log2(p / 0.25)
39
+
40
+ @cached_property
41
+ def info(self) -> np.ndarray:
42
+ """Information content (bits) of each column."""
43
+ p = np.clip(self.probs, 1e-9, 1)
44
+ return 2 + (p * np.log2(p)).sum(1)
45
+
46
+ @cached_property
47
+ def _int_scores(self) -> np.ndarray:
48
+ return np.round(self.logodds * SCALE).astype(np.int64)
49
+
50
+ @cached_property
51
+ def _pvalue_table(self) -> tuple[int, np.ndarray]:
52
+ """Exact P(score >= s) under the uniform background for every integer score s, as (min score, sf array)."""
53
+ m = self._int_scores
54
+ cur_lo = 0
55
+ cur = np.array([1.0])
56
+ for row in m:
57
+ rlo = int(row.min())
58
+ width = len(cur) + int(row.max()) - rlo
59
+ nxt = np.zeros(width)
60
+ for v in row:
61
+ off = int(v) - rlo
62
+ nxt[off : off + len(cur)] += cur * 0.25
63
+ cur, cur_lo = nxt, cur_lo + rlo
64
+ sf = np.cumsum(cur[::-1])[::-1]
65
+ return cur_lo, np.clip(sf, 1e-300, 1.0)
66
+
67
+ def pvalue(self, score_bits: np.ndarray) -> np.ndarray:
68
+ """P(score >= s) for scores in bits (array)."""
69
+ lo, sf = self._pvalue_table
70
+ idx = np.round(np.asarray(score_bits) * SCALE).astype(np.int64) - lo
71
+ idx = np.clip(idx, 0, len(sf) - 1)
72
+ return sf[idx]
73
+
74
+ @cached_property
75
+ def scan_matrix(self) -> np.ndarray:
76
+ """Log-odds rounded to 1/SCALE bit: scan scores then fall exactly on the p-value table's grid."""
77
+ return self._int_scores / SCALE
78
+
79
+ def reverse_complement(self) -> np.ndarray:
80
+ return self.scan_matrix[::-1, ::-1]
81
+
82
+
83
+ def one_hot(seqs: list[str] | np.ndarray) -> np.ndarray:
84
+ """n x len x 4 one-hot; N (or any other letter) is all zero, so it adds the column minimum below."""
85
+ arr = np.frombuffer("".join(seqs).encode(), dtype=np.uint8).reshape(len(seqs), -1)
86
+ out = np.zeros((*arr.shape, 4), dtype=np.float32)
87
+ for i, b in enumerate(BASES.encode()):
88
+ out[..., i] = arr == b
89
+ return out
90
+
91
+
92
+ def scan_snp(motif: Motif, oh: np.ndarray, centre: int) -> dict[str, np.ndarray]:
93
+ """Best hit overlapping position ``centre`` on either strand, for every sequence (n x len x 4 one-hot).
94
+
95
+ Returns per sequence: best score (bits), its start offset relative to the SNP (SNP index within the motif,
96
+ in motif orientation), strand (+1 / -1), and the score of every overlapping window (n x 2L) in a fixed order
97
+ so two alleles can be compared at the same site.
98
+ """
99
+ L = motif.length
100
+ n, length, _ = oh.shape
101
+ starts = np.arange(centre - L + 1, centre + 1)
102
+ ok = (starts >= 0) & (starts + L <= length)
103
+ starts = starts[ok]
104
+ unknown = 1.0 - oh.sum(2) # 1 where the base is N
105
+ out = []
106
+ for mat in (motif.scan_matrix, motif.reverse_complement()):
107
+ floor = mat.min(1)
108
+ s = np.stack(
109
+ [np.einsum("nlb,lb->n", oh[:, k : k + L], mat) + unknown[:, k : k + L] @ floor for k in starts],
110
+ axis=1,
111
+ )
112
+ out.append(s)
113
+ scores = np.concatenate(out, axis=1) # n x (2 * windows): forward windows then reverse windows
114
+ w = len(starts)
115
+ pos_fwd = centre - starts # SNP index within each window, forward orientation
116
+ window_snp_index = np.concatenate([pos_fwd, L - 1 - pos_fwd]) # in motif orientation, per window
117
+ window_strand = np.concatenate([np.ones(w, int), -np.ones(w, int)])
118
+ best = scores.argmax(1)
119
+ return {
120
+ "score": scores[np.arange(n), best],
121
+ "snp_index": window_snp_index[best],
122
+ "strand": window_strand[best],
123
+ "window_scores": scores,
124
+ "window_snp_index": window_snp_index,
125
+ }
126
+
127
+
128
+ def read_meme(path: str | Path, source: str, tf_of: dict[str, str] | None = None) -> list[Motif]:
129
+ """Read a MEME-format motif file. TF symbol: ``tf_of[name]`` if given, else the name's prefix."""
130
+ motifs: list[Motif] = []
131
+ lines = Path(path).read_text(encoding="utf-8").splitlines()
132
+ i = 0
133
+ while i < len(lines):
134
+ line = lines[i].strip()
135
+ if line.startswith("MOTIF"):
136
+ parts = line.split()
137
+ name = parts[1]
138
+ alt = parts[2] if len(parts) > 2 else ""
139
+ i += 1
140
+ while i < len(lines) and not lines[i].strip().lower().startswith("letter-probability"):
141
+ i += 1
142
+ i += 1
143
+ rows = []
144
+ while i < len(lines):
145
+ t = lines[i].strip()
146
+ if not t or t.startswith(("MOTIF", "URL")):
147
+ break
148
+ vals = t.split()
149
+ if len(vals) != 4:
150
+ break
151
+ rows.append([float(v) for v in vals])
152
+ i += 1
153
+ probs = np.array(rows, dtype=float)
154
+ probs = probs / probs.sum(1, keepdims=True)
155
+ tf = tf_of[name] if tf_of is not None and name in tf_of else _default_tf(name, alt, source)
156
+ motifs.append(Motif(name=name, tf=tf.upper(), source=source, probs=probs, alt_name=alt))
157
+ continue
158
+ i += 1
159
+ return motifs
160
+
161
+
162
+ def _default_tf(name: str, alt: str, source: str) -> str:
163
+ if source.startswith("hocomoco"):
164
+ return name.split(".")[0] # SPI1.H12CORE.0.P.B
165
+ # JASPAR: "MA0080.6 SPI1"; dimers like "FOS::JUN" keep the first partner as TF symbol
166
+ return (alt or name).split("::")[0]
167
+
168
+
169
+ def hocomoco_tfs(annotation_jsonl: str | Path) -> dict[str, str]:
170
+ """Motif name -> TF gene symbol from the HOCOMOCO v12 annotation (falls back to the name prefix)."""
171
+ import json
172
+
173
+ out = {}
174
+ for line in Path(annotation_jsonl).read_text(encoding="utf-8").splitlines():
175
+ if not line.strip():
176
+ continue
177
+ d = json.loads(line)
178
+ name = d.get("name")
179
+ sym = (d.get("masterlist_info", {}) or {}).get("species", {}).get("HUMAN", {}).get("gene_symbol")
180
+ if name:
181
+ out[name] = (sym or name.split(".")[0]).upper()
182
+ return out
183
+
184
+
185
+ def hocomoco_uniprot_symbols(annotation_jsonl: str | Path) -> dict[str, str]:
186
+ """UniProt entry name (``ZN143_HUMAN``) -> gene symbol (``ZNF143``) from the HOCOMOCO v12 annotation."""
187
+ import json
188
+
189
+ out = {}
190
+ for line in Path(annotation_jsonl).read_text(encoding="utf-8").splitlines():
191
+ if not line.strip():
192
+ continue
193
+ human = ((json.loads(line).get("masterlist_info") or {}).get("species") or {}).get("HUMAN") or {}
194
+ if human.get("uniprot_id") and human.get("gene_symbol"):
195
+ out[human["uniprot_id"].upper()] = human["gene_symbol"].upper()
196
+ return out
197
+
198
+
199
+ def by_tf(motifs: list[Motif]) -> dict[str, list[Motif]]:
200
+ out: dict[str, list[Motif]] = {}
201
+ for m in motifs:
202
+ out.setdefault(m.tf, []).append(m)
203
+ return out
asebind/mpra.py ADDED
@@ -0,0 +1,94 @@
1
+ """Allelic skew from MPRA counts (I-23, truth set for I-37).
2
+
3
+ Input: a counts table with one row per oligo (one allele of one variant in one orientation) and one column per
4
+ library: plasmid (DNA) replicates and RNA replicates. Libraries are scaled to counts per million.
5
+
6
+ activity(oligo, rep) = log2(RNA cpm in rep + 1) - log2(mean plasmid cpm + 1)
7
+ skew(pair, rep) = activity(allele 2, rep) - activity(allele 1, rep)
8
+
9
+ A pair is tested when both alleles have a mean plasmid count >= ``min_plasmid``. It is *active* when the mean
10
+ activity of its two alleles is above 0 (one-sample t-test over replicates, BH FDR < ``active_fdr``), and an
11
+ *emVar* when it is active and its skew differs from 0 (t-test over replicates, BH FDR < ``skew_fdr``). With
12
+ several orientations of one variant the smallest skew P value is kept, times the number of orientations.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ from scipy import stats
20
+
21
+
22
+ def bh(p: np.ndarray) -> np.ndarray:
23
+ """Benjamini-Hochberg adjusted P values (NaN kept)."""
24
+ p = np.asarray(p, float)
25
+ out = np.full_like(p, np.nan)
26
+ ok = ~np.isnan(p)
27
+ q = p[ok]
28
+ n = len(q)
29
+ if n == 0:
30
+ return out
31
+ order = np.argsort(q)
32
+ adj = q[order] * n / np.arange(1, n + 1)
33
+ adj = np.minimum.accumulate(adj[::-1])[::-1]
34
+ res = np.empty(n)
35
+ res[order] = np.clip(adj, 0, 1)
36
+ out[ok] = res
37
+ return out
38
+
39
+
40
+ def skew(
41
+ counts: pd.DataFrame,
42
+ pairs: pd.DataFrame,
43
+ plasmid: list[str],
44
+ rna: list[str],
45
+ min_plasmid: float = 20.0,
46
+ active_fdr: float = 0.01,
47
+ skew_fdr: float = 0.1,
48
+ ) -> pd.DataFrame:
49
+ """``counts``: index = oligo id, columns include ``plasmid`` and ``rna``. ``pairs``: variant, orientation,
50
+ oligo1, oligo2 (allele 1 and allele 2 of that variant in that orientation). One row per variant."""
51
+ cpm = counts[plasmid + rna].div(counts[plasmid + rna].sum(axis=0), axis=1) * 1e6
52
+ dna_mean = cpm[plasmid].mean(axis=1)
53
+ act = np.log2(cpm[rna] + 1).sub(np.log2(dna_mean + 1), axis=0)
54
+ raw_dna = counts[plasmid].mean(axis=1)
55
+ rows = []
56
+ for r in pairs.itertuples(index=False):
57
+ if r.oligo1 not in counts.index or r.oligo2 not in counts.index:
58
+ continue
59
+ if min(raw_dna[r.oligo1], raw_dna[r.oligo2]) < min_plasmid:
60
+ continue
61
+ a1, a2 = act.loc[r.oligo1].to_numpy(), act.loc[r.oligo2].to_numpy()
62
+ sk = a2 - a1
63
+ mean_act = (a1 + a2) / 2
64
+ rows.append(
65
+ {
66
+ "variant": r.variant,
67
+ "orientation": r.orientation,
68
+ "activity": mean_act.mean(),
69
+ "p_active": stats.ttest_1samp(mean_act, 0, alternative="greater").pvalue,
70
+ "log2_skew": sk.mean(),
71
+ "p_skew": stats.ttest_1samp(sk, 0).pvalue if np.any(sk != sk[0]) else 1.0,
72
+ }
73
+ )
74
+ o = pd.DataFrame(rows)
75
+ if o.empty:
76
+ return o
77
+ g = o.groupby("variant")
78
+ best = o.loc[g["p_skew"].idxmin()].set_index("variant")
79
+ per = pd.DataFrame(
80
+ {
81
+ "orientations": g.size(),
82
+ "activity": g["activity"].max(),
83
+ "p_active": g["p_active"].min(),
84
+ "log2_skew": best["log2_skew"],
85
+ "p_skew": (best["p_skew"] * g.size()).clip(upper=1.0),
86
+ }
87
+ ).reset_index()
88
+ per["fdr_active"] = bh(per["p_active"].to_numpy())
89
+ per["active"] = per["fdr_active"] < active_fdr
90
+ per["fdr_skew"] = np.nan
91
+ a = per["active"].to_numpy()
92
+ per.loc[a, "fdr_skew"] = bh(per.loc[a, "p_skew"].to_numpy())
93
+ per["emvar"] = per["active"] & (per["fdr_skew"] < skew_fdr)
94
+ return per
asebind/predict.py ADDED
@@ -0,0 +1,163 @@
1
+ """``asebind predict``: variants -> allele checks -> features per (variant, TF) -> calibrated P(gain/loss/none).
2
+
3
+ The effect allele is the risk allele when one is given (``direction`` = ``risk_vs_other``), else the alt allele.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Callable, Sequence
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from asebind.io.variants import build_check, check_alleles, read_variants
15
+ from asebind.model import features as F
16
+ from asebind.model.classifier import LABELS, BindingModel
17
+ from asebind.model.context import load_context, tier
18
+ from asebind.resources.genome import Fasta
19
+
20
+ CALL_MIN_P = 0.5 # a gain/loss call needs at least this calibrated probability
21
+
22
+
23
+ def add_model_features(
24
+ model: BindingModel,
25
+ X: pd.DataFrame,
26
+ rows: pd.DataFrame,
27
+ seqs: list[str],
28
+ ctx,
29
+ workers: int = 1,
30
+ log: Callable[[str], None] = print,
31
+ ) -> pd.DataFrame:
32
+ """Add the optional feature sets the model was trained with (I-35 other TFs' motifs).
33
+
34
+ The other TFs' motifs are scanned with every motif in the context, as in training (not only the chosen TFs).
35
+ Ancestral (I-32) and conservation (I-31) features are not computed here: a model that needs them is refused."""
36
+ need = set(model.features)
37
+ unsupported = need & set(F.ANCESTRAL_FEATURES + F.CONSERVATION_FEATURES)
38
+ if unsupported:
39
+ raise ValueError(
40
+ f"model needs features predict does not compute yet: {', '.join(sorted(unsupported))}"
41
+ )
42
+ if need & set(F.OTHER_FEATURES):
43
+ from asebind.model import other_motifs
44
+
45
+ oth = other_motifs.build(rows, seqs, ctx.motifs, workers=workers, log=log)
46
+ X = pd.concat([X.drop(columns=[c for c in oth.columns if c in X]), oth.set_index(X.index)], axis=1)
47
+ return X
48
+
49
+
50
+ def run(
51
+ variants: Path,
52
+ genome_fasta: Path,
53
+ resources_root: Path,
54
+ model_path: Path,
55
+ out: Path,
56
+ tfs: str | Sequence[str] = "all",
57
+ exclude: Sequence[str] = (),
58
+ risk_allele_column: str | None = None,
59
+ pwm_only_tier: bool = True,
60
+ workers: int = 1,
61
+ log: Callable[[str], None] = print,
62
+ ) -> dict[str, Path]:
63
+ out.mkdir(parents=True, exist_ok=True)
64
+ model = BindingModel.load(model_path)
65
+ ctx = load_context(resources_root)
66
+ v = read_variants(variants, risk_allele_column)
67
+ with Fasta(genome_fasta) as g:
68
+ checked = check_alleles(v, g)
69
+ bc = build_check(checked)
70
+ log(f"variants {bc['variants']}, matching the genome {bc['matching_genome']} ({bc['fraction']:.1%})")
71
+ if not bc["build_ok"]:
72
+ log("WARNING: fewer than 90% of variants match this genome; is the build right?")
73
+ usable = checked[checked["allele_check"] != "ref_mismatch"].reset_index(drop=True)
74
+ # effect allele: the risk allele when it is the reference base, else alt
75
+ risk_ref = usable["direction"].eq("risk_is_ref").to_numpy()
76
+ usable["base_allele"] = np.where(risk_ref, usable["alt"], usable["ref"])
77
+ usable["effect_allele"] = np.where(risk_ref, usable["ref"], usable["alt"])
78
+ usable["direction"] = np.where(risk_ref, "risk_vs_other", usable["direction"])
79
+ seqs, _ = F.flanks(g, usable)
80
+
81
+ trained = set(model.info.get("tfs", []))
82
+ if tfs == "all" or tfs == ["all"]:
83
+ chosen = sorted(set(ctx.motifs) & trained) if trained else sorted(ctx.motifs)
84
+ else:
85
+ chosen = sorted({t.upper() for t in ([tfs] if isinstance(tfs, str) else tfs)})
86
+ chosen = [t for t in chosen if t not in {e.upper() for e in exclude}]
87
+ tiers = {t: tier(ctx, t) for t in chosen}
88
+ missing = [t for t, tr in tiers.items() if tr == "none"]
89
+ if missing:
90
+ log(f"no motif for {len(missing)} TF(s), skipped: {', '.join(missing[:20])}")
91
+ chosen = [t for t in chosen if tiers[t] != "none" and (pwm_only_tier or tiers[t] == "pbm+pwm")]
92
+ log(f"{len(usable)} variants x {len(chosen)} TFs")
93
+
94
+ rows = usable.loc[usable.index.repeat(len(chosen))].reset_index(drop=True)
95
+ rows["tf"] = np.tile(chosen, len(usable))
96
+ rep_seqs = [s for s in seqs for _ in chosen]
97
+ feat_rows = rows.assign(ref=rows["base_allele"], alt=rows["effect_allele"])
98
+ X = F.build(feat_rows, rep_seqs, ctx, workers=workers, log=log)
99
+ X = add_model_features(model, X, feat_rows, rep_seqs, ctx, workers=workers, log=log)
100
+ p = model.predict_proba(X)
101
+ res = rows[
102
+ [
103
+ "id",
104
+ "chrom",
105
+ "pos",
106
+ "ref",
107
+ "alt",
108
+ "base_allele",
109
+ "effect_allele",
110
+ "direction",
111
+ "allele_check",
112
+ "strand_ambiguous",
113
+ "tf",
114
+ ]
115
+ ].copy()
116
+ res["tier"] = res["tf"].map(tiers)
117
+ for c, lab in enumerate(LABELS):
118
+ res[f"p_{lab}"] = p[:, c]
119
+ best = p.argmax(1)
120
+ res["call"] = np.where((best < 2) & (p.max(1) >= CALL_MIN_P), np.array(LABELS)[best], "none")
121
+ for k in ("lp_ref", "lp_alt", "d_lp", "lp_best", "e_max_ref", "e_max_alt"):
122
+ res[k] = X[k].to_numpy()
123
+ res = res.rename(
124
+ columns={
125
+ "lp_ref": "motif_lp_base",
126
+ "lp_alt": "motif_lp_effect",
127
+ "e_max_ref": "escore_base",
128
+ "e_max_alt": "escore_effect",
129
+ }
130
+ )
131
+ res["_called"] = res["call"].ne("none")
132
+ res = res.sort_values(["id", "_called", "p_none"], ascending=[True, False, True]).drop(columns="_called")
133
+
134
+ paths = {
135
+ "predictions": out / "asebind_predictions.tsv",
136
+ "variants": out / "asebind_variants.tsv",
137
+ "xlsx": out / "asebind_predictions.xlsx",
138
+ }
139
+ res.to_csv(paths["predictions"], sep="\t", index=False, float_format="%.4g")
140
+ checked.to_csv(paths["variants"], sep="\t", index=False)
141
+ calls = res[res["call"] != "none"]
142
+ with pd.ExcelWriter(paths["xlsx"]) as xw:
143
+ pd.DataFrame(
144
+ [
145
+ (
146
+ "What",
147
+ "ASEbind predictions: calibrated P(gain/loss/none) of TF binding for the effect allele.",
148
+ ),
149
+ (
150
+ "Effect allele",
151
+ "Risk allele if a risk column was given, else ALT; base allele is the other one.",
152
+ ),
153
+ ("Call", f"gained/lost when that probability is the largest and >= {CALL_MIN_P}; else none."),
154
+ ("Tier", "pbm+pwm: PBM E-scores and PWMs; pwm: PWMs only (lower evidence)."),
155
+ ("Model", str(model_path)),
156
+ ("Build check", f"{bc['matching_genome']}/{bc['variants']} variants match the genome"),
157
+ ],
158
+ columns=["Item", "Meaning"],
159
+ ).to_excel(xw, sheet_name="Read me", index=False)
160
+ calls.to_excel(xw, sheet_name="Calls", index=False)
161
+ res.to_excel(xw, sheet_name="All TFs", index=False)
162
+ checked.to_excel(xw, sheet_name="Variants", index=False)
163
+ return paths
@@ -0,0 +1 @@
1
+ """External resources: motif collections, PBM E-scores, genomes, allele-specific binding calls (Phase 2b)."""
@@ -0,0 +1,74 @@
1
+ """Ancestral alleles (I-32) from the Ensembl EPO primate reconstruction, one FASTA per chromosome.
2
+
3
+ Case carries confidence: upper case = high confidence, lower case = low confidence; N, -, . = unknown.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from asebind.resources.fetch import FetchError, manifest
15
+ from asebind.resources.genome import Fasta
16
+
17
+ _CHROM = re.compile(r"homo_sapiens_ancestor_([0-9XYMT]+)\.fa$")
18
+
19
+
20
+ class Ancestral:
21
+ def __init__(self, folder: str | Path) -> None:
22
+ self.files: dict[str, Path] = {}
23
+ for p in Path(folder).rglob("homo_sapiens_ancestor_*.fa"):
24
+ m = _CHROM.search(p.name)
25
+ if m:
26
+ self.files[m.group(1)] = p
27
+ if not self.files:
28
+ raise FetchError(f"no homo_sapiens_ancestor_<chrom>.fa under {folder}")
29
+ self._open: dict[str, Fasta] = {}
30
+
31
+ @classmethod
32
+ def from_resources(cls, root: str | Path) -> Ancestral:
33
+ if manifest("ancestral_grch38", Path(root)) is None:
34
+ raise FetchError(f"ancestral_grch38: not fetched under {root} (run `asebind fetch ancestral_grch38`)")
35
+ return cls(Path(root) / "ancestral_grch38")
36
+
37
+ def base(self, chrom: str, pos1: int) -> str:
38
+ """Ancestral base at a 1-based GRCh38 position, case kept; '' when the chromosome has no file."""
39
+ c = str(chrom).removeprefix("chr")
40
+ c = "MT" if c == "M" else c
41
+ if c not in self.files:
42
+ return ""
43
+ if c not in self._open:
44
+ self._open[c] = Fasta(self.files[c])
45
+ fa = self._open[c]
46
+ name = next(iter(fa.index))
47
+ return fa.fetch(name, pos1 - 1, pos1, upper=False)
48
+
49
+ def close(self) -> None:
50
+ for f in self._open.values():
51
+ f.close()
52
+ self._open.clear()
53
+
54
+ def __enter__(self) -> Ancestral:
55
+ return self
56
+
57
+ def __exit__(self, *exc: object) -> None:
58
+ self.close()
59
+
60
+
61
+ def ancestral_features(anc: Ancestral, rows: pd.DataFrame) -> pd.DataFrame:
62
+ """ANCESTRAL_FEATURES (see ``features``) for rows with chrom, pos (1-based GRCh38), ref, alt."""
63
+ known = np.zeros(len(rows))
64
+ direction = np.zeros(len(rows))
65
+ for i, (c, p, r, a) in enumerate(zip(rows["chrom"], rows["pos"], rows["ref"], rows["alt"], strict=True)):
66
+ b = anc.base(c, int(p))
67
+ if not b or b.upper() not in "ACGT":
68
+ continue
69
+ w = 1.0 if b.isupper() else 0.5
70
+ if b.upper() == str(r).upper():
71
+ known[i], direction[i] = w, w # ref ancestral: alt is the derived allele
72
+ elif b.upper() == str(a).upper():
73
+ known[i], direction[i] = w, -w
74
+ return pd.DataFrame({"anc_known": known, "anc_dir": direction}, index=rows.index)
@@ -0,0 +1,77 @@
1
+ """Conservation (I-31): base-wise phyloP from bigWig tracks, used as a weight, never as a direction.
2
+
3
+ Tracks (GRCh38): UCSC phyloP 100-way vertebrates and the Zoonomia 241-mammal Cactus phyloP. Positive = conserved,
4
+ negative = fast-evolving. Reading bigWig needs the optional ``pyBigWig`` package (``pip install asebind[evolution]``).
5
+
6
+ Features (symmetric, a swap leaves them unchanged), each for both tracks (prefix p100_ / p241_):
7
+ - *_snp: phyloP at the SNP; *_w7 / *_w21: mean over +-3 / +-10 bases.
8
+ One antisymmetric feature ties conservation to the motif change: cons_d_lp = d_lp x max(p241_snp, 0)
9
+ (falls back to p100 when the 241-way value is missing).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ from asebind.resources.fetch import FetchError, resource_file
20
+
21
+ TRACKS = {"p100": ("phylop100_hg38", "*.bw"), "p241": ("zoonomia241_phylop_hg38", "*.bw")}
22
+ WINDOWS = {"w7": 3, "w21": 10}
23
+
24
+
25
+ def open_tracks(root: str | Path) -> dict[str, object]:
26
+ try:
27
+ import pyBigWig
28
+ except ImportError as e: # pragma: no cover - depends on the environment
29
+ raise FetchError("conservation features need pyBigWig: pip install 'asebind[evolution]'") from e
30
+ out = {}
31
+ for prefix, (name, pattern) in TRACKS.items():
32
+ try:
33
+ out[prefix] = pyBigWig.open(str(resource_file(name, Path(root), pattern)))
34
+ except FetchError:
35
+ continue
36
+ if not out:
37
+ raise FetchError(f"no conservation track under {root}: run `asebind fetch {' '.join(n for n, _ in TRACKS.values())}`")
38
+ return out
39
+
40
+
41
+ def _values(bw, chrom: str, start: int, end: int) -> np.ndarray:
42
+ """phyloP over [start, end) (0-based), NaN where the track has no value or the chromosome is absent."""
43
+ chroms = bw.chroms()
44
+ c = chrom if chrom in chroms else ("chr" + chrom if "chr" + chrom in chroms else None)
45
+ if c is None:
46
+ return np.full(end - start, np.nan)
47
+ start, end = max(start, 0), min(end, chroms[c])
48
+ return np.asarray(bw.values(c, start, end, numpy=True), dtype=float)
49
+
50
+
51
+ def conservation_features(tracks: dict[str, object], rows: pd.DataFrame) -> pd.DataFrame:
52
+ """CONSERVATION_FEATURES for rows with chrom, pos (1-based GRCh38) and, for cons_d_lp, d_lp."""
53
+ n = len(rows)
54
+ half = max(WINDOWS.values())
55
+ # each distinct position read once, in genome order
56
+ pos = pd.DataFrame({"c": rows["chrom"].astype(str).to_numpy(), "p": rows["pos"].astype(int).to_numpy()})
57
+ uniq = pos.drop_duplicates().sort_values(["c", "p"]).reset_index(drop=True)
58
+ row_u = pos.merge(uniq.reset_index(), on=["c", "p"], how="left")["index"].to_numpy()
59
+ u: dict[str, np.ndarray] = {}
60
+ for prefix in TRACKS:
61
+ u[f"{prefix}_snp"] = np.full(len(uniq), np.nan)
62
+ for w in WINDOWS:
63
+ u[f"{prefix}_{w}"] = np.full(len(uniq), np.nan)
64
+ for prefix, bw in tracks.items():
65
+ for i, (c, p) in enumerate(zip(uniq["c"], uniq["p"], strict=True)):
66
+ v = _values(bw, c, p - 1 - half, p + half)
67
+ if len(v) != 2 * half + 1: # chromosome end: leave NaN
68
+ continue
69
+ u[f"{prefix}_snp"][i] = v[half]
70
+ for w, k in WINDOWS.items():
71
+ seg = v[half - k : half + k + 1]
72
+ u[f"{prefix}_{w}"][i] = np.nanmean(seg) if np.isfinite(seg).any() else np.nan
73
+ f = {k: a[row_u] for k, a in u.items()}
74
+ cons = np.where(np.isfinite(f["p241_snp"]), f["p241_snp"], f["p100_snp"])
75
+ d = rows["d_lp"].to_numpy(float) if "d_lp" in rows else np.full(n, np.nan)
76
+ f["cons_d_lp"] = d * np.clip(np.nan_to_num(cons), 0, None)
77
+ return pd.DataFrame(f, index=rows.index)