STHELAR_20x / README.md
FelicieGS's picture
Update README.md
d3f933b verified
metadata
license: cc-by-4.0
task_categories:
  - image-segmentation
  - image-classification
tags:
  - H&E
  - WholeSlideImages
  - CellTypeAnnotation
  - Segmentation
  - SpatialTranscriptomics
  - Cancer
  - Xenium
modalities: Image
pretty_name: STHELAR_20x
size_categories:
  - 100K<n<1M
arxiv: https://doi.org/10.1101/2025.07.11.664123
libraries: Datasets
configs:
  - config_name: default
    features:
      - name: file_name
        dtype: string
      - name: image
        dtype: image
      - name: slide_id
        dtype: string
      - name: tissue
        dtype:
          class_label:
            names:
              '0': Breast
              '1': Cervix
              '2': Colon
              '3': Heart
              '4': Kidney
              '5': Liver
              '6': Lung
              '7': LymphNode
              '8': Ovarian
              '9': Pancreatic
              '10': Prostate
              '11': Skin
              '12': Tonsil
      - name: cell_id_map
        dtype: binary
      - name: Dice
        dtype: float16
      - name: Jaccard
        dtype: float16
      - name: bPQ
        dtype: float16
    splits:
      - name: train
        num_bytes: 17638227887.18
        num_examples: 154814
    download_size: 17596467704
    dataset_size: 17638227887.18

STHELAR dataset (20x)

STHELAR (Spatial Transcriptomics and H&E histology for Large-scale Annotation Resource) is a multi-tissue dataset designed for developing models capable of predicting cell types directly from histological Hematoxylin & Eosin (H&E) whole slide images. It integrates high-resolution spatial transcriptomics data with histology, to provide detailed segmentation masks and cell-type annotations.


Available dataset versions

  • STHELAR_40x — 587,555 image patches at 40x magnification
  • STHELAR_20x — 154,814 image patches at 20x magnification

Both datasets share identical structures and metadata, differing only in image magnification levels.


Detailed background

The STHELAR dataset is built from spatial transcriptomics (ST) data combined with Hematoxylin and Eosin (H&E) images, specifically sourced from the 10X Genomics platform using Xenium technology. The dataset comprises 27 human tissue FFPE slides, representing 13 distinct tissue types, including samples from 20 cancerous patients. Both modalities were aligned. Cell-type annotations were generated using the Tangram method, aligning the ST data with single-cell RNA reference atlases, and were subsequently refined via Leiden clustering combined with differential gene expression analysis. The aligned H&E images were divided into H&E patches, each accompanied by masks for nuclei segmentation and cell-type classification. Quality control steps were conducted, notably by comparing STHELAR segmentation masks with predictions from the pretrained CellViT model on the PanNuke dataset.

Important change (v2 format): Instead of giving an instance_map + type_map (cell-type per pixel), we give a single cell_id_map (cell id per pixel) and provide per-slide parquet metadata to retrieve cell types + confidence + multiple label systems for each cell_id. This is more flexible: this allows the user to have access to alternative labels, to trace back to the initial data and to the various analyses stored in BioStudies for each cell_id and each slide_id, and to adjust the labels according to their convenience.


Dataset description

Each dataset (STHELAR_40x or STHELAR_20x) consists of:

  • file_name: Filename of the H&E image patch (e.g., breast_s0_10.png).
  • slide_id: Identifier of the slide from which the patch was extracted (e.g., breast_s0).
  • tissue: Tissue type, provided as categorical labels (e.g., Breast, Lung, Colon).
  • image: RGB color images of size 256×256 pixels, extracted from H&E-stained whole-slide images at 40x or 20x magnification, with a 64-pixel overlap between adjacent patches.
  • cell_id_map: Sparse segmentation mask (CSR matrix stored as .npz bytes) aligned with the H&E patch, where each nucleus pixel stores its biological cell_id integer (0 = background). This is a cell-identity mask, not an 'instance index' mask: the integer values are stable per slide and are designed to join with the per-slide metadata parquets below.
  • Dice: Dice similarity coefficient measuring the overlap between the provided segmentation masks and segmentation predicted by a pre-trained CellViT model (SAM-H encoder).
  • Jaccard: Jaccard index measuring segmentation accuracy relative to predictions made by a pre-trained CellViT model (SAM-H encoder).
  • bPQ: Binary Panoptic Quality score, evaluating segmentation and instance-detection accuracy simultaneously, computed relative to predictions made by a pre-trained CellViT model (SAM-H encoder).

