File size: 27,412 Bytes
724bb77
 
 
 
 
 
 
 
 
 
 
 
243996e
724bb77
 
 
 
 
 
d3f933b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243996e
 
724bb77
 
 
 
 
 
 
 
 
 
243996e
966f338
 
 
724bb77
 
 
243996e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
 
 
 
 
 
 
 
243996e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
 
 
 
 
 
 
243996e
724bb77
243996e
724bb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243996e
 
724bb77
 
 
 
 
 
 
 
 
 
 
 
 
5c24290
 
 
 
 
 
 
 
 
 
 
 
 
42d8f25
5c24290
 
 
724bb77
 
243996e
724bb77
243996e
724bb77
 
243996e
 
 
724bb77
243996e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
243996e
724bb77
243996e
724bb77
243996e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
243996e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
243996e
724bb77
243996e
724bb77
a01e22c
243996e
724bb77
243996e
724bb77
243996e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724bb77
 
a01e22c
243996e
724bb77
 
 
 
a01e22c
 
724bb77
 
 
 
 
 
 
 
 
a01e22c
724bb77
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
---
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`](https://huggingface.co/datasets/FelicieGS/STHELAR_40x)** — 587,555 image patches at **40x** magnification
* **[`STHELAR_20x`](https://huggingface.co/datasets/FelicieGS/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 comparing the provided segmentation mask with the segmentation mask predicted by the pre-trained CellViT model (SAM-H encoder).
* **Jaccard**: Jaccard index comparing the provided segmentation mask with the segmentation mask predicted by the pre-trained CellViT model (SAM-H encoder).
* **bPQ**: Binary Panoptic Quality score comparing the provided segmentation mask with the segmentation mask predicted by the 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](https://github.com/TIO-IKIM/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
```

---

## Patch-level overview

The repository also contains a global patch-level summary file for all slides together:  
`patches_overview_sthelar20x.parquet`

This file enables rapid dataset-level exploration and filtering without loading the images or per-cell metadata, and provides access to each patch’s coordinates on its originating slide.

This Parquet table contains one row per H&E patch and provides spatial location, segmentation quality metrics, and cell-type composition.  
It includes the following columns:
* **slide_id**: Identifier of the originating whole-slide image (e.g., breast_s0).
* **file_name**: Patch filename (`{slide_id}_{patch_number}.png`) (e.g., breast_s0_10.png).
* **xmin, ymin, xmax, ymax**: Patch coordinates in slide space.
* **Dice, Jaccard, bPQ**: Segmentation quality metrics.
* **T_NK, B_Plasma, Myeloid, Blood_vessel, Fibroblast_Myofibroblast, Epithelial, Specialized, Melanocyte, Other**: Number of cells present in the patch for each cell-type label (using `cells_final_label_group` labels).

---

## 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.

```python
# 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.

```python
# 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](assets/example_sample_STHELAR_20x.png)

---

## 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:

```python
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 wants to access more information about each slide_id and their cell_id in the BioStudies dataset (see below).*

---

## Associated publication and data resources

* **Main publication:** [STHELAR Sci Data](https://doi.org/10.1038/s41597-026-06937-6)
* **All data mentioned in the publication (BioStudies):** [S-BIAD2146](https://www.ebi.ac.uk/biostudies/bioimages/studies/S-BIAD2146)
* **Code repositories:**

  * [STHELAR pipeline](https://github.com/MICS-Lab/STHELAR)
  * [CellViT for STHELAR](https://github.com/MICS-Lab/CellViT_for_STHELAR)

---

## Citation

Giraud-Sauveur, F., Blampey, Q., Benkirane, H. et al. STHELAR, a multi-tissue dataset linking spatial transcriptomics and histology for cell type annotation. Sci Data (2026). https://doi.org/10.1038/s41597-026-06937-6

---

## License

Released under the **CC-BY 4.0 License**.