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/config.py ADDED
@@ -0,0 +1,340 @@
1
+ """Layered configuration (docs/CONFIG.md).
2
+
3
+ Precedence, later wins: built-in defaults < YAML file < environment ``ASEBIND_<SECTION>__<KEY>``
4
+ < command line.
5
+ Every leaf value remembers which layer set it, so ``asebind config show`` can say where it came from.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from collections.abc import Iterable, Mapping
12
+ from dataclasses import dataclass, field
13
+ from importlib import resources
14
+ from pathlib import Path
15
+ from typing import Any, Literal
16
+
17
+ import yaml
18
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
19
+
20
+ ENV_PREFIX = "ASEBIND_"
21
+ DEFAULT_SOURCE = "default"
22
+
23
+
24
+ # --------------------------------------------------------------------------- schema
25
+
26
+
27
+ class _Strict(BaseModel):
28
+ model_config = ConfigDict(extra="forbid")
29
+
30
+
31
+ class InputConfig(_Strict):
32
+ kind: Literal["vcf", "rsid", "gwas", "sequences"] = "vcf"
33
+ path: str | None = None
34
+ risk_allele_column: str | None = None
35
+ build: Literal["GRCh37", "GRCh38"] = "GRCh37"
36
+ window: int = Field(51, ge=9, le=1001)
37
+
38
+ @field_validator("window")
39
+ @classmethod
40
+ def _odd_window(cls, v: int) -> int:
41
+ if v % 2 == 0:
42
+ raise ValueError("window must be odd so the variant sits in the centre")
43
+ return v
44
+
45
+
46
+ class TfsConfig(_Strict):
47
+ include: Literal["all"] | list[str] | str = "all"
48
+ exclude: list[str] = Field(default_factory=list)
49
+ group_by_motif: bool = True
50
+ pwm_only_tier: bool = True
51
+
52
+
53
+ class ModelConfig(_Strict):
54
+ name: str = "asebind-v2-oth"
55
+ # trained model (.joblib); default <resources dir>/models/<name>/model.joblib, else the released model fetched
56
+ # with `asebind fetch asebind_model` (<resources dir>/asebind_model/model.joblib)
57
+ path: str | None = None
58
+ both_orders: bool = True
59
+ calibrated: bool = True
60
+ min_motif_p: float = Field(0.01, gt=0, le=1)
61
+
62
+
63
+ class ContextConfig(_Strict):
64
+ cell_type: str | None = None
65
+ chromatin_bed: str | None = None
66
+
67
+
68
+ class AseConfig(_Strict):
69
+ counts: str | None = None
70
+ reads: str | list[str] | None = None
71
+ genotypes: str | None = None
72
+ min_depth: int = Field(10, ge=1)
73
+ model: Literal["beta_binomial", "binomial"] = "beta_binomial"
74
+
75
+
76
+ class BenchmarkConfig(_Strict):
77
+ snpebot_dir: str | None = None
78
+
79
+
80
+ class ToolConfig(_Strict):
81
+ """How to find one external tool; the first method that works is used.
82
+
83
+ Order: path, module, conda, container, PATH.
84
+ """
85
+
86
+ path: str | None = None
87
+ module: str | None = None
88
+ conda_env: str | None = None
89
+ container: str | None = None
90
+ executable: str | None = None # name of the executable if it differs from the tool key
91
+ version_args: list[str] = Field(default_factory=lambda: ["--version"])
92
+
93
+
94
+ def _default_tools() -> dict[str, ToolConfig]:
95
+ return {
96
+ "fimo": ToolConfig(module="meme/5.1.1"),
97
+ "bedtools": ToolConfig(),
98
+ "samtools": ToolConfig(),
99
+ }
100
+
101
+
102
+ class SlurmConfig(_Strict):
103
+ account: str | None = None
104
+ partition: str | None = None
105
+ time: str = "02:00:00"
106
+ mem: str = "8G"
107
+ cpus: int = Field(4, ge=1)
108
+ array_chunk: int = Field(20, ge=1)
109
+ extra: list[str] = Field(default_factory=list)
110
+
111
+
112
+ class ExecutorConfig(_Strict):
113
+ kind: Literal["local", "slurm"] = "local"
114
+ workers: int = Field(4, ge=1)
115
+ slurm: SlurmConfig = Field(default_factory=SlurmConfig)
116
+
117
+
118
+ class GenomeConfig(_Strict):
119
+ build: Literal["GRCh37", "GRCh38"] = "GRCh37"
120
+ fasta: str | None = None
121
+
122
+
123
+ class ResourcesConfig(_Strict):
124
+ dir: str = "~/.cache/asebind"
125
+ cisbp_release: str = "3.10"
126
+ genome: GenomeConfig = Field(default_factory=GenomeConfig)
127
+
128
+
129
+ class OutputConfig(_Strict):
130
+ dir: str = "results"
131
+ formats: list[Literal["tsv", "xlsx"]] = Field(default_factory=lambda: ["tsv", "xlsx"])
132
+ plots: bool = True
133
+
134
+
135
+ class AsebindConfig(_Strict):
136
+ input: InputConfig = Field(default_factory=InputConfig)
137
+ tfs: TfsConfig = Field(default_factory=TfsConfig)
138
+ model: ModelConfig = Field(default_factory=ModelConfig)
139
+ context: ContextConfig = Field(default_factory=ContextConfig)
140
+ ase: AseConfig = Field(default_factory=AseConfig)
141
+ benchmark: BenchmarkConfig = Field(default_factory=BenchmarkConfig)
142
+ tools: dict[str, ToolConfig] = Field(default_factory=_default_tools)
143
+ executor: ExecutorConfig = Field(default_factory=ExecutorConfig)
144
+ resources: ResourcesConfig = Field(default_factory=ResourcesConfig)
145
+ tmp_dir: str | None = None
146
+ output: OutputConfig = Field(default_factory=OutputConfig)
147
+
148
+
149
+ # --------------------------------------------------------------------------- loading
150
+
151
+
152
+ class ConfigError(Exception):
153
+ """A configuration problem the user must fix; the message names the layer that caused it."""
154
+
155
+
156
+ @dataclass
157
+ class ResolvedConfig:
158
+ config: AsebindConfig
159
+ sources: dict[str, str] # dotted leaf key -> layer that set it
160
+ yaml_path: Path | None = None
161
+ layers: list[str] = field(default_factory=list)
162
+
163
+ def as_dict(self) -> dict[str, Any]:
164
+ return self.config.model_dump(mode="json")
165
+
166
+ def leaves(self) -> list[tuple[str, Any, str]]:
167
+ """(dotted key, value, source) for every leaf, in schema order."""
168
+ out = []
169
+ for key, value in _flatten(self.as_dict()):
170
+ out.append((key, value, self._source_of(key)))
171
+ return out
172
+
173
+ def _source_of(self, key: str) -> str:
174
+ # A list or dict set as a whole is recorded at its own key; a leaf inside inherits it.
175
+ parts = key.split(".")
176
+ for i in range(len(parts), 0, -1):
177
+ src = self.sources.get(".".join(parts[:i]))
178
+ if src is not None:
179
+ return src
180
+ return DEFAULT_SOURCE
181
+
182
+
183
+ def _flatten(d: Mapping[str, Any], prefix: str = "") -> Iterable[tuple[str, Any]]:
184
+ for k, v in d.items():
185
+ key = f"{prefix}{k}"
186
+ if isinstance(v, Mapping) and v:
187
+ yield from _flatten(v, key + ".")
188
+ else:
189
+ yield key, v
190
+
191
+
192
+ def _merge(
193
+ base: dict[str, Any], overlay: Mapping[str, Any], sources: dict[str, str], label: str, prefix: str = ""
194
+ ) -> None:
195
+ """Merge ``overlay`` into ``base`` in place. Mappings merge key by key; everything else replaces."""
196
+ for k, v in overlay.items():
197
+ key = f"{prefix}{k}"
198
+ if isinstance(v, Mapping) and isinstance(base.get(k), dict):
199
+ _merge(base[k], v, sources, label, key + ".")
200
+ elif isinstance(v, Mapping):
201
+ base[k] = {}
202
+ if not v:
203
+ sources[key] = label
204
+ _merge(base[k], v, sources, label, key + ".")
205
+ else:
206
+ # clear stale sources of a subtree this value replaces
207
+ for old in [s for s in sources if s.startswith(key + ".")]:
208
+ del sources[old]
209
+ base[k] = v
210
+ sources[key] = label
211
+
212
+
213
+ def parse_value(text: str) -> Any:
214
+ """Parse a command-line or environment value as YAML (``null``, ``4``, ``[a, b]``); times stay text."""
215
+ if ":" in text and not text.lstrip().startswith(("[", "{")):
216
+ return text # "02:00:00" would otherwise become a base-60 integer, "C:/x" a mapping
217
+ try:
218
+ return yaml.safe_load(text) if text.strip() else ""
219
+ except yaml.YAMLError:
220
+ return text
221
+
222
+
223
+ def _nest(dotted: str, value: Any) -> dict[str, Any]:
224
+ parts = [p for p in dotted.split(".") if p]
225
+ if not parts:
226
+ raise ConfigError(f"empty key in override {dotted!r}")
227
+ out: dict[str, Any] = {}
228
+ cur = out
229
+ for p in parts[:-1]:
230
+ cur = cur.setdefault(p, {})
231
+ cur[parts[-1]] = value
232
+ return out
233
+
234
+
235
+ def parse_assignment(text: str) -> tuple[str, Any]:
236
+ if "=" not in text:
237
+ raise ConfigError(f"expected KEY=VALUE, got {text!r}")
238
+ key, value = text.split("=", 1)
239
+ return key.strip(), parse_value(value)
240
+
241
+
242
+ def env_overrides(environ: Mapping[str, str]) -> list[tuple[str, str, Any]]:
243
+ """(env var name, dotted key, value) for every ``ASEBIND_*`` variable."""
244
+ out = []
245
+ for name in sorted(environ):
246
+ if not name.upper().startswith(ENV_PREFIX):
247
+ continue
248
+ rest = name[len(ENV_PREFIX) :]
249
+ if not rest:
250
+ continue
251
+ dotted = ".".join(p.lower() for p in rest.split("__"))
252
+ out.append((name, dotted, parse_value(environ[name])))
253
+ return out
254
+
255
+
256
+ def find_yaml(explicit: str | Path | None, cwd: Path | None = None, home: Path | None = None) -> Path | None:
257
+ if explicit is not None:
258
+ p = Path(explicit).expanduser()
259
+ if not p.is_file():
260
+ raise ConfigError(f"config file not found: {p}")
261
+ return p
262
+ cwd = cwd or Path.cwd()
263
+ home = home or Path.home()
264
+ for cand in (cwd / "asebind.yaml", home / ".config" / "asebind" / "config.yaml"):
265
+ if cand.is_file():
266
+ return cand
267
+ return None
268
+
269
+
270
+ def load_yaml(path: Path) -> dict[str, Any]:
271
+ try:
272
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
273
+ except yaml.YAMLError as e:
274
+ raise ConfigError(f"cannot parse {path}: {e}") from e
275
+ if data is None:
276
+ return {}
277
+ if not isinstance(data, dict):
278
+ raise ConfigError(f"{path}: top level must be a mapping, got {type(data).__name__}")
279
+ return data
280
+
281
+
282
+ def tool_overrides(tools: Iterable[str] = (), tool_modules: Iterable[str] = ()) -> list[tuple[str, Any]]:
283
+ """``--tool fimo=/path`` and ``--tool-module fimo=meme/5.1.1`` as dotted assignments."""
284
+ out: list[tuple[str, Any]] = []
285
+ for flag, field_name, items in (("--tool", "path", tools), ("--tool-module", "module", tool_modules)):
286
+ for item in items:
287
+ if "=" not in item:
288
+ raise ConfigError(f"{flag} expects NAME=VALUE, got {item!r}")
289
+ name, value = item.split("=", 1)
290
+ out.append((f"tools.{name.strip()}.{field_name}", value.strip()))
291
+ return out
292
+
293
+
294
+ def resolve(
295
+ config_path: str | Path | None = None,
296
+ sets: Iterable[str] = (),
297
+ tools: Iterable[str] = (),
298
+ tool_modules: Iterable[str] = (),
299
+ environ: Mapping[str, str] | None = None,
300
+ cwd: Path | None = None,
301
+ home: Path | None = None,
302
+ ) -> ResolvedConfig:
303
+ """Build the configuration from every layer and validate it."""
304
+ environ = os.environ if environ is None else environ
305
+ data: dict[str, Any] = AsebindConfig().model_dump(mode="json")
306
+ sources: dict[str, str] = {}
307
+ layers = [DEFAULT_SOURCE]
308
+
309
+ yaml_path = find_yaml(config_path, cwd=cwd, home=home)
310
+ if yaml_path is not None:
311
+ label = f"yaml:{yaml_path}"
312
+ _merge(data, load_yaml(yaml_path), sources, label)
313
+ layers.append(label)
314
+
315
+ for name, dotted, value in env_overrides(environ):
316
+ _merge(data, _nest(dotted, value), sources, f"env:{name}")
317
+ layers.append(f"env:{name}")
318
+
319
+ cli_items: list[tuple[str, Any]] = [parse_assignment(s) for s in sets]
320
+ cli_items += tool_overrides(tools, tool_modules)
321
+ for dotted, value in cli_items:
322
+ _merge(data, _nest(dotted, value), sources, "cli")
323
+ if cli_items:
324
+ layers.append("cli")
325
+
326
+ try:
327
+ cfg = AsebindConfig.model_validate(data)
328
+ except ValidationError as e:
329
+ lines = []
330
+ for err in e.errors():
331
+ key = ".".join(str(x) for x in err["loc"])
332
+ src = ResolvedConfig(AsebindConfig(), sources)._source_of(key)
333
+ lines.append(f" {key}: {err['msg']} [set by {src}]")
334
+ raise ConfigError("invalid configuration:\n" + "\n".join(lines)) from None
335
+ return ResolvedConfig(config=cfg, sources=sources, yaml_path=yaml_path, layers=layers)
336
+
337
+
338
+ def example_yaml() -> str:
339
+ """The commented example configuration shipped with the package."""
340
+ return resources.files("asebind").joinpath("data/asebind.example.yaml").read_text(encoding="utf-8")
@@ -0,0 +1,56 @@
1
+ # ASEbind example configuration (design draft, 2026-11-30). Command-line options override every value here.
2
+ # Example on the cluster: asebind predict --config asebind.yaml --input snps.vcf --set executor.kind=slurm
3
+
4
+ input:
5
+ kind: vcf # vcf | rsid | gwas | sequences
6
+ path: inputs/credible_set.vcf
7
+ risk_allele_column: null # for kind: gwas (effect/risk allele)
8
+ build: GRCh37 # checked against known positions
9
+ window: 51 # bp, variant in the centre
10
+
11
+ tfs:
12
+ include: all # all | list of HGNC symbols | file
13
+ exclude: []
14
+ group_by_motif: true # collapse TFs sharing a motif (I-8)
15
+ pwm_only_tier: true # score TFs without PBM data from PWMs, labelled as lower evidence (I-18)
16
+
17
+ model:
18
+ name: asebind-v1 # or snpebot-benchmark (runs the user's own SNPeBoT clone, see benchmark)
19
+ path: null # trained model; default <resources dir>/models/<name>/model.joblib
20
+ both_orders: true # antisymmetric scoring (I-12)
21
+ calibrated: true
22
+ min_motif_p: 0.01
23
+
24
+ context: # optional (I-17)
25
+ cell_type: null # e.g. LCL
26
+ chromatin_bed: null
27
+
28
+ ase: # allele-specific expression comparison (I-21, I-22)
29
+ counts: null # per-sample phased allele counts TSV, or
30
+ reads: null # BAM/FASTQ list for k-mer counting
31
+ genotypes: null # phased VCF
32
+ min_depth: 10
33
+ model: beta_binomial
34
+
35
+ benchmark:
36
+ snpebot_dir: null # path to the user's own SNPeBoT clone (never bundled)
37
+
38
+ tools:
39
+ fimo: {path: null, module: meme/5.1.1, conda_env: null}
40
+ bedtools: {path: null, module: null, conda_env: null}
41
+ samtools: {path: null, module: null, conda_env: null}
42
+
43
+ executor:
44
+ kind: local # local | slurm
45
+ workers: 4
46
+ slurm: {time: "02:00:00", mem: 8G, cpus: 4, array_chunk: 20, partition: null, account: null, extra: []}
47
+
48
+ resources:
49
+ dir: ~/.cache/asebind # on HPC: a scratch path (home quota)
50
+ cisbp_release: "3.10"
51
+ tmp_dir: null
52
+
53
+ output:
54
+ dir: results
55
+ formats: [tsv, xlsx]
56
+ plots: true
asebind/finemap.py ADDED
@@ -0,0 +1,86 @@
1
+ """Single-causal-variant fine-mapping with an ASEbind prior (I-37).
2
+
3
+ Per locus, each variant's evidence is a Wakefield approximate Bayes factor from its association z score:
4
+
5
+ ABF = sqrt(V / (V + W)) * exp(z^2 / 2 * W / (V + W)), V = 1 / n (standardised effect), W = prior_sd^2
6
+
7
+ and its posterior inclusion probability (one causal variant per locus) is PIP = prior x ABF / sum(prior x ABF).
8
+ Without an annotation the prior is flat. With ASEbind it is prior proportional to exp(lam x s), s = the variant's
9
+ binding-effect score in [0, 1]. ``lam`` = 0 gives back plain fine-mapping.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ from scipy import stats
17
+ from scipy.special import logsumexp
18
+
19
+
20
+ def z_from_p(p: np.ndarray, sign: np.ndarray) -> np.ndarray:
21
+ p = np.clip(np.asarray(p, float), 1e-300, 1.0)
22
+ return np.sign(sign) * stats.norm.isf(p / 2)
23
+
24
+
25
+ def log_abf(z: np.ndarray, n: float, prior_sd: float = 0.15) -> np.ndarray:
26
+ v, w = 1.0 / n, prior_sd**2
27
+ return 0.5 * np.log(v / (v + w)) + (np.asarray(z, float) ** 2) / 2 * w / (v + w)
28
+
29
+
30
+ def pip(df: pd.DataFrame, lam: float = 0.0, locus: str = "locus", score: str = "score") -> np.ndarray:
31
+ """PIP per row of ``df`` (columns: locus, log_abf, score)."""
32
+ lw = df["log_abf"].to_numpy() + lam * df[score].fillna(0).to_numpy()
33
+ out = np.empty(len(df))
34
+ for _, idx in df.groupby(locus, sort=False).indices.items():
35
+ out[idx] = np.exp(lw[idx] - logsumexp(lw[idx]))
36
+ return out
37
+
38
+
39
+ def rank_metrics(df: pd.DataFrame, col: str, truth: str = "emvar", locus: str = "locus") -> dict:
40
+ """Within-locus ranking of true variants by ``col`` (loci with >= 1 true and >= 2 variants).
41
+
42
+ top1: fraction of loci whose highest-ranked variant is true; recall_top3: fraction of true variants ranked
43
+ in their locus's top 3; mean_pip_true: mean value of ``col`` on true variants; auprc: pooled average
44
+ precision of ``col`` over all variants of these loci."""
45
+ from sklearn.metrics import average_precision_score
46
+
47
+ keep = df.groupby(locus)[truth].transform(lambda t: t.any() and len(t) >= 2)
48
+ d = df[keep.astype(bool)].copy()
49
+ if d.empty:
50
+ return {
51
+ "loci": 0,
52
+ "variants": 0,
53
+ "true_variants": 0,
54
+ "top1": np.nan,
55
+ "recall_top3": np.nan,
56
+ "mean_pip_true": np.nan,
57
+ "auprc": np.nan,
58
+ }
59
+ d["_rank"] = d.groupby(locus)[col].rank(ascending=False, method="first")
60
+ top = d[d["_rank"] == 1]
61
+ t = d[d[truth]]
62
+ return {
63
+ "loci": d[locus].nunique(),
64
+ "variants": len(d),
65
+ "true_variants": int(d[truth].sum()),
66
+ "top1": float(top[truth].mean()),
67
+ "recall_top3": float((t["_rank"] <= 3).mean()),
68
+ "mean_pip_true": float(t[col].mean()),
69
+ "auprc": float(average_precision_score(d[truth], d[col])),
70
+ }
71
+
72
+
73
+ def choose_lambda(
74
+ df: pd.DataFrame, lams: list[float], fold: str = "chrom", metric: str = "auprc", **kw
75
+ ) -> tuple[float, pd.DataFrame]:
76
+ """Leave-one-fold-out choice of lam: for each fold, the lam in ``lams`` that is best on the other folds.
77
+ Returns the median choice and the per-fold table (score each fold with its own lam for held-out results)."""
78
+ rows = []
79
+ for f in sorted(df[fold].unique()):
80
+ train = df[df[fold] != f]
81
+ best = max(
82
+ lams,
83
+ key=lambda lam: np.nan_to_num(rank_metrics(train.assign(_p=pip(train, lam, **kw)), "_p")[metric]),
84
+ )
85
+ rows.append({fold: f, "lam": best})
86
+ return float(pd.DataFrame(rows)["lam"].median()), pd.DataFrame(rows)
asebind/haplotype.py ADDED
@@ -0,0 +1,141 @@
1
+ """Haplotype-level binding score and its comparison with allele-specific expression (I-36).
2
+
3
+ ASE measures the combined effect of every variant on one copy of a gene, so the binding side is summed over the
4
+ same copy. For each unit (a gene, or a gene in one person) and each variant on the copy of interest, the
5
+ calibrated change in binding of that copy is
6
+
7
+ d = P(gain) - P(loss) oriented to the allele the copy carries (antisymmetry: the other allele gives -d)
8
+
9
+ and the unit's score is the sum over variants and TFs of sign(TF role) x distance weight x d. TF role is +1 for
10
+ activators (more binding -> more expression) and -1 for repressors; TFs without a role count as activators and
11
+ are reported as such. Binding is not expression (I-20): the comparison reports concordance, never "validated".
12
+
13
+ Tables
14
+ predictions ``asebind predict`` output: id, tf, base_allele, effect_allele, p_gained, p_lost
15
+ haplotypes unit, id, copy_allele [, distance] (allele on the copy of interest; distance to the TSS in bp)
16
+ ase unit and either log2_ratio (copy / other) or p_hat (copy share) [, p_value, ci_low, ci_high]
17
+ tf_roles tf, role (activator | repressor)
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+ from scipy import stats
25
+
26
+ ROLE_SIGN = {"activator": 1.0, "repressor": -1.0}
27
+
28
+
29
+ def _need(df: pd.DataFrame, cols: set[str], what: str) -> None:
30
+ missing = cols - set(df.columns)
31
+ if missing:
32
+ raise ValueError(f"{what}: missing columns {sorted(missing)}")
33
+
34
+
35
+ def contributions(
36
+ pred: pd.DataFrame,
37
+ haplotypes: pd.DataFrame,
38
+ tf_roles: pd.DataFrame | None = None,
39
+ distance_scale: float | None = None,
40
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
41
+ """One row per (unit, variant, TF) with its signed contribution, and the variants that could not be oriented."""
42
+ _need(pred, {"id", "tf", "base_allele", "effect_allele", "p_gained", "p_lost"}, "predictions")
43
+ _need(haplotypes, {"unit", "id", "copy_allele"}, "haplotypes")
44
+ h = haplotypes.copy()
45
+ h["copy_allele"] = h["copy_allele"].astype(str).str.upper()
46
+ p = pred[["id", "tf", "base_allele", "effect_allele", "p_gained", "p_lost"]].copy()
47
+ m = h.merge(p, on="id", how="left")
48
+ no_pred = m["tf"].isna()
49
+ eff = m["copy_allele"] == m["effect_allele"].astype(str).str.upper()
50
+ base = m["copy_allele"] == m["base_allele"].astype(str).str.upper()
51
+ bad = no_pred | ~(eff | base)
52
+ m["reason"] = np.where(no_pred, "no prediction", "copy allele is neither base nor effect allele")
53
+ skipped = m.loc[bad, ["unit", "id", "copy_allele", "reason"]].drop_duplicates()
54
+ c = m.loc[~bad].copy()
55
+ d = c["p_gained"] - c["p_lost"]
56
+ c["d_copy"] = np.where(eff[~bad], d, -d)
57
+ roles = {}
58
+ if tf_roles is not None:
59
+ _need(tf_roles, {"tf", "role"}, "tf_roles")
60
+ roles = dict(zip(tf_roles["tf"].str.upper(), tf_roles["role"].str.lower(), strict=True))
61
+ c["role"] = c["tf"].str.upper().map(roles).astype(object).fillna("activator (assumed)")
62
+ c["role_sign"] = c["role"].map(lambda r: ROLE_SIGN.get(r.split(" ")[0], 1.0))
63
+ if distance_scale and "distance" in c:
64
+ c["weight"] = np.exp(-np.abs(c["distance"].astype(float)) / distance_scale)
65
+ else:
66
+ c["weight"] = 1.0
67
+ c["contribution"] = c["role_sign"] * c["weight"] * c["d_copy"]
68
+ keep = ["unit", "id", "tf", "copy_allele", "d_copy", "role", "weight", "contribution"]
69
+ return c[keep].reset_index(drop=True), skipped.reset_index(drop=True)
70
+
71
+
72
+ def scores(contrib: pd.DataFrame, call_min_p: float = 0.5, min_abs_d: float = 0.1) -> pd.DataFrame:
73
+ """Per unit: the summed score; the sum over sites with |d| >= ``min_abs_d`` (``score_filtered``: many TFs
74
+ with near-zero d can add up to a sizeable sum that is noise); the sum over called sites; the strongest
75
+ contributor."""
76
+ rows = []
77
+ for unit, g in contrib.groupby("unit", sort=False):
78
+ top = g.loc[g["contribution"].abs().idxmax()]
79
+ called = g[g["d_copy"].abs() >= call_min_p]
80
+ clear = g[g["d_copy"].abs() >= min_abs_d]
81
+ rows.append(
82
+ {
83
+ "unit": unit,
84
+ "variants": g["id"].nunique(),
85
+ "pairs": len(g),
86
+ "score": g["contribution"].sum(),
87
+ "score_filtered": clear["contribution"].sum(),
88
+ "score_called": called["contribution"].sum(),
89
+ "copy_gains": int((g["d_copy"] >= call_min_p).sum()),
90
+ "copy_losses": int((g["d_copy"] <= -call_min_p).sum()),
91
+ "top_variant": top["id"],
92
+ "top_tf": top["tf"],
93
+ "top_contribution": top["contribution"],
94
+ }
95
+ )
96
+ return pd.DataFrame(rows)
97
+
98
+
99
+ def _ase_effect(ase: pd.DataFrame) -> pd.Series:
100
+ if "log2_ratio" in ase:
101
+ return ase["log2_ratio"].astype(float)
102
+ if "p_hat" in ase:
103
+ p = ase["p_hat"].astype(float).clip(1e-6, 1 - 1e-6)
104
+ return np.log2(p / (1 - p))
105
+ raise ValueError("ase: needs log2_ratio or p_hat")
106
+
107
+
108
+ def compare(
109
+ sc: pd.DataFrame, ase: pd.DataFrame, min_score: float = 0.0, alpha: float = 0.05
110
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
111
+ """Join scores and ASE per unit; summary of agreement (Spearman over all units, sign concordance over units
112
+ with |score| > ``min_score`` and, when ASE P values are given, P < ``alpha``)."""
113
+ _need(ase, {"unit"}, "ase")
114
+ a = ase.copy()
115
+ a["ase_log2_ratio"] = _ase_effect(a)
116
+ u = sc.merge(a, on="unit", how="inner")
117
+ u["predicted"] = np.select([u["score"] > min_score, u["score"] < -min_score], ["up", "down"], "none")
118
+ u["observed"] = np.where(u["ase_log2_ratio"] > 0, "up", np.where(u["ase_log2_ratio"] < 0, "down", "none"))
119
+ sig = u["p_value"] < alpha if "p_value" in u else pd.Series(True, index=u.index)
120
+ u["ase_significant"] = sig.to_numpy()
121
+ both = (u["predicted"] != "none") & (u["observed"] != "none")
122
+ u["concordant"] = pd.Series(u["predicted"] == u["observed"], dtype="boolean").where(both)
123
+ rows = [{"what": "units with ASE and a score", "value": len(u)}]
124
+ if len(u) >= 3:
125
+ r = stats.spearmanr(u["score"], u["ase_log2_ratio"])
126
+ rows += [
127
+ {"what": "spearman score vs ASE log2 ratio", "value": r.statistic},
128
+ {"what": "spearman p", "value": r.pvalue},
129
+ ]
130
+ t = u[(u["predicted"] != "none") & (u["observed"] != "none") & u["ase_significant"]]
131
+ k = int((t["predicted"] == t["observed"]).sum())
132
+ rows += [
133
+ {"what": "units tested for direction", "value": len(t)},
134
+ {"what": "direction concordant", "value": k},
135
+ ]
136
+ if len(t):
137
+ rows += [
138
+ {"what": "fraction concordant", "value": k / len(t)},
139
+ {"what": "binomial p (vs 0.5)", "value": stats.binomtest(k, len(t), 0.5).pvalue},
140
+ ]
141
+ return u, pd.DataFrame(rows)
asebind/io/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Variant input readers and allele checks."""