Skip to content

Scores

Read runs back and score them against the reference annotation. These calls need only the kdomainbench package, not the method environments, except kdb.metrics, which runs the paper's metric code in R and in kdb_py.

read_clusters

read_clusters(path)

Read the domains of one run.

PARAMETER DESCRIPTION
path

A run folder, or its cluster_results.csv.

TYPE: str or path

RETURNS DESCRIPTION
DataFrame

Indexed by spot_id, with the label (as a string) in cluster. Spots without a label are left out.

RAISES DESCRIPTION
FileNotFoundError

There is no such folder or file, or the run did not finish.

ValueError

The file has no cluster column, or it is the input .h5ad file.

Examples:

>>> clusters = kdb.read_clusters("kdb_results/SpaGCN/D3_151509_5k_cpu")
>>> clusters["cluster"].nunique()
4

reference_annotation

reference_annotation(h5ad, reference_key='clusters')

Read the reference annotation: the annotated domain of each spot.

PARAMETER DESCRIPTION
h5ad

The input file, or the data already in memory.

TYPE: str or path or AnnData

reference_key

Column of obs that holds the annotation.

TYPE: str DEFAULT: 'clusters'

RETURNS DESCRIPTION
Series

Label (as a string) per spot. Spots without a label are dropped.

RAISES DESCRIPTION
FileNotFoundError

h5ad is not a file.

KeyError

obs has no column reference_key. The message lists the columns it has.

ValueError

h5ad is not an .h5ad file.

Examples:

>>> kdb.reference_annotation("data/D3_151509_5k.h5ad").nunique()
7

evaluate

evaluate(clusters, reference, reference_key='clusters')

Score one run against the reference annotation.

k_estimated counts every label the method returned and k_reference every annotated domain. ARI and NMI use the spots that have both a label and an annotation. NMI is normalized by the arithmetic mean of the two entropies (the scikit-learn default).

PARAMETER DESCRIPTION
clusters

The run's labels, as returned by run or read_clusters, or its run folder.

TYPE: DataFrame or Series or path

reference

The .h5ad file or AnnData object, the labels from reference_annotation, or another run (its labels or its run folder) to see how far two methods agree.

TYPE: path or AnnData or Series or DataFrame

reference_key

Column of obs with the reference annotation, when reference is a file or an AnnData object.

TYPE: str DEFAULT: 'clusters'

RETURNS DESCRIPTION
dict

k_estimated, k_reference, k_error (estimated − reference), ARI and NMI (rounded to 4 digits, while metrics gives full precision) and n_spots_scored (the spots ARI and NMI were computed on).

RAISES DESCRIPTION
FileNotFoundError

The run folder or the .h5ad file is missing.

KeyError

obs has no column reference_key.

TypeError

clusters or reference is not one of the types above.

ValueError

No spot has both a label and an annotation (the two do not use the same barcodes), a barcode occurs twice, or the file is not an .h5ad file.

WARNS DESCRIPTION
UserWarning

reference is a file or an AnnData object, and some labels belong to none of its spots. They are not scored.

Examples:

>>> kdb.evaluate("kdb_results/SpaGCN/D3_151509_5k_cpu", "data/D3_151509_5k.h5ad")
{'k_estimated': 4, 'k_reference': 7, 'k_error': -3, 'ARI': 0.4487, 'NMI': 0.5694, 'n_spots_scored': 4786}

metrics

metrics(run, h5ad=None, recompute=False)

Compute the twelve metrics of the paper for one finished run.

Eleven metrics come from metrics.R, run in your R, and SCS from scs.py, run in kdb_py. The result is saved as metric.csv in the run folder, where load_results picks it up, and a later call reads it back.

The input file needs pixel coordinates in obs["pixel_row"], obs["pixel_col"] and obsm["spatial"], and a reference annotation in obs["clusters"] with at least two domains. Every spot needs both an annotation and a label from the run.

PARAMETER DESCRIPTION
run

A run folder with cluster_results.csv.

TYPE: str or path

h5ad

The input file. Default: the path recorded in the run's run_info.json. It is read only when the metrics are computed, not when metric.csv is read back.

TYPE: str or path DEFAULT: None

recompute

