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.
- asebind/__init__.py +3 -0
- asebind/__main__.py +4 -0
- asebind/ase/__init__.py +1 -0
- asebind/ase/betabinom.py +173 -0
- asebind/benchmark/__init__.py +1 -0
- asebind/benchmark/asbdata.py +107 -0
- asebind/benchmark/clean.py +38 -0
- asebind/benchmark/features.py +71 -0
- asebind/benchmark/metrics.py +69 -0
- asebind/benchmark/models.py +151 -0
- asebind/benchmark/retest.py +183 -0
- asebind/benchmark/splits.py +61 -0
- asebind/cli.py +302 -0
- asebind/cli_model.py +539 -0
- asebind/config.py +340 -0
- asebind/data/asebind.example.yaml +56 -0
- asebind/finemap.py +86 -0
- asebind/haplotype.py +141 -0
- asebind/io/__init__.py +1 -0
- asebind/io/variants.py +107 -0
- asebind/model/__init__.py +1 -0
- asebind/model/adastra.py +113 -0
- asebind/model/classifier.py +122 -0
- asebind/model/context.py +60 -0
- asebind/model/features.py +201 -0
- asebind/model/other_motifs.py +168 -0
- asebind/model/train.py +331 -0
- asebind/motifs/__init__.py +1 -0
- asebind/motifs/escore.py +112 -0
- asebind/motifs/pwm.py +203 -0
- asebind/mpra.py +94 -0
- asebind/predict.py +163 -0
- asebind/resources/__init__.py +1 -0
- asebind/resources/ancestral.py +74 -0
- asebind/resources/conservation.py +77 -0
- asebind/resources/fetch.py +227 -0
- asebind/resources/genome.py +93 -0
- asebind/resources/registry.py +304 -0
- asebind/runrecord.py +108 -0
- asebind/tools.py +170 -0
- asebind-0.1.0.dist-info/METADATA +138 -0
- asebind-0.1.0.dist-info/RECORD +45 -0
- asebind-0.1.0.dist-info/WHEEL +4 -0
- asebind-0.1.0.dist-info/entry_points.txt +2 -0
- asebind-0.1.0.dist-info/licenses/LICENSE +21 -0
asebind/__init__.py
ADDED
asebind/__main__.py
ADDED
asebind/ase/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Allele-specific expression tests (Phase 5, I-21, I-22)."""
|
asebind/ase/betabinom.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Beta-binomial test of allelic imbalance between the two copies of a gene (cases vs controls).
|
|
2
|
+
|
|
3
|
+
Data: per person, ``k`` reads on the copy of interest (e.g. the risk copy) out of ``n`` reads on both copies,
|
|
4
|
+
summed over that person's usable heterozygous SNVs. Cases (heterozygous for the variant) have mean fraction p;
|
|
5
|
+
controls (homozygous for it, with heterozygous SNVs elsewhere in the gene) have p = 0.5 and pin the
|
|
6
|
+
overdispersion. One rho is shared by cases and controls of a group.
|
|
7
|
+
|
|
8
|
+
logL(k, n | p, rho) = ln C(n, k) + ln B(k + a, n - k + b) - ln B(a, b),
|
|
9
|
+
a = p (1 - rho) / rho, b = (1 - p)(1 - rho) / rho
|
|
10
|
+
|
|
11
|
+
p-hat maximises the profile likelihood (rho refitted at every p, on a grid then refined); the test of 50:50 is a
|
|
12
|
+
likelihood-ratio test with 1 df; the 95% CI is the profile interval (logL >= max - 1.92).
|
|
13
|
+
|
|
14
|
+
Reference-allele bias (I-22): at the SNV level a per-observation null fraction ``q`` (the share of reads expected
|
|
15
|
+
on the copy of interest when there is no imbalance, e.g. estimated from controls' REF share at that SNV) enters
|
|
16
|
+
as an offset: mean = expit(logit(p) + logit(q)).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import pandas as pd
|
|
25
|
+
from scipy import stats
|
|
26
|
+
from scipy.optimize import minimize_scalar
|
|
27
|
+
from scipy.special import betaln, expit, gammaln, logit
|
|
28
|
+
|
|
29
|
+
LOGIT_RHO_BOUNDS = (-12.0, 4.0)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def loglik(k: np.ndarray, n: np.ndarray, mean: np.ndarray | float, rho: float) -> float:
|
|
33
|
+
k, n = np.asarray(k, float), np.asarray(n, float)
|
|
34
|
+
mean = np.clip(np.broadcast_to(mean, k.shape), 1e-9, 1 - 1e-9)
|
|
35
|
+
s = (1 - rho) / rho
|
|
36
|
+
a, b = mean * s, (1 - mean) * s
|
|
37
|
+
lc = gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1)
|
|
38
|
+
return float(np.sum(lc + betaln(k + a, n - k + b) - betaln(a, b)))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class Data:
|
|
43
|
+
k_case: np.ndarray
|
|
44
|
+
n_case: np.ndarray
|
|
45
|
+
k_ctrl: np.ndarray
|
|
46
|
+
n_ctrl: np.ndarray
|
|
47
|
+
q_case: np.ndarray | None = None # null fraction per case observation (reference-bias offset)
|
|
48
|
+
q_ctrl: np.ndarray | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _means(d: Data, p: float) -> tuple[np.ndarray, np.ndarray]:
|
|
52
|
+
mc = (
|
|
53
|
+
np.full(len(d.k_case), p)
|
|
54
|
+
if d.q_case is None
|
|
55
|
+
else expit(logit(p) + logit(np.clip(d.q_case, 1e-06, 1 - 1e-06)))
|
|
56
|
+
)
|
|
57
|
+
mk = np.full(len(d.k_ctrl), 0.5) if d.q_ctrl is None else np.clip(d.q_ctrl, 1e-6, 1 - 1e-6)
|
|
58
|
+
return mc, mk
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def profile(d: Data, p: float, rho: float | None = None) -> tuple[float, float]:
|
|
62
|
+
"""(max over rho of logL at this p, that rho); with ``rho`` given, logL at that rho."""
|
|
63
|
+
mc, mk = _means(d, p)
|
|
64
|
+
|
|
65
|
+
def nll(lr: float) -> float:
|
|
66
|
+
r = float(expit(lr))
|
|
67
|
+
return -(loglik(d.k_case, d.n_case, mc, r) + loglik(d.k_ctrl, d.n_ctrl, mk, r))
|
|
68
|
+
|
|
69
|
+
if rho is not None:
|
|
70
|
+
return -nll(float(logit(rho))), rho
|
|
71
|
+
res = minimize_scalar(nll, bounds=LOGIT_RHO_BOUNDS, method="bounded", options={"xatol": 1e-6})
|
|
72
|
+
return -float(res.fun), float(expit(res.x))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class Fit:
|
|
77
|
+
p: float
|
|
78
|
+
rho: float
|
|
79
|
+
rho0: float
|
|
80
|
+
loglik: float
|
|
81
|
+
loglik0: float
|
|
82
|
+
chi2: float
|
|
83
|
+
pvalue: float
|
|
84
|
+
ci_low: float
|
|
85
|
+
ci_high: float
|
|
86
|
+
grid: pd.DataFrame
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def fold(self) -> float:
|
|
90
|
+
return self.p / (1 - self.p)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def fit(d: Data, step: float = 0.005, lo: float = 0.02, hi: float = 0.98, rho: float | None = None) -> Fit:
|
|
94
|
+
grid = np.round(np.arange(lo, hi + step / 2, step), 6)
|
|
95
|
+
prof = [profile(d, float(p), rho) for p in grid]
|
|
96
|
+
ll = np.array([x[0] for x in prof])
|
|
97
|
+
i = int(ll.argmax())
|
|
98
|
+
a, b = grid[max(i - 1, 0)], grid[min(i + 1, len(grid) - 1)]
|
|
99
|
+
res = minimize_scalar(
|
|
100
|
+
lambda p: -profile(d, p, rho)[0], bounds=(a, b), method="bounded", options={"xatol": 1e-7}
|
|
101
|
+
)
|
|
102
|
+
p_hat = float(res.x) if -res.fun >= ll[i] else float(grid[i])
|
|
103
|
+
ll_hat, rho_hat = profile(d, p_hat, rho)
|
|
104
|
+
ll0, rho0 = profile(d, 0.5, rho)
|
|
105
|
+
chi2 = max(0.0, 2 * (ll_hat - ll0))
|
|
106
|
+
inside = grid[ll >= ll_hat - stats.chi2.ppf(0.95, 1) / 2]
|
|
107
|
+
return Fit(
|
|
108
|
+
p=p_hat,
|
|
109
|
+
rho=rho_hat,
|
|
110
|
+
rho0=rho0,
|
|
111
|
+
loglik=ll_hat,
|
|
112
|
+
loglik0=ll0,
|
|
113
|
+
chi2=chi2,
|
|
114
|
+
pvalue=float(stats.chi2.sf(chi2, 1)),
|
|
115
|
+
ci_low=float(inside.min()),
|
|
116
|
+
ci_high=float(inside.max()),
|
|
117
|
+
grid=pd.DataFrame({"p": grid, "loglik": ll, "rho": [x[1] for x in prof]}),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def per_person(counts: pd.DataFrame, min_snv_reads: int = 5, min_person_reads: int = 10) -> pd.DataFrame:
|
|
122
|
+
"""Sum a long table (sample, k, n [, population, role]) over SNVs: SNVs with < ``min_snv_reads`` reads and
|
|
123
|
+
people with < ``min_person_reads`` reads are dropped."""
|
|
124
|
+
c = counts[counts["n"] >= min_snv_reads]
|
|
125
|
+
keys = [x for x in ("sample", "population", "role") if x in c.columns]
|
|
126
|
+
g = c.groupby(keys, as_index=False)[["k", "n"]].sum()
|
|
127
|
+
g = g[g["n"] >= min_person_reads].reset_index(drop=True)
|
|
128
|
+
g["fraction"] = g["k"] / g["n"]
|
|
129
|
+
g["log2_ratio"] = np.log2((g["k"] + 0.5) / (g["n"] - g["k"] + 0.5))
|
|
130
|
+
return g
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_group(people: pd.DataFrame, rho: float | None = None, step: float = 0.005) -> dict:
|
|
134
|
+
"""Beta-binomial LRT plus the direction (sign) test and Wilcoxon on the cases' log2 ratios."""
|
|
135
|
+
case = people[people["role"] == "case"]
|
|
136
|
+
ctrl = people[people["role"] == "control"]
|
|
137
|
+
d = Data(case["k"].to_numpy(), case["n"].to_numpy(), ctrl["k"].to_numpy(), ctrl["n"].to_numpy())
|
|
138
|
+
f = fit(d, step=step, rho=rho)
|
|
139
|
+
higher = int((case["k"] > case["n"] - case["k"]).sum())
|
|
140
|
+
out = {
|
|
141
|
+
"cases": len(case),
|
|
142
|
+
"controls": len(ctrl),
|
|
143
|
+
"case_reads_copy": int(case["k"].sum()),
|
|
144
|
+
"case_reads_other": int((case["n"] - case["k"]).sum()),
|
|
145
|
+
"pooled_share": float(case["k"].sum() / case["n"].sum()) if len(case) else np.nan,
|
|
146
|
+
"p_hat": f.p,
|
|
147
|
+
"rho_hat": f.rho,
|
|
148
|
+
"rho0": f.rho0,
|
|
149
|
+
"chi2": f.chi2,
|
|
150
|
+
"p_value": f.pvalue,
|
|
151
|
+
"ci_low": f.ci_low,
|
|
152
|
+
"ci_high": f.ci_high,
|
|
153
|
+
"fold": f.fold,
|
|
154
|
+
"cases_copy_higher": higher,
|
|
155
|
+
"p_direction": float(stats.binomtest(higher, len(case), 0.5).pvalue) if len(case) else np.nan,
|
|
156
|
+
}
|
|
157
|
+
lr = (
|
|
158
|
+
case["log2_ratio"].to_numpy()
|
|
159
|
+
if "log2_ratio" in case
|
|
160
|
+
else np.log2((case["k"] + 0.5) / (case["n"] - case["k"] + 0.5))
|
|
161
|
+
)
|
|
162
|
+
out["p_wilcoxon"] = float(stats.wilcoxon(lr).pvalue) if len(lr) > 1 and np.any(lr != 0) else np.nan
|
|
163
|
+
return out
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def run(counts: pd.DataFrame, by: str | None = "population", **kw) -> pd.DataFrame:
|
|
167
|
+
"""All people together (``ALL``), then each value of ``by`` (each group with its own fitted rho)."""
|
|
168
|
+
people = per_person(counts, kw.pop("min_snv_reads", 5), kw.pop("min_person_reads", 10))
|
|
169
|
+
rows = [{"group": "ALL", **test_group(people, **kw)}]
|
|
170
|
+
if by and by in people.columns:
|
|
171
|
+
for g, d in people.groupby(by):
|
|
172
|
+
rows.append({"group": str(g), **test_group(d, **kw)})
|
|
173
|
+
return pd.DataFrame(rows)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Honest re-test of SNPeBoT-style binding-change models (benchmarks/REPORT.md)."""
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Read the SNPeBoT processed ASB table and its sequence file into named columns.
|
|
2
|
+
|
|
3
|
+
Layout of ``Processed_ASB_data.csv`` (no header; Data_and_Training/README.txt, checked on the file 2026-11-30):
|
|
4
|
+
columns 1-15 windowed E-scores of the reference allele, 16-30 of the alternate allele; 31 motif-change indicator;
|
|
5
|
+
32-39 / 40-47 non-windowed E-scores ref / alt (the eight 8-mers over the SNP); 48 label (gained / lost / none);
|
|
6
|
+
49-50 best FIMO p-value ref / alt; 51 ID ``chrom-pos-ref-alt-TF``.
|
|
7
|
+
|
|
8
|
+
The file is the authors' data: read it for analysis, never copy it into this repository.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
W_REF = [f"w_ref_{i}" for i in range(1, 16)]
|
|
19
|
+
W_ALT = [f"w_alt_{i}" for i in range(1, 16)]
|
|
20
|
+
NW_REF = [f"nw_ref_{i}" for i in range(1, 9)]
|
|
21
|
+
NW_ALT = [f"nw_alt_{i}" for i in range(1, 9)]
|
|
22
|
+
COLUMNS = [*W_REF, *W_ALT, "motif_change", *NW_REF, *NW_ALT, "label", "p_ref", "p_alt", "id"]
|
|
23
|
+
LABELS = ("gained", "lost", "none")
|
|
24
|
+
SWAP_LABEL = {"gained": "lost", "lost": "gained", "none": "none"}
|
|
25
|
+
|
|
26
|
+
SEQ_COLUMNS = [
|
|
27
|
+
"chrom",
|
|
28
|
+
"pos",
|
|
29
|
+
"ref",
|
|
30
|
+
"alt",
|
|
31
|
+
"cell_line",
|
|
32
|
+
"tf_raw",
|
|
33
|
+
"p_ref_asb",
|
|
34
|
+
"p_alt_asb",
|
|
35
|
+
"flag",
|
|
36
|
+
"ratio",
|
|
37
|
+
"region",
|
|
38
|
+
"seq_ref",
|
|
39
|
+
"seq_alt",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def normalise_tf(name: str) -> str:
|
|
44
|
+
"""One spelling per TF (``cebpb`` and ``CEBPB`` are the same factor, I-1/I-9)."""
|
|
45
|
+
return name.strip().upper()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_processed(path: str | Path) -> pd.DataFrame:
|
|
49
|
+
df = pd.read_csv(path, header=None, names=COLUMNS, skipinitialspace=True, dtype={"label": str, "id": str})
|
|
50
|
+
if df.shape[1] != len(COLUMNS):
|
|
51
|
+
raise ValueError(f"{path}: expected {len(COLUMNS)} columns, got {df.shape[1]}")
|
|
52
|
+
df["label"] = df["label"].str.strip().str.lower()
|
|
53
|
+
bad = sorted(set(df["label"]) - set(LABELS))
|
|
54
|
+
if bad:
|
|
55
|
+
raise ValueError(f"{path}: unexpected labels {bad}")
|
|
56
|
+
parts = df["id"].str.strip().str.split("-", n=4, expand=True)
|
|
57
|
+
if parts.shape[1] != 5 or parts.isna().any().any():
|
|
58
|
+
raise ValueError(f"{path}: IDs must look like chrom-pos-ref-alt-TF")
|
|
59
|
+
df["id"] = df["id"].str.strip()
|
|
60
|
+
df["chrom"] = parts[0]
|
|
61
|
+
df["pos"] = parts[1].astype(int)
|
|
62
|
+
df["ref"] = parts[2].str.upper()
|
|
63
|
+
df["alt"] = parts[3].str.upper()
|
|
64
|
+
df["tf_raw"] = parts[4]
|
|
65
|
+
df["tf"] = df["tf_raw"].map(normalise_tf)
|
|
66
|
+
df["snp"] = df["chrom"] + ":" + df["pos"].astype(str) + ":" + df["ref"] + ":" + df["alt"]
|
|
67
|
+
return df
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def read_sequences(path: str | Path) -> pd.DataFrame:
|
|
71
|
+
seq = pd.read_csv(path, sep="\t", header=None, names=SEQ_COLUMNS, dtype=str)
|
|
72
|
+
seq["pos"] = seq["pos"].astype(int)
|
|
73
|
+
seq["tf"] = seq["tf_raw"].map(normalise_tf)
|
|
74
|
+
seq["cell_line"] = seq["cell_line"].str.strip().str.lower()
|
|
75
|
+
return seq
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def attach_cell_lines(df: pd.DataFrame, seq: pd.DataFrame) -> pd.DataFrame:
|
|
79
|
+
"""Add ``cell_line``: the single named cell line of the row's (SNP, TF), else ``unknown`` / ``multiple``.
|
|
80
|
+
|
|
81
|
+
``placeholder`` in the sequence file means no cell line was recorded.
|
|
82
|
+
"""
|
|
83
|
+
key = ["chrom", "pos", "ref", "alt", "tf"]
|
|
84
|
+
named = seq[seq["cell_line"] != "placeholder"].drop_duplicates([*key, "cell_line"])
|
|
85
|
+
per = (
|
|
86
|
+
named.groupby(key)["cell_line"].agg(lambda s: s.iloc[0] if len(s) == 1 else "multiple").reset_index()
|
|
87
|
+
)
|
|
88
|
+
out = df.drop(columns=["cell_line"], errors="ignore").merge(per, on=key, how="left")
|
|
89
|
+
out["cell_line"] = out["cell_line"].fillna("unknown")
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def swap_alleles(df: pd.DataFrame) -> pd.DataFrame:
|
|
94
|
+
"""The same rows with reference and alternate exchanged (features, p-values and label)."""
|
|
95
|
+
out = df.copy()
|
|
96
|
+
for a, b in ((W_REF, W_ALT), (NW_REF, NW_ALT), (["p_ref"], ["p_alt"])):
|
|
97
|
+
out[a] = df[b].to_numpy()
|
|
98
|
+
out[b] = df[a].to_numpy()
|
|
99
|
+
out["label"] = df["label"].map(SWAP_LABEL)
|
|
100
|
+
if "ref" in df and "alt" in df:
|
|
101
|
+
out["ref"], out["alt"] = df["alt"].to_numpy(), df["ref"].to_numpy()
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def feature_matrix(df: pd.DataFrame) -> np.ndarray:
|
|
106
|
+
"""All 47 numeric features in file order (used to find identical rows)."""
|
|
107
|
+
return df[[*W_REF, *W_ALT, "motif_change", *NW_REF, *NW_ALT]].to_numpy(dtype=float)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Label cleaning (I-9): one spelling per TF, no duplicate rows, no rows whose identical features carry
|
|
2
|
+
different labels."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from asebind.benchmark.asbdata import feature_matrix
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def clean(df: pd.DataFrame) -> tuple[pd.DataFrame, dict[str, int]]:
|
|
12
|
+
"""Return the cleaned table and a log of how many rows each step removed."""
|
|
13
|
+
log: dict[str, int] = {"rows_in": len(df)}
|
|
14
|
+
log["tf_names_raw"] = df["tf_raw"].nunique()
|
|
15
|
+
log["tf_names_normalised"] = df["tf"].nunique()
|
|
16
|
+
|
|
17
|
+
# 1. Same SNP, same TF (after normalising), same label: one row.
|
|
18
|
+
d = df.drop_duplicates(["snp", "tf", "label"])
|
|
19
|
+
log["removed_duplicate_snp_tf_label"] = len(df) - len(d)
|
|
20
|
+
|
|
21
|
+
# 2. Same SNP and TF with different labels: conflicting, drop all.
|
|
22
|
+
n_labels = d.groupby(["snp", "tf"])["label"].transform("nunique")
|
|
23
|
+
conflicting = n_labels > 1
|
|
24
|
+
log["removed_conflicting_snp_tf"] = int(conflicting.sum())
|
|
25
|
+
d = d[~conflicting]
|
|
26
|
+
|
|
27
|
+
# 3. Identical feature vectors with different labels (any SNP/TF): the features cannot tell them apart.
|
|
28
|
+
fkey = pd.Series([hash(r.tobytes()) for r in feature_matrix(d)], index=d.index)
|
|
29
|
+
labels_per_vec = d.groupby(fkey)["label"].transform("nunique")
|
|
30
|
+
conflicting_vec = labels_per_vec > 1
|
|
31
|
+
log["removed_conflicting_identical_features"] = int(conflicting_vec.sum())
|
|
32
|
+
d = d[~conflicting_vec]
|
|
33
|
+
|
|
34
|
+
log["identical_feature_rows_kept"] = int(fkey[d.index].duplicated(keep=False).sum())
|
|
35
|
+
log["rows_out"] = len(d)
|
|
36
|
+
log["snps_out"] = d["snp"].nunique()
|
|
37
|
+
log["tfs_out"] = d["tf"].nunique()
|
|
38
|
+
return d.reset_index(drop=True), log
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Feature sets compared in the re-test (I-11, I-13).
|
|
2
|
+
|
|
3
|
+
Every set is built so that swapping the alleles maps it in a known way; the antisymmetry diagnostic
|
|
4
|
+
(models.flip_rate) then shows whether a model respects it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
|
|
12
|
+
from asebind.benchmark.asbdata import NW_ALT, NW_REF, W_ALT, W_REF
|
|
13
|
+
|
|
14
|
+
P_FLOOR = 1e-300
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _log10p(p: pd.Series) -> np.ndarray:
|
|
18
|
+
return np.log10(np.clip(p.to_numpy(dtype=float), P_FLOOR, 1.0))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def delta_motif(df: pd.DataFrame) -> np.ndarray:
|
|
22
|
+
"""Motif-match change alone: d = -log10 p(alt) - (-log10 p(ref)), and |d|. Positive d = better match on alt."""
|
|
23
|
+
d = _log10p(df["p_ref"]) - _log10p(df["p_alt"])
|
|
24
|
+
return np.column_stack([d, np.abs(d)])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def delta_escore(df: pd.DataFrame) -> np.ndarray:
|
|
28
|
+
"""PBM E-score change alone: max and mean of the windowed scores (alt - ref), and their absolute values."""
|
|
29
|
+
wr, wa = df[W_REF].to_numpy(float), df[W_ALT].to_numpy(float)
|
|
30
|
+
dmax = wa.max(1) - wr.max(1)
|
|
31
|
+
dmean = wa.mean(1) - wr.mean(1)
|
|
32
|
+
return np.column_stack([dmax, dmean, np.abs(dmax), np.abs(dmean)])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def engineered(df: pd.DataFrame) -> np.ndarray:
|
|
36
|
+
"""Explicit differences plus allele-symmetric context (I-13): what a small model should need."""
|
|
37
|
+
wr, wa = df[W_REF].to_numpy(float), df[W_ALT].to_numpy(float)
|
|
38
|
+
nr, na = df[NW_REF].to_numpy(float), df[NW_ALT].to_numpy(float)
|
|
39
|
+
lr, la = _log10p(df["p_ref"]), _log10p(df["p_alt"])
|
|
40
|
+
diff = np.column_stack([wa - wr, na - nr, (lr - la)[:, None]])
|
|
41
|
+
summ = np.column_stack([wa + wr, na + nr, (lr + la)[:, None]])
|
|
42
|
+
extra = np.column_stack(
|
|
43
|
+
[
|
|
44
|
+
wa.max(1) - wr.max(1),
|
|
45
|
+
np.abs(wa.max(1) - wr.max(1)),
|
|
46
|
+
np.abs(lr - la),
|
|
47
|
+
df["motif_change"].to_numpy(float),
|
|
48
|
+
]
|
|
49
|
+
)
|
|
50
|
+
return np.column_stack([diff, summ, extra])
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cnn_grid(df: pd.DataFrame) -> np.ndarray:
|
|
54
|
+
"""SNPeBoT's CNN input: 30 windowed E-scores then the two raw best-hit p-values, row-major into 8 x 4."""
|
|
55
|
+
x = np.column_stack(
|
|
56
|
+
[
|
|
57
|
+
df[W_REF].to_numpy(float),
|
|
58
|
+
df[W_ALT].to_numpy(float),
|
|
59
|
+
df["p_ref"].to_numpy(float),
|
|
60
|
+
df["p_alt"].to_numpy(float),
|
|
61
|
+
]
|
|
62
|
+
)
|
|
63
|
+
return x.reshape(-1, 8, 4, 1)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
FEATURE_SETS = {
|
|
67
|
+
"delta_motif": delta_motif,
|
|
68
|
+
"delta_escore": delta_escore,
|
|
69
|
+
"engineered": engineered,
|
|
70
|
+
"cnn_grid": cnn_grid,
|
|
71
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Metrics. ``keras_binary_accuracy`` and ``micro_auc`` reproduce what the SNPeBoT notebook printed as
|
|
2
|
+
"accuracy" and "auc" (Keras BinaryAccuracy / AUC over the three one-hot outputs), so our random-split number can
|
|
3
|
+
be compared with theirs; the multiclass metrics are the ones to read."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import warnings
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from sklearn.metrics import (
|
|
11
|
+
accuracy_score,
|
|
12
|
+
balanced_accuracy_score,
|
|
13
|
+
f1_score,
|
|
14
|
+
log_loss,
|
|
15
|
+
recall_score,
|
|
16
|
+
roc_auc_score,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from asebind.benchmark.asbdata import LABELS
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _onehot(y: np.ndarray) -> np.ndarray:
|
|
23
|
+
return np.eye(len(LABELS))[y]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def scores(y: np.ndarray, p: np.ndarray) -> dict[str, float]:
|
|
27
|
+
with warnings.catch_warnings():
|
|
28
|
+
warnings.simplefilter("ignore", UserWarning) # folds without every class (e.g. one TF)
|
|
29
|
+
return _scores(y, p)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _scores(y: np.ndarray, p: np.ndarray) -> dict[str, float]:
|
|
33
|
+
pred = p.argmax(1)
|
|
34
|
+
oh = _onehot(y)
|
|
35
|
+
out = {
|
|
36
|
+
"n": float(len(y)),
|
|
37
|
+
"accuracy": accuracy_score(y, pred),
|
|
38
|
+
"balanced_accuracy": balanced_accuracy_score(y, pred),
|
|
39
|
+
"macro_f1": f1_score(y, pred, average="macro", labels=range(3), zero_division=0),
|
|
40
|
+
"keras_binary_accuracy": float(((p > 0.5) == oh.astype(bool)).mean()),
|
|
41
|
+
"log_loss": log_loss(y, _renorm(p), labels=range(3)),
|
|
42
|
+
}
|
|
43
|
+
rec = recall_score(y, pred, labels=range(3), average=None, zero_division=np.nan)
|
|
44
|
+
for lab, r in zip(LABELS, rec, strict=True):
|
|
45
|
+
out[f"recall_{lab}"] = float(r)
|
|
46
|
+
present = np.unique(y)
|
|
47
|
+
out["macro_auc"] = (
|
|
48
|
+
roc_auc_score(oh[:, present], p[:, present], average="macro") if len(present) > 1 else float("nan")
|
|
49
|
+
)
|
|
50
|
+
out["micro_auc"] = roc_auc_score(oh.ravel(), p.ravel()) if len(present) > 1 else float("nan")
|
|
51
|
+
# Direction only: among true gains/losses, how often is gain vs loss ranked correctly?
|
|
52
|
+
gl = y != 2
|
|
53
|
+
if gl.sum() > 1 and len(np.unique(y[gl])) == 2:
|
|
54
|
+
out["gain_vs_loss_auc"] = roc_auc_score(y[gl] == 0, p[gl, 0] - p[gl, 1])
|
|
55
|
+
else:
|
|
56
|
+
out["gain_vs_loss_auc"] = float("nan")
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def flip_rate(p: np.ndarray, p_swapped: np.ndarray) -> float:
|
|
61
|
+
"""Share of rows whose call flips correctly when the alleles are swapped (gain<->loss, none->none)."""
|
|
62
|
+
a, b = p.argmax(1), p_swapped.argmax(1)
|
|
63
|
+
expected = np.array([1, 0, 2])[a]
|
|
64
|
+
return float((b == expected).mean())
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _renorm(p: np.ndarray) -> np.ndarray:
|
|
68
|
+
q = np.clip(p, 1e-7, 1.0)
|
|
69
|
+
return q / q.sum(1, keepdims=True)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Models compared in the re-test. Each takes the row table, builds its own features and returns
|
|
2
|
+
probabilities in ``LABELS`` order (gained, lost, none)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from sklearn.ensemble import HistGradientBoostingClassifier
|
|
9
|
+
from sklearn.linear_model import LogisticRegression
|
|
10
|
+
from sklearn.pipeline import make_pipeline
|
|
11
|
+
from sklearn.preprocessing import StandardScaler
|
|
12
|
+
|
|
13
|
+
from asebind.benchmark.asbdata import LABELS, swap_alleles
|
|
14
|
+
from asebind.benchmark.features import FEATURE_SETS
|
|
15
|
+
|
|
16
|
+
LABEL_INDEX = {lab: i for i, lab in enumerate(LABELS)}
|
|
17
|
+
SWAP_COLS = [LABEL_INDEX["lost"], LABEL_INDEX["gained"], LABEL_INDEX["none"]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def encode(labels: pd.Series) -> np.ndarray:
|
|
21
|
+
return labels.map(LABEL_INDEX).to_numpy(dtype=int)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SkModel:
|
|
25
|
+
def __init__(self, name: str, features: str, estimator_factory, seed: int = 0) -> None:
|
|
26
|
+
self.name, self.features, self._factory, self.seed = name, features, estimator_factory, seed
|
|
27
|
+
|
|
28
|
+
def fit(self, df: pd.DataFrame) -> SkModel:
|
|
29
|
+
self.est = self._factory(self.seed)
|
|
30
|
+
self.est.fit(FEATURE_SETS[self.features](df), encode(df["label"]))
|
|
31
|
+
return self
|
|
32
|
+
|
|
33
|
+
def predict_proba(self, df: pd.DataFrame) -> np.ndarray:
|
|
34
|
+
p = self.est.predict_proba(FEATURE_SETS[self.features](df))
|
|
35
|
+
out = np.zeros((len(df), len(LABELS)))
|
|
36
|
+
out[:, self.est.classes_] = p
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Antisymmetric:
|
|
41
|
+
"""I-12: train on both allele orders and average P(x) with the label-swapped P(swap(x)).
|
|
42
|
+
|
|
43
|
+
P(gained | ref,alt) = P(lost | alt,ref) holds exactly by construction.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, base) -> None:
|
|
47
|
+
self.base = base
|
|
48
|
+
self.name = base.name + "+antisym"
|
|
49
|
+
self.features = base.features
|
|
50
|
+
|
|
51
|
+
def fit(self, df: pd.DataFrame) -> Antisymmetric:
|
|
52
|
+
self.base.fit(pd.concat([df, swap_alleles(df)], ignore_index=True))
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def predict_proba(self, df: pd.DataFrame) -> np.ndarray:
|
|
56
|
+
p = self.base.predict_proba(df)
|
|
57
|
+
q = self.base.predict_proba(swap_alleles(df))[:, SWAP_COLS]
|
|
58
|
+
return (p + q) / 2
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class SnpebotCNN:
|
|
62
|
+
"""Our re-implementation of the SNPeBoT CNN from the published description (fixed hyperparameters):
|
|
63
|
+
Conv2D 4-4 (2x2, same, relu) -> MaxPool (2,1) -> Conv2D 48-96 -> MaxPool (2,2) -> Dense 64 -> softmax 3;
|
|
64
|
+
Adam 1e-3, categorical cross-entropy, 40 epochs, batch 64, class weights max/count. Needs tensorflow."""
|
|
65
|
+
|
|
66
|
+
features = "cnn_grid"
|
|
67
|
+
|
|
68
|
+
def __init__(self, name: str = "cnn_snpebot", epochs: int = 40, seed: int = 0) -> None:
|
|
69
|
+
self.name, self.epochs, self.seed = name, epochs, seed
|
|
70
|
+
|
|
71
|
+
def fit(self, df: pd.DataFrame) -> SnpebotCNN:
|
|
72
|
+
import tensorflow as tf
|
|
73
|
+
|
|
74
|
+
tf.keras.utils.set_random_seed(self.seed)
|
|
75
|
+
layers = tf.keras.layers
|
|
76
|
+
m = tf.keras.Sequential(
|
|
77
|
+
[
|
|
78
|
+
tf.keras.Input(shape=(8, 4, 1)),
|
|
79
|
+
layers.Conv2D(4, (2, 2), padding="same", activation="relu"),
|
|
80
|
+
layers.Conv2D(4, (2, 2), padding="same", activation="relu"),
|
|
81
|
+
layers.MaxPool2D(pool_size=(2, 1)),
|
|
82
|
+
layers.Conv2D(48, (2, 2), padding="same", activation="relu"),
|
|
83
|
+
layers.Conv2D(96, (2, 2), padding="same", activation="relu"),
|
|
84
|
+
layers.MaxPool2D(pool_size=(2, 2)),
|
|
85
|
+
layers.Flatten(),
|
|
86
|
+
layers.Dense(64, activation="relu"),
|
|
87
|
+
layers.Dense(3, activation="softmax"),
|
|
88
|
+
]
|
|
89
|
+
)
|
|
90
|
+
m.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3), loss="categorical_crossentropy")
|
|
91
|
+
y = encode(df["label"])
|
|
92
|
+
counts = np.bincount(y, minlength=3)
|
|
93
|
+
cw = {i: counts.max() / c for i, c in enumerate(counts) if c > 0}
|
|
94
|
+
x = FEATURE_SETS["cnn_grid"](df)
|
|
95
|
+
m.fit(
|
|
96
|
+
x,
|
|
97
|
+
tf.keras.utils.to_categorical(y, 3),
|
|
98
|
+
epochs=self.epochs,
|
|
99
|
+
batch_size=64,
|
|
100
|
+
shuffle=True,
|
|
101
|
+
class_weight=cw,
|
|
102
|
+
verbose=0,
|
|
103
|
+
)
|
|
104
|
+
self.model = m
|
|
105
|
+
return self
|
|
106
|
+
|
|
107
|
+
def predict_proba(self, df: pd.DataFrame) -> np.ndarray:
|
|
108
|
+
return self.model.predict(FEATURE_SETS["cnn_grid"](df), verbose=0, batch_size=1024)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _lr(seed: int):
|
|
112
|
+
return make_pipeline(
|
|
113
|
+
StandardScaler(), LogisticRegression(max_iter=2000, class_weight="balanced", random_state=seed)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _hgb(seed: int):
|
|
118
|
+
return HistGradientBoostingClassifier(
|
|
119
|
+
max_iter=300,
|
|
120
|
+
learning_rate=0.05,
|
|
121
|
+
max_leaf_nodes=31,
|
|
122
|
+
l2_regularization=1.0,
|
|
123
|
+
class_weight="balanced",
|
|
124
|
+
random_state=seed,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build(name: str, seed: int = 0, cnn_epochs: int = 40):
|
|
129
|
+
"""Model by name; ``+antisym`` suffix wraps it (I-12)."""
|
|
130
|
+
if name.endswith("+antisym"):
|
|
131
|
+
return Antisymmetric(build(name.removesuffix("+antisym"), seed, cnn_epochs))
|
|
132
|
+
table = {
|
|
133
|
+
"lr_delta_motif": lambda: SkModel("lr_delta_motif", "delta_motif", _lr, seed),
|
|
134
|
+
"lr_delta_escore": lambda: SkModel("lr_delta_escore", "delta_escore", _lr, seed),
|
|
135
|
+
"lr_engineered": lambda: SkModel("lr_engineered", "engineered", _lr, seed),
|
|
136
|
+
"hgb_engineered": lambda: SkModel("hgb_engineered", "engineered", _hgb, seed),
|
|
137
|
+
"cnn_snpebot": lambda: SnpebotCNN(epochs=cnn_epochs, seed=seed),
|
|
138
|
+
}
|
|
139
|
+
if name not in table:
|
|
140
|
+
raise ValueError(f"unknown model {name!r}; choose from {sorted(table)} (+antisym)")
|
|
141
|
+
return table[name]()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
DEFAULT_MODELS = (
|
|
145
|
+
"lr_delta_motif",
|
|
146
|
+
"lr_delta_escore",
|
|
147
|
+
"lr_engineered",
|
|
148
|
+
"hgb_engineered",
|
|
149
|
+
"hgb_engineered+antisym",
|
|
150
|
+
"cnn_snpebot",
|
|
151
|
+
)
|