Cell type labels & per-cell metadata

Each pixel stores a cell_id integer in cell_id_map, and you retrieve the associated annotations from a per-slide_id parquet:

  • cell_metadata/{slide_id}_cell_metadata.parquet
  • plus an index: cell_metadata/index.parquet (and index.csv)

Each slide_id parquet compiles, for all cell IDs, the nucleus and whole-cell cell type labels, alternative labels, as well as the associated confidence metrics. It contains the following columns:

  • cell_id: Unique identifier of the biological cell within the given slide - Xenium Explorer cell identifier (string, e.g. aaaachba-1).
  • cell_id_int (recommended join key): Integer form of cell_id matching the values stored in cell_id_map - See below how to switch between cell_id and cell_id_int.
  • nuclei_ct_tangram: Fine-grained cell-type label predicted by Tangram using nucleus RNA counts.
  • nuclei_ct_tangram_group: Grouped version of nuclei_ct_tangram, obtained by mapping Tangram’s fine labels to the harmonized label space used in STHELAR.
  • nuclei_label1: Curated nucleus-derived label assigned after Tangram-guided and marker-gene-driven refinement, level 1 annotation for nuclei (first-stage label used during refinement; slide-specific granularity).
  • nuclei_label2: Curated nucleus-derived label assigned after Tangram-guided and marker-gene-driven refinement, level 2 annotation for nuclei (more precise/secondary label level; slide-specific granularity).
  • nuclei_label3: Attempt to label "cancer" versus "normal" cell, level 3 annotation for nuclei.
  • nuclei_final_label: nuclei_label1 harmonized across slides. Categories are "Epithelial", "Blood_vessel", "Fibroblast_Myofibroblast", "Myeloid", "B_Plasma", "T_NK", "Melanocyte", "Glioblastoma", "Specialized", "Stem_like", "Unknown", and "Less10".
  • nuclei_final_label_group: Grouped nuclei_final_label labels, where low-information categories are collapsed ("Less10", "Unknown", "Stem_like" to "Other").
  • cells_label1: Curated whole-cell-derived label assigned after Tangram-guided and marker-gene-driven refinement, level 1 annotation for cells (first-stage label used during refinement; slide-specific granularity).
  • cells_label2: Curated whole-cell-derived label assigned after Tangram-guided and marker-gene-driven refinement, level 2 annotation for cells (more precise/secondary label level; slide-specific granularity).
  • cells_label3: Attempt to label "cancer" versus "normal" cell, level 3 annotation for cells.
  • cells_final_label: cells_label1 harmonized across slides. Categories are "Epithelial", "Blood_vessel", "Fibroblast_Myofibroblast", "Myeloid", "B_Plasma", "T_NK", "Melanocyte", "Glioblastoma", "Specialized", "Stem_like", "Unknown", and "Less10".
  • cells_final_label_group: Grouped cells_final_label labels, where low-information categories are collapsed ("Less10", "Unknown", "Stem_like" to "Other").
  • cells_transcript_counts: Total number of detected transcripts assigned to the whole cell (library size for that cell; used both for QC and as an RNA-depth proxy).
  • cells_singleR: Fine-grained reference-based label predicted by SingleR from whole-cell RNA counts.
  • cells_singleR_group: Grouped version of cells_singleR, obtained by mapping SingleR’s fine labels to the harmonized label space used in STHELAR.
  • cells_final_label_confidence: Neighborhood purity score $= 1 -$ normalized Shannon entropy of the full kNN label distribution induced by connectivities weights ([0,1]; higher = more locally unambiguous). Also named "ct_confidence" in the following analysis.
  • cells_final_label_prob: Assigned-label agreement $= p_i$(assigned label), i.e. the connectivity-weighted fraction of neighbor mass matching the cell’s label. Also named "ct_support" in the following analysis.
  • cells_final_label_alt1: First alternative label according to the kNN-neighborhood label distribution.
  • cells_final_label_alt1_prob: Probability/support associated with cells_final_label_alt1 in the kNN-neighborhood label distribution.
  • cells_final_label_alt2: Second alternative label according to the kNN-neighborhood label distribution.
  • cells_final_label_alt2_prob: Probability/support associated with cells_final_label_alt2.
  • cells_final_label_alt3: Third alternative label according to the kNN-neighborhood label distribution.
  • cells_final_label_alt3_prob: Probability/support associated with cells_final_label_alt3.
  • cells_knn_row_sum: Total kNN-graph connectivity weight for the cell (row-sum of the Scanpy connectivities matrix, equals the cell’s weighted degree/strength in the neighbor graph, after self-edge removal). Low values indicate weak/absent neighborhood connectivity and can make confidence/support undefined (NaN when row-sum is 0).
  • cells_rna_depth_log1p: Log-transformed RNA depth proxy computed as log(1+cells_transcript_counts), providing a stabilized per-cell library-size measure.
  • cells_rna_depth_quantile: Within-slide rank-based quantile of RNA depth (in[0,1]), enabling comparison of RNA abundance across cells in the same slide independently of panel size and scale.
  • combined_final_label: Label obtained from the "table_combined" (integration of nuclear and cytoplasmic RNA information using MFA analysis).

