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
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Run the honest re-test: every model on every split, raw and cleaned data; write TSV + xlsx results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from asebind.benchmark import asbdata, clean, metrics, models, splits
|
|
14
|
+
|
|
15
|
+
RAW_SPLITS = ("snpebot_random", "random_row")
|
|
16
|
+
MIN_TF_ROWS = 50
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _summarise(folds: pd.DataFrame) -> pd.DataFrame:
|
|
20
|
+
metric_cols = [c for c in folds.columns if c not in ("data", "model", "split", "fold", "seconds")]
|
|
21
|
+
g = folds.groupby(["data", "split", "model"], sort=False)
|
|
22
|
+
mean = g[metric_cols].mean().add_suffix("_mean")
|
|
23
|
+
sd = g[metric_cols].std(ddof=1).add_suffix("_sd")
|
|
24
|
+
out = pd.concat([g.size().rename("folds"), mean, sd], axis=1).reset_index()
|
|
25
|
+
return out
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _per_tf(pred: pd.DataFrame) -> pd.DataFrame:
|
|
29
|
+
rows = []
|
|
30
|
+
for (data, split, model, tf), d in pred.groupby(["data", "split", "model", "tf"], sort=False):
|
|
31
|
+
if len(d) < MIN_TF_ROWS:
|
|
32
|
+
continue
|
|
33
|
+
y = d["y"].to_numpy()
|
|
34
|
+
p = d[["p_gained", "p_lost", "p_none"]].to_numpy()
|
|
35
|
+
s = metrics.scores(y, p)
|
|
36
|
+
rows.append({"data": data, "split": split, "model": model, "tf": tf, **s})
|
|
37
|
+
return pd.DataFrame(rows)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run(
|
|
41
|
+
processed: Path,
|
|
42
|
+
sequences: Path | None,
|
|
43
|
+
out: Path,
|
|
44
|
+
model_names: Sequence[str] = models.DEFAULT_MODELS,
|
|
45
|
+
split_names: Sequence[str] = splits.SPLITS,
|
|
46
|
+
seeds: Sequence[int] = (0,),
|
|
47
|
+
k: int = 5,
|
|
48
|
+
cnn_epochs: int = 40,
|
|
49
|
+
log: Callable[[str], None] = print,
|
|
50
|
+
) -> dict[str, Path]:
|
|
51
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
raw = asbdata.read_processed(processed)
|
|
53
|
+
if sequences is not None:
|
|
54
|
+
raw = asbdata.attach_cell_lines(raw, asbdata.read_sequences(sequences))
|
|
55
|
+
else:
|
|
56
|
+
raw["cell_line"] = "unknown"
|
|
57
|
+
cleaned, clog = clean.clean(raw)
|
|
58
|
+
log(f"rows raw {len(raw)}, cleaned {len(cleaned)}")
|
|
59
|
+
|
|
60
|
+
summary_rows = [
|
|
61
|
+
{"data": name, "what": what, "value": value}
|
|
62
|
+
for name, d in (("raw", raw), ("clean", cleaned))
|
|
63
|
+
for what, value in [
|
|
64
|
+
("rows", len(d)),
|
|
65
|
+
("snps", d["snp"].nunique()),
|
|
66
|
+
("tfs", d["tf"].nunique()),
|
|
67
|
+
("tf_names_as_written", d["tf_raw"].nunique()),
|
|
68
|
+
("chromosomes", d["chrom"].nunique()),
|
|
69
|
+
*[(f"label_{lab}", int((d["label"] == lab).sum())) for lab in asbdata.LABELS],
|
|
70
|
+
*[(f"cell_line_{c}", int(n)) for c, n in d["cell_line"].value_counts().items()],
|
|
71
|
+
*[
|
|
72
|
+
(f"label_{lab}_cell_line_{c}", int(n))
|
|
73
|
+
for (c, lab), n in d.groupby(["cell_line", "label"]).size().items()
|
|
74
|
+
],
|
|
75
|
+
*[(f"top_tf_{t}", int(n)) for t, n in d["tf"].value_counts().head(10).items()],
|
|
76
|
+
]
|
|
77
|
+
]
|
|
78
|
+
pd.DataFrame(summary_rows).to_csv(out / "data_summary.tsv", sep="\t", index=False)
|
|
79
|
+
pd.DataFrame([{"step": k_, "rows": v} for k_, v in clog.items()]).to_csv(
|
|
80
|
+
out / "cleaning_log.tsv", sep="\t", index=False
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
fold_rows, pred_parts, skipped = [], [], []
|
|
84
|
+
for data_name, d in (("raw", raw), ("clean", cleaned)):
|
|
85
|
+
wanted = [s for s in split_names if data_name == "clean" or s in RAW_SPLITS]
|
|
86
|
+
swapped = asbdata.swap_alleles(d)
|
|
87
|
+
for split, fold, tr, te in splits.make_splits(d, wanted, k=k, seeds=seeds):
|
|
88
|
+
train, test = d.iloc[tr], d.iloc[te]
|
|
89
|
+
missing = sorted(set(asbdata.LABELS) - set(train["label"]))
|
|
90
|
+
if missing:
|
|
91
|
+
# e.g. by_cell_line: cell lines are recorded only for "none" rows, so holding one out
|
|
92
|
+
# leaves a training set without gains or losses. Such a fold cannot be scored.
|
|
93
|
+
skipped.append(
|
|
94
|
+
{"data": data_name, "split": split, "fold": fold, "missing_in_train": ",".join(missing)}
|
|
95
|
+
)
|
|
96
|
+
log(
|
|
97
|
+
f"{data_name:5} {split:15} fold {fold:<4} skipped: no {'/'.join(missing)} rows in training"
|
|
98
|
+
)
|
|
99
|
+
continue
|
|
100
|
+
y = models.encode(test["label"])
|
|
101
|
+
for mname in model_names:
|
|
102
|
+
t0 = time.time()
|
|
103
|
+
m = models.build(mname, seed=fold, cnn_epochs=cnn_epochs).fit(train)
|
|
104
|
+
p = m.predict_proba(test)
|
|
105
|
+
ps = m.predict_proba(swapped.iloc[te])
|
|
106
|
+
s = metrics.scores(y, p)
|
|
107
|
+
s["flip_rate"] = metrics.flip_rate(p, ps)
|
|
108
|
+
secs = round(time.time() - t0, 1)
|
|
109
|
+
fold_rows.append(
|
|
110
|
+
{"data": data_name, "model": mname, "split": split, "fold": fold, **s, "seconds": secs}
|
|
111
|
+
)
|
|
112
|
+
log(
|
|
113
|
+
f"{data_name:5} {split:15} fold {fold:<4} {mname:24} acc {s['accuracy']:.3f} "
|
|
114
|
+
f"bal {s['balanced_accuracy']:.3f} keras_bin {s['keras_binary_accuracy']:.3f} "
|
|
115
|
+
f"flip {s['flip_rate']:.3f} ({secs}s)"
|
|
116
|
+
)
|
|
117
|
+
pred_parts.append(
|
|
118
|
+
pd.DataFrame(
|
|
119
|
+
{
|
|
120
|
+
"data": data_name,
|
|
121
|
+
"split": split,
|
|
122
|
+
"fold": fold,
|
|
123
|
+
"model": mname,
|
|
124
|
+
"id": test["id"].to_numpy(),
|
|
125
|
+
"tf": test["tf"].to_numpy(),
|
|
126
|
+
"y": y,
|
|
127
|
+
"p_gained": p[:, 0],
|
|
128
|
+
"p_lost": p[:, 1],
|
|
129
|
+
"p_none": p[:, 2],
|
|
130
|
+
}
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
pd.DataFrame(skipped, columns=["data", "split", "fold", "missing_in_train"]).to_csv(
|
|
135
|
+
out / "skipped_folds.tsv", sep="\t", index=False
|
|
136
|
+
)
|
|
137
|
+
if not fold_rows:
|
|
138
|
+
raise ValueError(f"every fold was skipped (see {out / 'skipped_folds.tsv'}); nothing to score")
|
|
139
|
+
folds = pd.DataFrame(fold_rows)
|
|
140
|
+
pred = pd.concat(pred_parts, ignore_index=True)
|
|
141
|
+
summary = _summarise(folds)
|
|
142
|
+
per_tf = _per_tf(pred)
|
|
143
|
+
|
|
144
|
+
paths = {
|
|
145
|
+
"folds": out / "results_folds.tsv",
|
|
146
|
+
"summary": out / "results_summary.tsv",
|
|
147
|
+
"per_tf": out / "results_per_tf.tsv",
|
|
148
|
+
"predictions": out / "predictions.tsv.gz",
|
|
149
|
+
"xlsx": out / "retest_results.xlsx",
|
|
150
|
+
"settings": out / "retest_settings.json",
|
|
151
|
+
}
|
|
152
|
+
folds.to_csv(paths["folds"], sep="\t", index=False)
|
|
153
|
+
summary.to_csv(paths["summary"], sep="\t", index=False)
|
|
154
|
+
per_tf.to_csv(paths["per_tf"], sep="\t", index=False)
|
|
155
|
+
pred.to_csv(paths["predictions"], sep="\t", index=False, float_format="%.5g")
|
|
156
|
+
with pd.ExcelWriter(paths["xlsx"]) as xw:
|
|
157
|
+
summary.to_excel(xw, sheet_name="Summary", index=False)
|
|
158
|
+
folds.to_excel(xw, sheet_name="Folds", index=False)
|
|
159
|
+
per_tf.to_excel(xw, sheet_name="Per TF", index=False)
|
|
160
|
+
pd.DataFrame(summary_rows).to_excel(xw, sheet_name="Data", index=False)
|
|
161
|
+
pd.DataFrame([{"step": k_, "rows": v} for k_, v in clog.items()]).to_excel(
|
|
162
|
+
xw, sheet_name="Cleaning", index=False
|
|
163
|
+
)
|
|
164
|
+
paths["settings"].write_text(
|
|
165
|
+
json.dumps(
|
|
166
|
+
{
|
|
167
|
+
"processed": str(processed),
|
|
168
|
+
"sequences": str(sequences) if sequences else None,
|
|
169
|
+
"models": list(model_names),
|
|
170
|
+
"splits": list(split_names),
|
|
171
|
+
"seeds": list(seeds),
|
|
172
|
+
"k": k,
|
|
173
|
+
"cnn_epochs": cnn_epochs,
|
|
174
|
+
"min_tf_rows": MIN_TF_ROWS,
|
|
175
|
+
"numpy": np.__version__,
|
|
176
|
+
"pandas": pd.__version__,
|
|
177
|
+
},
|
|
178
|
+
indent=2,
|
|
179
|
+
)
|
|
180
|
+
+ "\n",
|
|
181
|
+
encoding="utf-8",
|
|
182
|
+
)
|
|
183
|
+
return paths
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Train/test splits (I-10).
|
|
2
|
+
|
|
3
|
+
``snpebot_random`` reproduces the published protocol: per class, a random 70 % of the smallest class goes to
|
|
4
|
+
training (balanced), every other row is test. The grouped splits keep a SNP, a TF, a chromosome or a cell line
|
|
5
|
+
entirely on one side.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Iterator
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
from sklearn.model_selection import GroupKFold, StratifiedKFold
|
|
15
|
+
|
|
16
|
+
Split = tuple[str, int, np.ndarray, np.ndarray] # (split name, fold, train idx, test idx)
|
|
17
|
+
|
|
18
|
+
GROUP_COLUMN = {"by_snp": "snp", "by_tf": "tf", "by_chrom": "chrom", "by_cell_line": "cell_line"}
|
|
19
|
+
SPLITS = ("snpebot_random", "random_row", *GROUP_COLUMN)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def snpebot_random(labels: pd.Series, seed: int, frac: float = 0.7) -> tuple[np.ndarray, np.ndarray]:
|
|
23
|
+
rng = np.random.default_rng(seed)
|
|
24
|
+
lab = labels.to_numpy()
|
|
25
|
+
n_train = int(min(np.sum(lab == c) for c in np.unique(lab)) * frac)
|
|
26
|
+
train = np.concatenate(
|
|
27
|
+
[rng.choice(np.flatnonzero(lab == c), n_train, replace=False) for c in np.unique(lab)]
|
|
28
|
+
)
|
|
29
|
+
test = np.setdiff1d(np.arange(len(lab)), train)
|
|
30
|
+
return np.sort(train), test
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _shuffled_groups(groups: pd.Series, seed: int) -> np.ndarray:
|
|
34
|
+
"""GroupKFold is deterministic; relabel groups at random so the seed decides the folds."""
|
|
35
|
+
uniq = groups.unique()
|
|
36
|
+
perm = dict(zip(uniq, np.random.default_rng(seed).permutation(len(uniq)), strict=True))
|
|
37
|
+
return groups.map(perm).to_numpy()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def make_splits(df: pd.DataFrame, names=SPLITS, k: int = 5, seeds=(0,)) -> Iterator[Split]:
|
|
41
|
+
for name in names:
|
|
42
|
+
for seed in seeds:
|
|
43
|
+
if name == "snpebot_random":
|
|
44
|
+
tr, te = snpebot_random(df["label"], seed)
|
|
45
|
+
yield name, seed, tr, te
|
|
46
|
+
elif name == "random_row":
|
|
47
|
+
skf = StratifiedKFold(n_splits=k, shuffle=True, random_state=seed)
|
|
48
|
+
for f, (tr, te) in enumerate(skf.split(np.zeros(len(df)), df["label"])):
|
|
49
|
+
yield name, seed * 100 + f, tr, te
|
|
50
|
+
elif name in GROUP_COLUMN:
|
|
51
|
+
col = GROUP_COLUMN[name]
|
|
52
|
+
usable = np.flatnonzero(~df[col].isin(["unknown", "multiple"]).to_numpy())
|
|
53
|
+
groups = df[col].iloc[usable]
|
|
54
|
+
n_groups = groups.nunique()
|
|
55
|
+
if n_groups < 2:
|
|
56
|
+
continue
|
|
57
|
+
gkf = GroupKFold(n_splits=min(k, n_groups))
|
|
58
|
+
for f, (tr, te) in enumerate(gkf.split(usable, groups=_shuffled_groups(groups, seed))):
|
|
59
|
+
yield name, seed * 100 + f, usable[tr], usable[te]
|
|
60
|
+
else:
|
|
61
|
+
raise ValueError(f"unknown split {name!r}; choose from {SPLITS}")
|
asebind/cli.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Command line: ``asebind doctor | fetch | predict | ase | compare | report | benchmark | config``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
from asebind import __version__
|
|
15
|
+
from asebind.config import ConfigError, ResolvedConfig, example_yaml, resolve
|
|
16
|
+
from asebind.runrecord import build_record, package_versions, write_record
|
|
17
|
+
from asebind.tools import resolve_all
|
|
18
|
+
|
|
19
|
+
DEFAULT_MODELS = (
|
|
20
|
+
"lr_delta_motif",
|
|
21
|
+
"lr_delta_escore",
|
|
22
|
+
"lr_engineered",
|
|
23
|
+
"hgb_engineered",
|
|
24
|
+
"hgb_engineered+antisym",
|
|
25
|
+
"cnn_snpebot",
|
|
26
|
+
) # kept here so `asebind --help` does not import scikit-learn; must match benchmark.models.DEFAULT_MODELS
|
|
27
|
+
SPLITS = ("snpebot_random", "random_row", "by_snp", "by_tf", "by_chrom", "by_cell_line")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class State:
|
|
31
|
+
def __init__(
|
|
32
|
+
self, config: str | None, sets: tuple[str, ...], tools: tuple[str, ...], tool_modules: tuple[str, ...]
|
|
33
|
+
) -> None:
|
|
34
|
+
self.config_path = config
|
|
35
|
+
self.sets = sets
|
|
36
|
+
self.tools = tools
|
|
37
|
+
self.tool_modules = tool_modules
|
|
38
|
+
self._resolved: ResolvedConfig | None = None
|
|
39
|
+
|
|
40
|
+
def resolved(self) -> ResolvedConfig:
|
|
41
|
+
if self._resolved is None:
|
|
42
|
+
try:
|
|
43
|
+
self._resolved = resolve(self.config_path, self.sets, self.tools, self.tool_modules)
|
|
44
|
+
except ConfigError as e:
|
|
45
|
+
raise click.ClickException(str(e)) from None
|
|
46
|
+
return self._resolved
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
pass_state = click.make_pass_decorator(State)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
53
|
+
@click.version_option(__version__, prog_name="asebind")
|
|
54
|
+
@click.option(
|
|
55
|
+
"--config",
|
|
56
|
+
"config",
|
|
57
|
+
type=click.Path(dir_okay=False),
|
|
58
|
+
default=None,
|
|
59
|
+
help="YAML config (default: ./asebind.yaml, then ~/.config/asebind/config.yaml).",
|
|
60
|
+
)
|
|
61
|
+
@click.option(
|
|
62
|
+
"--set",
|
|
63
|
+
"sets",
|
|
64
|
+
multiple=True,
|
|
65
|
+
metavar="KEY=VALUE",
|
|
66
|
+
help="Override any config value, e.g. --set executor.kind=slurm (repeatable).",
|
|
67
|
+
)
|
|
68
|
+
@click.option(
|
|
69
|
+
"--tool",
|
|
70
|
+
"tools",
|
|
71
|
+
multiple=True,
|
|
72
|
+
metavar="NAME=PATH",
|
|
73
|
+
help="Executable or bin directory for a tool, e.g. --tool fimo=/opt/meme/bin/fimo.",
|
|
74
|
+
)
|
|
75
|
+
@click.option(
|
|
76
|
+
"--tool-module",
|
|
77
|
+
"tool_modules",
|
|
78
|
+
multiple=True,
|
|
79
|
+
metavar="NAME=MODULE",
|
|
80
|
+
help="HPC module providing a tool, e.g. --tool-module fimo=meme/5.1.1.",
|
|
81
|
+
)
|
|
82
|
+
@click.pass_context
|
|
83
|
+
def cli(
|
|
84
|
+
ctx: click.Context,
|
|
85
|
+
config: str | None,
|
|
86
|
+
sets: tuple[str, ...],
|
|
87
|
+
tools: tuple[str, ...],
|
|
88
|
+
tool_modules: tuple[str, ...],
|
|
89
|
+
) -> None:
|
|
90
|
+
"""ASEbind: predict variant effects on TF binding and test them against allele-specific expression."""
|
|
91
|
+
ctx.obj = State(config, sets, tools, tool_modules)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --------------------------------------------------------------------------- config
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@cli.group("config")
|
|
98
|
+
def config_group() -> None:
|
|
99
|
+
"""Show or create the configuration."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@config_group.command("show")
|
|
103
|
+
@click.option("--format", "fmt", type=click.Choice(["table", "yaml"]), default="table", show_default=True)
|
|
104
|
+
@pass_state
|
|
105
|
+
def config_show(state: State, fmt: str) -> None:
|
|
106
|
+
"""Print the resolved configuration and where each value came from."""
|
|
107
|
+
rc = state.resolved()
|
|
108
|
+
if fmt == "yaml":
|
|
109
|
+
click.echo(yaml.safe_dump(rc.as_dict(), sort_keys=False).rstrip())
|
|
110
|
+
return
|
|
111
|
+
click.echo(f"# layers: {' < '.join(rc.layers)}")
|
|
112
|
+
rows = [(k, _fmt(v), src) for k, v, src in rc.leaves()]
|
|
113
|
+
w = max(len(k) for k, _, _ in rows)
|
|
114
|
+
wv = min(max(len(v) for _, v, _ in rows), 50)
|
|
115
|
+
for k, v, src in rows:
|
|
116
|
+
click.echo(f"{k:<{w}} {v:<{wv}} [{src}]")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _fmt(v: Any) -> str:
|
|
120
|
+
if v is None:
|
|
121
|
+
return "null"
|
|
122
|
+
if isinstance(v, bool):
|
|
123
|
+
return str(v).lower()
|
|
124
|
+
return str(v)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@config_group.command("init")
|
|
128
|
+
@click.argument("path", type=click.Path(dir_okay=False), default="asebind.yaml")
|
|
129
|
+
@click.option("--force", is_flag=True, help="Overwrite an existing file.")
|
|
130
|
+
def config_init(path: str, force: bool) -> None:
|
|
131
|
+
"""Write the commented example configuration to PATH (default ./asebind.yaml)."""
|
|
132
|
+
p = Path(path)
|
|
133
|
+
if p.exists() and not force:
|
|
134
|
+
raise click.ClickException(f"{p} exists; use --force to overwrite")
|
|
135
|
+
p.write_text(example_yaml(), encoding="utf-8")
|
|
136
|
+
click.echo(f"wrote {p}")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# --------------------------------------------------------------------------- doctor
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@cli.command()
|
|
143
|
+
@click.option(
|
|
144
|
+
"--out",
|
|
145
|
+
type=click.Path(file_okay=False),
|
|
146
|
+
default=None,
|
|
147
|
+
help="Also write a run record (asebind_run.json) to this directory.",
|
|
148
|
+
)
|
|
149
|
+
@click.option("--strict", is_flag=True, help="Exit with status 1 if any configured tool is missing.")
|
|
150
|
+
@pass_state
|
|
151
|
+
def doctor(state: State, out: str | None, strict: bool) -> None:
|
|
152
|
+
"""Check Python, packages, directories and every external tool in the config."""
|
|
153
|
+
rc = state.resolved()
|
|
154
|
+
cfg = rc.config
|
|
155
|
+
problems = 0
|
|
156
|
+
|
|
157
|
+
click.echo(f"asebind {__version__} python {sys.version.split()[0]} ({sys.platform})")
|
|
158
|
+
click.echo(f"config: {rc.yaml_path or 'none (defaults)'}")
|
|
159
|
+
|
|
160
|
+
click.echo("\npackages")
|
|
161
|
+
for name, ver in package_versions().items():
|
|
162
|
+
click.echo(f" {name:<14} {ver}")
|
|
163
|
+
|
|
164
|
+
click.echo("\ndirectories")
|
|
165
|
+
for label, raw in (
|
|
166
|
+
("resources.dir", cfg.resources.dir),
|
|
167
|
+
("tmp_dir", cfg.tmp_dir or tempfile.gettempdir()),
|
|
168
|
+
("output.dir", cfg.output.dir),
|
|
169
|
+
):
|
|
170
|
+
ok, msg = _dir_status(Path(os.path.expandvars(raw)).expanduser())
|
|
171
|
+
problems += 0 if ok else 1
|
|
172
|
+
click.echo(f" {'ok ' if ok else 'WARN'} {label:<14} {msg}")
|
|
173
|
+
|
|
174
|
+
click.echo("\ntools")
|
|
175
|
+
resolved_tools = resolve_all(cfg.tools)
|
|
176
|
+
missing = 0
|
|
177
|
+
for t in resolved_tools:
|
|
178
|
+
if t.found:
|
|
179
|
+
click.echo(
|
|
180
|
+
f" ok {t.name:<10} via {t.method:<9} {t.executable} {t.version or '(version unknown)'}"
|
|
181
|
+
)
|
|
182
|
+
else:
|
|
183
|
+
missing += 1
|
|
184
|
+
click.echo(f" MISS {t.name:<10} " + "; ".join(t.tried))
|
|
185
|
+
|
|
186
|
+
if out:
|
|
187
|
+
rec = build_record(sys.argv, rc, resolved_tools)
|
|
188
|
+
click.echo(f"\nrun record: {write_record(Path(out), rec)}")
|
|
189
|
+
|
|
190
|
+
click.echo(f"\n{missing} tool(s) missing, {problems} directory warning(s)")
|
|
191
|
+
if strict and missing:
|
|
192
|
+
sys.exit(1)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _dir_status(p: Path) -> tuple[bool, str]:
|
|
196
|
+
if p.is_dir():
|
|
197
|
+
return (os.access(p, os.W_OK), f"{p} ({'writable' if os.access(p, os.W_OK) else 'NOT writable'})")
|
|
198
|
+
parent = next((a for a in p.parents if a.exists()), None)
|
|
199
|
+
if parent is not None and os.access(parent, os.W_OK):
|
|
200
|
+
return True, f"{p} (will be created)"
|
|
201
|
+
return False, f"{p} (cannot be created)"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# --------------------------------------------------------------------------- later phases
|
|
205
|
+
|
|
206
|
+
_PLANNED = {
|
|
207
|
+
"report": ("Joint per-locus report.", "Phase 5"),
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _planned(name: str, help_text: str, phase: str) -> click.Command:
|
|
212
|
+
@click.command(
|
|
213
|
+
name,
|
|
214
|
+
help=f"{help_text} (not implemented yet: {phase})",
|
|
215
|
+
context_settings={"ignore_unknown_options": True, "allow_extra_args": True},
|
|
216
|
+
)
|
|
217
|
+
def cmd() -> None:
|
|
218
|
+
click.echo(f"asebind {name}: not implemented yet ({phase})", err=True)
|
|
219
|
+
sys.exit(2)
|
|
220
|
+
|
|
221
|
+
return cmd
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
for _name, (_help, _phase) in _PLANNED.items():
|
|
225
|
+
cli.add_command(_planned(_name, _help, _phase))
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@cli.group()
|
|
229
|
+
def benchmark() -> None:
|
|
230
|
+
"""Honest re-test of SNPeBoT-style models (Phase 2)."""
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@benchmark.command("retest")
|
|
234
|
+
@click.option(
|
|
235
|
+
"--data",
|
|
236
|
+
"processed",
|
|
237
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
238
|
+
required=True,
|
|
239
|
+
help="SNPeBoT Processed_ASB_data.csv (read only; never copied into the repository).",
|
|
240
|
+
)
|
|
241
|
+
@click.option(
|
|
242
|
+
"--sequences",
|
|
243
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
244
|
+
default=None,
|
|
245
|
+
help="ASB_sequences.tsv, used for cell lines (enables the by_cell_line split).",
|
|
246
|
+
)
|
|
247
|
+
@click.option("--out", type=click.Path(file_okay=False), required=True)
|
|
248
|
+
@click.option(
|
|
249
|
+
"--models",
|
|
250
|
+
"model_names",
|
|
251
|
+
default=",".join(DEFAULT_MODELS),
|
|
252
|
+
show_default=True,
|
|
253
|
+
help="Comma-separated; add +antisym to a name for the antisymmetric version.",
|
|
254
|
+
)
|
|
255
|
+
@click.option("--splits", "split_names", default=",".join(SPLITS), show_default=True)
|
|
256
|
+
@click.option("--seeds", default="0", show_default=True, help="Comma-separated split seeds.")
|
|
257
|
+
@click.option("--folds", "k", type=int, default=5, show_default=True)
|
|
258
|
+
@click.option("--cnn-epochs", type=int, default=40, show_default=True)
|
|
259
|
+
@pass_state
|
|
260
|
+
def benchmark_retest(
|
|
261
|
+
state: State,
|
|
262
|
+
processed: str,
|
|
263
|
+
sequences: str | None,
|
|
264
|
+
out: str,
|
|
265
|
+
model_names: str,
|
|
266
|
+
split_names: str,
|
|
267
|
+
seeds: str,
|
|
268
|
+
k: int,
|
|
269
|
+
cnn_epochs: int,
|
|
270
|
+
) -> None:
|
|
271
|
+
"""Every model on every split (random as published, and grouped by SNP, TF, chromosome, cell line)."""
|
|
272
|
+
from asebind.benchmark.retest import run
|
|
273
|
+
|
|
274
|
+
rc = state.resolved()
|
|
275
|
+
outdir = Path(out)
|
|
276
|
+
paths = run(
|
|
277
|
+
Path(processed),
|
|
278
|
+
Path(sequences) if sequences else None,
|
|
279
|
+
outdir,
|
|
280
|
+
model_names=_csv(model_names),
|
|
281
|
+
split_names=_csv(split_names),
|
|
282
|
+
seeds=[int(x) for x in _csv(seeds)],
|
|
283
|
+
k=k,
|
|
284
|
+
cnn_epochs=cnn_epochs,
|
|
285
|
+
log=click.echo,
|
|
286
|
+
)
|
|
287
|
+
res = [Path(processed)] + ([Path(sequences)] if sequences else [])
|
|
288
|
+
write_record(outdir, build_record(sys.argv, rc, resources=res))
|
|
289
|
+
for name, p in paths.items():
|
|
290
|
+
click.echo(f"{name:12} {p}")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _csv(text: str) -> list[str]:
|
|
294
|
+
return [x.strip() for x in text.split(",") if x.strip()]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def main() -> None:
|
|
298
|
+
cli(prog_name="asebind")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# fetch / model / predict live in cli_model.py; importing it registers them on `cli`
|
|
302
|
+
from asebind import cli_model # noqa: E402, F401
|