CosciaLab/histo: Output¶
Introduction¶
This document describes the output produced by the pipeline.
What runs¶
Three example routes; the metro map in the README draws the whole-slide and TMA ones. Everything else is off by default. Each column’s segmentation is an example: any methods and targets fit any route.
Read down a column to get one run’s process list, in order. The QC steps and
COMPARE_SEGMENTATIONS read the store without writing to it, so they run alongside publishing.
| Station | mIF slide | WSI, background subtracted | TMA, dearrayed |
|---|---|---|---|
| Segmentation | Cellpose + InstanSeg, cells + nuclei | Cellpose, cells | InstanSeg, cells + nuclei |
BASICPY | x | x | x |
ASHLAR | x | x | x |
COREOGRAPH | x | ||
BACKSUB | x | optional | |
TO_SPATIALDATA | x | x | x |
SET_CHANNEL_NAMES | x | x | x |
MAKE_IMAGE_PATCHES | x | x | x |
SEGMENT_PATCH_CELLPOSE | per patch × target | per patch | |
SEGMENT_PATCH_INSTANSEG | per patch × target | per patch × target | |
RESOLVE | per method × target | x | per target |
LINK_COMPARTMENTS | per method | x | |
AGGREGATE | per method | x | x |
WRITE_SEGMENTATIONS | x | x | x |
MERGE_SPATIALDATA | x | ||
PUBLISH_SPATIALDATA | x | x | x, per slide |
QC_METRICS | per method | x | x |
QC_IMAGES | per method | x | x |
QC_REPORT | per method | x | x |
COMPARE_SEGMENTATIONS | x | ||
MERGE_REPORT | x |
Everything after COREOGRAPH, BACKSUB included, runs once per core on the TMA path.
MERGE_SPATIALDATA then puts one slide’s cores back together, and PUBLISH_SPATIALDATA
publishes the result, so publication happens once per slide rather than once per core. The
per-core stores are not published: the merged store copies every element family and every table
out of them, prefixed by core, so publishing both would write the slide out twice.
Variations not in the table:
LINK_COMPARTMENTSruns for a method with both targets (segment_cells,segment_nuclei).COMPARE_SEGMENTATIONSruns when both methods segment cells anduse_qcis true.TISSUE_SEGMENTATIONis off in all three runs. It sits beforeMAKE_IMAGE_PATCHES.use_preprocessing = falseis a fourth entry point, for images arriving pre-stitched. It starts atTO_SPATIALDATAand skipsSET_CHANNEL_NAMES, because such an image is assumed to carry its own channel names.Supplying illumination profiles in the samplesheet bypasses
BASICPY.preprocessing_onlyends every path at the preprocessing outputs.use_projectionaddsPROJECT_CHANNELSbeforeMAKE_IMAGE_PATCHES; Cellpose segments the projection, andWRITE_SEGMENTATIONSremoves it unlesskeep_projection.
Pipeline overview¶
The directories listed below will be created in the results directory after the pipeline has finished. All paths are relative to the top-level results directory.
The pipeline is built using Nextflow and outputs the following information:
Preprocessing - Illumination profiles, the stitched image, and the optional background-subtracted and dearrayed images.
SpatialData directory - Full SpatialData object with the segmented and aggregated data.
QC report - Per-sample HTML summary of segmentation and aggregation
Pipeline information - Report metrics generated during the workflow execution
Preprocessing¶
Output files
preprocessing/illumination/{sample}_cycle{n}-dfp.ome.tifand-ffp.ome.tif, the dark-field and flat-field profiles BaSiCPy wrote for each cycle. Absent for a cycle whose profiles were supplied in the samplesheet, since nothing was computed.
preprocessing/registration/{sample}.ome.tif, the stitched and registered mosaic from Ashlar. This is the handoff boundary between the two halves of the pipeline, and the file to inspect first when segmentation looks wrong.{sample}_ashlar_qc/, Ashlar’s own account of how it stitched and registered, whenuse_qcis true. On a TMA it is per slide, since Ashlar runs before dearraying.qc.jsonsummarises it;edges.csvhas one row per neighbouring tile pair in cycle 1 (shift, error, why it was rejected),tiles.csvone row per tile per cycle (nominal and final position, residual, angle, why it was discarded),null_errors.csvthe errors of random non-overlapping strips the rejection threshold comes from;overlay_cycleN.jpgputs cycle 1 in magenta over cycle N+1 in green at their final positions, beside each cycle’sthumb_cycleN.jpg;{sample}_ashlar_report.pdfhas per-tile maps;ashlar.logis the console output. Ashlar counts cycles from 0 in the JSON and CSVs; the reports count from 1. Written before the mosaic, so a failed write still leaves it in the task’s work directory.
preprocessing/background_subtraction/{sample}_backsub.ome.tifand{sample}_backsub.csv. Only whenuse_backsubis true. The CSV is backsub’s own marker sheet rather than a copy of the input: rows whoseremovecolumn was set are gone andchannel_numberis renumbered over what survives, so this is the sheet that describes the image everything downstream reads.
preprocessing/dearray/{slide}_core001.ome.tifand one per core, plusmasks/{slide}_core001_mask.tif,{slide}_coremask.tif,{slide}_tma_map.tifand{slide}_centroids.txt. Only whenuse_tma_dearrayis true. The TMA map and centroids are what to check when a core is missing or two cores were merged into one.
preprocessing/dearray/sweep/{slide}_sweep.tsv: one row per downsample factor, best first, with its core count, median diameter, size spread, score and any warning.{slide}_sweep_overlays.pngshows the detected cores at every factor side by side. Only withoutcoreograph_args.{slide}_selection.json(the chosen factor), and per factor{slide}_k{k}_metrics.json,_coremask.tif,_centroids.txtand_overlay.png.
The _backsub suffix appears on backsub’s own two files and on the store’s image element. Core
identity comes from the slide name rather than from the filename it was cut out of, so a slide
processed with and without background subtraction produces cores with matching names.
With preprocessing_only, these files and pipeline_info/ are the whole output. There is no
HTML report then, so {sample}_ashlar_qc/{sample}_ashlar_report.pdf is where to check stitching.
SpatialData directory¶
Output files
{sample}.zarr/, per method{m}(cellpose,instanseg):images/: the image. Withkeep_projection, also<image>_projected: thenuclearandcellchannels Cellpose segmented, at full resolution.shapes/{m}_cells(segment_cells): cell polygons, indexed by cell id.shapes/{m}_nuclei(segment_nuclei): nucleus polygons. With both targets, itslinked_cell_idnames the cell holding at least half of the nucleus; null if none.shapes/{m}_cytoplasm(both targets): each cell minus its linked nuclei, for cells with non-empty cytoplasm only, indexed by their cell ids.tables/{m}_table: one row per cell, or per nucleus in a nuclei-only run. Below.tables/{m}_nimbus(use_nimbus): Nimbus scores, one row per cell. See Nimbus scores.tables/{m}_virtues(use_virtues): VirTues embeddings, one row per cell. See VirTues embeddings.shapes/virtues_niches,tables/virtues_niches_table,tables/virtues_tissue(use_virtues): 128 µm tissue squares and their embeddings, and one embedding per store.
{slide}_merged.zarr/and{slide}_merge_manifest.jsonDearrayed slides only, instead of per-core stores: every core’s elements in one store, and the manifest of what was merged.
The {sample}.zarr directory contains a SpatialData object, where the sample name is either (i) specified by the samplesheet, or (ii) based on the name of the corresponding input directory.
Shapes and tables named {cellpose,instanseg}_{cells,nuclei,cytoplasm,table} belong to the
pipeline: each run replaces those it writes and removes the rest, logging each. Do not give your
own elements these names.
Cell ids are {image}_{m}_cells_{n} ({image}_{m}_nuclei_{n} for nuclei), unique within a
store: the shapes’ index and the table’s obs_names and obs['cell_id'] are the same ids.
{m}_table holds:
X: the statistics per marker over the whole cell (the nucleus in a nuclei-only run), afterexpand_radius_ratioif set, float32.var_namesare{marker}_{statistic}(CD3_mean);varhas columnsmarkerandstatistic. Statistics are set byquantification_statistics(defaultmean,median,std);stdis the population SD.layers['nucleus'],layers['cytoplasm'](both targets): the samevarover the cell’s nucleus compartment (its linked nuclei, clipped to the cell) and over its cytoplasm.obs:region({m}_cells, or{m}_nuclei),cell_id,slide, andcore_idon a dearrayed TMA. Shape features of the unexpanded polygon, in px and px²:cell_area,cell_perimeter,cell_circularity(NaN below 30 px²),cell_solidity,cell_eccentricity,cell_major_axis_length,cell_minor_axis_length. With both targets alson_nuclei(linked nuclei),nucleus_id(the largest),cytoplasm_area, the same seven asnucleus_*over the nucleus compartment, andnc_ratio(nucleus_area / cell_area). A nuclei-only run hasnucleus_*for its own rows and nocell_*.obsm['spatial']: centroids of the unexpanded cells.uns['quantification']:statistics,tile_sizeandmax_window_px, the largest read window.uns['segmentation']: the settings each segmentation was requested with, keyed by name ({m}_cells,{m}_nuclei). Unset options are absent; sopa’s defaults applied.{m}_kwargsis kept as given, as text, inmethod_kwargs_extra. Lists such aschannelsread back as numpy arrays ofStringDType, not Python lists.
NaN means “not measured”, 0 means “measured, nothing there”:
| Cell | layers | nucleus_area | cytoplasm_area |
|---|---|---|---|
| No linked nucleus | nucleus, cytoplasm NaN | 0 | NaN |
| Nuclei fill the cell | cytoplasm NaN | > 0 | 0 |
| Covers no pixel centre | X and both layers NaN |
Without a linked nucleus, the other nucleus_* shape columns and nc_ratio are NaN.
Cells are never dropped. A cell covering no pixel centre is left out of the QC clustering.
To select one statistic:
adata[:, adata.var.statistic == "median"]slide and core_id say where cells came from: slide is the sample name from the
samplesheet, core_id the core (e.g. TMA01_core001). Runs without dearraying have no
core_id column. Ids may repeat across stores, so keep these columns when concatenating tables
of several stores, and make obs_names unique (e.g. anndata.concat(..., index_unique="-")).
Refer to the SpatialData docs for usage details, or to the documentation of sopa as a Python package.
PUBLISH_SPATIALDATA copies the store here, and exists only for that: it runs after the last
step that writes to the store.
Nimbus scores¶
use_nimbus adds tables/{m}_nimbus for each method: the same cells as {m}_table, one column per
marker, each value a confidence in [0, 1] that the marker is positive in that cell.
sdata["cellpose_nimbus"][:, "CD3"].XX: float32, cells by markers. NaN for a channel with no nonzero pixel, or a cell covering no pixel centre.var_names: the marker names, innimbus_channelsorder when given, else marker-sheet order.obs:region,slide,core_idandcell_idwhere present, copied from{m}_table.uns['nimbus']: how the scores were made.
uns['nimbus'] key | Meaning |
|---|---|
nimbus_version | Nimbus-Inference version. |
weights | Weights file. |
weights_sha256 | sha256 of the weights file. |
channels | Markers scored. |
factors | Per-channel normalisation factor (0.999 quantile). |
unscored | Channels with no nonzero pixel; their columns are NaN. |
pixel_size | µm per pixel given by pixel_size. |
model_um_per_px | µm per model pixel (1.0). Provisional; see decisions. |
magnification | 10 * model_um_per_px / pixel_size. |
tile_size | Tile edge, in image pixels (2048 model pixels). |
margin | Context added around each tile, in image pixels. |
halo | Model halo measured at start-up, in model pixels. |
min_window | Smallest window, in image pixels (1056 model pixels). |
test_time_aug | Always true. |
device | cpu or cuda. |
The same keys are published as learned_features/{sample}_{m}_nimbus.json, so provenance can be read without
opening the store.
VirTues embeddings¶
use_virtues adds three kinds of table, each row a 512-number embedding:
tables/{m}_virtues, for each method: the same cells as{m}_table.shapes/virtues_nichesandtables/virtues_niches_table: non-overlapping 128 × 128 µm squares with at least 30% tissue, one row each, withtissue_fractioninobs. Neither exists when no square qualifies.tables/virtues_tissue: one row per store (a core on a TMA, else the image): the mean of the kept squares, withn_nichesinobs. NaN when no square is kept, or when tissue segmentation found no tissue in the store; its cells are still embedded.
sdata["cellpose_virtues"].X # cells x 512, float16X: float16. NaN for a cell covering no pixel at 1 µm/px, counted inn_cells_without_pixel.var_names:virtues_0tovirtues_511. The columns have no marker meaning.obs:region,slide,core_idandcell_idwhere present, copied from{m}_table. The cell table’s region is{m}_cellsand its instance keycell_id; the squares’ isniche_id.uns['virtues']: how the embeddings were made, the same on all of them.
uns['virtues'] key | Meaning |
|---|---|
virtues_commit | VirTues code commit. |
weights | Weights file (sp32). |
weights_sha256 | sha256 of the weights file. |
esm_model | ESM-2 model that embeds each marker’s sequence. |
uniprot_release | UniProt release of the sequences. |
channels | Marker name to uniprot_id, for channels embedded. |
unembedded | Channels without an ID, left out. |
stats | Per marker: uniprot_id, cap, mean, sd, tissue_pixels. |
pixel_size | µm per pixel given by pixel_size. |
model_um_per_px | µm per model pixel (1.0). |
crop_size, crop_step | Crop edge (128) and step between a cell’s crops (42), in model pixels. |
patch_size | Patch edge (8), in model pixels. |
padding | Zeros added round the image edge (120), in model pixels. |
tile_size | Tile edge (2048), in model pixels. |
batch_size | Crops per GPU batch. |
device | cuda. |
n_cells | Cells per method. |
n_cells_without_pixel | Cells per method with a NaN row. |
n_niches_kept | Squares kept. |
n_niches_dropped | Squares dropped for too little tissue. |
Also published to learned_features/: {sample}_virtues.json with these keys, and, unless
virtues_stats is given, {slide}_virtues_stats.json with the statistics computed, one per slide.
From 1.x¶
| 1.x | 2.0 |
|---|---|
tables/table | tables/{m}_table |
shapes/cellpose_boundaries, instanseg_boundaries | shapes/{m}_cells |
qc/{sample}_qc.json, _qc_report.html | qc/{sample}_{m}_qc.json, _qc_report.html |
qc/{sample}_qc_images/ | qc/{sample}_{m}_qc_images/ |
qc/{slide}_slide_report.html | qc/{slide}_{m}_slide_report.html |
obs_names renumbered by sopa | the cell ids of the shapes |
a cell covering no pixel centre: X 0 | NaN |
Removed parameters stop the run at startup: use_stardist and every StarDist option,
instanseg_target (use segment_cells, segment_nuclei), min_intensity_ratio,
technology and aggregate_channels. Cells crossing an image chunk edge were measured with a
shifted mask in 1.x, so their intensities change (CHANGELOG).
From 2.x¶
obs['area']isobs['cell_area'](nucleus_areain a nuclei-only run).Columns are per statistic:
adata[:, "CD3"]isadata[:, "CD3_mean"].Xand the layers are float32.
QC report¶
Output files
qc/{sample}_{method}_qc.jsonEvery QC metric as machine-readable JSON. This is the file an unattended run should read. Per-channel intensity statistics measured on every pixel of the full-resolution image, cell-area distribution and the count below a degenerate-cell threshold, channel-name agreement between the image, the table and the marker sheet, cells per segmentation patch, and — when background subtraction ran — the same channel statistics from before subtraction, so the two can be compared. That comparison is available on dearrayed slides too:
COREOGRAPHruns beforeBACKSUB, so every core is subtracted on its own and keeps an unsubtracted twin of matching shape. With both targets,linking: cells by number of nuclei (0, 1, 2+), unlinked nuclei and cells without cytoplasm. It sets no thresholds and returns no exit code: the numbers that would justify a threshold need more than one dataset behind them.
qc/{sample}_{method}_qc_report.htmlThe same metrics rendered for a person, plus the images. Self-contained: no external scripts, fonts or network access, so it can be copied anywhere and opened offline. Includes segmentation overlays at full resolution across the density range, a cross-cycle nuclear-stain comparison, Ashlar’s stitching and registration QC (not on TMA cores; it is on the slide report), a Leiden clustering tree over a resolution sweep, the cluster-by-marker profile, and representative cells per cluster. Every chart has a table view beneath it.
Stitching and registration QC
Not copied into
qc/: the report’s “Stitching and registration” section readspreprocessing/registration/{sample}_ashlar_qc/(above) and links to its PDF. It shows whether every tile pair aligned, whether the mosaic is one connected piece, how many tiles each cycle discarded and why, the residual misalignment per cycle, and the cycle overlays. See usage.md for what to change.
qc/{sample}_projection.pngandqc/{sample}_projection.jsonWith
use_projectiononly. The two channels Cellpose segmented, downsampled, nuclear in magenta and cell in green; and the markers in each, their rescaling bounds, the share of pixels in which each is the brightest (win_share), and the method.dominantlists any marker brightest in over half of a channel, which then decides that channel alone; the task log warns about it too. The projection is removed from the store unlesskeep_projection.
qc/{sample}_{method}_qc_images/The PNGs the report embeds, kept as files so they can be used on their own. Absent when
use_qc_images: false.
qc/{slide}_{method}_slide_report.htmlDearrayed slides only. One page for the whole slide, from the per-core metrics: cells per core against the slide total, the integrity checks rolled up so a check passes only when every core passes and the ones that failed are named, mean intensity per channel with one column per core, and the slide’s stitching and registration QC. The per-core intensity table is the comparison a single core’s report cannot make: its own page shows a channel against its own histogram, which says whether the channel has signal, not whether it has the same signal as the rest of the slide. Core detail that is only actionable on one core, the crops, the clusters, the per-channel histograms and the patch layout, stays in that core’s report rather than being repeated.
qc/{sample}_comparison.jsonandqc/{sample}_comparison.htmlWhen both methods segment cells. Cell counts, median areas (px²), the share of each method’s cells matched one-to-one at IoU ≥ 0.5, and both outlines on the same three crops across the density range. Keys are listed in
bin/compare_segmentations.py.
The QC report is produced per sample and method (cellpose, instanseg), which on a dearrayed
slide means per core and method. use_qc: false
skips it entirely; use_qc_images: false keeps the metrics and the charts but drops the
clustering and the image crops, which are the slow part. Tuning for the image step — the Leiden
resolution ladder, the arcsinh cofactor, how many crops — goes through ext.args for QC_IMAGES
in conf/modules.config rather than through pipeline parameters.
Upstream nf-core/sopa also produced a {sample}.explorer/ directory holding a Xenium Explorer
bundle and a standalone adata.h5ad. This pipeline does not export to Xenium Explorer. The
cell tables are inside {sample}.zarr under tables/, and can be pulled out with
spatialdata.read_zarr(...).tables.
Pipeline information¶
Output files
pipeline_info/From Nextflow:
execution_report_{ts}.html,execution_timeline_{ts}.html,execution_trace_{ts}.txtandpipeline_dag_{ts}.html.histo_software_versions.yml, every tool version, andparams_{ts}.json, the parameters used.pipeline_report.htmland.txt, only whenemailoremail_on_failis set.
Nextflow provides excellent functionality for generating various reports relevant to the running and execution of the pipeline. This will allow you to troubleshoot errors with the running of the pipeline, and also provide you with other information such as launch commands, run times and resource usage.