See the article for more details about each label.

🔆🔆 Recommended label 🔆🔆

Use cells_final_label_group as the default target label (robust + harmonized + typically highest-confidence) - See article for more details.
Its categories are: Epithelial, Blood_vessel, Fibroblast_Myofibroblast, Myeloid, B_Plasma, T_NK, Melanocyte, Specialized, Other.

Cell type Description
Epithelial Includes various epithelial cells often specific to individual tissues. For instance, in pancreatic tissue, it includes pancreatic acinar, ductal, and islet cells.
Blood_vessel Covers endothelial cells, pericytes, and smooth muscle cells.
Fibroblast_Myofibroblast Contains fibroblasts, myofibroblasts, and mesenchymal stromal cells.
Myeloid Comprises macrophages, monocytes, dendritic cells, neutrophils, mast cells, and plasmacytoid dendritic cells (pDCs). Due to their dual myeloid/lymphoid characteristics and rarity, pDCs were grouped here, with minimal impact expected.
B_Plasma Combines B lymphocytes and plasma cells.
T_NK Includes T lymphocytes and natural killer (NK) cells.
Melanocyte Represents melanocytes or melanoma cells specifically found in skin tissue.
Specialized Captures tissue-specific cells such as cardiomyocytes, osteoblasts, osteoclasts, and some endocrine cells.
Other Encompasses cells without marker genes or those with fewer than 10 RNAs.

Tissue types and associated slides

The dataset covers a variety of normal and cancerous human tissues:

Tissue type Included slides (WSIs)
Breast breast_s0, breast_s1, breast_s3, breast_s6
Cervix cervix_s0
Colon colon_s1, colon_s2
Heart heart_s0
Kidney kidney_s0, kidney_s1
Liver liver_s0, liver_s1
Lung lung_s1, lung_s3
LymphNode lymph_node_s0
Ovarian ovary_s0, ovary_s1
Pancreatic pancreatic_s0, pancreatic_s1, pancreatic_s2
Prostate prostate_s0
Skin skin_s1, skin_s2, skin_s3, skin_s4
Tonsil tonsil_s0, tonsil_s1

Slides with cancerous tissue are: 'breast_s0', 'breast_s1', 'breast_s3', 'breast_s6', 'cervix_s0', 'colon_s1', 'colon_s2', 'kidney_s1', 'liver_s1', 'lung_s1', 'lung_s3', 'ovary_s0', 'ovary_s1', 'pancreatic_s0', 'pancreatic_s1', 'pancreatic_s2', 'prostate_s0', 'skin_s2', 'skin_s3', 'skin_s4'.


Quality control

Segmentation and alignment quality were assessed using metrics from comparisons to segmentation predictions by pre-trained CellViT (SAM-H) model.

Metrics included:

  • Dice coefficient: Measures overlap accuracy.
  • Jaccard index: Intersection-over-union metric.
  • Binary Panoptic Quality (bPQ): Evaluates segmentation and detection quality simultaneously.