True = compute again when the run folder already has metric.csv, for example after the annotation changed.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
Series

ARI, spARI, NMI, FM, AMI, Purity, HOM, COM, PAS, CHAOS, LISI and SCS. SCS is NaN for a run with one domain.

RAISES DESCRIPTION
MetricsFailed

The metric code stopped, for example because a package is missing or a spot has no label.

FileNotFoundError

run is not a run folder, or the input file or an environment is missing.

Examples:

>>> kdb.metrics("kdb_results/DR.SC/D3_151509_5k_cpu").round(4).head(3)
metric
ARI      0.2333
spARI    0.2110
NMI      0.4826
Name: value, dtype: float64

MetricsFailed

Bases: RuntimeError

The metric code stopped with an error or returned no value.

The message names the run's metric.log, which holds the output of the metric code.

load_results

load_results(root='kdb_results', reference_key='clusters', score=True, h5ad=None)

Collect every run under a folder into one table.

Reads each run_info.json under root, at any depth. Each successful run is scored against the reference annotation of its own .h5ad file.

PARAMETER DESCRIPTION
root

Folder that holds the run folders.

TYPE: str or path DEFAULT: 'kdb_results'

reference_key

Column of obs with the reference annotation.

TYPE: str DEFAULT: 'clusters'

score

False = only collect the run records, without scoring.

TYPE: bool DEFAULT: True

h5ad

Where the input file is now, when the runs were made elsewhere: one file when all runs are of one dataset, else {dataset: file}. Default: the path recorded in each run_info.json.

TYPE: str or path or dict DEFAULT: None

RETURNS DESCRIPTION
DataFrame

One row per run, always with method, dataset, device_requested, device_used, kmax, k_estimated, k_reference, k_error, ARI, NMI, wall_time_s, peak_rss_mb, success, n_spots_scored, score_error and out_dir (the run folder), then the other fields of run_info.json except command (n_spots is the number of labeled spots). A run that could not be scored, for example because its file has no annotation, has the reason in score_error and no k_reference, k_error, ARI or NMI. With reference_key="clusters", a run with a metric.csv from metrics also has the ten other metrics of the paper as columns. The table is empty, with the columns above, when root holds no run.

RAISES DESCRIPTION
FileNotFoundError

root is not a folder, or a file given as h5ad does not exist or is a folder.

TypeError

h5ad is an AnnData object, not a file.

ValueError

A file given as h5ad is not an .h5ad file, h5ad is one file and the runs are of several datasets, or h5ad names a dataset that has no run under root.

WARNS DESCRIPTION
UserWarning

Successful runs could not be scored, for example because their input file is not found, or labels of a run belong to no spot of its input file. A file without an annotation gives no warning.

Examples:

>>> summary = kdb.load_results("kdb_results")
>>> summary[["method", "k_estimated", "k_error", "ARI"]].head(3)
        method  k_estimated  k_error     ARI
0     BNPSpace            2       -5  0.0480
1   BayesSpace            4       -3  0.3745
2  CellCharter            2       -5  0.3657

k_accuracy

k_accuracy(summary)

Summarize how well each method estimates k.

Each method is summarized over all its runs in summary. Filter the table first to compare within one dataset or device. Failed runs and runs without a reference annotation are left out.

PARAMETER DESCRIPTION
summary

The table from load_results.

TYPE: DataFrame

RETURNS DESCRIPTION
DataFrame

One row per method, best first (smallest mean absolute k error, then highest mean ARI): runs, mean_abs_k_error, exact_rate (fraction of runs with exactly the reference k) and mean_ARI. Empty when no run has a reference annotation.

RAISES DESCRIPTION
TypeError

summary is not a table, for example a folder name.

KeyError

summary lacks a column of the load_results table.

WARNS DESCRIPTION
UserWarning

There are successful runs, but none of them could be scored. The warning quotes the first score_error.

Examples:

>>> kdb.k_accuracy(kdb.load_results("kdb_results")).head(3)
         runs  mean_abs_k_error  exact_rate  mean_ARI
method
PRECAST     1               2.0         0.0    0.2615
DeepST      1               3.0         0.0    0.5416
SpaGCN      1               3.0         0.0    0.4487