GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - swarbricklab/mkobj: Snakemake workflow to create merged Seurat objects from Cell Ranger output

BranchesTags
Open more actions menu

Latest commit

 

History

126 Commits
126 Commits

Folders and files

NameName
Last commit message
Last commit date
.dvc
.dvc
 
 
config
config
 
 
docs
docs
 
 
env
env
 
 
profiles
profiles
 
 
resources/lineage_classifier
resources/lineage_classifier
 
 
test
test
 
 
tools
tools
 
 
workflow
workflow
 
 
.dvcignore
.dvcignore
 
 
.gitignore
.gitignore
 
 
.gitmodules
.gitmodules
 
 
README.md
README.md
 
 
run_mod.sh
run_mod.sh
 
 
run_test.sh
run_test.sh
 
 

Repository files navigation

mkobj

Create merged Seurat and AnnData objects from Cell Ranger filtered feature barcode matrices.

Overview

This workflow processes 10X Chromium single-cell data from Cell Ranger output and creates both:

  • Seurat objects (.qs) via the R/Bioconductor ecosystem
  • AnnData objects (.h5ad) via the Python/Scanpy ecosystem

It supports:

  • Unimodal data: Gene expression only
  • Multimodal data: Gene expression + Antibody Capture (CITE-seq)

The workflow can optionally attach:

  • Sample assignments from SNP-based demultiplexing
  • Cell type annotations
  • Ambient RNA profiles
  • Sample-level subsetting (keep only cells from a specified cohort)

Modes

This workflow can be run in either standalone mode or module mode.

Standalone mode

In "standalone" mode, the data is included in the same repo as the workflow. This mode is used mainly for testing.

./run_test.sh

Module mode

This workflow can be embedded into a dataset as a git submodule.

To use in module mode:

  1. Add this workflow as a submodule to your dataset
  2. Copy and configure the config file
  3. Run the workflow using run_mod.sh
# From the dataset root
git submodule add <repo-url> modules/mkobj
mkdir -p config/mkobj
cp modules/mkobj/config/template.yaml config/mkobj/config.yaml
# Edit config.yaml for your dataset
./modules/mkobj/run_mod.sh

Cluster profiles

mkobj has two NCI cluster profiles:

Profile Snakemake Submission / status check Used by
profiles/global/nci (recommended) 7.32.4 pbs_submit.py / pbs_status.sh (qstat -x) dataset wrappers, e.g. the brca_mega_atlas raw deposit
profiles/cluster >= 8.0 qxub exec / qxtat check run_mod.sh

profiles/global is the lab-wide snakemake_config profile. It's pinned here as a nested submodule, as in the other workflow modules, and is populated by git submodule update --init --recursive. Its status check asks PBS directly, so it doesn't depend on the shared qxub sqlite database. That database has repeatedly corrupted on gdata, and when it does, profiles/cluster runs abort with Failed to obtain job status.

To use the global profile, layer a workflow profile with the per-rule resources on top of it:

# From the dataset root
conda activate snakemake_7.32.4
module load singularity
snakemake \
    --profile modules/mkobj/profiles/global/nci \
    --workflow-profile config/mkobj/profiles/<name> \
    --snakefile modules/mkobj/workflow/Snakefile \
    --configfile config/mkobj/config.yaml

The workflow profile needs the following:

  • threads under set-resources for every rule, not just under set-threads. pbs_submit.py takes -l ncpus from resources.threads, which defaults to 1.
  • use-conda: True. Snakemake 7 rejects the global profile's conda-prefix without it.
  • Optionally, singularity-prefix: /g/data/a56/conda/snakecache/apptainer, to reuse the container images that profiles/cluster already pulled. Snakemake 7 and 8 use the same md5(url).simg names, so nothing is pulled again.

The global profile picks the queue from mem_mb (normal below about 192 GB, otherwise hugemem) and writes PBS job logs to logs/joblogs/<rule>/.

Workflow Structure

The workflow is organized into parallel Seurat and AnnData pipelines that run concurrently:

Cell Ranger matrices
        │
        ├──► create_seurat_object (per capture) ──► merge_captures ──► merged.qs
        │
        └──► create_anndata_object (per capture) ──► merge_anndata_captures ──► merged.h5ad

Seurat Pipeline (R)

  1. create_seurat_object: Create individual Seurat objects per capture

    • Reads Cell Ranger filtered matrices (barcodes.tsv.gz, features.tsv.gz, matrix.mtx.gz)
    • Handles multimodal data (GEX + AB stored as a separate assay)
    • Attaches sample assignments, annotations, and ambient profiles to cell metadata
    • Optionally subsets cells to a specified cohort via samples.csv
    • Prefixes barcodes with capture ID for uniqueness across captures
  2. merge_captures: Merge all per-capture objects into one

    • Combines all captures using Seurat's merge() function
    • Joins layers for proper integration
    • Output: merged.qs