These metrics facilitate dynamic filtering based on required accuracy thresholds (e.g., retaining patches with Jaccard index ≥ 0.45).
A high score generally reflects good alignment and segmentation quality for our dataset. Conversely, a low score does not always indicate poor quality—it may result from actual data issues or from inaccurate predictions by CellViT (see article for details).


Dataset format

license: cc-by-4.0
data_files:
  - split: train
    path: data/train-*
dataset_info:
  features:
  - name: file_name
    dtype: string
  - name: image
    dtype: image
  - name: slide_id
    dtype: string
  - name: tissue
    dtype:
      class_label:
        names:
          '0': Breast
          '1': Cervix
          '2': Colon
          '3': Heart
          '4': Kidney
          '5': Liver
          '6': Lung
          '7': LymphNode
          '8': Ovarian
          '9': Pancreatic
          '10': Prostate
          '11': Skin
          '12': Tonsil
  - name: cell_id_map
    dtype: binary # CSR .npz bytes
  - name: Dice
    dtype: float16
  - name: Jaccard
    dtype: float16
  - name: bPQ
    dtype: float16
  splits:
  - name: train
    num_examples: 154814

Loading the dataset

1) Full download + training use (includes cell-metadata join)

This downloads the full split once, and shows the way to join cell_id_map with the per-slide parquet.

# pip install -U datasets huggingface_hub pandas pyarrow scipy
import io
from functools import lru_cache
import numpy as np
import pandas as pd
import scipy.sparse as sp
from datasets import load_dataset
from huggingface_hub import snapshot_download

REPO = "FelicieGS/STHELAR_20x"  # or "FelicieGS/STHELAR_40x"

# --- 1) Download the dataset split (one-time, then cached) ---
ds = load_dataset(REPO, data_files={"train": "data/train-*.parquet"}, split="train")

# --- 2) Download ALL sidecar metadata once (27 slides) ---
meta_root = snapshot_download(
    REPO,
    repo_type="dataset",
    allow_patterns=["cell_metadata/*.parquet", "cell_metadata/index.*"],
)

def decode_cell_id_map(npz_bytes: bytes) -> np.ndarray:
    """Decode CSR .npz bytes -> dense uint32 (256x256). (Safe to densify at this patch size.)"""
    return sp.load_npz(io.BytesIO(npz_bytes)).toarray().astype(np.uint32, copy=False)

@lru_cache(maxsize=None)
def load_slide_meta(slide_id: str) -> pd.DataFrame:
    """
    Load ONE slide parquet (cached in-process). Keep only the columns you need.
    Join key: `cell_id_int` <-> values in `cell_id_map`.
    """
    path = f"{meta_root}/cell_metadata/{slide_id}_cell_metadata.parquet"
    cols = [
        "cell_id_int",
        "cell_id",
        "cells_final_label_group",        # recommended label
    ]
    return pd.read_parquet(path, columns=cols).set_index("cell_id_int", drop=False)

# --- Example: take one patch and join with its slide metadata ---
ex = ds[0]
cell_id = decode_cell_id_map(ex["cell_id_map"])          # (H,W), 0 = background
slide_meta = load_slide_meta(ex["slide_id"])             # per-cell table for that slide

ids_in_patch = np.unique(cell_id)
ids_in_patch = ids_in_patch[ids_in_patch != 0]           # drop background
meta_patch = slide_meta.loc[slide_meta.index.intersection(ids_in_patch)]

print("file_name:", ex["file_name"])
print("slide_id:", ex["slide_id"])
print("tissue:", ds.features["tissue"].int2str(ex["tissue"]))
print("Dice/Jaccard/bPQ:", ex["Dice"], ex["Jaccard"], ex["bPQ"])
print("\nPatch label histogram (recommended label):")
print(meta_patch["cells_final_label_group"].value_counts())

# --- Optional: build a dense per-pixel label map as small ints ---
LABELS = [
    "Epithelial", "Blood_vessel", "Fibroblast_Myofibroblast", "Myeloid",
    "B_Plasma", "T_NK", "Melanocyte", "Specialized", "Other",
]
label_to_int = {lab: i + 1 for i, lab in enumerate(LABELS)}  # reserve 0 for background/unknown

