Atera kidney: check a low-quality cell filter by eye¶
Removing cells with few transcripts and a small area is a standard quality
control step, but its thresholds are usually chosen from histograms alone.
Spatial data let you look at the cells a filter would remove before you apply
it. This notebook selects the cells a low-quality filter would remove, samples a
representative set with dega.select, and reviews them in a Yearbook. You
flag the cells that look healthy, measure how many good cells the filter would
discard, and decide whether to keep the thresholds.
The data are the public 10x Genomics Atera WTA FFPE human non-diseased kidney dataset, using the same prepared DegaFiles as the Atera kidney tutorial. The notebook downloads only what it needs (cell IDs, plus each cell's transcript count and area, read from the annotated H5AD without downloading all of it); the Yearbook streams images and cell boundaries as you page.
This example requires Celldega 0.29.1 or later: pip install "celldega>=0.29.1".
from pathlib import Path
from urllib.request import urlretrieve
import anndata as ad
import fsspec
import h5py
import pandas as pd
import celldega as dega
SAMPLE = "Atera_v1_WTA_Kidney_non_diseased_FFPE"
DATA_REVISION = "3a46ab4db67821eef3b8ff8d1c3704fb7b3bb48f"
BASE_URL = f"https://raw.githubusercontent.com/broadinstitute/Celldega_{SAMPLE}/{DATA_REVISION}"
ANNDATA_URL = (
"https://huggingface.co/datasets/broadinstitute/Celldega_Supporting_Data/"
f"resolve/main/{SAMPLE}.h5ad"
)
cwd = Path.cwd().resolve()
repo = next((p for p in [cwd, *cwd.parents] if (p / "pyproject.toml").is_file()), None)
cache = (repo or cwd) / "data/atera_kidney_review"
cache.mkdir(parents=True, exist_ok=True)
def fetch(relative):
"""Download one DegaFiles file into the cache, once."""
path = cache / relative
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
urlretrieve(f"{BASE_URL}/{relative}", path)
return path
cell_ids = pd.Index(
pd.read_parquet(fetch("cell_metadata.parquet"), columns=["name"])["name"].astype(str),
name="cell_id",
)
f"{len(cell_ids):,} cells"
'399,120 cells'
1. Load each cell's transcript count and area¶
total_counts and cell_area come from the obs table of the annotated
counts H5AD.
Only those two columns and the cell IDs are read over HTTP (about 25 MB of the
1.31 GiB file). The selector needs nothing else: an AnnData with these columns
in obs.
qc_path = cache / "cell_qc.parquet"
if not qc_path.exists():
with (
fsspec.open(ANNDATA_URL, block_size=2**20, cache_type="blockcache") as remote,
h5py.File(remote, "r") as h5,
):
pd.DataFrame(
{"total_counts": h5["obs/total_counts"][:], "cell_area": h5["obs/cell_area"][:]},
index=pd.Index(h5["obs/_index"].asstr()[:], name="cell_id"),
).to_parquet(qc_path)
cells = ad.AnnData(obs=pd.read_parquet(qc_path).reindex(cell_ids))
cells.obs.describe(percentiles=[0.01, 0.05, 0.5]).round(1)
| total_counts | cell_area | |
|---|---|---|
| count | 399120.0 | 399120.0 |
| mean | 2288.5 | 60.8 |
| std | 2102.8 | 42.2 |
| min | 0.0 | 1.6 |
| 1% | 63.0 | 10.2 |
| 5% | 202.0 | 16.9 |
| 50% | 1595.0 | 49.9 |
| max | 25521.0 | 663.3 |
2. Define the filter¶
The filter removes cells with fewer than 100 transcripts and an area below 20 µm², about 1% of the section. Change the thresholds to try others.
MIN_COUNTS, MIN_AREA = 100, 20
selector = dega.select.Selector(cells)
low_quality = (selector.attr("total_counts") < MIN_COUNTS) & (
selector.attr("cell_area") < MIN_AREA
)
to_remove = selector.select(query=low_quality, sampler="all")
print(f"The filter would remove {len(to_remove):,} of {cells.n_obs:,} cells "
f"({len(to_remove) / cells.n_obs:.1%}).")
The filter would remove 4,390 of 399,120 cells (1.1%).
3. Sample representative cells¶
Looking at the first cells in the list, or the ones you happen to find while
panning, gives a biased view. A seeded random sample of the cells the filter
would remove is representative and reproducible: the same seed gives the same
100 cells, and the Selection records the query and sampler that produced
them.
review = selector.select(query=low_quality, sampler=selector.samplers.random(n=100, seed=0))
review.to_dataframe().head()
| id | rank | |
|---|---|---|
| 0 | iahadpfo-1 | 0 |
| 1 | jbpfeamf-1 | 1 |
| 2 | iegjmjbh-1 | 2 |
| 3 | ihfajgbk-1 | 3 |
| 4 | lbibbgja-1 | 4 |
4. Review them in a Yearbook¶
Each portrait centers one cell, with its neighbors around it. Page through the 100 cells and check the box at the lower right of any portrait that looks like a healthy cell that should be kept: a cell with an intact nucleus and a clear boundary, such as a small lymphocyte. Cells that are fragments at the edge of another cell, slivers of debris, or boundaries without a nucleus are what the filter is meant to remove.
yearbook = dega.viz.Yearbook(
name="kidney_low_quality_review", base_url=BASE_URL, selection=review,
rows=3, cols=5, portrait_size_um=30,
dataset_name="Atera kidney: cells the filter would remove", width=0, height=850,
)
yearbook.layout.width = "100%"
yearbook
5. Measure and decide¶
yearbook.selected_cells returns the cells you flagged. Their share of the
sample estimates the filter's false positive rate: the fraction of removed
cells that should have been kept. For example: "I inspected 100 representative
cells that the filter removes and found 3 that look healthy. A 3% false positive
rate is acceptable, so we keep these thresholds." If the rate is too high,
loosen the thresholds and review a new sample.
flagged = yearbook.selected_cells
if flagged:
rate = len(flagged) / len(review)
print(f"{len(flagged)} of {len(review)} reviewed cells look healthy: "
f"an estimated false positive rate of {rate:.0%}.")
else:
print("No cells flagged yet: check portraits in a live notebook, then rerun this cell.")
No cells flagged yet: check portraits in a live notebook, then rerun this cell.
Once you're satisfied, apply the filter to the full data, keeping the flagged cells' IDs as a record of the review:
adata = adata[~adata.obs_names.isin(to_remove.names())].copy()
adata.uns["low_quality_review"] = {"reviewed": review.to_dict(), "flagged": flagged}
Optional: look at the extremes¶
A random sample shows typical removed cells. To see the most extreme ones, rank
instead of sampling: the 30 cells with the fewest transcripts. Pass the result
to yearbook.selection (or a new Yearbook) to page through them.
extremes = selector.select(
query=low_quality,
sampler=selector.samplers.rank(attr=selector.attr("total_counts"), n=30, by="low"),
)
extremes.to_dataframe().head()
| id | rank | score | |
|---|---|---|---|
| 0 | egmnjjfh-1 | 0 | 0.0 |
| 1 | ekamfpbe-1 | 1 | 0.0 |
| 2 | elmenkgo-1 | 2 | 0.0 |
| 3 | ijhpginl-1 | 3 | 0.0 |
| 4 | ipbmfckn-1 | 4 | 0.0 |