Normalization
Cells differ in how many molecules the experiment captured from them, so raw counts are not comparable between cells. sc-best-practices runs three normalizations, the shifted logarithm, scran pooling and analytic Pearson residuals. This page applies the shifted logarithm and the Pearson residuals to the filtered PBMC 3k cells and compares them. scran pooling runs through the scran R package, and the pages of this section run Python only.
Load and filter
Section titled “Load and filter”The setup repeats the loading and the filter of the Quality Control page and ends with 2,428 cells and 13,474 genes.
Setup code and its output
The MAD helper below adapts cells 18, 20 and 22 of the archived quality-control notebook. This version computes MAD with pandas and changes the filter combination. The source is copyright 2021 Theislab under Apache 2.0.
The source matrix is 10x Genomics’ PBMC 3k dataset, processed with Cell Ranger 1.1.0 and published in 2016. The provider licenses it under CC BY 4.0. This lesson converts the matrix to AnnData and derives the displayed summaries and analysis results.
import numpy as npimport scanpy as scimport matplotlib.pyplot as plt
sc.settings.verbosity = 3np.random.seed(42)
adata = sc.read_10x_mtx("/opt/data/pbmc3k", var_names="gene_symbols", make_unique=True)adata.layers["counts"] = adata.X.copy()adata.var["mt"] = adata.var_names.str.startswith("MT-")sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], percent_top=None, log1p=False, inplace=True)
def is_outlier(adata, metric, nmads): """Flag cells whose metric sits more than nmads MADs from the median.
Args: adata: AnnData object holding the metric in .obs. metric: Column of adata.obs to test. nmads: Number of median absolute deviations for the cutoff.
Returns: Boolean Series, True where the cell is an outlier. """ values = adata.obs[metric] median = values.median() mad = (values - median).abs().median() return (values < median - nmads * mad) | (values > median + nmads * mad)
adata.obs["log1p_total_counts"] = np.log1p(adata.obs["total_counts"])adata.obs["log1p_n_genes_by_counts"] = np.log1p( adata.obs["n_genes_by_counts"])adata.obs["outlier"] = ( is_outlier(adata, "log1p_total_counts", 5) | is_outlier(adata, "log1p_n_genes_by_counts", 5) | is_outlier(adata, "pct_counts_mt", 3))adata = adata[~adata.obs["outlier"]].copy()sc.pp.filter_genes(adata, min_cells=3)print(adata.shape)(2428, 13474)The shifted logarithm
Section titled “The shifted logarithm”# The shifted logarithm is the default normalization in# sc-best-practices: scale each cell to a common library size, then# take the log of the scaled counts.sc.pp.normalize_total(adata, target_sum=1e4)sc.pp.log1p(adata)adata.layers["normalized"] = adata.X.copy()
# Four well-expressed genes, so the sample shows the transform at work.genes = ["MALAT1", "B2M", "LYZ", "CD3D"]columns = [adata.var_names.get_loc(gene) for gene in genes]library = np.asarray(adata.layers["counts"][:3].sum(axis=1)).ravel()raw = adata.layers["counts"][:3, columns].toarray()normalized = adata.layers["normalized"][:3, columns].toarray()print("genes:", genes)print("library sizes:", library)print("raw counts:\n", raw)print("shifted log:\n", np.round(normalized, 3))genes: ['MALAT1', 'B2M', 'LYZ', 'CD3D']library sizes: [2419. 3147. 2639.]raw counts: [[ 49. 76. 1. 4.] [171. 69. 2. 10.] [ 11. 41. 24. 0.]]shifted log: [[5.316 5.753 1.636 2.864] [6.3 5.395 1.995 3.49 ] [3.754 5.052 4.521 0. ]]The shifted logarithm divides each count by the library size of its cell, scales it to 10,000 and takes log(1 + x). In the first cell, 49 MALAT1 counts in a library of 2,419 become 202.6 per 10,000 and then 5.316. A zero count stays zero, as CD3D in the third cell shows, so the matrix stays sparse.
Analytic Pearson residuals
Section titled “Analytic Pearson residuals”# The analytic Pearson residuals are the alternative sc-best-practices# recommends. They model counts with an overdispersed Poisson and need# no library-size scaling, and they are the basis of the Pearson# flavour of highly variable gene selection.adata_pearson = adata.copy()adata_pearson.X = adata.layers["counts"].copy()sc.experimental.pp.normalize_pearson_residuals(adata_pearson)
x_sample = adata_pearson.X[:3, columns]if hasattr(x_sample, "toarray"): x_sample = x_sample.toarray()print("pearson residuals:\n", np.round(x_sample, 3))pearson residuals: [[-1.254 3.615 -2.779 1.959] [ 7.583 0.897 -2.948 5.578] [-5.297 -1.087 3.543 -1.288]]A Pearson residual compares a count with the count that the gene’s mean and the cell’s library size predict, in units of standard deviations. MALAT1 in the second cell, 171 counts, sits 7.58 above its expectation, and MALAT1 in the third cell, 11 counts, sits 5.30 below. CD3D in the third cell has no count and a residual of -1.288, so a zero is no longer zero and the residual matrix is dense.
Comparing the transforms
Section titled “Comparing the transforms”def gene_mean_variance(matrix): """Return per-gene mean and variance from a cells-by-genes matrix.
Args: matrix: Cells-by-genes matrix, sparse or dense.
Returns: Tuple of per-gene means and per-gene variances. """ if hasattr(matrix, "toarray"): matrix = matrix.toarray() return matrix.mean(axis=0), matrix.var(axis=0)
transformed = { "raw counts": adata.layers["counts"], "shifted log": adata.layers["normalized"], "pearson residuals": adata_pearson.X,}
fig, axes = plt.subplots(1, 3, figsize=(15, 4), sharex=True, sharey=True)for ax, (name, matrix) in zip(axes, transformed.items()): means, variances = gene_mean_variance(matrix) ax.scatter(means, variances, s=2, alpha=0.2) ax.set_xscale("log") ax.set_yscale("log") ax.set_title(name) ax.set_xlabel("gene mean") ax.set_ylabel("gene variance")plt.tight_layout()plt.savefig("outputs/normalization_meanvar.png", dpi=150, bbox_inches="tight")plt.close()
On raw counts the gene variance spans about six orders of magnitude and rises with the mean, so the most expressed genes would dominate any distance between cells. The shifted logarithm narrows the range to about three orders of magnitude, but the variance still rises with the mean up to a mean near 1 and falls after it. The Pearson residuals put the genes on a band near a variance of 1. All three panels share one logarithmic x axis, so the residual panel shows only part of the genes. Residuals are centered, so the mean residual of a gene sits close to zero and is often negative, and a log axis cannot place a mean of zero or below.
Scientific references
Section titled “Scientific references”Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.
Further reading
Section titled “Further reading”The Single-cell best practices normalization chapter compares shifted logarithms and analytic Pearson residuals. It explains the assumptions behind the two representations compared here.
The 10x Genomics PBMC 3k record describes the original matrix and sequencing context. The lesson derives normalized representations from that shared count input.