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/cli_model.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
"""CLI commands for resources, model building and prediction (``fetch``, ``model ...``, ``predict``).
|
|
2
|
+
|
|
3
|
+
Kept apart from cli.py so `asebind --help` stays fast: heavy imports happen inside each command.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import click
|
|
13
|
+
|
|
14
|
+
from asebind.cli import State, _csv, cli, pass_state
|
|
15
|
+
from asebind.config import ResolvedConfig
|
|
16
|
+
from asebind.runrecord import build_record, write_record
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _default_model(root: Path, name: str) -> Path:
|
|
20
|
+
"""<root>/models/<name>/model.joblib when trained locally, else the released model (`asebind fetch
|
|
21
|
+
asebind_model`); the first path when neither exists, for the error message."""
|
|
22
|
+
own = root / "models" / name / "model.joblib"
|
|
23
|
+
released = root / "asebind_model" / "model.joblib"
|
|
24
|
+
return own if own.exists() or not released.exists() else released
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _resources_root(rc: ResolvedConfig) -> Path:
|
|
28
|
+
return Path(os.path.expanduser(rc.config.resources.dir))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# --------------------------------------------------------------------------- resources
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@cli.command()
|
|
35
|
+
@click.argument("names", nargs=-1)
|
|
36
|
+
@click.option(
|
|
37
|
+
"--list", "list_only", is_flag=True, help="List the resources ASEbind knows and what is fetched."
|
|
38
|
+
)
|
|
39
|
+
@click.option(
|
|
40
|
+
"--register",
|
|
41
|
+
"register_path",
|
|
42
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
43
|
+
default=None,
|
|
44
|
+
help="Record a file obtained by hand (e.g. the CIS-BP E-score table) for the one NAME given.",
|
|
45
|
+
)
|
|
46
|
+
@click.option("--force", is_flag=True, help="Download again even if the files are present.")
|
|
47
|
+
@pass_state
|
|
48
|
+
def fetch(
|
|
49
|
+
state: State, names: tuple[str, ...], list_only: bool, register_path: str | None, force: bool
|
|
50
|
+
) -> None:
|
|
51
|
+
"""Download resources into <resources.dir>/<name>/ with a manifest (URL, release, size, md5, sha256)."""
|
|
52
|
+
from asebind.resources import fetch as F
|
|
53
|
+
from asebind.resources.registry import RESOURCES
|
|
54
|
+
|
|
55
|
+
root = _resources_root(state.resolved())
|
|
56
|
+
if list_only or not names:
|
|
57
|
+
click.echo(f"resources dir: {root}")
|
|
58
|
+
for name, r in RESOURCES.items():
|
|
59
|
+
man = F.manifest(name, root)
|
|
60
|
+
state_txt = f"{man['mode']} {man['written'][:10]}" if man else "not fetched"
|
|
61
|
+
click.echo(f" {name:22} {state_txt:22} {r.description}")
|
|
62
|
+
return
|
|
63
|
+
try:
|
|
64
|
+
if register_path:
|
|
65
|
+
if len(names) != 1:
|
|
66
|
+
raise click.UsageError("--register takes exactly one NAME")
|
|
67
|
+
F.register(names[0], Path(register_path), root, log=click.echo)
|
|
68
|
+
return
|
|
69
|
+
for name in names:
|
|
70
|
+
F.fetch(name, root, force=force, log=click.echo)
|
|
71
|
+
except F.FetchError as e:
|
|
72
|
+
raise click.ClickException(str(e)) from None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# --------------------------------------------------------------------------- model building (Phase 3)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@cli.group("model")
|
|
79
|
+
def model_group() -> None:
|
|
80
|
+
"""Build the ASEbind binding model: labels, features, evaluation, final training (Phase 3)."""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@model_group.command("escore-cache")
|
|
84
|
+
@click.option(
|
|
85
|
+
"--table",
|
|
86
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
87
|
+
default=None,
|
|
88
|
+
help="CIS-BP E-score table (default: the registered cisbp_escores_3.10 file).",
|
|
89
|
+
)
|
|
90
|
+
@pass_state
|
|
91
|
+
def model_escore_cache(state: State, table: str | None) -> None:
|
|
92
|
+
"""Convert the CIS-BP E-score text table to a memory-mapped matrix (once)."""
|
|
93
|
+
from asebind.model.context import ESCORE_CACHE
|
|
94
|
+
from asebind.motifs.escore import build_cache
|
|
95
|
+
from asebind.resources.fetch import resource_file
|
|
96
|
+
|
|
97
|
+
root = _resources_root(state.resolved())
|
|
98
|
+
src = Path(table) if table else resource_file("cisbp_escores_3.10", root, "*")
|
|
99
|
+
click.echo(f"building E-score cache from {src}")
|
|
100
|
+
click.echo(str(build_cache(src, root / ESCORE_CACHE)))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@model_group.command("labels")
|
|
104
|
+
@click.option(
|
|
105
|
+
"--adastra-tf-dir",
|
|
106
|
+
type=click.Path(exists=True, file_okay=False),
|
|
107
|
+
required=True,
|
|
108
|
+
help="The TF/ folder of the unpacked ADASTRA release.",
|
|
109
|
+
)
|
|
110
|
+
@click.option("--out", type=click.Path(dir_okay=False), required=True, help="labels .tsv.gz")
|
|
111
|
+
@click.option("--fdr", type=float, default=0.05, show_default=True)
|
|
112
|
+
@click.option("--none-fdr", type=float, default=0.5, show_default=True)
|
|
113
|
+
@click.option("--min-cover", type=int, default=40, show_default=True)
|
|
114
|
+
@click.option("--none-per-asb", type=float, default=2.0, show_default=True)
|
|
115
|
+
@pass_state
|
|
116
|
+
def model_labels(
|
|
117
|
+
state: State,
|
|
118
|
+
adastra_tf_dir: str,
|
|
119
|
+
out: str,
|
|
120
|
+
fdr: float,
|
|
121
|
+
none_fdr: float,
|
|
122
|
+
min_cover: int,
|
|
123
|
+
none_per_asb: float,
|
|
124
|
+
) -> None:
|
|
125
|
+
"""Gain / loss / none labels from ADASTRA for every TF with a motif."""
|
|
126
|
+
from asebind.model.adastra import build_labels
|
|
127
|
+
from asebind.model.context import load_motifs, uniprot_symbols
|
|
128
|
+
|
|
129
|
+
rc = state.resolved()
|
|
130
|
+
root = _resources_root(rc)
|
|
131
|
+
tfs = set(load_motifs(root))
|
|
132
|
+
lab, counts = build_labels(
|
|
133
|
+
adastra_tf_dir,
|
|
134
|
+
tfs,
|
|
135
|
+
symbol_of=uniprot_symbols(root),
|
|
136
|
+
fdr=fdr,
|
|
137
|
+
none_fdr=none_fdr,
|
|
138
|
+
min_cover=min_cover,
|
|
139
|
+
none_per_asb=none_per_asb,
|
|
140
|
+
log=click.echo,
|
|
141
|
+
)
|
|
142
|
+
outp = Path(out)
|
|
143
|
+
outp.parent.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
lab.to_csv(outp, sep="\t", index=False)
|
|
145
|
+
counts.to_csv(outp.with_name("label_counts_per_tf.tsv"), sep="\t", index=False)
|
|
146
|
+
click.echo(f"{len(lab)} rows, {lab['tf'].nunique()} TFs: {lab['label'].value_counts().to_dict()}")
|
|
147
|
+
write_record(outp.parent, build_record(sys.argv, rc, resources=[Path(adastra_tf_dir)]))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def genome_for(rc: ResolvedConfig, build: str) -> Path:
|
|
151
|
+
g = rc.config.resources.genome
|
|
152
|
+
if g.fasta and g.build == build:
|
|
153
|
+
return Path(os.path.expanduser(g.fasta))
|
|
154
|
+
from asebind.resources.fetch import FetchError, resource_file
|
|
155
|
+
|
|
156
|
+
name = {"GRCh37": "hg19", "GRCh38": "hg38"}[build]
|
|
157
|
+
try:
|
|
158
|
+
return resource_file(name, _resources_root(rc), "*.fa")
|
|
159
|
+
except FetchError as e:
|
|
160
|
+
raise click.ClickException(f"{e}; or set resources.genome.fasta") from None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@model_group.command("features")
|
|
164
|
+
@click.option("--labels", "labels_path", type=click.Path(exists=True, dir_okay=False), required=True)
|
|
165
|
+
@click.option("--build", type=click.Choice(["GRCh37", "GRCh38"]), default="GRCh38", show_default=True)
|
|
166
|
+
@click.option("--out", type=click.Path(dir_okay=False), required=True, help="labels + features .tsv.gz")
|
|
167
|
+
@click.option("--workers", type=int, default=1, show_default=True)
|
|
168
|
+
@pass_state
|
|
169
|
+
def model_features(state: State, labels_path: str, build: str, out: str, workers: int) -> None:
|
|
170
|
+
"""Our own features (PWM scan of every overlapping hit, both strands; E-scores) for labelled rows."""
|
|
171
|
+
import pandas as pd
|
|
172
|
+
|
|
173
|
+
from asebind.model import features as F
|
|
174
|
+
from asebind.model.context import load_context
|
|
175
|
+
from asebind.resources.genome import Fasta
|
|
176
|
+
|
|
177
|
+
rc = state.resolved()
|
|
178
|
+
lab = pd.read_csv(labels_path, sep="\t", dtype={"chrom": str})
|
|
179
|
+
ctx = load_context(_resources_root(rc))
|
|
180
|
+
click.echo(f"{len(lab)} rows; motifs for {len(ctx.motifs)} TFs; E-scores: {ctx.escores is not None}")
|
|
181
|
+
with Fasta(genome_for(rc, build)) as g:
|
|
182
|
+
seqs, match = F.flanks(g, lab)
|
|
183
|
+
click.echo(f"reference allele matches the genome for {match.mean():.4%} of rows")
|
|
184
|
+
X = F.build(lab, seqs, ctx, workers=workers, log=click.echo)
|
|
185
|
+
res = pd.concat([lab.reset_index(drop=True), X.reset_index(drop=True)], axis=1)
|
|
186
|
+
res["ref_matches_genome"] = match
|
|
187
|
+
res.to_csv(out, sep="\t", index=False, float_format="%.5g")
|
|
188
|
+
write_record(Path(out).parent, build_record(sys.argv, rc, resources=[Path(labels_path)]))
|
|
189
|
+
click.echo(f"wrote {out}")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@model_group.command("add-features")
|
|
193
|
+
@click.option(
|
|
194
|
+
"--data",
|
|
195
|
+
"data_path",
|
|
196
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
197
|
+
required=True,
|
|
198
|
+
help="labels + features .tsv.gz (from `model features`)",
|
|
199
|
+
)
|
|
200
|
+
@click.option(
|
|
201
|
+
"--set",
|
|
202
|
+
"feature_set",
|
|
203
|
+
type=click.Choice(["oth", "anc", "cons"]),
|
|
204
|
+
required=True,
|
|
205
|
+
help="oth: the other TFs' motifs at the SNP (I-35); anc: ancestral vs derived allele (I-32); "
|
|
206
|
+
"cons: phyloP conservation (I-31). anc and cons: GRCh38",
|
|
207
|
+
)
|
|
208
|
+
@click.option("--build", type=click.Choice(["GRCh37", "GRCh38"]), default="GRCh38", show_default=True)
|
|
209
|
+
@click.option("--out", type=click.Path(dir_okay=False), required=True)
|
|
210
|
+
@click.option("--workers", type=int, default=1, show_default=True)
|
|
211
|
+
@pass_state
|
|
212
|
+
def model_add_features(
|
|
213
|
+
state: State, data_path: str, feature_set: str, build: str, out: str, workers: int
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Add an optional feature set to a features table (same rows, same order, new columns)."""
|
|
216
|
+
import numpy as np
|
|
217
|
+
import pandas as pd
|
|
218
|
+
|
|
219
|
+
from asebind.model import features as F
|
|
220
|
+
from asebind.model import other_motifs
|
|
221
|
+
from asebind.model.context import load_motifs
|
|
222
|
+
from asebind.resources.genome import Fasta
|
|
223
|
+
|
|
224
|
+
rc = state.resolved()
|
|
225
|
+
data = pd.read_csv(data_path, sep="\t", dtype={"chrom": str})
|
|
226
|
+
root = _resources_root(rc)
|
|
227
|
+
if feature_set == "oth":
|
|
228
|
+
with Fasta(genome_for(rc, build)) as g:
|
|
229
|
+
seqs, _ = F.flanks(g, data)
|
|
230
|
+
X = other_motifs.build(data, seqs, load_motifs(root), workers=workers, log=click.echo)
|
|
231
|
+
elif feature_set == "cons":
|
|
232
|
+
from asebind.resources.conservation import conservation_features, open_tracks
|
|
233
|
+
|
|
234
|
+
if build != "GRCh38":
|
|
235
|
+
raise click.ClickException("conservation tracks are fetched for GRCh38 only")
|
|
236
|
+
tracks = open_tracks(root)
|
|
237
|
+
click.echo(f"conservation tracks: {', '.join(tracks)}")
|
|
238
|
+
X = conservation_features(tracks, data)
|
|
239
|
+
for bw in tracks.values():
|
|
240
|
+
bw.close()
|
|
241
|
+
click.echo(f"phyloP at the SNP known for {np.isfinite(X['p241_snp']).mean():.1%} (241-way) of rows")
|
|
242
|
+
else:
|
|
243
|
+
from asebind.resources.ancestral import Ancestral, ancestral_features
|
|
244
|
+
|
|
245
|
+
if build != "GRCh38":
|
|
246
|
+
raise click.ClickException("ancestral alleles are fetched for GRCh38 only")
|
|
247
|
+
with Ancestral.from_resources(root) as anc:
|
|
248
|
+
X = ancestral_features(anc, data)
|
|
249
|
+
click.echo(f"ancestral allele known for {(X['anc_known'] > 0).mean():.1%} of rows")
|
|
250
|
+
data = pd.concat([data.drop(columns=[c for c in X.columns if c in data]), X], axis=1)
|
|
251
|
+
data.to_csv(out, sep="\t", index=False, float_format="%.5g")
|
|
252
|
+
write_record(Path(out).parent, build_record(sys.argv, rc, resources=[Path(data_path)]))
|
|
253
|
+
click.echo(f"wrote {out} (+{len(X.columns)} columns: {', '.join(X.columns)})")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _load_data(path: str):
|
|
257
|
+
import pandas as pd
|
|
258
|
+
|
|
259
|
+
data = pd.read_csv(path, sep="\t", dtype={"chrom": str})
|
|
260
|
+
return data[data["ref_matches_genome"].astype(bool)].reset_index(drop=True)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@model_group.command("evaluate")
|
|
264
|
+
@click.option("--data", "data_path", type=click.Path(exists=True, dir_okay=False), required=True)
|
|
265
|
+
@click.option("--out", type=click.Path(file_okay=False), required=True)
|
|
266
|
+
@click.option(
|
|
267
|
+
"--models", "model_names", default="pwm_delta_lr,hgb,asebind,asebind_pwm_only", show_default=True
|
|
268
|
+
)
|
|
269
|
+
@click.option("--splits", "split_names", default="by_snp,by_chrom,by_tf", show_default=True)
|
|
270
|
+
@click.option("--seeds", default="0", show_default=True)
|
|
271
|
+
@click.option("--folds", "k", type=int, default=5, show_default=True)
|
|
272
|
+
@click.option(
|
|
273
|
+
"--task", type=int, default=None, help="run only unit N (one split x fold x model; array task id)"
|
|
274
|
+
)
|
|
275
|
+
@click.option("--merge-only", is_flag=True, help="only merge finished units from <out>/parts")
|
|
276
|
+
@click.option("--count-units", is_flag=True, help="print the number of units and exit")
|
|
277
|
+
@pass_state
|
|
278
|
+
def model_evaluate(
|
|
279
|
+
state: State,
|
|
280
|
+
data_path: str,
|
|
281
|
+
out: str,
|
|
282
|
+
model_names: str,
|
|
283
|
+
split_names: str,
|
|
284
|
+
seeds: str,
|
|
285
|
+
k: int,
|
|
286
|
+
task: int | None,
|
|
287
|
+
merge_only: bool,
|
|
288
|
+
count_units: bool,
|
|
289
|
+
) -> None:
|
|
290
|
+
"""Grouped cross-validation of the ASEbind model against simpler models.
|
|
291
|
+
|
|
292
|
+
Each (split, fold, model) unit is saved in <out>/parts when it finishes, so a rerun continues and the
|
|
293
|
+
units can run as a SLURM array (--task), followed by --merge-only.
|
|
294
|
+
"""
|
|
295
|
+
from asebind.model.train import eval_units, evaluate
|
|
296
|
+
|
|
297
|
+
rc = state.resolved()
|
|
298
|
+
data = _load_data(data_path)
|
|
299
|
+
args = (_csv(model_names), _csv(split_names), [int(x) for x in _csv(seeds)], k)
|
|
300
|
+
if count_units:
|
|
301
|
+
click.echo(len(eval_units(data, *args)))
|
|
302
|
+
return
|
|
303
|
+
paths = evaluate(data, Path(out), *args, log=click.echo, task=task, merge_only=merge_only)
|
|
304
|
+
if task is not None:
|
|
305
|
+
return
|
|
306
|
+
write_record(Path(out), build_record(sys.argv, rc, resources=[Path(data_path)]))
|
|
307
|
+
for name, p in paths.items():
|
|
308
|
+
click.echo(f"{name:16} {p}")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@model_group.command("train")
|
|
312
|
+
@click.option("--data", "data_path", type=click.Path(exists=True, dir_okay=False), required=True)
|
|
313
|
+
@click.option(
|
|
314
|
+
"--out",
|
|
315
|
+
type=click.Path(dir_okay=False),
|
|
316
|
+
default=None,
|
|
317
|
+
help="model .joblib (default <resources dir>/models/<model.name>/model.joblib)",
|
|
318
|
+
)
|
|
319
|
+
@click.option(
|
|
320
|
+
"--model-type",
|
|
321
|
+
default="asebind",
|
|
322
|
+
show_default=True,
|
|
323
|
+
help="asebind, or asebind+<set>[+<set>] with sets oth/anc/cons (the table must hold those columns)",
|
|
324
|
+
)
|
|
325
|
+
@pass_state
|
|
326
|
+
def model_train(state: State, data_path: str, out: str | None, model_type: str) -> None:
|
|
327
|
+
"""Train the final model on all labelled rows (calibrated on 5-fold out-of-fold predictions)."""
|
|
328
|
+
from asebind.model.train import train_final
|
|
329
|
+
|
|
330
|
+
rc = state.resolved()
|
|
331
|
+
path = Path(out) if out else _resources_root(rc) / "models" / rc.config.model.name / "model.joblib"
|
|
332
|
+
p = train_final(
|
|
333
|
+
_load_data(data_path),
|
|
334
|
+
path,
|
|
335
|
+
info={"data": str(data_path), "model_name": rc.config.model.name},
|
|
336
|
+
model=model_type,
|
|
337
|
+
)
|
|
338
|
+
write_record(path.parent, build_record(sys.argv, rc, resources=[Path(data_path)]))
|
|
339
|
+
click.echo(f"wrote {p}")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# --------------------------------------------------------------------------- predict
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@cli.command()
|
|
346
|
+
@click.argument("variants", type=click.Path(exists=True, dir_okay=False), required=False)
|
|
347
|
+
@click.option("--out", type=click.Path(file_okay=False), default=None, help="default: output.dir")
|
|
348
|
+
@click.option("--workers", type=int, default=None, help="default: executor.workers")
|
|
349
|
+
@pass_state
|
|
350
|
+
def predict(state: State, variants: str | None, out: str | None, workers: int | None) -> None:
|
|
351
|
+
"""Predict TF-binding changes (calibrated P(gain/loss/none)) for variants in a VCF or TSV."""
|
|
352
|
+
from asebind.predict import run
|
|
353
|
+
|
|
354
|
+
rc = state.resolved()
|
|
355
|
+
cfg = rc.config
|
|
356
|
+
path = variants or cfg.input.path
|
|
357
|
+
if not path:
|
|
358
|
+
raise click.UsageError("give VARIANTS or set input.path")
|
|
359
|
+
if cfg.input.kind not in ("vcf", "gwas"):
|
|
360
|
+
raise click.UsageError(f"input.kind {cfg.input.kind!r} is not supported yet; use a VCF or TSV")
|
|
361
|
+
root = _resources_root(rc)
|
|
362
|
+
model_path = Path(cfg.model.path) if cfg.model.path else _default_model(root, cfg.model.name)
|
|
363
|
+
if not model_path.exists():
|
|
364
|
+
raise click.ClickException(
|
|
365
|
+
f"model not found: {model_path} (run `asebind fetch asebind_model`, set model.path, "
|
|
366
|
+
"or train one with `asebind model train`)"
|
|
367
|
+
)
|
|
368
|
+
outdir = Path(out or cfg.output.dir)
|
|
369
|
+
paths = run(
|
|
370
|
+
Path(path),
|
|
371
|
+
genome_for(rc, cfg.input.build),
|
|
372
|
+
root,
|
|
373
|
+
model_path,
|
|
374
|
+
outdir,
|
|
375
|
+
tfs=cfg.tfs.include,
|
|
376
|
+
exclude=cfg.tfs.exclude,
|
|
377
|
+
risk_allele_column=cfg.input.risk_allele_column,
|
|
378
|
+
pwm_only_tier=cfg.tfs.pwm_only_tier,
|
|
379
|
+
workers=workers or cfg.executor.workers,
|
|
380
|
+
log=click.echo,
|
|
381
|
+
)
|
|
382
|
+
write_record(outdir, build_record(sys.argv, rc, resources=[Path(path), model_path]))
|
|
383
|
+
for name, p in paths.items():
|
|
384
|
+
click.echo(f"{name:12} {p}")
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# --------------------------------------------------------------------------- ASE (Phase 5)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
@cli.command()
|
|
391
|
+
@click.argument("counts", type=click.Path(exists=True, dir_okay=False), required=False)
|
|
392
|
+
@click.option("--out", type=click.Path(file_okay=False), default=None, help="default: output.dir")
|
|
393
|
+
@click.option(
|
|
394
|
+
"--by", default="population", show_default=True, help="Column to test separately ('' for none)."
|
|
395
|
+
)
|
|
396
|
+
@click.option("--min-snv-reads", type=int, default=5, show_default=True)
|
|
397
|
+
@pass_state
|
|
398
|
+
def ase(state: State, counts: str | None, out: str | None, by: str, min_snv_reads: int) -> None:
|
|
399
|
+
"""Beta-binomial allelic-imbalance test from per-person (x SNV) counts.
|
|
400
|
+
|
|
401
|
+
COUNTS: TSV with columns sample, role (case/control), k (reads on the copy of interest), n (reads on both
|
|
402
|
+
copies), and optionally population and snv. Cases have mean fraction p; controls pin the overdispersion.
|
|
403
|
+
"""
|
|
404
|
+
import pandas as pd
|
|
405
|
+
|
|
406
|
+
from asebind.ase.betabinom import per_person, run
|
|
407
|
+
|
|
408
|
+
rc = state.resolved()
|
|
409
|
+
cfg = rc.config.ase
|
|
410
|
+
path = counts or cfg.counts
|
|
411
|
+
if not path:
|
|
412
|
+
raise click.UsageError("give COUNTS or set ase.counts")
|
|
413
|
+
df = pd.read_csv(path, sep="\t")
|
|
414
|
+
need = {"sample", "role", "k", "n"}
|
|
415
|
+
if not need <= set(df.columns):
|
|
416
|
+
raise click.ClickException(f"{path}: needs columns {sorted(need)}")
|
|
417
|
+
kw = {"min_snv_reads": min_snv_reads, "min_person_reads": cfg.min_depth}
|
|
418
|
+
res = run(df, by=by or None, **kw)
|
|
419
|
+
if cfg.model == "binomial":
|
|
420
|
+
click.echo("note: ase.model=binomial ignores overdispersion; P values will be too small", err=True)
|
|
421
|
+
outdir = Path(out or rc.config.output.dir)
|
|
422
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
423
|
+
people = per_person(df, min_snv_reads, cfg.min_depth)
|
|
424
|
+
res.to_csv(outdir / "ase_tests.tsv", sep="\t", index=False, float_format="%.6g")
|
|
425
|
+
people.to_csv(outdir / "ase_per_person.tsv", sep="\t", index=False, float_format="%.6g")
|
|
426
|
+
with pd.ExcelWriter(outdir / "ase_tests.xlsx") as xw:
|
|
427
|
+
res.to_excel(xw, sheet_name="Tests", index=False)
|
|
428
|
+
people.to_excel(xw, sheet_name="Per person", index=False)
|
|
429
|
+
write_record(outdir, build_record(sys.argv, rc, resources=[Path(path)]))
|
|
430
|
+
click.echo(
|
|
431
|
+
res[["group", "cases", "controls", "p_hat", "ci_low", "ci_high", "p_value"]].to_string(index=False)
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
# --------------------------------------------------------------------------- compare (I-36)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
@cli.command()
|
|
439
|
+
@click.option(
|
|
440
|
+
"--predictions",
|
|
441
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
442
|
+
required=True,
|
|
443
|
+
help="asebind predict output (asebind_predictions.tsv)",
|
|
444
|
+
)
|
|
445
|
+
@click.option(
|
|
446
|
+
"--haplotypes",
|
|
447
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
448
|
+
required=True,
|
|
449
|
+
help="TSV: unit, id, copy_allele [, distance]: the allele on the copy of interest per variant",
|
|
450
|
+
)
|
|
451
|
+
@click.option(
|
|
452
|
+
"--ase",
|
|
453
|
+
"ase_path",
|
|
454
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
455
|
+
required=True,
|
|
456
|
+
help="TSV: unit and log2_ratio or p_hat [, p_value] (e.g. asebind ase output with a unit column)",
|
|
457
|
+
)
|
|
458
|
+
@click.option(
|
|
459
|
+
"--tf-roles",
|
|
460
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
461
|
+
default=None,
|
|
462
|
+
help="TSV: tf, role (activator/repressor); TFs without a role count as activators",
|
|
463
|
+
)
|
|
464
|
+
@click.option(
|
|
465
|
+
"--distance-scale",
|
|
466
|
+
type=float,
|
|
467
|
+
default=None,
|
|
468
|
+
help="weight exp(-|distance| / scale) when the haplotypes table has a distance column",
|
|
469
|
+
)
|
|
470
|
+
@click.option(
|
|
471
|
+
"--min-score", type=float, default=0.0, show_default=True, help="|score| needed to predict a direction"
|
|
472
|
+
)
|
|
473
|
+
@click.option(
|
|
474
|
+
"--alpha",
|
|
475
|
+
type=float,
|
|
476
|
+
default=0.05,
|
|
477
|
+
show_default=True,
|
|
478
|
+
help="ASE P value needed for a unit to count in the direction test (when p_value is given)",
|
|
479
|
+
)
|
|
480
|
+
@click.option("--out", type=click.Path(file_okay=False), default=None, help="default: output.dir")
|
|
481
|
+
@pass_state
|
|
482
|
+
def compare(
|
|
483
|
+
state: State,
|
|
484
|
+
predictions: str,
|
|
485
|
+
haplotypes: str,
|
|
486
|
+
ase_path: str,
|
|
487
|
+
tf_roles: str | None,
|
|
488
|
+
distance_scale: float | None,
|
|
489
|
+
min_score: float,
|
|
490
|
+
alpha: float,
|
|
491
|
+
out: str | None,
|
|
492
|
+
) -> None:
|
|
493
|
+
"""Sum the predicted binding changes over each copy of interest and compare with its ASE (I-36).
|
|
494
|
+
|
|
495
|
+
Reports concordance, never validation: binding is not expression (I-20)."""
|
|
496
|
+
import pandas as pd
|
|
497
|
+
|
|
498
|
+
from asebind import haplotype as H
|
|
499
|
+
|
|
500
|
+
rc = state.resolved()
|
|
501
|
+
rd = lambda p: pd.read_csv(p, sep=" ") # noqa: E731
|
|
502
|
+
contrib, skipped = H.contributions(
|
|
503
|
+
rd(predictions), rd(haplotypes), rd(tf_roles) if tf_roles else None, distance_scale
|
|
504
|
+
)
|
|
505
|
+
sc = H.scores(contrib)
|
|
506
|
+
units, summary = H.compare(sc, rd(ase_path), min_score=min_score, alpha=alpha)
|
|
507
|
+
outdir = Path(out or rc.config.output.dir)
|
|
508
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
509
|
+
tables = {
|
|
510
|
+
"compare_units": units,
|
|
511
|
+
"compare_summary": summary,
|
|
512
|
+
"haplotype_scores": sc,
|
|
513
|
+
"haplotype_contributions": contrib,
|
|
514
|
+
"skipped_variants": skipped,
|
|
515
|
+
}
|
|
516
|
+
for name, df in tables.items():
|
|
517
|
+
df.to_csv(outdir / f"{name}.tsv", sep=" ", index=False, float_format="%.6g")
|
|
518
|
+
with pd.ExcelWriter(outdir / "compare.xlsx") as xw:
|
|
519
|
+
pd.DataFrame(
|
|
520
|
+
[
|
|
521
|
+
("What", "Predicted binding change summed over the copy of interest vs that copy's ASE."),
|
|
522
|
+
(
|
|
523
|
+
"Score",
|
|
524
|
+
"sum of role x weight x (P(gain) - P(loss)) of the copy's allele, over variants and TFs",
|
|
525
|
+
),
|
|
526
|
+
("Role", "activator +1, repressor -1; TFs without a role are assumed activators"),
|
|
527
|
+
("Caution", "binding is not expression: concordance, not validation"),
|
|
528
|
+
],
|
|
529
|
+
columns=["Item", "Meaning"],
|
|
530
|
+
).to_excel(xw, sheet_name="Read me", index=False)
|
|
531
|
+
for name, df in tables.items():
|
|
532
|
+
df.to_excel(xw, sheet_name=name[:31], index=False)
|
|
533
|
+
write_record(
|
|
534
|
+
outdir, build_record(sys.argv, rc, resources=[Path(predictions), Path(haplotypes), Path(ase_path)])
|
|
535
|
+
)
|
|
536
|
+
if len(skipped):
|
|
537
|
+
click.echo(f"{skipped['id'].nunique()} variant(s) skipped (see skipped_variants.tsv)", err=True)
|
|
538
|
+
for _, r in summary.iterrows():
|
|
539
|
+
click.echo(f"{r['what']:36} {r['value']:.4g}")
|