Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue 81, "call empty droplets" #301

Merged
merged 34 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
6d81894
minimum inclusion for module
Jan 31, 2024
afe4904
update input_type labels
Feb 1, 2024
d03d81f
fixed workflow conversions to work with star align results
Feb 2, 2024
796afba
include modifications for working with cellranger
Feb 5, 2024
c9c38ea
fix the path of matrices when running non-standard kallisto workflow …
Feb 7, 2024
a9ee3f1
fix spliced/unspliced empty_drops conversion
Feb 7, 2024
0cb2a2f
solve number of list levels when having spliced / unspliced
Feb 7, 2024
8a2e818
Merge branch 'dev' of https://github.com/nf-core/scrnaseq into 81-cal…
Feb 14, 2024
6458e2d
update shared nf-test config
Feb 14, 2024
c5cc1ca
update alevin file names
Feb 14, 2024
c539399
update alevin tests to also include the .rds files
fmalmeida Feb 14, 2024
2d7c90e
update the number of tasks that are executed, and include raw/filtere…
fmalmeida Feb 14, 2024
c72c8f2
fix naming of generated files (kallisto)
fmalmeida Feb 14, 2024
5d1d783
update the amount of tasks and generated file names raw/filtered (star)
fmalmeida Feb 14, 2024
4095c3d
update gitignore
fmalmeida Feb 14, 2024
6981c44
add new params to schema
fmalmeida Feb 15, 2024
030322a
Merge branch 'dev' into 81-call-empty-droplets
grst Mar 7, 2024
e350399
Update bin/emptydrops_cell_calling.R
fmalmeida Mar 8, 2024
7daa310
fixing stub snippet
Mar 11, 2024
c24a05d
fix transposition snippet in new module
Mar 11, 2024
618c721
Merge branch 'dev' of https://github.com/nf-core/scrnaseq into 81-cal…
Mar 11, 2024
492598b
fixed problem on loading fasta&gtf from params.genome
Mar 12, 2024
6207655
fixed transposition
Mar 12, 2024
8c5702b
fixed file used
Mar 12, 2024
7c8ed95
Merge branch 'dev' into 81-call-empty-droplets
grst Mar 13, 2024
3adeb65
updating documentation
Mar 13, 2024
48dd996
remove unused parameter
Mar 13, 2024
9cd8edd
adjust modules to handle kallisto outputs form non-standard (lamanno …
Mar 13, 2024
d77eda8
when running kallisto non-standard workflow store emptydrops in subdi…
Mar 13, 2024
c460f28
update modules to get them from nf-core/modules
Mar 18, 2024
1c1f1ac
prettier fix
fmalmeida Mar 18, 2024
6351f76
small update as file names changed
fmalmeida Mar 18, 2024
9734ace
add ending line
fmalmeida Mar 18, 2024
2406600
update changelog
fmalmeida Mar 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ log/
reports/
testme.sh
.nf-test/
.nf-test.log
49 changes: 49 additions & 0 deletions bin/emptydrops_cell_calling.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env Rscript
library("DropletUtils")
library("Matrix")

args <- commandArgs(trailingOnly=TRUE)

fn_mtx <- args[1]
fn_barcodes <- args[2]
fn_genes <- args[3]
outdir <- args[4]
aligner <- args[5]

# Read matrix/barcodes/genes
genes <- read.table(fn_genes,sep='\t')
barcodes <- read.table(fn_barcodes,sep='\t')
mtx <- readMM(fn_mtx)

get_name <- function(file) {
name <- as.character(basename(file))
name <- gsub('\\.gz', '', name)
fmalmeida marked this conversation as resolved.
Show resolved Hide resolved
return(name)
}

# Check if barcodes are in columns, if not, transpose mtx
is_transposed<-FALSE
if (dim(barcodes)[1]!=dim(mtx)[2]){
mtx<-t(mtx)
is_transposed<-TRUE
print('Matrix was tranposed.')
}
fmalmeida marked this conversation as resolved.
Show resolved Hide resolved

# Call empty drops
e.out <- emptyDrops(mtx)
is.cell <- e.out$FDR <= 0.01

# Slice matrix and barcodes
mtx_filtered <-mtx[,which(is.cell),drop=FALSE]
barcodes_filtered<-barcodes[which(is.cell),]

# If matrix was transposed early, need to transpose back
if (is_transposed){
mtx_filtered<-t(mtx_filtered)
print('Transposing back matrix.')
}

# Write output
writeMM(mtx_filtered,file.path(outdir,get_name(fn_mtx)))
write.table(barcodes_filtered,file=file.path(outdir,get_name(fn_barcodes)),col.names=FALSE,row.names=FALSE,sep='\t',quote=FALSE)
write.table(genes,file=file.path(outdir,get_name(fn_genes)),col.names=FALSE,row.names=FALSE,sep='\t',quote=FALSE)
42 changes: 30 additions & 12 deletions bin/mtx_to_h5ad.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,13 @@ def _mtx_to_adata(
aligner: str,
):
adata = sc.read_mtx(mtx_file)
if (
aligner == "star"
): # for some reason star matrix comes transposed and doesn't fit when values are appended directly
# for some reason star matrix comes transposed and doesn't fit when values are appended directly
# also true for cellranger files ( this is only used when running with the custom emptydrops_filtered files )
# otherwise, it uses the cellranger .h5 files
if aligner in [
"cellranger",
"star",
]:
adata = adata.transpose()

adata.obs_names = pd.read_csv(barcode_file, header=None, sep="\t")[0].values
Expand All @@ -57,22 +61,36 @@ def input_to_adata(
if verbose and (txp2gene or star_index):
print("Reading in {}".format(input_data))

if aligner == "cellranger":
#
# open main data
#
if aligner == "cellranger" and input_data.lower().endswith('.h5'):
adata = _10x_h5_to_adata(input_data, sample)
else:
adata = _mtx_to_adata(input_data, barcode_file, feature_file, sample, aligner)

#
# open gene information
#
if verbose and (txp2gene or star_index):
print("Reading in {}".format(txp2gene))

if txp2gene:
t2g = pd.read_table(txp2gene, header=None, names=["gene_id", "gene_symbol"], usecols=[1, 2])
elif star_index:
t2g = pd.read_table(
f"{star_index}/geneInfo.tab", header=None, skiprows=1, names=["gene_id", "gene_symbol"], usecols=[0, 1]
)

if txp2gene or star_index:
if aligner == "cellranger" and not input_data.lower().endswith('.h5'):
#
# for cellranger workflow, we do not have a txp2gene file, so, when using this normal/manual function for empty drops
# we need to provide this information coming directly from the features.tsv file
# by not using the .h5 file for conversion, we loose the two col information: feature_types and genome
#
t2g = pd.read_table(feature_file, header=None, names=["gene_id", "gene_symbol", "feature_types"], usecols=[0, 1, 2])
else:
if txp2gene:
t2g = pd.read_table(txp2gene, header=None, names=["gene_id", "gene_symbol"], usecols=[1, 2])
elif star_index:
t2g = pd.read_table(
f"{star_index}/geneInfo.tab", header=None, skiprows=1, names=["gene_id", "gene_symbol"], usecols=[0, 1]
)

if txp2gene or star_index or (aligner == "cellranger" and not input_data.lower().endswith('.h5')):
t2g = t2g.drop_duplicates(subset="gene_id").set_index("gene_id")
adata.var["gene_symbol"] = t2g["gene_symbol"]

Expand Down
35 changes: 26 additions & 9 deletions bin/mtx_to_seurat.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,40 @@ library(Seurat)

args <- commandArgs(trailingOnly=TRUE)

mtx_file <- args[1]
barcode_file <- args[2]
feature_file <- args[3]
out.file <- args[4]
aligner <- args[5]
mtx_file <- args[1]
barcode_file <- args[2]
feature_file <- args[3]
out.file <- args[4]
aligner <- args[5]
is_emptydrops <- args[6]

if (is_emptydrops == "--is_emptydrops") {
is_emptydrops <- TRUE
} else{
is_emptydrops <- FALSE
}

if(aligner %in% c("kallisto", "alevin")) {
if (aligner %in% c( "kallisto", "alevin" )) {
print("1")
# for kallisto and alevin, the features file contains only one column and matrix needs to be transposed
expression.matrix <- ReadMtx(
mtx = mtx_file, features = feature_file, cells = barcode_file, feature.column = 1, mtx.transpose = TRUE
)
} else {
expression.matrix <- ReadMtx(
mtx = mtx_file, features = feature_file, cells = barcode_file
)
if (aligner %in% c( "cellranger", "star" ) && is_emptydrops) {
print("2")
expression.matrix <- ReadMtx(
mtx = mtx_file, features = feature_file, cells = barcode_file, feature.column = 1
)
} else{
print("3")
expression.matrix <- ReadMtx(
mtx = mtx_file, features = feature_file, cells = barcode_file
)
}
}


seurat.object <- CreateSeuratObject(counts = expression.matrix)

dir.create(basename(dirname(out.file)), showWarnings = FALSE)
Expand Down
18 changes: 17 additions & 1 deletion conf/modules.config
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ process {
saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
]
}

withName: CUSTOM_DUMPSOFTWAREVERSIONS {
publishDir = [
path: { "${params.outdir}/pipeline_info" },
Expand All @@ -45,6 +46,20 @@ process {
]
}

if (!params.skip_emptydrops) {
withName: EMPTYDROPS_CELL_CALLING {
publishDir = [
path: { "${params.outdir}/${params.aligner}" },
mode: params.publish_dir_mode,
saveAs: { filename ->
if ( params.aligner == 'cellranger' ) "count/${meta.id}/${filename}"
else if ( params.aligner == 'kallisto' ) "${meta.id}.count/${filename}"
else "${meta.id}/${filename}"
}
]
}
}

withName: 'MTX_TO_H5AD|CONCAT_H5AD|MTX_TO_SEURAT' {
publishDir = [
path: { "${params.outdir}/${params.aligner}/mtx_conversions" },
Expand Down Expand Up @@ -204,11 +219,12 @@ if (params.aligner == 'kallisto') {
]
}
withName: KALLISTOBUSTOOLS_COUNT {
def kb_filter = (params.kb_filter) ? '--filter' : ''
publishDir = [
path: { "${params.outdir}/${params.aligner}" },
mode: params.publish_dir_mode
]
ext.args = "--workflow ${params.kb_workflow}"
ext.args = "--workflow ${params.kb_workflow} ${kb_filter}"
}
}
}
3 changes: 2 additions & 1 deletion conf/test.config
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ params {
max_time = '6.h'

// Input data
input = 'https://github.com/nf-core/test-datasets/raw/scrnaseq/samplesheet-2-0.csv'
input = 'https://github.com/nf-core/test-datasets/raw/scrnaseq/samplesheet-2-0.csv'
skip_emptydrops = true // module does not work on small dataset

// Genome references
fasta = 'https://github.com/nf-core/test-datasets/raw/scrnaseq/reference/GRCm38.p6.genome.chr19.fa'
Expand Down
4 changes: 2 additions & 2 deletions modules/local/concat_h5ad.nf
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ process CONCAT_H5AD {
'biocontainers/scanpy:1.7.2--pyhdfd78af_0' }"

input:
path h5ad
tuple val(input_type), path(h5ad)
path samplesheet

output:
Expand All @@ -20,7 +20,7 @@ process CONCAT_H5AD {
"""
concat_h5ad.py \\
--input $samplesheet \\
--out combined_matrix.h5ad \\
--out combined_${input_type}_matrix.h5ad \\
--suffix "_matrix.h5ad"
"""

Expand Down
82 changes: 82 additions & 0 deletions modules/local/emptydrops.nf
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
process EMPTYDROPS_CELL_CALLING {
tag "$meta.id"
label 'process_medium'

conda "bioconda::bioconductor-dropletutils"
container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ?
'https://depot.galaxyproject.org/singularity/bioconductor-dropletutils:1.18.0--r42hf17093f_1' :
'quay.io/biocontainers/bioconductor-dropletutils:1.18.0--r42hf17093f_1' }"

input:
// inputs from cellranger nf-core module does not come in a single sample dir
// for each sample, the sub-folders and files come directly in array.
tuple val(meta), path(inputs)

output:
tuple val(meta), path("emptydrops_filtered"), emit: filtered_matrices

when:
task.ext.when == null || task.ext.when

script:
if (params.aligner == "cellranger") {

matrix = "matrix.mtx.gz"
barcodes = "barcodes.tsv.gz"
features = "features.tsv.gz"

} else if (params.aligner == "kallisto") {

matrix = "counts_unfiltered/*.mtx"
barcodes = "counts_unfiltered/*.barcodes.txt"
features = "counts_unfiltered/*.genes.txt"

} else if (params.aligner == "alevin") {

matrix = "*_alevin_results/af_quant/alevin/quants_mat.mtx"
barcodes = "*_alevin_results/af_quant/alevin/quants_mat_rows.txt"
features = "*_alevin_results/af_quant/alevin/quants_mat_cols.txt"

} else if (params.aligner == 'star') {

matrix = "raw/matrix.mtx.gz"
barcodes = "raw/barcodes.tsv.gz"
features = "raw/features.tsv.gz"

}

//
// run script
//
if (params.aligner == 'kallisto' && params.kb_workflow != 'standard')
"""
mkdir emptydrops_filtered/
# convert file types
for splice_type in spliced unspliced ; do
emptydrops_cell_calling.R \\
counts_unfiltered/\${splice_type}.mtx \\
counts_unfiltered/\${splice_type}.barcodes.txt \\
counts_unfiltered/\${splice_type}.genes.txt \\
emptydrops_filtered \\
${params.aligner} \\
0
done
"""
grst marked this conversation as resolved.
Show resolved Hide resolved

else
"""
mkdir emptydrops_filtered/
emptydrops_cell_calling.R \\
$matrix \\
$barcodes \\
$features \\
emptydrops_filtered \\
${params.aligner} \\
0
"""

stub:
"""
touch emptydrops_filtered/*
fmalmeida marked this conversation as resolved.
Show resolved Hide resolved
"""
}
Loading
Loading