ids_all, inv = np.unique(cell_id, return_inverse=True)  # includes 0
lab_for_id = (
    slide_meta["cells_final_label_group"]
    .reindex(ids_all)              # align labels to ids present in this patch
    .fillna("BACKGROUND")
    .to_numpy()
)
lut = np.fromiter((label_to_int.get(x, 0) for x in lab_for_id), dtype=np.uint8, count=len(ids_all))
label_map = lut[inv].reshape(cell_id.shape)              # uint8, 0..9

# `meta_patch` is the per-cell joined table for this patch.
# `label_map` is a per-pixel target map (0=background/unknown, 1..9=labels above).

2) Quick inspection via streaming (no full download) + visualization + metadata

Streaming avoids downloading all dataset shards. You only fetch the few samples you iterate over, which is perfect to quickly verify the format, masks, and the metadata join.

# pip install -U datasets huggingface_hub pandas pyarrow scipy matplotlib
import io
from functools import lru_cache
import numpy as np
import pandas as pd
import scipy.sparse as sp
import matplotlib.pyplot as plt
from datasets import load_dataset, Image
from huggingface_hub import hf_hub_download

REPO = "FelicieGS/STHELAR_20x"  # or "FelicieGS/STHELAR_40x"

def decode_cell_id_map(npz_bytes: bytes) -> np.ndarray:
    return sp.load_npz(io.BytesIO(npz_bytes)).toarray().astype(np.uint32, copy=False)

@lru_cache(maxsize=32)
def load_slide_meta(slide_id: str) -> pd.DataFrame:
    # Downloads only the needed parquet; cached by hf_hub_download + LRU in-process.
    p = hf_hub_download(
        repo_id=REPO,
        repo_type="dataset",
        filename=f"cell_metadata/{slide_id}_cell_metadata.parquet",
    )
    cols = ["cell_id_int", "cell_id", "cells_final_label_group"]
    return pd.read_parquet(p, columns=cols).set_index("cell_id_int", drop=False)

# Stream 1 sample (optionally: ds = ds.shuffle(buffer_size=10_000, seed=0))
ds = load_dataset(
    REPO,
    data_files={"train": "data/train-*.parquet"},
    split="train",
    streaming=True,
).cast_column("image", Image(decode=True))
ex = next(iter(ds))

rgb = np.asarray(ex["image"])
cell_id = decode_cell_id_map(ex["cell_id_map"])

slide_id = ex["slide_id"]
meta = load_slide_meta(slide_id)

ids_in_patch = np.unique(cell_id)
ids_in_patch = ids_in_patch[ids_in_patch != 0]
meta_patch = meta.loc[meta.index.intersection(ids_in_patch)]
counts = meta_patch["cells_final_label_group"].value_counts()

print("file_name:", ex["file_name"])
print("slide_id:", slide_id)
print("tissue:", ds.features["tissue"].int2str(ex["tissue"]))
print("Dice/Jaccard/bPQ:", ex["Dice"], ex["Jaccard"], ex["bPQ"])
print("\nTop labels in patch:")
print(counts.head(10))
print("\nExample joined per-cell rows (first 5):")
print(meta_patch[["cell_id", "cells_final_label_group"]].head(5))

# Simple visualization: RGB, cell_id_map, RGB with cell-type-colored boundaries
# Build a per-pixel cell-type id map (0=background/unknown, 1..N=cell types)
LABELS = [
    "Epithelial", "Blood_vessel", "Fibroblast_Myofibroblast", "Myeloid",
    "B_Plasma", "T_NK", "Melanocyte", "Specialized", "Other",
]
label_to_int = {lab: i + 1 for i, lab in enumerate(LABELS)}  # reserve 0

ids_all, inv = np.unique(cell_id, return_inverse=True)  # includes 0
lab_for_id = (
    meta["cells_final_label_group"]
    .reindex(ids_all)            # align labels to the IDs appearing in this patch
    .fillna("BACKGROUND")
    .to_numpy()
)
lut = np.fromiter((label_to_int.get(x, 0) for x in lab_for_id), dtype=np.uint8, count=len(ids_all))
label_id_map = lut[inv].reshape(cell_id.shape)  # uint8 in [0..len(LABELS)]

