Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

CosciaLab/histo: Usage

Quick start

nextflow run CosciaLab/histo -r v3.2.0 \
    -profile singularity,size_small,slurm \
    -params-file params.yml

Give 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.csv

marker_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,FITC

channel_role is required and states what the pipeline should do with the channel:

RoleMeaning
dnaA nuclear stain. Every cycle needs at least one: registration, segmentation and the cross-cycle photobleaching check all read it.
markerA biological readout.
autofluorescenceAcquired in order to be subtracted rather than interpreted. This is what background must point at.
blankExpected 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 reportLikely causeTry
Rejected pairs or several components inside tissueStage error larger than --maximum-shift, or a weak alignment channelRaise --maximum-shift; check -c is a bright nuclear stain
Pair errors overlap the random-strip errorsAlignment channel has little structureA different -c; --filter-sigma 1 for noisy images
One cycle with many tiles too far from the modelTissue moved or deformed in that cycleRaise --maximum-shift; inspect that cycle’s overlay
Kept tiles no better than chanceRegistration locked onto noise in background tilesUsually harmless at the tissue edge; check the overlay
Overlay shows doubled nuclei everywhere in one cycleCoarse cycle offset or rotation failedCheck 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.

ParameterDefaultChange it when
use_preprocessingtrueYour image is already stitched. Then the samplesheet is one row per sample with a data_path column.
preprocessing_onlyfalseYou only want stitched images. No segmentation, quantification or sample QC; Ashlar’s QC stays.
ashlar_args--maximum-shift 30Stitching misaligns.
use_backsubfalseYou have background channels to subtract.
skip_reference_dna_checkfalseAshlar or Coreograph should deliberately use a channel that is not dna.
use_tma_dearrayfalseYour slide is a tissue microarray. Each core is then processed alone and the results merged per slide.
tma_expected_coresnoneWith use_tma_dearray: how many cores the slide has. See TMA dearray.
tma_core_diameter_mmnoneWith use_tma_dearray: the core diameter in mm.
pixel_sizenoneYou use use_instanseg, use_nimbus or use_virtues: µm per pixel of your image (OME PhysicalSizeX).
use_cellposefalseAt least one of use_cellpose and use_instanseg; both may be on.
cellpose_channelsnoneAlways, unless use_projection. Marker names, nuclear last, e.g. "CD45 DNA_1".
use_projectionfalseCellpose should see many markers, not one. See below.
use_instansegfalseYou want InstanSeg. Needs pixel_size; channels default from each sheet.
segment_cellstrueYou want nuclei only. See Methods and targets.
segment_nucleifalseYou want nuclei, linked to their cells.
use_nimbusfalseYou want a per-cell marker positivity score. Needs pixel_size and segment_cells. See Nimbus.
use_virtuesfalseYou want 512-number embeddings per cell, tissue square and core. See VirTues.
use_gpufalseOn the cluster: one GPU per segmentation patch. See GPU segmentation.
patch_width_pixel2000Your slide is larger than a few TMA cores. See below.
patch_overlap_pixel100Set to roughly twice a cell diameter.
use_tissue_segmentationfalseLarge empty areas you want skipped.

Every parameter and its default is in two generated files. assets/params_template_compact.yml has one line each: copy it to params.yml and uncomment what you change. assets/params_template.yml has the full descriptions. null 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 image20005000800010000
3k × 3k4111
25k × 25k16925169
50k × 50k6251004925
115k × 115k3364529225144

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

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

ProfileFor
size_tinyunder ~1 GB, test data
size_smallup 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: 50

Running 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 -resume

All 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.yml

Nimbus

use_nimbus: true scores every marker in every cell, per segmentation method. Output is in output.md.

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.

Fetching images

On a well-connected Linux machine:

nf-core pipelines download CosciaLab/histo \
    -r <tag> \
    --container-system singularity \
    --outdir ~/histo-download

Do 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 -u

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