AnnData Pipeline (Python)

  1. create_anndata_object: Create individual AnnData objects per capture

    • Reads Cell Ranger filtered matrices (barcodes.tsv.gz, features.tsv.gz, matrix.mtx.gz)
    • Handles multimodal data — gene expression in X, antibody capture in obsm['AB'] with feature names in uns['AB_features']
    • Attaches sample assignments, annotations, and ambient profiles to obs
    • Keeps every called cell in the capture (no cohort subsetting), so doublet detection sees passenger cells too
    • Prefixes barcodes with capture ID for uniqueness across captures
    • Converts string columns with NA values to proper string type for h5ad compatibility
  2. detect_doublets (and the other annotation-stage rules): Scrublet (+ optional cross-lineage markers) per capture, on all called cells read straight from the Cell Ranger matrix. Calls are persisted in doublets/<capture_id>.csv

  3. merge_anndata_captures: Merge all per-capture objects into one

    • Restores the Scrublet obs columns (doublet_score, predicted_doublet, predicted_scrublet, predicted_cross_lineage_doublet, …) from doublets/<capture_id>.csv
    • Attaches per-cell annotations as obs columns, joined on (capture, barcode) and only when their source exists (params.attach): lineage_* from lineages/, doublet_score_<engine> / doublet_call_<engine> / known_doublet from doublets/, and somatic_evaluable / somatic_burden_matched / somatic_malignant / somatic_p_tumour from deps.somatifind_calls. Join coverage is logged per capture
    • Subsets each capture to the cohort via samples.csv (keeps cohort singlets, demux doublets, and unassigned cells) — after doublet detection
    • Combines all captures using anndata.concat() with join='outer'
    • Preserves multimodal data in obsm across captures
    • Output: merged.h5ad

Re-running with additional captures

Adding a capture is not an incremental operation. The per-capture objects are temp() — create_seurat_object (per_capture/{capture}.rds), and create_anndata_object (per_capture_raw/{capture}.h5ad) — so they are deleted once a merge succeeds. On the next run they are missing, and every merge that consumes them has to rebuild them.

Per-capture objects are shared across subsets, so the rebuild is not confined to the subset you edited. Adding one capture to subset A also regenerates the captures A shares with B, which in turn makes B's merged object out of date:

subset A: X, Y     add W to A only     rebuilds X, Y, W  and  Y, Z
subset B: Y, Z          ────────►      re-merges BOTH A and B

Snakemake reports the two cases differently — Set of input files has changed since last execution for the subset you actually edited, and Input files updated by another job for the ones dragged in with it. Expect work proportional to the union of every subset that shares a capture with the one you changed, which in a well-connected dataset is most of it.

Always check the size of the job before committing to it:

./modules/mkobj/run_mod.sh -n     # per-rule job counts

Keeping the per-capture objects

If a dataset grows by a few captures at a time, the rebuild is usually worse than the disk it saves. Snakemake's --notemp ignores the temp() declarations and leaves the per-capture objects in place:

./modules/mkobj/run_mod.sh --notemp

Every later addition is then genuinely incremental: only the new capture is built, and only the subsets whose capture list actually changed are re-merged — the cascade above does not happen, because the shared captures are still on disk and unchanged.

The cost is one full set of per-capture objects. Measured on a 148-capture dataset: roughly 12 GB of per_capture/ plus 35 GB of per_capture_raw/. Weigh that against recomputing three rules per capture across every connected subset.

temp() is the better default for a one-shot build, where those files are pure waste. It is the wrong default for a dataset you keep adding to.

Under DVC

Datasets embedding mkobj as a submodule usually wrap it in a DVC stage. DVC removes a stage's outputs before re-running it, so with no further configuration the merged objects for every subset are deleted first — nothing can be skipped even in principle, and a failed run leaves neither the new results nor the old ones.

persist: true on the stage outputs prevents that deletion:

outs:
  - data/objects:
      persist: true

But check your cache.type first. persist does not simply skip the removal — in Stage.remove_outs() it substitutes unprotect for remove, and unprotecting a symlinked or hardlinked file means byte-copying it back into the workspace. With cache.type = hardlink,symlink the pre-run step becomes a full copy of every file in the stage's outputs, and it is charged before any compute starts. On a stage with multi-terabyte outputs this can cost far more than the rebuild it was meant to avoid, and it duplicates data the links existed to share.

With the default cache.type=copy there is no link to break, so persist is cheap and the above does not apply.

Where the unprotect pass is too expensive, run the workflow directly and register the result afterwards:

./modules/mkobj/run_mod.sh --notemp     # snakemake decides what to skip
dvc commit <stage>                      # record the outputs DVC did not produce

This keeps the incremental behaviour at the cost of the stage no longer being reproducible purely through dvc repro — a deliberate trade, worth a note in the dataset repo when you make it.

Two-stage use under DVC (annotate → assemble)

