CosciaLab/histo: Usage¶
Quick start¶
nextflow run CosciaLab/histo -r v3.2.0 \
-profile singularity,size_small,slurm \
-params-file params.ymlGive a container engine, a size and, on the cluster, slurm (plus mdc at the MDC).
Parameters go in -params-file, never in -c. Custom config files can set anything except
parameters.
Inputs¶
Two files: a samplesheet and a marker sheet.
Samplesheet, one row per acquisition cycle:
sample,cycle_number,image_tiles,marker_sheet
mysample,1,/abs/path/cycle01.ome.tiff,/abs/path/markers_mysample.csv
mysample,2,/abs/path/cycle02.ome.tiff,/abs/path/markers_mysample.csv
othersample,1,/abs/path/other_cycle01.ome.tiff,/abs/path/markers_other.csvmarker_sheet is required and names the sheet for that sample. It repeats on every cycle row of a
sample and every copy must be the same file, because the sheet describes the whole stitched image
rather than one cycle of it. Two samples may name different sheets, which is the reason this is a
column rather than a parameter: one run can carry samples with different channel layouts.
Optional dfp and ffp columns supply pre-computed illumination profiles. If you give them for one
cycle you must give them for all; otherwise BaSiCPy computes them.
Marker sheet, one row per channel, channel_number running 1..N without gaps:
channel_number,cycle_number,marker_name,channel_role,channel_compartment,filter
1,1,DNA_1,dna,nuclear,DAPI
2,1,CD45,marker,membrane,FITCchannel_role is required and states what the pipeline should do with the channel:
| Role | Meaning |
|---|---|
dna | A nuclear stain. Every cycle needs at least one: registration, segmentation and the cross-cycle photobleaching check all read it. |
marker | A biological readout. |
autofluorescence | Acquired in order to be subtracted rather than interpreted. This is what background must point at. |
blank | Expected to be dark. QC checks that it is, rather than reporting it as a result. |
Giving the role explicitly is what stops the pipeline guessing which channel is a nuclear stain by matching its name, which works until someone stains with Hoechst.
channel_compartment is optional and states where the signal belongs: nuclear, cytoplasm,
membrane, or a +-joined combination such as nuclear+cytoplasm. Order is not significant. QC
can only judge whether a marker landed where it should if the sheet says where that is, so leaving
it blank costs a check rather than breaking a run.
segmentation is optional and only read with --use_projection. It sets which projected
channel a marker feeds: nuclear, cell or none. Without the column, the first dna channel is
nuclear, and every marker whose channel_compartment includes membrane or cytoplasm is
cell. Setting it on any row makes the column the whole selection, and blank rows are left out.
--use_backsub additionally needs exposure and background columns. background names the
marker_name of the channel to subtract, and that channel must itself have channel_role set to
autofluorescence. The two columns describe one fact, so they are checked against each other.
remove set to true drops a channel after backsub; without --use_backsub it is ignored with a
warning. Keep at least one dna channel, and do not name a removed channel in cellpose_channels
or instanseg_channels; both are rejected at startup.
Ashlar registers every cycle on the same within-cycle channel (-c in ashlar_args, default
0), and Coreograph dearrays on one channel of the stitched image: the marker sheet’s first dna
channel, or --channel in coreograph_args. Both indices may be -1 for the last channel. The
run stops at startup when either index lands on a channel that is not dna; set
skip_reference_dna_check: true to run anyway.
TMA dearray¶
Coreograph finds cores reliably only at the right --downsampleFactor, and a wrong one fails
silently: cores split along tissue bands, or neighbours merge. So the pipeline asks how many
cores to expect (tma_expected_cores, a count, not rows × columns) and how large
(tma_core_diameter_mm). It detects cores at factors 3 to 7, keeps the one whose cores best
match, and dearrays once with it. Both values apply to every slide in the run, so run arrays
with different layouts separately. Check preprocessing/dearray/sweep/{slide}_sweep_overlays.png;
the log warns when even the best factor is off by more than 10 % in count or 25 % in diameter.
To run Coreograph exactly as you say instead, set coreograph_args, for example
'--downsampleFactor 4 --channel 0 --buffer 2'. The sweep is then skipped.
When stitching or registration looks wrong¶
Open the “Stitching and registration” section of the QC report (the slide report on a TMA),
then preprocessing/registration/{sample}_ashlar_qc/ for detail. What the section shows, and
what to try in ashlar_args:
| Symptom in the report | Likely cause | Try |
|---|---|---|
| Rejected pairs or several components inside tissue | Stage error larger than --maximum-shift, or a weak alignment channel | Raise --maximum-shift; check -c is a bright nuclear stain |
| Pair errors overlap the random-strip errors | Alignment channel has little structure | A different -c; --filter-sigma 1 for noisy images |
| One cycle with many tiles too far from the model | Tissue moved or deformed in that cycle | Raise --maximum-shift; inspect that cycle’s overlay |
| Kept tiles no better than chance | Registration locked onto noise in background tiles | Usually harmless at the tissue edge; check the overlay |
| Overlay shows doubled nuclei everywhere in one cycle | Coarse cycle offset or rotation failed | Check that cycle’s dashed outline in the Ashlar PDF |
Paths must be absolute.
Parameters¶
Required: input, outdir and, unless preprocessing_only, at least one segmentation method.
Cellpose also needs cellpose_channels or use_projection; InstanSeg needs
pixel_size. Everything else has a default. Parameters removed in 2.0 stop the run at
startup; see output.md.
Booleans on the command line follow Nextflow’s rule: a bare flag means true, and anything else
means use the default. --use_backsub switches it on. To switch something off, leave it out, or
use a params file where use_backsub: false is a real boolean. Writing a value after the flag does
not work and never did: Nextflow reads the flag on its own, sets it true, and throws the value away
before the pipeline sees it, so --use_backsub false would perform background subtraction. The
pipeline stops at startup rather than letting that happen, for every boolean it declares.
| Parameter | Default | Change it when |
|---|---|---|
use_preprocessing | true | Your image is already stitched. Then the samplesheet is one row per sample with a data_path column. |
preprocessing_only | false | You only want stitched images. No segmentation, quantification or sample QC; Ashlar’s QC stays. |
ashlar_args | --maximum-shift 30 | Stitching misaligns. |
use_backsub | false | You have background channels to subtract. |
skip_reference_dna_check | false | Ashlar or Coreograph should deliberately use a channel that is not dna. |
use_tma_dearray | false | Your slide is a tissue microarray. Each core is then processed alone and the results merged per slide. |
tma_expected_cores | none | With use_tma_dearray: how many cores the slide has. See TMA dearray. |
tma_core_diameter_mm | none | With use_tma_dearray: the core diameter in mm. |
pixel_size | none | You use use_instanseg, use_nimbus or use_virtues: µm per pixel of your image (OME PhysicalSizeX). |
use_cellpose | false | At least one of use_cellpose and use_instanseg; both may be on. |
cellpose_channels | none | Always, unless use_projection. Marker names, nuclear last, e.g. "CD45 DNA_1". |
use_projection | false | Cellpose should see many markers, not one. See below. |
use_instanseg | false | You want InstanSeg. Needs pixel_size; channels default from each sheet. |
segment_cells | true | You want nuclei only. See Methods and targets. |
segment_nuclei | false | You want nuclei, linked to their cells. |
use_nimbus | false | You want a per-cell marker positivity score. Needs pixel_size and segment_cells. See Nimbus. |
use_virtues | false | You want 512-number embeddings per cell, tissue square and core. See VirTues. |
use_gpu | false | On the cluster: one GPU per segmentation patch. See GPU segmentation. |
patch_width_pixel | 2000 | Your slide is larger than a few TMA cores. See below. |
patch_overlap_pixel | 100 | Set to roughly twice a cell diameter. |
use_tissue_segmentation | false | Large empty areas you want skipped. |
Every parameter and its default is in two generated files.
assetsparams.yml and uncomment what you change.
assetsnull in
either means off or unset. --help prints the same list.
Methods and targets¶
Each enabled method (use_cellpose, use_instanseg) segments each enabled target
(segment_cells, segment_nuclei), and each method gets its own table, {method}_table.
With both targets, each nucleus is linked to the cell holding at least half of it, the cytoplasm
is the cell minus its nuclei, and the table gains nucleus and cytoplasm layers. With both
methods segmenting cells and use_qc, qc/{sample}_comparison.html compares them. The layout is in
output.md.
Cellpose segments nuclei on the last of cellpose_channels (with use_projection, the
nuclear channel). InstanSeg segments nuclei on dna channels only, unless
instanseg_channels is set. Each method × target is one more pass over every patch, so two
methods with two targets cost four segmentations.
Choosing patch_width_pixel¶
This decides whether segmentation parallelises, and it is not automatic. The default, 2000 px
with 100 px overlap, suits TMA cores and small slides; set it for anything larger. Aim for
16 to 200 patches: patch_width_pixel = sqrt(width * height / target_patches).
| Stitched image | 2000 | 5000 | 8000 | 10000 |
|---|---|---|---|---|
| 3k × 3k | 4 | 1 | 1 | 1 |
| 25k × 25k | 169 | 25 | 16 | 9 |
| 50k × 50k | 625 | 100 | 49 | 25 |
| 115k × 115k | 3364 | 529 | 225 | 144 |
One patch means no parallelism at all. Thousands means the scheduler costs more than the work.
InstanSeg’s memory follows the patch: each task asks for 2 GB + megapixels × max(1.3, 0.3 ×
channels), megapixels counted at its model’s 0.5 µm/px. At the default 2000 px and 0.65 µm/px that
is 13 GB for 5 channels and 78 GB for 37; fewer instanseg_channels or a smaller patch ask for less.
Above 64 GB the run warns and names a patch_width_pixel that fits.
Get the dimensions with
python -c "import tifffile; print(tifffile.TiffFile('stitched.ome.tif').series[0].shape)".
Two-channel segmentation (use_projection)¶
Cellpose takes a nuclear and a cell channel, but an mIF panel spreads cell boundaries over many
markers, each on some cell types only. --use_projection builds the two channels from the marker
sheet (see segmentation above) and segments those; quantification still reads every marker.
Each marker is rescaled between its 1st and 99.9th percentile (zero padding ignored), then
combined per channel by maximum. Maximum keeps a marker found on one cell type at full
brightness; projection_method: mean dims it and loses those cells. On hazy raw images,
projection_low_percentile: 50 removes the haze from the cell channel.
The Cellpose defaults suit projection. flow_threshold: 0.6, cellprob_threshold: -1, no
CLAHE and no smoothing come from a
benchmark
against manual outlines. sopa’s own values (2, -6, CLAHE 0.2) tile the whole tissue into cells
whatever the image shows. The default cell channel already leaves out autofluorescence and
nuclear markers, which the benchmark favoured; keep them out when you set the segmentation
column.
use_cellpose: true
use_projection: trueCheck qc/{sample}_projection.png first when cells look wrong: it is what Cellpose saw, nuclear in
magenta and cell in green. In the JSON, a marker under dominant swamps the others: one diffuse,
bright cytoplasm marker can make Cellpose miss whole groups of cells. Leave it out with the
segmentation column. keep_projection: true also keeps it at full resolution in the store,
as <image>_projected, to view with the cell boundaries. How the defaults were chosen is in
decisions.md.
Profiles¶
Size — pick by stitched image size. Only size_tiny is derived from measurement; the rest are
estimates and will change.
| Profile | For |
|---|---|
size_tiny | under ~1 GB, test data |
size_small | up to ~50 GB |
size_medium | ~50–200 GB |
size_huge | ~200 GB and up |
Executor — slurm, or omit for local execution. Without it every task runs on the machine you
launched from.
MDC — add mdc after slurm to request nodes with Ceph storage (--constraint=ceph).
Containers — singularity on the cluster. Images must be pre-staged; see
Fetching images.
Example¶
input: /abs/path/samplesheet.csv
outdir: /abs/path/results
use_preprocessing: true
use_cellpose: true
cellpose_channels: "DNA_1"
patch_width_pixel: 1500
patch_overlap_pixel: 50Running on the cluster¶
Stage the images first, once per release: see Fetching images below.
Launch from a directory that is not the pipeline clone, so run artifacts do not land in the
source tree. Nextflow submits the SLURM jobs itself; you never write an sbatch script. Run it inside
tmux so it outlives your session.
mkdir -p ~/runs/myrun && cd ~/runs/myrun
# Keep temporary files off the shared /tmp, which is small and communal. Without
# this a run dies with "No space left on device" on a path under /tmp, which looks
# like a disk-quota problem and is not one.
export TMPDIR=/fast/AG_Coscia/$USER/tmp
export NXF_TEMP="$TMPDIR"
export NXF_OPTS="-Djava.io.tmpdir=$TMPDIR"
mkdir -p "$TMPDIR"
# Stops a launch-time fetch of a config this pipeline does not use.
export NXF_OFFLINE=true
nextflow run /path/to/histo -profile singularity,size_small,slurm -params-file params.yml -resumeAll three temp variables are needed for different consumers: TMPDIR for tools inside
containers, NXF_TEMP for Nextflow’s own scratch, and java.io.tmpdir for the JVM,
which is the one that fails first and least helpfully.
-resume and the store¶
Tasks that write a sample’s store in place (e.g. WRITE_SEGMENTATIONS) are cached like any
other. After a later run has changed the store, -resume back to earlier parameters reuses those
tasks and does not restore the earlier store; nor does a Cellpose patch task find the projection
a later run deleted (“projection removed by an earlier run”). Rerun those samples without
-resume.
GPU segmentation¶
use_gpu: true gives each Cellpose and InstanSeg patch task, and each Nimbus and VirTues task, one GPU.
With -profile …,slurm,mdc that is an A40 (--gres=gpu:a40:1): every A40 node has Ceph, and the
sopa image cannot run on the V100s. At most 16 patches per method run at once. Cellpose tasks get
1 CPU and 8 GB on size_tiny and size_small, else 2 CPUs and 16 GB; InstanSeg tasks keep their
CPU sizing. A task fails if CUDA is not usable in it, rather than running on CPU. Not on the Mac:
Docker there has no GPU.
InstanSeg on GPU takes at most 10 channels, until its GPU memory is measured
(ROADMAP). A run with more, named in instanseg_channels or taken from a marker
sheet, stops at startup: name 10 or fewer, or leave use_gpu off.
Validate before submitting — this catches bad paths and parameter types in seconds rather than after a queue wait:
nextflow run /path/to/histo -profile laptop -stub -params-file params.ymlNimbus¶
use_nimbus: true scores every marker in every cell, per segmentation method. Output is in
output.md.
pixel_sizeis required, in µm per pixel. Nimbus rescales the image with it.segment_cellsis required: Nimbus was trained on whole cells.Markers come from the marker sheet (
markerrole).nimbus_channelsoverrides them, and is required for a stitched image with no sheet.Use
use_gpu. CPU gives near-identical scores but a whole slide can take days, so it only warns.Test-time augmentation is always on, with the same setting on CPU and GPU. It costs several forward passes per window. On exemplar-002, CPU and GPU scores differed by 5e-4 on average and 0.11 at most, with the same share of positive cells per marker. Cellpose ran on CPU too, so part of that is from slightly different cell outlines. NIMBUS took ~12 min per core on CPU against ~1 min on an A40.
Tiling can shift scores: at 0.65 µm/px a tiled run differed from a whole-image run by up to 0.41 (mean 0.011) on a test crop. See decisions.
Each channel is divided by its 0.999 quantile within one store: per core on a TMA, per image otherwise. This keeps differences between patients’ cores. In a core with no positive cells, noise is stretched to [0, 1] and can score as signal.
NIMBUS has its own cap of 16 tasks at once, separate from the segmentation patches.
VirTues¶
use_virtues: true embeds every cell, every 128 µm tissue square and each core or slide, per
segmentation method. Output is in
output.md.
Required, or the run stops at startup:
use_gpu,use_preprocessing,use_tissue_segmentation,segment_cellsandpixel_size. Withuse_gpu, segmentation runs on the GPU too.Add a
uniprot_idcolumn to the marker sheet. A channel is embedded if and only if its row has one, e.g.P08246; an isoform takes a suffix (P08575-8). IDs must be unique and the format is checked. An ID missing from the bundled human Swiss-Prot sequences fails the task, naming it.tests/stub_data/markers_virtues.csvis an example.DNA stains are not embedded: a
dnarow with an ID stops the run.Intensities are scaled with statistics per slide over tissue pixels, written to
learned_features/{slide}_virtues_stats.json.virtues_stats(advanced) takes one such file and applies it to every slide, e.g. to freeze a rerun or scale a cohort alike; no statistics file is then written. It must cover every embedded marker with the sameuniprot_id, and is an error withoutuse_virtues.“standard deviation is zero (constant marker)” stops the run when at least 99% of a marker’s tissue pixels are 0, so its 0.99 cap is 0. Usually backsub removed the signal: check that marker’s
exposureandbackground. Otherwise leave itsuniprot_idempty.One
VIRTUEStask per store, one GPU. FlashAttention 2 needs an Ampere or newer GPU:mdcasks for an A40; elsewhere, request one in your config. On a V100 the task fails in the model.Memory does not grow with image area; per-cell results take about 2 GB per million cells per method. An exemplar-002 core (22 markers, A40): about 1 min, 3.5 GB peak.
A core where tissue segmentation found no tissue still gets its cells embedded, with a warning; a slide with no tissue at all stops with a message naming it.
The weights (
sp32) are CC BY-NC 4.0.
Fetching images¶
On a well-connected Linux machine:
nf-core pipelines download CosciaLab/histo \
-r <tag> \
--container-system singularity \
--outdir ~/histo-downloadDo this once per release. It resolves every image the pipeline declares and writes the SIFs alongside the pipeline code.
Cross-check what it fetched against the manifest. They should agree, and if they do not, the manifest generator has a parsing bug rather than the download being wrong:
nextflow inspect . -profile singularity | grep -o '"container": "[^"]*"' | sort -uStaging images into the shared cache¶
Each user sets NXF_SINGULARITY_CACHEDIR in their own environment (e.g. ~/.bashrc); the pipeline
sets no default. At a site it is usually a shared filesystem path that colleagues also use.
Check first, copy second:
# what is already there
ls "$NXF_SINGULARITY_CACHEDIR"
# copy in only new files, never overwriting an existing one
rsync -av --ignore-existing ~/histo-download/singularity-images/ "$NXF_SINGULARITY_CACHEDIR/"Our own images (docker.io/josenimo/sopa:2.3.0-1, docker.io/josenimo/nimbus:0.0.5,
docker.io/josenimo/virtues:d2c25e1-2) are staged the same way. The Nimbus image is needed for
use_nimbus and the VirTues image for use_virtues; each has its weights inside.
To build one SIF yourself, from a registry or a docker save tar, submit
tools/build_sif.sbatch after sourcing the histo setup.sh. It builds straight into
$NXF_SINGULARITY_CACHEDIR under the name Nextflow looks for, renames the file only once it is
verified, and refuses to replace an image already there. The log goes to the cache’s logs/
(--help for options, including building elsewhere):
sbatch tools/build_sif.sbatch docker.io/josenimo/nimbus:0.0.5--ignore-existing rather than plain rsync is deliberate: an image already in the cache is one a
colleague may have a job attached to right now, and replacing it mid-run is how you break someone
else’s week.