kdomainbench 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.
- kdomainbench/__init__.py +22 -0
- kdomainbench/cli.py +330 -0
- kdomainbench/config.py +133 -0
- kdomainbench/envs/install_r_packages.R +83 -0
- kdomainbench/envs/kdb_py.yml +253 -0
- kdomainbench/envs/kdb_spatialde.yml +133 -0
- kdomainbench/example.py +56 -0
- kdomainbench/methods/bayesspace.R +90 -0
- kdomainbench/methods/bnpspace.R +40 -0
- kdomainbench/methods/bnpspace_R/LICENSE +21 -0
- kdomainbench/methods/bnpspace_R/fix_clusters_model.cpp +305 -0
- kdomainbench/methods/bnpspace_R/main.R +184 -0
- kdomainbench/methods/bnpspace_R/model.cpp +452 -0
- kdomainbench/methods/bnpspace_R/utils.R +227 -0
- kdomainbench/methods/drsc.R +34 -0
- kdomainbench/methods/iscmeb.R +60 -0
- kdomainbench/methods/precast.R +78 -0
- kdomainbench/methods/run_cellcharter.py +87 -0
- kdomainbench/methods/run_deepst.py +90 -0
- kdomainbench/methods/run_spagcn.py +85 -0
- kdomainbench/methods/run_spatialde.py +56 -0
- kdomainbench/methods/scmeb.R +62 -0
- kdomainbench/metric_scripts/metrics.R +141 -0
- kdomainbench/metric_scripts/scs.py +120 -0
- kdomainbench/paper_metrics.py +120 -0
- kdomainbench/plotting.py +469 -0
- kdomainbench/registry.py +145 -0
- kdomainbench/results.py +416 -0
- kdomainbench/runner.py +340 -0
- kdomainbench-0.1.0.dist-info/METADATA +83 -0
- kdomainbench-0.1.0.dist-info/RECORD +36 -0
- kdomainbench-0.1.0.dist-info/WHEEL +5 -0
- kdomainbench-0.1.0.dist-info/entry_points.txt +2 -0
- kdomainbench-0.1.0.dist-info/licenses/LICENSE +674 -0
- kdomainbench-0.1.0.dist-info/licenses/src/kdomainbench/methods/bnpspace_R/LICENSE +21 -0
- kdomainbench-0.1.0.dist-info/top_level.txt +1 -0
kdomainbench/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""kdomainbench: benchmark of spatial-domain number (k) estimation methods.
|
|
2
|
+
|
|
3
|
+
import kdomainbench as kdb
|
|
4
|
+
clusters = kdb.run("SpaGCN", "data/D3_151509_5k.h5ad", kmax=30)
|
|
5
|
+
"""
|
|
6
|
+
__version__ = "0.1.0" # first: runner records it, and pyproject.toml reads it
|
|
7
|
+
|
|
8
|
+
from .config import set_env
|
|
9
|
+
from .example import example_data
|
|
10
|
+
from .paper_metrics import MetricsFailed, metrics
|
|
11
|
+
from .registry import METHODS, Method, get_method, list_methods
|
|
12
|
+
from .results import evaluate, k_accuracy, load_results, read_clusters, reference_annotation
|
|
13
|
+
from .runner import MethodFailed, run, run_all
|
|
14
|
+
from . import plotting as pl
|
|
15
|
+
|
|
16
|
+
__all__ = ["run", "run_all", "list_methods", "get_method", "Method", "METHODS", "set_env", "MethodFailed",
|
|
17
|
+
"read_clusters", "reference_annotation", "evaluate", "metrics", "MetricsFailed", "load_results",
|
|
18
|
+
"k_accuracy", "example_data", "pl"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def __dir__(): # tab completion of kdb shows the public names, not the modules behind them
|
|
22
|
+
return [*__all__, "__version__"]
|
kdomainbench/cli.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Run the ten k-estimation methods, compute their metrics and summarize the runs.
|
|
2
|
+
|
|
3
|
+
kdomainbench install create the environments, install the R packages
|
|
4
|
+
kdomainbench check do the environments start?
|
|
5
|
+
kdomainbench run -m all -i sample.h5ad one run folder per method under kdb_results/
|
|
6
|
+
kdomainbench metrics the twelve metrics of the paper for every run
|
|
7
|
+
kdomainbench summarize --csv summary.csv the runs, scored against the reference annotation
|
|
8
|
+
|
|
9
|
+
Exit status: 0 done, 1 an environment, a method or a metric failed, a file is missing or a value
|
|
10
|
+
cannot be used (an unknown method, a kmax out of range), 2 the command line cannot be parsed.
|
|
11
|
+
|
|
12
|
+
Documentation: https://pyanglab.github.io/domainNumber/
|
|
13
|
+
"""
|
|
14
|
+
import argparse
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import shlex
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
import warnings
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
import matplotlib
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pandas as pd
|
|
28
|
+
|
|
29
|
+
from . import __version__, config
|
|
30
|
+
from .paper_metrics import METRICS, MetricsFailed, metrics
|
|
31
|
+
from .plotting import plot_k_estimates
|
|
32
|
+
from .registry import METHODS, get_method
|
|
33
|
+
from .results import k_accuracy, load_results
|
|
34
|
+
from . import runner
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _methods(_):
|
|
38
|
+
print(f"{'method':<12}{'language':<9}{'env':<11}{'GPU':<5}uses kmax")
|
|
39
|
+
for method in METHODS.values():
|
|
40
|
+
gpu, uses_kmax = "yes" if method.gpu else "-", "yes" if method.uses_kmax else "no (auto)"
|
|
41
|
+
print(f"{method.name:<12}{method.language:<9}{method.env:<11}{gpu:<5}{uses_kmax}")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_CHECKS = {
|
|
45
|
+
"py": "import torch, cellcharter, deepstkit, SpaGCN; print('torch', torch.__version__, '| CUDA available:', torch.cuda.is_available())",
|
|
46
|
+
"spatialde": "import SpatialDE, tensorflow as tf; print('tensorflow', tf.__version__, '| GPUs:', len(tf.config.list_physical_devices('GPU')))",
|
|
47
|
+
# R: every package the method scripts load is there, and an .h5ad file can be read
|
|
48
|
+
# (zellkonverter fetches its reader on first use, which needs internet once)
|
|
49
|
+
"r": """args <- commandArgs(trailingOnly = TRUE)
|
|
50
|
+
packages <- strsplit(args[2], ",")[[1]]
|
|
51
|
+
absent <- packages[!vapply(packages, requireNamespace, logical(1), quietly = TRUE)]
|
|
52
|
+
shown <- c("PRECAST", "SC.MEB", "BayesSpace", "DR.SC", "iSC.MEB", "zellkonverter")
|
|
53
|
+
for (package in setdiff(intersect(shown, packages), absent))
|
|
54
|
+
cat(package, as.character(packageVersion(package)), "\n")
|
|
55
|
+
if (length(absent)) stop("missing R packages: ", paste(absent, collapse = ", "),
|
|
56
|
+
". Install them with 'kdomainbench install r' (", args[3], ")")
|
|
57
|
+
x <- suppressMessages(zellkonverter::readH5AD(args[1]))
|
|
58
|
+
cat("reads .h5ad files:", ncol(x), "spots\n")""",
|
|
59
|
+
}
|
|
60
|
+
_NO_GPU = 3 # exit code of the two snippets below
|
|
61
|
+
_NEEDS_GPU = {
|
|
62
|
+
"py": f"; import sys; sys.exit(0 if torch.cuda.is_available() else {_NO_GPU})",
|
|
63
|
+
"spatialde": f"; import sys; sys.exit(0 if tf.config.list_physical_devices('GPU') else {_NO_GPU})",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _install(args):
|
|
68
|
+
parts = list(dict.fromkeys(args.part or ["py", "spatialde", "r"]))
|
|
69
|
+
unknown = [part for part in parts if part not in ("py", "spatialde", "r", "metrics")]
|
|
70
|
+
if unknown:
|
|
71
|
+
sys.exit(f"kdomainbench: error: install takes py, spatialde, r or metrics, not {', '.join(unknown)}")
|
|
72
|
+
folder = os.environ.get("KDB_ENVS_DIR") and config.from_here(os.environ["KDB_ENVS_DIR"])
|
|
73
|
+
script = str(config.ENV_FILES / "install_r_packages.R")
|
|
74
|
+
steps = [] # every command is settled before the first one runs
|
|
75
|
+
for part in parts:
|
|
76
|
+
if part in config.DEFAULT_ENV_NAMES:
|
|
77
|
+
try: # creating it again would overwrite it, or ask to
|
|
78
|
+
print(f"[kdomainbench] {part} is there already: {config.interpreter(part)}")
|
|
79
|
+
continue
|
|
80
|
+
except FileNotFoundError:
|
|
81
|
+
pass
|
|
82
|
+
conda = next((found for name in (os.environ.get("CONDA"), "mamba", "conda")
|
|
83
|
+
if name and (found := shutil.which(name))), None)
|
|
84
|
+
if not conda:
|
|
85
|
+
sys.exit("kdomainbench: error: conda or mamba not found on PATH: load it (for example 'module "
|
|
86
|
+
"load conda'), install Miniforge from https://conda-forge.org/download/ and open a new "
|
|
87
|
+
"terminal, or set CONDA=/path/to/conda")
|
|
88
|
+
name = config.DEFAULT_ENV_NAMES[part]
|
|
89
|
+
target = ["-p", os.path.join(folder, name)] if folder else ["-n", name]
|
|
90
|
+
# as a method runs: pip must not count the packages of ~/.local or PYTHONPATH as installed
|
|
91
|
+
steps.append((part, [conda, "env", "create", *target, "-f", str(config.ENV_FILES / f"{name}.yml")],
|
|
92
|
+
config.child_env("Python")))
|
|
93
|
+
else:
|
|
94
|
+
# as the code runs: a second R for the metrics does not get KDB_R_LIB
|
|
95
|
+
own_r = part == "metrics" and config.configured("metrics")
|
|
96
|
+
library = None if own_r else config.r_lib()
|
|
97
|
+
steps.append((part, [config.interpreter(part if part == "metrics" else "r"), script,
|
|
98
|
+
*(["--metrics"] if part == "metrics" else []), *([library] if library else [])],
|
|
99
|
+
config.child_env("R", r_library=not own_r)))
|
|
100
|
+
for part, command, env in steps:
|
|
101
|
+
print("[kdomainbench] " + shlex.join(command), flush=True)
|
|
102
|
+
if subprocess.run(command, env=env).returncode:
|
|
103
|
+
sys.exit(f"kdomainbench: error: installing {part} failed")
|
|
104
|
+
if folder:
|
|
105
|
+
print(f"[kdomainbench] keep KDB_ENVS_DIR={folder} set: kdomainbench looks for the environments there")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _r_packages():
|
|
109
|
+
"""Every package the R method scripts load: library(x), x::f and Rcpp::depends(x)."""
|
|
110
|
+
names = set()
|
|
111
|
+
for f in runner.METHODS_DIR.rglob("*"):
|
|
112
|
+
if f.suffix == ".R":
|
|
113
|
+
text = f.read_text()
|
|
114
|
+
names.update(re.findall(r"^[^#\n]*\b(?:library|require)\(\"?([A-Za-z][\w.]*)", text, flags=re.M))
|
|
115
|
+
names.update(re.findall(r"^[^#\n]*?\b([A-Za-z][\w.]*)::", text, flags=re.M))
|
|
116
|
+
elif f.suffix == ".cpp":
|
|
117
|
+
names.update(re.findall(r"Rcpp::depends\((\w+)\)", f.read_text()))
|
|
118
|
+
return sorted(names)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _check(args):
|
|
122
|
+
passed = True
|
|
123
|
+
with tempfile.TemporaryDirectory() as scratch:
|
|
124
|
+
for key, code in _CHECKS.items():
|
|
125
|
+
try:
|
|
126
|
+
interpreter = config.interpreter(key)
|
|
127
|
+
except FileNotFoundError as e:
|
|
128
|
+
print(f"[{key}] MISSING: {e}")
|
|
129
|
+
passed = False
|
|
130
|
+
continue
|
|
131
|
+
if key == "r":
|
|
132
|
+
import anndata # slow to import, and needed by `check` only
|
|
133
|
+
h5ad = Path(scratch) / "check.h5ad"
|
|
134
|
+
anndata.AnnData(np.ones((3, 2), dtype="float32")).write_h5ad(h5ad)
|
|
135
|
+
command = [interpreter, "-e", code, str(h5ad), ",".join(_r_packages()),
|
|
136
|
+
f"{config.DOCS}/installation.html"]
|
|
137
|
+
else:
|
|
138
|
+
command = [interpreter, "-c", code + (_NEEDS_GPU[key] if args.gpu else "")]
|
|
139
|
+
method = next(method for method in METHODS.values() if method.env == key) # any method of it
|
|
140
|
+
env = runner.build_env(method, "gpu" if args.gpu else "cpu", args.gpu_id)
|
|
141
|
+
done = subprocess.run(command, env=env, capture_output=True, text=True)
|
|
142
|
+
if done.returncode in (0, _NO_GPU):
|
|
143
|
+
lines = done.stdout.strip().splitlines() + (["no GPU visible"] if done.returncode else [])
|
|
144
|
+
else:
|
|
145
|
+
lines = done.stdout.strip().splitlines() + ["FAILED"] + done.stderr.strip().splitlines()[-3:]
|
|
146
|
+
print(f"[{key}] {interpreter}\n " + "\n ".join(lines))
|
|
147
|
+
passed &= done.returncode == 0
|
|
148
|
+
if args.metrics:
|
|
149
|
+
passed &= _check_metrics(Path(scratch))
|
|
150
|
+
sys.exit(0 if passed else 1)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _check_metrics(scratch):
|
|
154
|
+
"""Compute the twelve metrics on a small made-up sample: the real test of the metric code."""
|
|
155
|
+
import anndata
|
|
156
|
+
row, column = np.divmod(np.arange(200), 20) # a 10 x 20 grid of spots
|
|
157
|
+
obs = pd.DataFrame({"clusters": np.where(column < 10, "left", "right"), "pixel_row": row * 10.0,
|
|
158
|
+
"pixel_col": column * 10.0}, index=[f"spot{i}" for i in range(200)])
|
|
159
|
+
adata = anndata.AnnData(np.ones((200, 2), dtype="float32"), obs=obs)
|
|
160
|
+
adata.obsm["spatial"] = obs[["pixel_col", "pixel_row"]].to_numpy()
|
|
161
|
+
adata.write_h5ad(scratch / "sample.h5ad")
|
|
162
|
+
(scratch / "run").mkdir()
|
|
163
|
+
labels = pd.DataFrame({"spot_id": obs.index, "cluster": row // 4})
|
|
164
|
+
labels.to_csv(scratch / "run" / "cluster_results.csv", index=False)
|
|
165
|
+
try:
|
|
166
|
+
values = metrics(scratch / "run", scratch / "sample.h5ad")
|
|
167
|
+
except (MetricsFailed, FileNotFoundError) as e:
|
|
168
|
+
print("[metrics] FAILED\n " + str(e).strip().replace("\n", "\n "))
|
|
169
|
+
return False
|
|
170
|
+
print(f"[metrics] {config.interpreter('metrics')} and {config.interpreter('py')}\n"
|
|
171
|
+
f" compute the {len(values)} metrics on a test sample")
|
|
172
|
+
return True
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _run(args):
|
|
176
|
+
everything = [name.lower() for name in args.method] == ["all"]
|
|
177
|
+
# each method once, under its own name: the count below needs it
|
|
178
|
+
methods = None if everything else list(dict.fromkeys(get_method(name).name for name in args.method))
|
|
179
|
+
done = runner.run_all(args.input, kmax=args.kmax, device=args.device, methods=methods,
|
|
180
|
+
out_root=args.out, gpu_id=args.gpu_id)
|
|
181
|
+
if len(done) < len(methods or METHODS): # run_all's warning has named them
|
|
182
|
+
sys.exit(1)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _inputs(args):
|
|
186
|
+
"""``--h5ad`` files as ``{dataset: file}``: each scores the runs of the dataset of its name."""
|
|
187
|
+
return {Path(f).stem: f for f in args.h5ad or []}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _metrics(args):
|
|
191
|
+
files = _inputs(args)
|
|
192
|
+
# h5ad= for its checks: a missing file, a name without a run
|
|
193
|
+
runs = load_results(args.root, score=False, h5ad=files)
|
|
194
|
+
runs = runs[runs["success"].astype(bool)]
|
|
195
|
+
if runs.empty:
|
|
196
|
+
sys.exit(f"kdomainbench: error: no successful run under {args.root!r} (looked for run_info.json files)")
|
|
197
|
+
rows, failed = {}, []
|
|
198
|
+
for run in runs.itertuples():
|
|
199
|
+
name = os.path.relpath(run.out_dir, args.root) # unique, also for two runs of one method
|
|
200
|
+
print(f"[kdomainbench] metrics of {name}", flush=True)
|
|
201
|
+
try:
|
|
202
|
+
rows[name] = metrics(run.out_dir, h5ad=files.get(run.dataset), recompute=args.force)
|
|
203
|
+
except (MetricsFailed, FileNotFoundError) as e:
|
|
204
|
+
print(f"[kdomainbench] {e}")
|
|
205
|
+
failed.append(name)
|
|
206
|
+
if rows:
|
|
207
|
+
print("\n" + pd.DataFrame(rows).T[METRICS].round(4).to_string())
|
|
208
|
+
if failed:
|
|
209
|
+
sys.exit(f"kdomainbench: error: no metrics for: {', '.join(failed)}")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _summarize(args):
|
|
213
|
+
with warnings.catch_warnings():
|
|
214
|
+
warnings.filterwarnings("ignore", message="successful runs without a score") # listed below, each one
|
|
215
|
+
summary = load_results(args.root, reference_key=args.reference_key, h5ad=_inputs(args))
|
|
216
|
+
if summary.empty:
|
|
217
|
+
sys.exit(f"kdomainbench: error: no run under {args.root!r} (looked for run_info.json files)")
|
|
218
|
+
shown = ["method", "dataset", "device_used", "k_estimated", "k_reference", "k_error", "ARI", "NMI",
|
|
219
|
+
"wall_time_s", "peak_rss_mb", "success"] # the CSV has every column
|
|
220
|
+
print(summary[shown].to_string(index=False))
|
|
221
|
+
for reason, n in summary["score_error"].dropna().value_counts().items():
|
|
222
|
+
print(f"not scored ({n} of {len(summary)}): {reason}")
|
|
223
|
+
if summary["score_error"].notna().any():
|
|
224
|
+
print("--h5ad FILE gives an input file that is elsewhere, --reference-key COLUMN another annotation column")
|
|
225
|
+
if args.csv:
|
|
226
|
+
summary.to_csv(args.csv, index=False)
|
|
227
|
+
if not summary["success"].any():
|
|
228
|
+
sys.exit(f"kdomainbench: error: no successful run under {args.root!r}")
|
|
229
|
+
if args.plot:
|
|
230
|
+
matplotlib.use("Agg")
|
|
231
|
+
plot_k_estimates(summary).figure.savefig(args.plot, dpi=150, bbox_inches="tight")
|
|
232
|
+
if summary["k_error"].notna().any(): # else the lines above say why no run was scored
|
|
233
|
+
print("\n" + k_accuracy(summary).to_string())
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def parser():
|
|
237
|
+
"""The argument parser of the ``kdomainbench`` command."""
|
|
238
|
+
top = argparse.ArgumentParser(prog="kdomainbench", description=__doc__,
|
|
239
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
240
|
+
top.add_argument("--version", action="version", version=f"kdomainbench {__version__}")
|
|
241
|
+
commands = top.add_subparsers(dest="command", required=True)
|
|
242
|
+
commands.add_parser(
|
|
243
|
+
"methods", help="list the methods",
|
|
244
|
+
description="Print one line per method: language, environment, GPU support and use of kmax.",
|
|
245
|
+
).set_defaults(function=_methods)
|
|
246
|
+
|
|
247
|
+
install = commands.add_parser(
|
|
248
|
+
"install", help="create the conda environments and install the R packages",
|
|
249
|
+
description="Create the two conda environments and install the R packages, from the files that come "
|
|
250
|
+
"with the package. With KDB_ENVS_DIR set, the environments go to that folder. With "
|
|
251
|
+
"KDB_R_LIB set, the R packages go to that library.")
|
|
252
|
+
install.add_argument("part", nargs="*", metavar="{py,spatialde,r,metrics}",
|
|
253
|
+
help="what to install: the conda environment kdb_py (py) or kdb_spatialde (spatialde), "
|
|
254
|
+
"the R packages of the methods (r), or those of the metric code (metrics). "
|
|
255
|
+
"Default: py spatialde r")
|
|
256
|
+
install.set_defaults(function=_install)
|
|
257
|
+
|
|
258
|
+
check = commands.add_parser(
|
|
259
|
+
"check", help="check that the three environments start",
|
|
260
|
+
description="Start each of the three environments once and print its key packages. "
|
|
261
|
+
"Exits 1 when one is missing or fails.")
|
|
262
|
+
check.add_argument("--gpu", action="store_true", help="check with the GPU visible, and fail when none is")
|
|
263
|
+
check.add_argument("--gpu-id", metavar="N",
|
|
264
|
+
help="GPU to make visible with --gpu (default: those in CUDA_VISIBLE_DEVICES, else 0)")
|
|
265
|
+
check.add_argument("--metrics", action="store_true",
|
|
266
|
+
help="also compute the twelve metrics on a small test sample")
|
|
267
|
+
check.set_defaults(function=_check)
|
|
268
|
+
|
|
269
|
+
run = commands.add_parser(
|
|
270
|
+
"run", help="run methods on an .h5ad file",
|
|
271
|
+
description="Run methods on an .h5ad file, one after another, each into its own run folder. "
|
|
272
|
+
"Exits 1 when a method did not finish.")
|
|
273
|
+
run.add_argument("-m", "--method", nargs="+", required=True, metavar="METHOD",
|
|
274
|
+
help="method names as 'kdomainbench methods' prints them (case-insensitive), or 'all'")
|
|
275
|
+
run.add_argument("-i", "--input", required=True, metavar="FILE", help="input .h5ad file")
|
|
276
|
+
run.add_argument("-k", "--kmax", type=int, default=30,
|
|
277
|
+
help="largest number of domains a method may consider, at least 2 (default: %(default)s). "
|
|
278
|
+
"BNPSpace accepts at most 30, and DeepST and SpaGCN do not use it")
|
|
279
|
+
run.add_argument("-d", "--device", choices=["cpu", "gpu"], default="cpu",
|
|
280
|
+
help="device. A method without GPU code runs on the CPU and warns (default: %(default)s)")
|
|
281
|
+
run.add_argument("--gpu-id", metavar="N",
|
|
282
|
+
help="GPU for -d gpu (default: those in CUDA_VISIBLE_DEVICES, else 0)")
|
|
283
|
+
run.add_argument("-o", "--out", default="kdb_results", metavar="DIR",
|
|
284
|
+
help="results folder. Each run goes to DIR/<method>/<dataset>_<device> and replaces a run "
|
|
285
|
+
"already there (default: %(default)s)")
|
|
286
|
+
run.set_defaults(function=_run)
|
|
287
|
+
|
|
288
|
+
root = dict(nargs="?", default="kdb_results", help="results folder (default: %(default)s)")
|
|
289
|
+
inputs = dict(action="append", metavar="FILE",
|
|
290
|
+
help="input file named <dataset>.h5ad, for runs whose recorded input file is not on this "
|
|
291
|
+
"machine. Repeat it for several datasets")
|
|
292
|
+
paper_metrics = commands.add_parser(
|
|
293
|
+
"metrics", help="compute the twelve metrics of every finished run",
|
|
294
|
+
description="Print the twelve metrics of the paper for every finished run under root. "
|
|
295
|
+
"A run without metric.csv is computed first.")
|
|
296
|
+
paper_metrics.add_argument("root", **root)
|
|
297
|
+
paper_metrics.add_argument("--h5ad", **inputs)
|
|
298
|
+
paper_metrics.add_argument("--force", action="store_true",
|
|
299
|
+
help="compute again for runs that already have metric.csv")
|
|
300
|
+
paper_metrics.set_defaults(function=_metrics)
|
|
301
|
+
|
|
302
|
+
summarize = commands.add_parser(
|
|
303
|
+
"summarize", help="score every run and print the tables",
|
|
304
|
+
description="Print the table of the runs under root, why runs were not scored, and the "
|
|
305
|
+
"k accuracy of each method.")
|
|
306
|
+
summarize.add_argument("root", **root)
|
|
307
|
+
summarize.add_argument("--h5ad", **inputs)
|
|
308
|
+
summarize.add_argument("--reference-key", default="clusters", metavar="COLUMN",
|
|
309
|
+
help="obs column with the reference annotation (default: %(default)s)")
|
|
310
|
+
summarize.add_argument("--csv", metavar="FILE",
|
|
311
|
+
help="also save the table of runs, with every column, as a CSV file")
|
|
312
|
+
summarize.add_argument("--plot", metavar="FILE",
|
|
313
|
+
help="also save the k-estimate figure. The extension gives the format (png, pdf, svg)")
|
|
314
|
+
summarize.set_defaults(function=_summarize)
|
|
315
|
+
commands.metavar = "{" + ",".join(commands.choices) + "}" # else a bare "kdomainbench" asks for "command"
|
|
316
|
+
return top
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def main(argv=None):
|
|
320
|
+
args = parser().parse_args(argv)
|
|
321
|
+
with warnings.catch_warnings(): # a warning prints as one message, without Python's source line
|
|
322
|
+
warnings.showwarning = lambda message, *_: print(f"kdomainbench: warning: {message}", file=sys.stderr)
|
|
323
|
+
try:
|
|
324
|
+
args.function(args)
|
|
325
|
+
except (ValueError, OSError) as e: # a wrong argument or a missing file: one line, no traceback
|
|
326
|
+
sys.exit(f"kdomainbench: error: {e}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
if __name__ == "__main__":
|
|
330
|
+
main()
|
kdomainbench/config.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Where the three method environments live.
|
|
2
|
+
|
|
3
|
+
Each environment is found, in order, from
|
|
4
|
+
1. an environment variable (KDB_PY_PYTHON, KDB_SPATIALDE_PYTHON, KDB_RSCRIPT, KDB_R_LIB, and
|
|
5
|
+
KDB_METRICS_RSCRIPT for the metric code, which otherwise runs in the R of the methods),
|
|
6
|
+
2. a value set with ``kdomainbench.set_env(...)``,
|
|
7
|
+
3. a conda env with the default name (kdb_py, kdb_spatialde) in the folder KDB_ENVS_DIR names,
|
|
8
|
+
next to the environment kdomainbench runs in or under the usual conda roots, and ``Rscript``
|
|
9
|
+
on PATH for R.
|
|
10
|
+
"""
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
DOCS = "https://pyanglab.github.io/domainNumber"
|
|
17
|
+
ENV_FILES = Path(__file__).resolve().parent / "envs" # kdb_py.yml, kdb_spatialde.yml, install_r_packages.R
|
|
18
|
+
DEFAULT_ENV_NAMES = {"py": "kdb_py", "spatialde": "kdb_spatialde"}
|
|
19
|
+
_ENV_VARS = {"py": "KDB_PY_PYTHON", "spatialde": "KDB_SPATIALDE_PYTHON", "r": "KDB_RSCRIPT",
|
|
20
|
+
"metrics": "KDB_METRICS_RSCRIPT"}
|
|
21
|
+
_overrides = {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def set_env(key, interpreter=None, r_lib=None):
|
|
25
|
+
"""Point one method environment at an interpreter, for this Python session.
|
|
26
|
+
|
|
27
|
+
An environment variable (``KDB_PY_PYTHON``, ``KDB_SPATIALDE_PYTHON``, ``KDB_RSCRIPT``,
|
|
28
|
+
``KDB_METRICS_RSCRIPT``, ``KDB_R_LIB``) still wins over this setting.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
key : str
|
|
33
|
+
``"py"`` (kdb_py), ``"spatialde"`` (kdb_spatialde), ``"r"`` (your R) or ``"metrics"``
|
|
34
|
+
(the R of the metric code, when it is not the R of the methods).
|
|
35
|
+
interpreter : str or path, optional
|
|
36
|
+
The environment's ``python``, or ``Rscript`` for ``"r"`` and ``"metrics"``. It is
|
|
37
|
+
checked when a method starts, not here.
|
|
38
|
+
r_lib : str or path, optional
|
|
39
|
+
An isolated R library for the R methods, whatever ``key`` is. They then see only this
|
|
40
|
+
library and base R. The metric code uses it too, unless ``"metrics"`` names its own
|
|
41
|
+
``Rscript``.
|
|
42
|
+
|
|
43
|
+
Raises
|
|
44
|
+
------
|
|
45
|
+
ValueError
|
|
46
|
+
Unknown key.
|
|
47
|
+
|
|
48
|
+
Examples
|
|
49
|
+
--------
|
|
50
|
+
>>> kdb.set_env("spatialde", "/opt/envs/kdb_spatialde/bin/python")
|
|
51
|
+
>>> kdb.set_env("r", "/usr/bin/Rscript", r_lib="/path/to/R/library")
|
|
52
|
+
"""
|
|
53
|
+
if key not in _ENV_VARS:
|
|
54
|
+
raise ValueError(f"key must be one of {list(_ENV_VARS)}, not {key!r}")
|
|
55
|
+
if interpreter:
|
|
56
|
+
_overrides[key] = str(interpreter)
|
|
57
|
+
if r_lib:
|
|
58
|
+
_overrides["r_lib"] = str(r_lib)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _env_dirs():
|
|
62
|
+
"""Folders that may hold the conda envs: KDB_ENVS_DIR, then the one this Python's own env is in."""
|
|
63
|
+
folders = [Path(sys.prefix).parent]
|
|
64
|
+
if os.environ.get("KDB_ENVS_DIR"):
|
|
65
|
+
folders.insert(0, Path(from_here(os.environ["KDB_ENVS_DIR"])))
|
|
66
|
+
for variable in ("CONDA_EXE", "MAMBA_EXE"):
|
|
67
|
+
if os.environ.get(variable):
|
|
68
|
+
folders.append(Path(os.environ[variable]).resolve().parent.parent / "envs")
|
|
69
|
+
if os.environ.get("CONDA_PREFIX"):
|
|
70
|
+
prefix = Path(os.environ["CONDA_PREFIX"])
|
|
71
|
+
folders.append(prefix.parent if prefix.parent.name == "envs" else prefix / "envs")
|
|
72
|
+
home = Path.home()
|
|
73
|
+
folders += [home / name / "envs" for name in ("anaconda3", "miniconda3", "mambaforge", "miniforge3", ".conda")]
|
|
74
|
+
return list(dict.fromkeys(folders))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def configured(key):
|
|
78
|
+
"""The interpreter set by environment variable or set_env, else None."""
|
|
79
|
+
for source, path in ((_ENV_VARS[key], os.environ.get(_ENV_VARS[key])),
|
|
80
|
+
(f"set_env({key!r}, ...)", _overrides.get(key))):
|
|
81
|
+
if path:
|
|
82
|
+
found = shutil.which(path)
|
|
83
|
+
if not found:
|
|
84
|
+
raise FileNotFoundError(f"{source} points to {path}, which is not an interpreter")
|
|
85
|
+
return from_here(found)
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def from_here(path):
|
|
90
|
+
"""A relative path counted from the current folder, since a method starts in its run folder."""
|
|
91
|
+
return path if os.path.isabs(path) else os.path.join(os.getcwd(), path)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def interpreter(key):
|
|
95
|
+
"""The interpreter of ``"py"``, ``"spatialde"``, ``"r"`` or ``"metrics"``, looked up in the order of the
|
|
96
|
+
module docstring. ``"metrics"`` without a setting of its own is ``"r"``. The FileNotFoundError says how to
|
|
97
|
+
install or name it."""
|
|
98
|
+
path = configured(key)
|
|
99
|
+
if path:
|
|
100
|
+
return path
|
|
101
|
+
if key == "metrics":
|
|
102
|
+
return interpreter("r")
|
|
103
|
+
if key == "r":
|
|
104
|
+
found = shutil.which("Rscript")
|
|
105
|
+
if found:
|
|
106
|
+
return found
|
|
107
|
+
raise FileNotFoundError("Rscript not found: install R 4.4 or later, or load it (for example "
|
|
108
|
+
f"'module load R'), or set KDB_RSCRIPT=/path/to/Rscript ({DOCS}/installation.html)")
|
|
109
|
+
name = DEFAULT_ENV_NAMES[key]
|
|
110
|
+
for folder in _env_dirs():
|
|
111
|
+
python = folder / name / "bin" / "python"
|
|
112
|
+
if python.exists():
|
|
113
|
+
return str(python)
|
|
114
|
+
raise FileNotFoundError(f"conda env {name!r} not found: create it with 'kdomainbench install {key}' "
|
|
115
|
+
f"({DOCS}/installation.html), or set {_ENV_VARS[key]}=/path/to/python")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def r_lib():
|
|
119
|
+
"""Optional isolated R library (only this library + base R are visible to the R methods)."""
|
|
120
|
+
library = os.environ.get("KDB_R_LIB") or _overrides.get("r_lib")
|
|
121
|
+
return library and from_here(library)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def child_env(language, r_library=True):
|
|
125
|
+
"""The environment variables for a method or metric process, without the caller's own packages."""
|
|
126
|
+
env = dict(os.environ)
|
|
127
|
+
if language == "Python":
|
|
128
|
+
env["PYTHONNOUSERSITE"] = "1" # keep ~/.local packages out of the environment
|
|
129
|
+
env["PYTHONUNBUFFERED"] = "1" # stream the log while the process runs
|
|
130
|
+
env.pop("PYTHONPATH", None)
|
|
131
|
+
elif r_library and r_lib(): # isolated R library: hide user and site libraries
|
|
132
|
+
env.update(R_LIBS=r_lib(), R_LIBS_USER="/nonexistent", R_LIBS_SITE="/nonexistent")
|
|
133
|
+
return env
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Install the R packages kdomainbench needs into your own R.
|
|
2
|
+
# Only missing packages are installed, from CRAN and Bioconductor as usual.
|
|
3
|
+
# Usage: kdomainbench install r, or kdomainbench install metrics. They run
|
|
4
|
+
# Rscript install_r_packages.R [--metrics] [library]
|
|
5
|
+
# (default) the packages of the six R methods (R >= 4.4)
|
|
6
|
+
# --metrics the packages of the metric code instead (R >= 4.5 with Bioconductor >= 3.22,
|
|
7
|
+
# the first release with spARI)
|
|
8
|
+
# library optional separate library. Then set KDB_R_LIB to it.
|
|
9
|
+
# The versions of the benchmark are listed in envs/kdb_r.lock.csv of the repository (for reference).
|
|
10
|
+
args <- commandArgs(trailingOnly = TRUE)
|
|
11
|
+
metrics <- "--metrics" %in% args
|
|
12
|
+
args <- setdiff(args, "--metrics")
|
|
13
|
+
needed <- if (metrics) "4.5" else "4.4"
|
|
14
|
+
if (getRversion() < needed) # before a long install that could only fail
|
|
15
|
+
stop("this R is ", getRversion(), " (", R.home("bin"), "), and the packages need R >= ", needed,
|
|
16
|
+
". Name another Rscript in ", if (metrics) "KDB_METRICS_RSCRIPT" else "KDB_RSCRIPT")
|
|
17
|
+
if (length(args) > 0) {
|
|
18
|
+
# A separate library is all the R methods see with KDB_R_LIB (plus base R), so a package
|
|
19
|
+
# that is only in your user or site library counts as missing here.
|
|
20
|
+
lib <- args[1]
|
|
21
|
+
dir.create(lib, recursive = TRUE, showWarnings = FALSE)
|
|
22
|
+
.libPaths(lib, include.site = FALSE)
|
|
23
|
+
} else {
|
|
24
|
+
lib <- .libPaths()[1]
|
|
25
|
+
if (file.access(lib, 2) != 0) {
|
|
26
|
+
# e.g. an R from a module, whose first library is the read-only system one
|
|
27
|
+
lib <- Sys.getenv("R_LIBS_USER")
|
|
28
|
+
dir.create(lib, recursive = TRUE, showWarnings = FALSE)
|
|
29
|
+
.libPaths(c(lib, .libPaths()))
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
cat("installing missing packages into", lib, "\n")
|
|
33
|
+
if (is.null(getOption("repos")) || getOption("repos")["CRAN"] %in% c("@CRAN@", NA))
|
|
34
|
+
options(repos = c(CRAN = "https://cloud.r-project.org"))
|
|
35
|
+
|
|
36
|
+
if (metrics) {
|
|
37
|
+
# what src/kdomainbench/metric_scripts/metrics.R calls. HDF5Array and rhdf5 are behind
|
|
38
|
+
# zellkonverter's reader = "R". The GitHub packages are pinned to the commits of the paper.
|
|
39
|
+
cran <- c("clevr", "aricode", "ClusterR", "remotes", "BiocManager")
|
|
40
|
+
bioc <- c("spARI", "zellkonverter", "SummarizedExperiment", "HDF5Array", "rhdf5")
|
|
41
|
+
github <- c(lisi = "immunogenomics/lisi@a917556310d8d2c66833dcc35aa3d0f4d1b6e0f4",
|
|
42
|
+
SPARK = "xzhoulab/SPARK@a8b4bf27b804604dfda53da42992f100b8e4e727",
|
|
43
|
+
SpatialPCA = "shangll123/SpatialPCA@1d4dbb1fe6f23b77bb7ed805ce2de8bbc017ef66")
|
|
44
|
+
archive <- character()
|
|
45
|
+
} else {
|
|
46
|
+
# what the method scripts load, and mclust, which SC.MEB 1.1 depends on
|
|
47
|
+
cran <- c("PRECAST", "DR.SC", "Seurat", "Rcpp", "RcppArmadillo", "flexclust",
|
|
48
|
+
"philentropy", "fastcluster", "dynamicTreeCut", "purrr", "deldir", "glue", "ggplot2",
|
|
49
|
+
"mclust", "remotes", "BiocManager")
|
|
50
|
+
bioc <- c("BayesSpace", "zellkonverter", "SingleCellExperiment", "SummarizedExperiment", "scran",
|
|
51
|
+
"scater", "scuttle", "BiocSingular")
|
|
52
|
+
# iSC.MEB is no longer on CRAN. This commit of its authors' repository is its release 1.0.
|
|
53
|
+
github <- c(iSC.MEB = "XiaoZhangryy/iSC.MEB@233471ca6a96e2b5ada79f150d3574c1cd906e15")
|
|
54
|
+
# SC.MEB was archived on CRAN. 1.1 is its last release.
|
|
55
|
+
archive <- c(SC.MEB = "https://cran.r-project.org/src/contrib/Archive/SC.MEB/SC.MEB_1.1.tar.gz")
|
|
56
|
+
}
|
|
57
|
+
missing <- function(p) p[!vapply(p, requireNamespace, logical(1), quietly = TRUE)]
|
|
58
|
+
|
|
59
|
+
if (getOption("Ncpus", 1L) == 1L) options(Ncpus = min(4L, parallel::detectCores())) # build 4 packages at a time
|
|
60
|
+
todo <- missing(c("remotes", "BiocManager"))
|
|
61
|
+
if (length(todo)) install.packages(todo, lib = lib)
|
|
62
|
+
# CRAN and this R's Bioconductor release as one source. DR.SC and PRECAST are on CRAN and need
|
|
63
|
+
# Bioconductor packages, so the two cannot be installed one after the other. And from here on,
|
|
64
|
+
# dependencies come from this release, never a newer one.
|
|
65
|
+
options(repos = BiocManager::repositories())
|
|
66
|
+
todo <- missing(c(cran, bioc))
|
|
67
|
+
if (length(todo)) install.packages(todo, lib = lib)
|
|
68
|
+
if (length(c(github, archive))) {
|
|
69
|
+
# lisi, SPARK and SC.MEB ask for C++11, which RcppArmadillo >= 15.4 no longer compiles under:
|
|
70
|
+
# build them as C++14. R_MAKEVARS_USER replaces ~/.R/Makevars, so its lines are kept.
|
|
71
|
+
user <- Sys.getenv("R_MAKEVARS_USER", "~/.R/Makevars")
|
|
72
|
+
makevars <- tempfile("Makevars")
|
|
73
|
+
writeLines(c(if (file.exists(user)) readLines(user), "CXX11STD = -std=gnu++14"), makevars)
|
|
74
|
+
Sys.setenv(R_MAKEVARS_USER = makevars)
|
|
75
|
+
}
|
|
76
|
+
for (p in missing(names(github))) remotes::install_github(github[[p]], lib = lib, upgrade = "never")
|
|
77
|
+
for (p in missing(names(archive))) remotes::install_url(archive[[p]], lib = lib, upgrade = "never")
|
|
78
|
+
|
|
79
|
+
left <- missing(c(cran, bioc, names(github), names(archive)))
|
|
80
|
+
if ("spARI" %in% left)
|
|
81
|
+
message("spARI is in Bioconductor from release 3.22 (R 4.5). This R uses release ", BiocManager::version())
|
|
82
|
+
if (length(left)) stop("not installed: ", paste(left, collapse = ", "))
|
|
83
|
+
cat("all R packages of the kdomainbench", if (metrics) "metrics" else "methods", "are installed\n")
|