Lineage labels and doublet calls from mkobj feed other modules (somatifind de novo discovery and validation, ambient_calibration), whose outputs mkobj then attaches to the merged objects. One DVC stage can't do both without a cycle, so run mkobj as two stages:

  1. annotate: snakemake annotate builds only the per-capture CSVs (lineages/, doublets/, including doublets/known/, doublets/report/, doublets/scdblfinder_params/). No objects are merged.
  2. assemble: snakemake all (the default target) builds the merged objects and attaches the downstream outputs. It reuses the persisted CSVs. The annotation-stage rules read only source inputs (Cell Ranger matrices, demux files, the lineage model) and never the temp per-capture objects, so rebuilding per_capture_raw/ for the merge does not rerun them.
# dataset dvc.yaml (paths illustrative)
stages:
  mkobj_annotate:
    cmd: ./modules/mkobj/run_mod.sh annotate
    deps:
      - modules/mkobj/workflow
      - config/mkobj/config.yaml
      - data/counts
      - data/demux
      - resources/lineage_classifier/wu2021-v1
    outs:
      - data/objects/lineages
      - data/objects/doublets

  somatifind:
    cmd: ./modules/somatifind/run_mod.sh
    deps:
      - data/objects/lineages
      - data/objects/doublets
    outs:
      - data/somatifind

  mkobj_assemble:
    cmd: ./modules/mkobj/run_mod.sh all
    deps:
      - modules/mkobj/workflow
      - config/mkobj/config.yaml
      - data/counts
      - data/objects/lineages
      - data/objects/doublets
      - data/somatifind
    outs:
      - data/objects/merged.h5ad   # plus processed.h5ad, cellxgene.h5ad, ...

The annotation rules mark their directory inputs (Cell Ranger matrices, the demux root) ancient(). dvc pull/checkout gives every file a fresh mtime, and Snakemake never checksums directories, so otherwise the assemble stage would recompute (and overwrite) the annotate stage's outputs. When the source data really change, DVC re-runs the annotate stage and removes its outputs first. In single-stage use, delete the affected lineages/ and doublets/ outputs (or use -R annotate_lineages detect_doublets ...) after changing Cell Ranger or demux inputs.

all still builds everything from scratch when nothing exists yet, so single-stage use is unchanged. Before running the assemble stage, run_mod.sh all -n should list no annotate_lineages, detect_doublets*, extract_known_doublets, combine_doublet_calls or doublet_concordance* jobs.

Configuration

See the configuration guide for detailed instructions.

Quick start:

deps:
  cellranger: "data/counts"
  captures: "config/mkobj/captures.csv"
  demux: "data/demux"

outs:
  results: "data/objects"
  logs: "logs/mkobj"

Outputs

File Description
merged.qs Merged Seurat object (R, serialized with qs)
merged.h5ad Merged AnnData object (Python, HDF5-backed)
lineages/<capture_id>.csv Per-capture lineage labels for every called cell (doublets included), when params.lineages.enabled: capture_id, barcode, lineage_major, lineage_fine, confidence_major, confidence_fine, label_source.
doublets/known/<capture_id>.csv Genotype-detected doublets per barcode (known_doublet, demux_status, known_source), when deps.demux is set.
doublets/report/concordance_<capture_id>.csv, concordance_cohort.csv With params.doublets.report: per engine, recall on genotype doublets (overall / cross-lineage / same-lineage), calls among genotype singlets vs n_singlets × d_within, and agreement between engines.
doublets/scdblfinder_params/<capture_id>.csv Per-capture scDblFinder parameters actually used (dbr_used, dbr_sd_used, dbr_source_used, fallback reason). Only with the scdblfinder engine.
doublets/<capture_id>.csv Per-capture doublet calls, persisted (not temp). Long format, one row per called barcode per engine: capture_id, barcode, engine, doublet_score, doublet_call (+ cross_lineage_flag when lineage markers are configured, known_doublet when deps.demux is set). barcode is the raw Cell Ranger barcode, without the capture prefix. Not written when skip_scrublet/raw_only is set.

Both outputs contain identical data — the same cells, metadata, and (where applicable) multimodal assays — in their respective ecosystem formats.

Requirements

  • Snakemake: 7.32.4 with profiles/global, or >= 8.0 with profiles/cluster
  • For profiles/cluster only:
    • snakemake-executor-plugin-cluster-generic
    • qxub (PBS submission)
  • Conda
  • Apptainer/Singularity (for containerized environments)

Rule-level conda environments are defined in workflow/envs/ and installed automatically:

Environment Key packages
seurat.yaml R, Seurat 5.1, SeuratObject, qs, tidyverse
scanpy.yaml Python >= 3.10, scanpy >= 1.10, anndata >= 0.10, pandas, numpy, scipy

Authors

Originally developed as part of the Swarbrick Lab data processing pipelines.

About

Snakemake workflow to create merged Seurat objects from Cell Ranger output

Resources

Readme
Activity
Custom properties

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.