veryMADpy
Version 0.1.0
MAD-based quality control for cell-level metrics in AnnData and pandas workflows.
veryMADpy fits transparent, pooled or sample-wise thresholds to existing QC metrics. It annotates potential outliers for review and leaves filtering decisions to you. It does not recalculate QC metrics or access expression matrices during fitting and plotting.
Start with three calls
Given an AnnData object with raw counts in X, a Boolean mitochondrial annotation in var["mt"], and sample_id in .obs:
import scanpy as sc
import verymadpy as vm
sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], out=False)
vm.pp.flag_mad_outliers(adata, batch_key="sample_id")
adata_filtered = vm.pp.filter(adata)
The first call calculates standard Scanpy QC columns. The second stores flags and fitted thresholds; the third returns a filtered AnnData copy. Review the optional summary before filtering when the data or policy warrants it.
An example of sample-wise fits on the four-donor PBMC validation data. Thresholds shown are from the stored fit.
Project links
GitHub repository · Releases · Cite veryMADpy
veryMADpy uses AnnData directly and follows Scanpy-style preprocessing and plotting namespaces. This describes interoperability; it is not a claim of official scverse ecosystem membership or endorsement.
Installation
veryMADpy requires Python 3.10 or later. Add the core package to a uv project:
uv add veryMADpy
Install plotting dependencies only when using verymadpy.pl:
uv add "veryMADpy[plot]"
Scanpy is optional. If you need scanpy.pp.calculate_qc_metrics(), install it with uv add scanpy or python -m pip install scanpy.
With pip, install veryMADpy using python -m pip install veryMADpy. Add the optional plotting dependencies with python -m pip install "veryMADpy[plot]".
For development from a local checkout, see Contributing. For Scanpy versions before the out=False convention, pass inplace=True to calculate_qc_metrics(); veryMADpy itself accepts the generated .obs metrics independently of Scanpy.
Quick start
Create a small count-based AnnData object and annotate mitochondrial genes:
import anndata as ad
import numpy as np
import pandas as pd
import scanpy as sc
import verymadpy as vm
rng = np.random.default_rng(0)
counts = rng.negative_binomial(1, 0.55, size=(80, 500))
obs = pd.DataFrame(
{"sample_id": pd.Categorical(["sample_A"] * 40 + ["sample_B"] * 40)},
index=[f"cell_{i}" for i in range(counts.shape[0])],
)
var_names = [f"gene_{i}" for i in range(counts.shape[1])]
var_names[:50] = [f"MT-GENE_{i}" for i in range(50)]
var = pd.DataFrame(index=var_names)
var["mt"] = var.index.str.startswith("MT-")
adata = ad.AnnData(X=counts, obs=obs, var=var)
Then calculate metrics, flag candidate outliers by sample, and return a filtered copy:
# Three-call QC workflow
sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], out=False)
vm.pp.flag_mad_outliers(adata, batch_key="sample_id")
adata_filtered = vm.pp.filter(adata)
The example uses the standard Scanpy observation columns total_counts, n_genes_by_counts, and pct_counts_mt. veryMADpy reads these values from .obs; it does not use Scanpy’s precomputed log1p_* columns, so the default count transformations are applied once.
The example was checked with Scanpy 1.13.0, which supports out=False. For Scanpy versions whose calculate_qc_metrics() signature does not include out, use inplace=True. See single-cell QC for inspection and undefined classifications.
Single-cell quality control
Objective: fit pooled MAD thresholds to QC metrics, inspect the resulting flags, then choose how to handle observations that cannot be classified.
Start with an AnnData object whose QC metrics have already been calculated; the quick start creates one. This example uses a named run so it remains separate from the default fit.
import verymadpy as vm
vm.pp.flag_mad_outliers(adata, key_added="pooled_qc")
qc_table = vm.pp.summarize_mad(adata, key_added="pooled_qc", include_combined=True)
The default policy uses four scaled MADs in both tails of log1p(total_counts) and log1p(n_genes_by_counts), plus four scaled MADs in the upper tail of pct_counts_mt. The two count metrics are required. If mitochondrial percentage is unavailable, veryMADpy warns and fits the two count metrics only. The default does not include other percentage metrics.
The combined flag is true when any metric flags a cell, false when all metric results are defined and false, and undefined otherwise. summarize_mad() distinguishes fit-time counts from counts on the current object. Before filtering, inspect undefined values and decide whether to raise, keep, or drop them:
adata_reviewed = vm.pp.filter(adata, key_added="pooled_qc", na_policy="keep")
filter() uses the existing combined flag; it does not refit thresholds. Its default na_policy="raise" prevents undefined cells from silently passing QC. Flagging and filtering do not automatically alter genes or normalize expression. See flag_mad_outliers, summarize_mad, and filter.
Sample-aware QC
Objective: estimate thresholds independently within each sample and compare the resulting sample-specific QC outcomes.
Use a string or categorical observation column for batch_key. With adata from the quick start, fit a separate run:
import verymadpy as vm
vm.pp.flag_mad_outliers(adata, batch_key="sample_id", key_added="sample_qc")
sample_table = vm.pp.summarize_mad(
adata,
key_added="sample_qc",
include_combined=True,
)
For each observed sample, veryMADpy estimates a median, MAD, and metric thresholds from that sample’s valid observations. It applies each threshold only within its sample and preserves observation order. Empty categorical levels are ignored. Missing labels, groups below min_n (five by default), and degenerate distributions can yield undefined classifications; no pooled fallback is applied.
Inspect sample-specific thresholds and flag rates before deciding whether to filter:
fig, axes = vm.pl.qc_summary(adata, key_added="sample_qc", show=False)
Different samples can have different biological and technical distributions. A sample-specific fit does not guarantee equal flag rates, and equal rates are not a QC target. See flag_mad_outliers, summarize_mad, and qc_summary.
Custom QC policies
Objective: replace the built-in metric set and set metric-specific tail directions, transforms, and MAD cutoffs.
Metric columns must already exist in adata.obs or a pandas DataFrame. This example creates a proportion under an explicit name from Scanpy’s mitochondrial percentage column, then specifies the full policy. The example uses the adata created in the quick start.
import verymadpy as vm
adata.obs["mitochondrial_fraction"] = adata.obs["pct_counts_mt"] / 100.0
vm.pp.flag_mad_outliers(
adata,
metrics={
"total_counts": {"tail": "both", "transform": "log1p"},
"n_genes_by_counts": {"tail": "both", "transform": "log1p"},
"mitochondrial_fraction": {
"tail": "upper",
"transform": "none",
"n_mads": 3,
},
},
n_mads=4,
batch_key="sample_id",
mad_scale="scaled",
key_added="custom_qc",
)
custom_table = vm.pp.summarize_mad(adata, key_added="custom_qc", include_combined=True)
Passing metrics replaces the default metric set. Global values apply where a metric does not specify its own value; a per-metric setting takes precedence. Supported tails are lower, upper, and both; supported transformations are none, log1p, and log10. log1p requires nonnegative values and log10 requires positive values. veryMADpy does not infer percentage units or clip boundaries.
The default convention uses scaled MAD, 1.4826 × raw_MAD. Three scaled MADs correspond to about 4.4478 raw MADs; five raw MADs correspond to about 3.3725 scaled MADs. Use flag_mad_outliers for all settings and precedence rules.
Visualization
Objective: inspect fitted distributions and outlier outcomes without changing the data or refitting thresholds.
Plot functions read the existing QC metric columns and stored fit metadata. They require the optional plot extra. With show=False, they return Matplotlib handles for further composition.
import matplotlib.pyplot as plt
import verymadpy as vm
axes = vm.pl.violin(adata, key_added="sample_qc", show=False)
axes = vm.pl.raincloud(adata, key_added="sample_qc", max_points=500, seed=0, show=False)
vm.pl.outlier_summary(
adata,
key_added="sample_qc",
percent=True,
combined_only=True,
save="outcomes.svg",
show=False,
)
fig, axes = vm.pl.qc_summary(
adata,
key_added="sample_qc",
kind="raincloud",
save="qc-review.pdf",
show=False,
)
The violin plot limits displayed values per metric and sample by default. Raincloud density and boxplot statistics use every valid observation; max_points limits only the reproducibly sampled, rasterized points. Neither plot uses sampled values to estimate thresholds.
outlier_summary(percent=True) uses all current observations in each group as the denominator, including undefined classifications. Per-metric bars can overlap. combined_only=True displays the mutually exclusive retained, flagged, and undefined outcomes. See violin, raincloud, outlier_summary, and qc_summary.
Compose with Matplotlib
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
vm.pl.violin(
adata,
metrics=["total_counts"],
key_added="sample_qc",
ax=axes[0],
show=False,
)
vm.pl.outlier_summary(
adata,
key_added="sample_qc",
percent=True,
combined_only=True,
ax=axes[1],
show=False,
)
fig.savefig("qc-review.png", dpi=180)
Figures can be exported directly with save="figure.svg", "figure.pdf", or "figure.png". The plotting functions use Matplotlib and Seaborn without changing global plotting settings.
API reference
veryMADpy exposes a compact preprocessing and plotting API. Each function page is generated from its public Python signature and NumPy-style docstring.
Preprocessing (verymadpy.pp)
| Function | Description |
|---|---|
flag_mad_outliers | Flag observations outside fitted median absolute deviation thresholds. |
filter | Remove observations flagged by an existing QC run. |
summarize_mad | Summarize fitted thresholds and current observation flags. |
mad_scale | Robustly center or scale a numeric vector or matrix. |
vm.pp.flag_mad_outliers
Flag observations outside fitted median absolute deviation thresholds.
Signature
def flag_mad_outliers(
data: anndata.AnnData | pandas.DataFrame,
*,
metrics: collections.abc.Mapping[str, str | collections.abc.Mapping[str, str | float]]
| collections.abc.Sequence[str]
| None = None,
n_mads: float | None = None,
transform: str | collections.abc.Mapping[str, str] | None = None,
min_n: int = 5,
zero_mad: str = "na",
overwrite: bool = False,
copy: bool = False,
batch_key: str | None = None,
mad_scale: str = "scaled",
key_added: str | None = None,
) -> anndata.AnnData | pandas.DataFrame | None: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `anndata.AnnData | pandas.DataFrame` | required |
metrics | `collections.abc.Mapping[str, str | collections.abc.Mapping[str, str | float]] |
n_mads | `float | None` | None |
transform | `str | collections.abc.Mapping[str, str] | None` |
min_n | int | 5 | Minimum number of finite values required per metric and batch. |
zero_mad | str | 'na' | Use missing flags (na), use the median as the threshold (zero), or raise an error (error) when the fitted MAD is zero. |
overwrite | bool | False | Allow replacing output columns and metadata for this run. |
copy | bool | False | Return a modified AnnData copy. DataFrames always return a copy. |
batch_key | `str | None` | None |
mad_scale | str | 'scaled' | Use scaled (1.4826 times raw MAD) or raw MAD. |
key_added | `str | None` | None |
Returns
AnnData, DataFrame, or None
With copy=True, return an annotated copy. Otherwise, annotate AnnData in place and return None; DataFrame input always returns a copy.
Raises
TypeError
If the input, metric values, or Boolean options have invalid types.
ValueError
If a setting is invalid or a transformation is outside its domain.
KeyError
If a required metric or batch column is missing.
Notes
AnnData flags are written to .obs and fitted settings and thresholds to
.uns['verymad']. DataFrame metadata is stored in .attrs. Missing
metric values and observations that cannot be classified remain undefined.
The default policy requires total_counts and n_genes_by_counts;
absent pct_counts_mt is omitted with a warning. Supplying metrics
replaces the default metric set.
See Also
Examples
import verymadpy as vm
vm.pp.flag_mad_outliers(adata, batch_key="sample_id")
vm.pp.filter
Remove observations flagged by an existing QC run.
Signature
def filter(
data: anndata.AnnData | pandas.DataFrame,
*,
key_added: str | None = None,
na_policy: str = "raise",
copy: bool = True,
) -> anndata.AnnData | pandas.DataFrame | None: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `anndata.AnnData | pandas.DataFrame` | required |
key_added | `str | None` | None |
na_policy | str | 'raise' | Raise on undefined flags (raise), retain them (keep), or remove them (drop). |
copy | bool | True | Return a filtered copy. False subsets the supplied object in place. |
Returns
AnnData, pandas.DataFrame, or None
Filtered copy, or None for an in-place operation. The selected run records the latest filtering counts alongside the original fit.
Raises
KeyError
If the selected run or its combined flag is missing.
TypeError
If the combined flag is not Boolean or copy is not Boolean.
ValueError
If na_policy is invalid, classifications are undefined under na_policy='raise', or backed AnnData must first be loaded into memory.
Notes
AnnData filtering subsets observations and preserves the other annotated
data fields. The stored fit and thresholds remain unchanged; filtering
counts are added to the selected run. DataFrame filtering preserves row
order and records metadata in .attrs. No thresholds are refit.
See Also
Examples
import verymadpy as vm
adata_filtered = vm.pp.filter(adata, na_policy="keep")
vm.pp.summarize_mad
Summarize fitted thresholds and current observation flags.
Signature
def summarize_mad(
data: anndata.AnnData | pandas.DataFrame,
*,
key_added: str | None = None,
include_combined: bool = False,
) -> pandas.DataFrame: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `anndata.AnnData | pandas.DataFrame` | required |
key_added | `str | None` | None |
include_combined | bool | False | Append one combined row per batch (or one pooled row), including the unique number flagged and the number flagged by multiple metrics. |
Returns
pandas.DataFrame
One row per fitted metric and batch. Fitted counts describe the original fit. Current counts reflect the supplied observations. Flagged fractions use classified observations as the denominator.
Raises
KeyError
If the selected run or one of its flag columns is missing.
TypeError
If stored threshold metadata has an invalid type.
ValueError
If the metadata schema version is not supported.
Notes
The returned table distinguishes historical fit counts (columns ending in
_fit) from counts on the supplied object. Combined rows report unique
flagged observations and, where requested, observations flagged by more
than one metric. This function does not modify data.
See Also
Examples
import verymadpy as vm
summary = vm.pp.summarize_mad(adata, include_combined=True)
vm.pp.mad_scale
Robustly center or scale a numeric vector or matrix.
Signature
def mad_scale(
x: numpy.ndarray | pandas.Series | pandas.DataFrame,
*,
axis: int = 0,
center: bool = True,
scale: bool = True,
constant: float = 1.4826,
na_rm: bool = True,
zero_mad: str = "zero",
) -> numpy.ndarray | pandas.Series | pandas.DataFrame: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
x | `numpy.ndarray | pandas.Series | pandas.DataFrame` |
axis | int | 0 | Scale columns with 0 or rows with 1. Ignored for vectors. |
center | bool | True | Subtract the median. |
scale | bool | True | Divide by the MAD multiplied by constant. |
constant | float | 1.4826 | Positive MAD scaling factor. Use 1 for raw MAD. |
na_rm | bool | True | Ignore NaNs when estimating location and spread. |
zero_mad | str | 'zero' | Use zero (zero), return missing values (na), or raise (error) for a slice with zero MAD. |
Returns
numpy.ndarray, pandas.Series, or pandas.DataFrame
Scaled data in the input container type.
Raises
TypeError
If the input is not numeric or Boolean options have invalid types.
ValueError
If the axis or scale factor is invalid, values contain infinities, or a zero MAD is encountered with zero_mad='error'.
Notes
The default scaling factor (1.4826) converts raw MAD to the normal
consistency scale. Set constant=1 to use raw MAD. Missing values are
preserved in the result. This function does not modify its input.
See Also
Examples
import verymadpy as vm
scaled = vm.pp.mad_scale(adata.obs["total_counts"])
Plotting (verymadpy.pl)
| Function | Description |
|---|---|
qc_summary | Compose metric distributions and combined QC outcomes in one figure. |
violin | Plot fitted metrics with lower (dashed) and upper (dotted) cutoffs. |
raincloud | Draw QC distributions as half violins, boxplots, and jittered points. |
outlier_summary | Plot flagged and undefined counts for each metric and the combined flag. |
vm.pl.qc_summary
Compose metric distributions and combined QC outcomes in one figure.
Signature
def qc_summary(
data: ad.AnnData | pd.DataFrame,
*,
kind: str = "violin",
metrics: Sequence[str] | str | None = None,
key_added: str | None = None,
order: Sequence[str | None] | None = None,
palette: str | Sequence = "Set2",
figsize: tuple[float, float] | None = None,
transformed: bool = False,
show: bool = True,
save: str | Path | None = None,
) -> tuple[Figure, tuple[Axes, ...]] | None: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `ad.AnnData | pd.DataFrame` | required |
kind | str | 'violin' | Distribution style: "violin" or "raincloud". |
metrics | `Sequence[str] | str | None` |
key_added | `str | None` | None |
order | `Sequence[str | None] | None` |
palette | `str | Sequence` | 'Set2' |
figsize | `tuple[float, float] | None` | None |
transformed | bool | False | Plot distributions in fitted transformation units. |
show | bool | True | Display the figure. If False, return the figure and active axes. |
save | `str | Path | None` |
Returns
tuple of matplotlib.figure.Figure and tuple of matplotlib.axes.Axes, or None
The figure and active axes in reading order when show=False; the combined outcome axes are last.
Raises
ImportError
If the optional plotting dependencies are not installed.
KeyError
If the fitted run or a requested metric is missing.
ValueError
If kind or the metric selection is invalid.
Notes
Metric panels use the stored thresholds and the current observation
distributions. The outcome panel covers the full selected run on the
supplied object, even when metrics selects only some distribution
panels. No statistics are refit and the input is not modified.
See Also
Examples
import verymadpy as vm
fig, axes = vm.pl.qc_summary(adata, kind="raincloud", show=False)
vm.pl.violin
Plot fitted metrics with lower (dashed) and upper (dotted) cutoffs.
Signature
def violin(
data: ad.AnnData | pd.DataFrame,
*,
metrics: Sequence[str] | str | None = None,
key_added: str | None = None,
groupby: str | None = None,
order: Sequence[str | None] | None = None,
transformed: bool = False,
inner: str | None = "box",
show_thresholds: bool = True,
palette: str | Sequence = "Set2",
titles: Sequence[str] | None = None,
figsize: tuple[float, float] | None = None,
ax: Axes | Sequence[Axes] | np.ndarray | None = None,
max_points: int | None = 2000,
random_state: int = 0,
show: bool = True,
save: str | Path | None = None,
) -> tuple[Axes, ...] | None: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `ad.AnnData | pd.DataFrame` | required |
metrics | `Sequence[str] | str | None` |
key_added | `str | None` | None |
groupby | `str | None` | None |
order | `Sequence[str | None] | None` |
transformed | bool | False | Plot fitting units instead of the original metric units. |
inner | `str | None` | 'box' |
show_thresholds | bool | True | Overlay stored thresholds. Batch cutoffs require the fitted grouping. |
palette | `str | Sequence` | 'Set2' |
titles | `Sequence[str] | None` | None |
figsize | `tuple[float, float] | None` | None |
ax | `Axes | Sequence[Axes] | np.ndarray |
max_points | `int | None` | 2000 |
random_state | int | 0 | Seed for display sampling. Thresholds always use the full fit. |
show | bool | True | Display the figure. |
save | `str | Path | None` |
Returns
tuple of matplotlib.axes.Axes or None
One axes per metric when show is False.
Raises
ImportError
If the optional plotting dependencies are not installed.
KeyError
If a requested metric, grouping column, or fitted run is missing.
ValueError
If the metric selection, group order, or display options are invalid.
Notes
Metric values and fitted thresholds are read from the existing observation
table and stored fit. Thresholds are never refitted. In original units,
overlays use inverse-transformed stored thresholds; transformed=True
plots and labels values in fitting units. Display subsampling controlled by
max_points and random_state does not affect thresholds.
See Also
Examples
import verymadpy as vm
axes = vm.pl.violin(adata, groupby="sample_id", show=False)
vm.pl.raincloud
Draw QC distributions as half violins, boxplots, and jittered points.
Signature
def raincloud(
data: ad.AnnData | pd.DataFrame,
*,
metrics: Sequence[str] | str | None = None,
key_added: str | None = None,
groupby: str | None = None,
order: Sequence[str | None] | None = None,
transformed: bool = False,
show_thresholds: bool = True,
palette: str | Sequence = "Set2",
titles: Sequence[str] | None = None,
figsize: tuple[float, float] | None = None,
ax: Axes | Sequence[Axes] | np.ndarray | None = None,
max_points: int | None = 1000,
seed: int = 0,
show: bool = True,
save: str | Path | None = None,
) -> tuple[Axes, ...] | None: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `ad.AnnData | pd.DataFrame` | required |
metrics | `Sequence[str] | str | None` |
key_added | `str | None` | None |
groupby | `str | None` | None |
order | `Sequence[str | None] | None` |
transformed | bool | False | Plot values in fitting units instead of original metric units. |
show_thresholds | bool | True | Overlay defined thresholds from the stored fit. |
palette | `str | Sequence` | 'Set2' |
titles | `Sequence[str] | None` | None |
figsize | `tuple[float, float] | None` | None |
ax | `Axes | Sequence[Axes] | np.ndarray |
max_points | `int | None` | 1000 |
seed | int | 0 | Random seed for reproducible point subsampling and jitter. |
show | bool | True | Display the figure. If False, return the axes. |
save | `str | Path | None` |
Returns
tuple of matplotlib.axes.Axes or None
One axes per metric when show=False.
Raises
ImportError
If the optional plotting dependencies are not installed.
KeyError
If a requested metric, grouping column, or fitted run is missing.
ValueError
If the metric selection, group order, or display options are invalid.
Notes
Density and boxplot statistics use every finite observation. max_points
limits only the rasterized jittered points. Stored thresholds are not
refitted. Plotting reads the observation table and fit metadata without
changing them.
See Also
Examples
import verymadpy as vm
axes = vm.pl.raincloud(adata, max_points=500, seed=1, show=False)
vm.pl.outlier_summary
Plot flagged and undefined counts for each metric and the combined flag.
Signature
def outlier_summary(
data: ad.AnnData | pd.DataFrame,
*,
key_added: str | None = None,
percent: bool = False,
combined_only: bool = False,
order: Sequence[str | None] | None = None,
palette: str | Sequence = ("#a03526", "#747983"),
figsize: tuple[float, float] | None = None,
ax: Axes | None = None,
show: bool = True,
save: str | Path | None = None,
) -> Axes | None: ...
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
data | `ad.AnnData | pd.DataFrame` | required |
key_added | `str | None` | None |
percent | bool | False | Plot percentages of all current observations in each batch, including undefined observations. Otherwise plot counts. |
combined_only | bool | False | Show mutually exclusive retained, flagged, and undefined outcomes from the combined flag for each batch. |
order | `Sequence[str | None] | None` |
palette | `str | Sequence` | ('#a03526', '#747983') |
figsize | `tuple[float, float] | None` | None |
ax | `Axes | None` | None |
show | bool | True | Display the figure. |
save | `str | Path | None` |
Returns
matplotlib.axes.Axes or None
Plot axes when show is False.
Raises
ImportError
If the optional plotting dependencies are not installed.
KeyError
If fitted run or flag metadata is missing.
ValueError
If the requested batch order is invalid.
Notes
Per-metric bars may overlap because an observation can be flagged on more
than one metric. combined_only=True shows mutually exclusive retained,
flagged, and undefined counts. Percentages use all current observations in
each group, including undefined classifications. The plot is built from
the output of :func:verymadpy.pp.summarize_mad and does not refit.
See Also
Examples
import verymadpy as vm
ax = vm.pl.outlier_summary(adata, percent=True, show=False)
MAD-based QC
veryMADpy applies established median absolute deviation (MAD) thresholds to observation-level QC metrics. A flag indicates a statistical outlier under the selected policy; it is not a biological annotation or an automatic decision to remove a cell.
Estimation and thresholds
For valid transformed metric values (z_1, \ldots, z_n), veryMADpy estimates the median (m) and raw MAD:
[ m = \operatorname{median}(z_i), \qquad \mathrm{MAD}_{\mathrm{raw}} = \operatorname{median}(|z_i - m|). ]
By default, it uses the normal-consistent scaled MAD:
[ \mathrm{MAD}{\mathrm{scaled}} = 1.4826,\mathrm{MAD}{\mathrm{raw}}. ]
For n_mads = k, the lower and upper limits are (m-k,\mathrm{MAD}) and (m+k,\mathrm{MAD}). Raw and scaled MAD are distinct units: three scaled MADs are approximately 4.4478 raw MADs; five raw MADs are approximately 3.3725 scaled MADs.
Built-in policy
When metrics=None, veryMADpy uses the standard Scanpy metric columns below. The default is an opinionated starting policy, not a universal recommendation.
| Metric | Transformation | Tail | Default cutoff |
|---|---|---|---|
total_counts | log1p | lower and upper | 4 scaled MADs |
n_genes_by_counts | log1p | lower and upper | 4 scaled MADs |
pct_counts_mt | none | upper | 4 scaled MADs |
The library-size and detected-gene columns are required by the default policy. If pct_counts_mt is absent, veryMADpy warns and fits the two count metrics. Other percentage metrics are not included automatically. Supplying metrics replaces the default metric set. See Custom QC policies for metric-specific overrides.
Tail direction and transformation
The lower tail flags values below the lower threshold; upper flags values above the upper threshold; both applies both checks. none, log1p, and log10 are supported. Transformations are applied to the metric before fitting and flagging. Threshold metadata retains the fitted and inverse-transformed values for plotting and inspection.
Pooled and sample-wise fits
Without batch_key, a single threshold is fitted across all observations. With batch_key, medians, MADs, and cutoffs are estimated independently for each observed batch and applied only to that batch. veryMADpy does not silently fall back to pooled thresholds for small or degenerate groups. Sample-wise fitting can reduce shifts caused by technical differences, but it can also change which observations are flagged when distributions differ biologically.
Missing and undefined classifications
NaN metric values do not contribute to estimation and remain undefined when that metric cannot classify the observation. Infinite metric values are rejected. A batch label that is missing has no fitted batch threshold. Groups with fewer than min_n valid values (five by default), all-missing metrics, and zero-MAD distributions are diagnosed and remain undefined under the default zero_mad="na" policy. zero_mad="zero" instead uses the median as the cutoff; zero_mad="error" raises.
Metric flags use nullable Boolean values. The combined result follows three-valued OR logic: a true metric flag makes the combined result true; it is false only when all metrics are defined and false; otherwise it remains undefined. Filtering raises on undefined classifications by default. Choose na_policy="keep" or "drop" explicitly after review.
Interpretation and limits
QC distributions can reflect both technical quality and genuine cell-state differences. Rare populations, large cells, or transcriptionally active cells may be flagged under a chosen policy. Inspect distributions, threshold summaries, and per-sample outcomes before filtering; use dataset-specific absolute rules where scientifically justified. MAD-based detection is a familiar robust univariate method, not a biological classifier.
Validation
Four-donor GEM-X PBMC data
The real-data evaluation used Cell Ranger-filtered 10x Genomics GEM-X v4 human PBMC feature-barcode matrices from four donors (22,203 barcodes total). No additional QC was applied before fitting. Donor 1 includes vendor model cell-type labels; donors 2–4 do not have comparable labels. Dataset URLs, preparation commands, and full result tables are available in the validation archive.
The four-scaled-MAD default policy with sample-wise fitting flagged 1,549 cells (6.98%). Rates varied across donors:
| Donor | Flagged | Retained | Flagged (%) |
|---|---|---|---|
| 1 | 200 | 5,510 | 3.50 |
| 2 | 690 | 5,299 | 11.52 |
| 3 | 256 | 4,526 | 5.35 |
| 4 | 403 | 5,319 | 7.04 |
The per-metric flags overlap; their counts are not additive. The combined count reports unique observations. The current-policy summary table and figures below use the same stored fit.
Default policy, sample-wise fits; thresholds were fitted once and reused for plotting.
Combined outcomes are mutually exclusive. No classifications were undefined in this dataset.
Method comparison
In a parity evaluation with equivalent three-scaled-MAD settings, Python and R scuttle::isOutlier() agreed on all 133,218 matched per-metric calls across pooled and donor-wise fits; the largest cutoff difference was (5.33\times 10^{-15}). This supports numerical implementation agreement for that matched policy. It does not validate the current four-MAD policy, which additionally flags upper-tail count and detected-gene outliers.
The Single-cell Best Practices comparison followed its documented raw-MAD example, including a top-20-gene fraction and an absolute mitochondrial cutoff. Those policy and convention differences mean the comparison is descriptive, not a ranking. The archived historical comparison reported 9.24% flagged for an earlier batch fit and 6.21% for the Best Practices policy; neither is the current default result.
The historical cell-type retention comparison used the earlier three-scaled-MAD fit. Donor 1 labels are model calls rather than ground truth, and its retention differences do not show whether flagged cells were technically poor or biologically distinct. The current default’s cell-type retention has not been reevaluated.
Scope of evidence
The measurements cover four filtered PBMC donor matrices. They do not establish that a particular cutoff or retention rate is suitable for other tissues, platforms, chemistries, or biological populations. See the reproducible validation workflow and archived detailed report.
Contributing
Contributions should preserve the package’s focused scope: MAD-based QC over existing observation-level metrics. The package accepts AnnData and pandas objects and follows useful Scanpy conventions; it is not an officially listed scverse package.
From a checkout, install the development, Scanpy integration-test, and plotting extras:
python -m pip install -e ".[dev,test-scanpy,plot]"
pytest -q
ruff check .
ruff format --check .
The mdBook site is generated from Markdown under docs/src. API pages are generated from public exports and NumPy-style docstrings:
python docs/scripts/generate_api.py
python docs/scripts/generate_api.py --check
python docs/scripts/check_docs.py
mdbook build docs
The checks detect public API drift, missing parameter and docstring sections, invalid local links, pages absent from navigation, and failures in marked tutorial examples. Docs-only dependencies are installed in the documentation workflow, not required by the package at runtime.
For scverse conventions, consult the ecosystem package guidance, cookiecutter-scverse, and Scanpy documentation guidance. Interoperability with AnnData does not imply ecosystem membership or endorsement.
Changelog
See the repository’s changelog for release history. The current documentation describes the 0.1.0 API.
References
Methodological inspiration
These works provide examples and guidance for single-cell QC. They do not introduce, evaluate, or endorse veryMADpy.
- Lun, A. T. L., McCarthy, D. J., & Marioni, J. C. (2016). A step-by-step workflow for low-level analysis of single-cell RNA-seq data with Bioconductor. F1000Research, 5, 2122. doi:10.12688/f1000research.9501.2.
- Heumos, L., et al. (2023). Best practices for single-cell analysis across modalities. Nature Reviews Genetics, 24, 550–572. doi:10.1038/s41576-023-00586-w.
- Single-cell Best Practices: Quality control.
- Amezquita, R. A., et al. (2020). Orchestrating single-cell analysis with Bioconductor. Nature Methods, 17, 137–145. doi:10.1038/s41592-019-0654-x. See the OSCA basic QC chapter and advanced QC chapter.
Software citation
Cite the software separately from its methodological inspiration using the repository’s CITATION.cff.
Interoperability and documentation conventions
veryMADpy uses AnnData observation annotations and Scanpy-style pp and pl namespaces. This is interoperability with the scverse data model and usage conventions, not official ecosystem membership or endorsement. See the scverse ecosystem package guidelines, Scanpy documentation guide, Scanpy usage principles, and mdBook documentation.