Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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
79 changes: 79 additions & 0 deletions src/methods_proteomics_normalization/clr_normalization/script.py
Original file line number Diff line number Diff line change
@@ -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()))
7 changes: 7 additions & 0 deletions src/testing/test_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}'")

Expand Down
3 changes: 2 additions & 1 deletion src/workflows/run_benchmark/config.vsh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/workflows/run_benchmark/main.nf
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,8 @@ workflow run_wf {
norm_methods = [
no_normalization,
total_log1p_normalization,
arcsinh_normalization
arcsinh_normalization,
clr_normalization
]

norm_ch = qc_ch
Expand Down