diff --git a/CHANGELOG.md b/CHANGELOG.md index b4a3a83..526933b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,13 @@ carried across. * Six metric families in `metrics_proteomics`, wrapping [`sprotmetrics`](https://github.com/theislab/sprotmetrics) `0.1.0`. +### New methods + +* `methods_proteomics_normalization/clr_normalization`: per-cell centred + log-ratio, `log1p(x / exp(mean(log1p(x))))`, as in Seurat's CLR for + antibody-derived tags. Part of `run_benchmark`'s default + `--normalization_methods`, and covered by the shared normalization test. + ### Conformance to the OpenProblems structure * `src/api/file_score.yaml` describes what a metric component actually writes: diff --git a/src/methods_proteomics_normalization/clr_normalization/config.vsh.yaml b/src/methods_proteomics_normalization/clr_normalization/config.vsh.yaml new file mode 100755 index 0000000..3d63b14 --- /dev/null +++ b/src/methods_proteomics_normalization/clr_normalization/config.vsh.yaml @@ -0,0 +1,38 @@ +__merge__: /src/api/comp_method_proteomics_normalization.yaml + +name: clr_normalization +label: "CLR normalization" +summary: "Per-cell centred log-ratio transformation of raw intensities" +description: | + Centred log-ratio (CLR) normalization, computed per cell across markers as in + Seurat's CLR for CITE-seq antibody-derived tags. For each cell, raw marker + intensities are divided by the geometric-mean-like factor + exp(mean(log1p(x))) and then log1p-transformed. This removes per-cell + differences in overall staining intensity while keeping relative marker + levels, and is a common choice for antibody-based protein measurements. +references: + doi: + - 10.1038/nmeth.4380 +links: + documentation: https://satijalab.org/seurat/reference/normalizedata + repository: https://github.com/satijalab/seurat + +resources: + - type: python_script + path: script.py + +engines: + - type: docker + image: openproblems/base_python:1 + setup: + - type: python + pypi: + - "anndata>=0.10.0" + - "numpy" + - "scipy" + - "zarr<3.0.0" + - type: native + +runners: + - type: executable + - type: nextflow diff --git a/src/methods_proteomics_normalization/clr_normalization/script.py b/src/methods_proteomics_normalization/clr_normalization/script.py new file mode 100755 index 0000000..20e7db4 --- /dev/null +++ b/src/methods_proteomics_normalization/clr_normalization/script.py @@ -0,0 +1,79 @@ +import numpy as np +import anndata as ad + +try: + import scipy.sparse as sp +except Exception: # pragma: no cover + sp = None + + +def _dense(x) -> np.ndarray: + if sp is not None and sp.issparse(x): + return x.toarray() + return np.asarray(x) + + +def _get_counts_matrix(adata: ad.AnnData) -> np.ndarray: + if "counts" in adata.layers: + return _dense(adata.layers["counts"]) + return _dense(adata.X) + + +def clr_transform(X: np.ndarray) -> np.ndarray: + """Per-cell centred log-ratio, as in Seurat's CLR (margin = cells). + + For each cell, g = exp(mean_j log1p(x_j)) over all markers, and + x_j -> log1p(x_j / g). Negative intensities are clipped to 0 first, + because the log-ratio is undefined for them. + """ + X = np.clip(np.asarray(X, dtype=np.float64), 0.0, None) + log_geo = np.log1p(X).mean(axis=1, keepdims=True) + return np.log1p(X / np.exp(log_geo)) + + +def run(par: dict): + in_path = par["input"] + out_path = par["output"] + + adata = ad.read_h5ad(in_path) + X = _get_counts_matrix(adata) + + adata.layers["normalized"] = clr_transform(X).astype(np.float32) + adata.uns.setdefault("normalization", {}) + adata.uns["normalization"].update( + { + "method": "clr_normalization", + "description": "Per-cell centred log-ratio: log1p(x / exp(mean(log1p(x)))).", + "scale": None, + "cofactor": None, + } + ) + + adata.write_h5ad(out_path, compression="gzip") + + +## VIASH START +par = { + "input": "input.h5ad", + "scale": 10000.0, + "cofactor": 5.0, + "transform": "log1p", + "output": "output.h5ad", +} +meta = {"name": "clr_normalization"} +## VIASH END + + +if __name__ == "__main__": + if "par" in globals(): + run(par) + else: + import argparse + + ap = argparse.ArgumentParser() + ap.add_argument("--input", required=True) + ap.add_argument("--scale", type=float, default=10000.0) + ap.add_argument("--cofactor", type=float, default=5.0) + ap.add_argument("--transform", default="log1p") + ap.add_argument("--output", required=True) + run(vars(ap.parse_args())) diff --git a/src/testing/test_normalization.py b/src/testing/test_normalization.py index 3b0b4df..96c0bc2 100644 --- a/src/testing/test_normalization.py +++ b/src/testing/test_normalization.py @@ -90,6 +90,13 @@ assert np.allclose(norm, expected, rtol=1e-4, atol=1e-5), ( "normalized layer does not match arcsinh(x / cofactor)" ) +elif name == "clr_normalization": + clipped = np.clip(raw, 0.0, None) + geo = np.exp(np.log1p(clipped).mean(axis=1, keepdims=True)) + expected = np.log1p(clipped / geo) + assert np.allclose(norm, expected, rtol=1e-4, atol=1e-5), ( + "normalized layer does not match per-cell CLR log1p(x / exp(mean(log1p(x))))" + ) else: raise AssertionError(f"no expected transformation defined for component '{name}'") diff --git a/src/workflows/run_benchmark/config.vsh.yaml b/src/workflows/run_benchmark/config.vsh.yaml index 6ceedc2..dce8bbc 100644 --- a/src/workflows/run_benchmark/config.vsh.yaml +++ b/src/workflows/run_benchmark/config.vsh.yaml @@ -117,7 +117,7 @@ argument_groups: - name: "--normalization_methods" type: string multiple: true - default: [no_normalization, total_log1p_normalization, arcsinh_normalization] + default: [no_normalization, total_log1p_normalization, arcsinh_normalization, clr_normalization] - name: Method parameters arguments: @@ -198,6 +198,7 @@ dependencies: - name: methods_proteomics_normalization/no_normalization - name: methods_proteomics_normalization/total_log1p_normalization - name: methods_proteomics_normalization/arcsinh_normalization + - name: methods_proteomics_normalization/clr_normalization - name: metrics_proteomics/basic - name: metrics_proteomics/marker_distribution - name: metrics_proteomics/normalization_diagnostics diff --git a/src/workflows/run_benchmark/main.nf b/src/workflows/run_benchmark/main.nf index 7c698a8..d102731 100644 --- a/src/workflows/run_benchmark/main.nf +++ b/src/workflows/run_benchmark/main.nf @@ -194,7 +194,8 @@ workflow run_wf { norm_methods = [ no_normalization, total_log1p_normalization, - arcsinh_normalization + arcsinh_normalization, + clr_normalization ] norm_ch = qc_ch