thickness = 3  # radius in pixels

boundary = (
    (cell_id != np.roll(cell_id,  thickness, axis=0)) |
    (cell_id != np.roll(cell_id, -thickness, axis=0)) |
    (cell_id != np.roll(cell_id,  thickness, axis=1)) |
    (cell_id != np.roll(cell_id, -thickness, axis=1))
) & (cell_id != 0)

rgb_overlay = rgb.copy()
# Color boundaries by cell type (based on the cell_id at each boundary pixel)
cmap = plt.get_cmap("tab10", len(LABELS) + 1)  # discrete colors: 0..N
lut_rgb = (cmap(np.arange(len(LABELS) + 1))[:, :3] * 255).astype(np.uint8)  # (N+1, 3), uint8
rgb_overlay[boundary] = lut_rgb[label_id_map[boundary]]

fig, ax = plt.subplots(1, 3, figsize=(12, 4))
ax[0].imshow(rgb)
ax[0].set_title("RGB patch")
ax[0].axis("off")
ax[1].imshow(cell_id, cmap="nipy_spectral")
ax[1].set_title("cell_id_map (IDs)")
ax[1].axis("off")
ax[2].imshow(rgb_overlay)
ax[2].set_title("RGB + nucleus boundaries")
ax[2].axis("off")

# Optional: legend (only labels present in this patch)
import matplotlib.patches as mpatches
present = [lab for lab in counts.index.to_list() if lab in label_to_int]  # `counts` computed above
handles = [
    mpatches.Patch(color=tuple(lut_rgb[label_to_int[lab]] / 255.0), label=lab)
    for lab in present
]
if handles:
    ax[2].legend(handles=handles, loc="lower left", bbox_to_anchor=(1.02, 0), borderaxespad=0.0)

plt.tight_layout()
plt.show()

# Patch label distribution (bar plot)
plt.figure(figsize=(7, 3))
labs = counts.index.to_numpy()
vals = counts.to_numpy()
plt.bar(labs, vals)
plt.xticks(rotation=45, ha="right")
plt.title("cells_final_label_group counts in this patch")
plt.tight_layout(); plt.show()

You will get for instance for one patch:

file_name: breast_s0_10000.png
slide_id: breast_s0
tissue: Breast
Dice/Jaccard/bPQ: 0.85302734375 0.74365234375 0.57666015625

Top labels in patch:
cells_final_label_group
Epithelial                  50
Fibroblast_Myofibroblast    21
Myeloid                     15
T_NK                         7
B_Plasma                     1
Blood_vessel                 1
Name: count, dtype: int64

Example joined per-cell rows (first 5):
                cell_id   cells_final_label_group
cell_id_int                                      
189324       aaacodil-1                Epithelial
189325       aaacodim-1                   Myeloid
189326       aaacodin-1                      T_NK
189327       aaacodio-1                Epithelial
189328       aaacodip-1  Fibroblast_Myofibroblast

example_sample_STHELAR_20x


Cell ID encoding (Xenium Explorer) and conversions

The per-slide parquet contains cell_id as a Xenium string ID (e.g. aaaachba-1). cell_id_map stores an integer version (cell_id_int).

If you ever need to convert between the two:

def int_cell_id(cell_id_str: str) -> int:
    cell_id_str = cell_id_str[:-2]  # remove '-1'
    cell_id = 0
    for char in cell_id_str:
        cell_id = cell_id * 16 + (ord(char) - 97)  # (a-p -> 0-15)
    return cell_id + 1  # shift to avoid 0 (background)

def str_cell_id(cell_id: int) -> str:
    cell_id -= 1
    coefs = []
    for _ in range(8):
        cell_id, coef = divmod(cell_id, 16)
        coefs.append(coef)
    return "".join([chr(97 + c) for c in coefs][::-1]) + "-1"

To know the Xenium string ID is useful if the user want to access to more information about each slide_id and their cell_id in the BioStudies dataset (see below).


Associated publication and data resources


Citation

Giraud-Sauveur, F. et al. STHELAR, a multi-tissue dataset linking spatial transcriptomics and histology for cell type annotation. bioRxiv (2025) doi:10.1101/2025.07.11.664123.


License

Released under the CC-BY 4.0 License.