Snakemake workflow: 10X single-cell + LARRY

public public 1yr ago Version: v0.0.1 0 bookmarks

A Snakemake workflow to process single-cell libraries generated with 10XGenomics platform (RNA, ATAC and RNA+ATAC) together with LARRY barcoding .

Setup

The following files a

Code Snippets

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
shell:
    """
    cellranger count \
    {params.feature_ref} \
    {params.n_cells} \
    {params.extra_p}  \
    {params.introns} \
    --id {wildcards.sample} \
    --transcriptome {params.genome} \
    --libraries {input.libraries} \
    --localcores {threads} \
    --localmem {params.mem_gb} \
    &> {log} && \
    # a folder in results/counts/{wildcards.sample} is automatically created due to the output declared, which 
    # is a problem to move the cellranger output files. The workaround of deleting that folder fixes that.
    rm -r results/01_counts/{wildcards.sample} && \
    mv {wildcards.sample} results/01_counts/{wildcards.sample}
    """
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
shell:
    """
    cellranger-atac count \
    {params.extra_p} \
    --id {wildcards.sample} \
    --reference {params.genome} \
    --fastqs data/clean \
    --localcores {threads} \
    --localmem {params.mem_gb} \
    &> {log} && \
    # a folder in results/counts/{wildcards.sample} is automatically created due to the output declared, which 
    # is a problem to move the cellranger output files. The workaround of deleting that folder fixes that.
    rm -r results/01_counts/{wildcards.sample} && \
    mv {wildcards.sample} results/01_counts/{wildcards.sample}
"""
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
shell:
    """
    cellranger-arc count \
    {params.introns} \
    {params.extra_p} \
    --id {wildcards.sample} \
    --reference {params.genome} \
    --libraries {input.libraries} \
    --localcores {threads} \
    --localmem {params.mem_gb} \
    &> {log} && \
    # a folder in results/counts/{wildcards.sample} is automatically created due to the output declared, which 
    # is a problem to move the cellranger output files. The workaround of deleting that folder fixes that.
    rm -r results/01_arc/{wildcards.sample} && \
    mv {wildcards.sample} results/01_arc/{wildcards.sample}
    """
SnakeMake From line 132 of rules/counts.smk
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
shell:
    """
    cellranger count \
    {params.feature_ref} \
    {params.n_cells} \
    {params.extra_p}  \
    {params.introns} \
    --id {wildcards.sample} \
    --chemistry=ARC-v1 \
    --transcriptome {params.genome} \
    --libraries {input.libraries} \
    --localcores {threads} \
    --localmem {params.mem_gb} \
    &> {log} && \
    # a folder in results/counts/{wildcards.sample} is automatically created due to the output declared, which 
    # is a problem to move the cellranger output files. The workaround of deleting that folder fixes that.
    rm -r results/01_counts/{wildcards.sample} && \
    mv {wildcards.sample} results/01_counts/{wildcards.sample}
    """
SnakeMake From line 179 of rules/counts.smk
24
25
script:
    "../scripts/python/extract_barcodes.py"
41
42
43
44
shell:
    """
    java -Xmx200G -Xss1G -jar /UMICollapse/umicollapse.jar fastq -k {wildcards.hd} --tag -i {input} -o {output} 2> {log}
    """
61
62
script:
    "../scripts/python/correct_barcodes.py"
78
79
80
81
shell:
    """
    cat {input} > {output}
    """
 99
100
script:
    "../scripts/R/generate_feature_ref_larry.R"
26
27
script:
    "../scripts/R/create_seurat.R"
47
48
script:
    "../scripts/R/barcode_summary.Rmd"
70
71
script:
    "../scripts/R/barcode_filtering.R"
89
90
script:
    "../scripts/R/merge_seurat.R"
113
114
script:
    "../scripts/R/RNA_exploration.Rmd"
10
11
12
13
14
shell:
    """
    ln -s {input[0]} {output.fw}
    ln -s {input[1]} {output.rv}
    """
23
24
25
26
shell:
    """
    ln -s {input} {output}
    """
45
46
47
48
49
shell:
    """
    cat {input.fw} > {output.fw} 2> {log}
    cat {input.rv} > {output.rv} 2>> {log}
    """
63
64
65
66
shell:
    """
    cat {input} > {output} 2> {log}
    """
79
80
81
82
83
shell:
    """
    mv {input.fw} {output.fw}
    mv {input.rv} {output.rv}
    """
 96
 97
 98
 99
100
shell:
    """
    mv {input.fw} {output.fw}
    mv {input.rv} {output.rv}
    """
115
116
117
118
119
120
shell:
    """
    mv {input.fw} {output.fw}
    mv {input.rv} {output.rv}
    mv {input.r3} {output.r3}
    """
133
134
script:
    "../scripts/python/create_library_csv.py"
145
146
script:
    "../scripts/python/generate_cellhashing_ref.py"
158
159
script:
    "../scripts/R/generate_feature_ref.R"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import gzip
import re
import pandas as pd
from Bio.SeqIO.QualityIO import FastqGeneralIterator

input_file    = snakemake.input[0]
output_fastq  = snakemake.output["corrected_fq"]
feature_ref   = snakemake.output["feature_ref"]
color         = snakemake.wildcards.larry_color
read          = snakemake.wildcards.read_fb

#------------------------------------------------------------------------------------------------------------------------------------
# Declare functions
#------------------------------------------------------------------------------------------------------------------------------------

def create_feature_ref(reference_dict, color, read, feature_ref):
    """
    Generate a dictionary with barcode sequences and their corresponding larry color to 
    generate the feature reference csv file required by cellranger.

    It takes as input a dictionary with read cluster id's as keys and sequences (corresponding to the
    reference barcode of the clusetr) as values.
    """
    extra_nts = r'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT'
    bc_dict = {str(key): color for key in reference_dict.values()}

    bc_df                 = pd.DataFrame.from_dict(bc_dict, orient='index', columns = ['id'])
    bc_df                 = bc_df.rename_axis("sequence").reset_index()
    bc_df['sequence']     = bc_df['sequence'].str.replace(extra_nts, '', regex=True).astype('str')
    bc_df['name']         = bc_df.groupby('id').cumcount() + 1
    bc_df['name']         = bc_df['id'] + "_" + bc_df['name'].astype(str)
    bc_df['id']           = bc_df['name']
    bc_df['read']         = read
    bc_df['pattern']      = extra_nts + "(BC)"
    bc_df['feature_type'] = "Custom"

    bc_df.to_csv(feature_ref, index = False)


def get_reference_barcodes(input_fastq):
    """
    This function will parse a fastq processed by UMIcollapse https://github.com/Daniel-Liu-c0deb0t/UMICollapse.
    By parsing the fastq, it will create a dictionary with read cluster id's as keys and the sequences of the
    reference barcodes of the cluster as values.

    It also returns a list containing all the fastq records to be used later and avoid having to parse again the fastq.
    """

    fastq_entries     = []
    cluster_dict_id   = dict()
    reference_pattern = re.compile(r'cluster_size=')

    with gzip.open(input_fastq, 'rt') as input_handle:
        for title, seq, qual in FastqGeneralIterator(input_handle):
            fastq_entries += [[title, seq, qual]]
            match = reference_pattern.search(title)
            if match:
                # Create a dictionary with the cluster id and the corresponding consensus sequence
                cluster_id = re.sub('^.* cluster_id=([0-9]+).*', r'\1', title)
                cluster_dict_id[cluster_id] = "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT" + seq

    return(cluster_dict_id, fastq_entries)


def write_corrected_fastq(output_fastq, reference_dict, fastq_entries):
    """
    This function will correct the sequences from the fastq file by substituting them by the reference sequence 
    of every read cluster and write a new fastq file.

    Takes as input a dictionary with read cluster id's as keys and the sequences of the
    reference barcodes of the cluster as values and a list containing all the records of the
    fastq file. Using the dictionary, it will update all the sequences from the list based on the reference sequence
    present in the dictionary.
    """

    with gzip.open(output_fastq, 'wt') as output_handle:
        for title, seq, qual in fastq_entries:
        # Get cluster id for read, use that cluster id to access cluster_dict_id dict
        # which contains the reference sequence. This way I generate a second dict in which
        # Every read id is a associated to a specific sequence.
        # Remove the tag from umicollapse from read_id (title)
            cluster_id = re.sub('^.* cluster_id=([0-9]+).*', r'\1', title)
            seq = reference_dict[cluster_id]
            title = re.sub("\scluster_id.*$", "", title)
            qual = "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" + qual # Fake qscore for the extra 50 fake T's
            _ = output_handle.write(f"@{title}\n{seq}\n+\n{qual}\n")


#------------------------------------------------------------------------------------------------------------------------------------
# Main
#------------------------------------------------------------------------------------------------------------------------------------
# Create dict with reference barcodes, store fastq in list
reference_dict, fastq_records = get_reference_barcodes(input_file)

# Correct fastq file with reference barcodes and save output fastq
write_corrected_fastq(output_fastq, reference_dict, fastq_records)

# Generate a feature ref csv from the dictionary of reference barcodes
create_feature_ref(reference_dict, color, read, feature_ref)
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import os

"""Create the content of library.csv for the feature barcoding and multiome pipeline
from cellranger.

Based on what is written in the column lib_type from the units file,
write the following: "fastq folder,fastq name,library type".
"""

abs_path        = os.getcwd()
sample          = snakemake.wildcards["sample"]
is_feature_bc   = snakemake.params["is_feature_bc"]
is_cell_hashing = snakemake.params["is_cell_hashing"]
lib_type        = snakemake.params["library_type"]

lib_csv = dict()


########################################################################################################
# Create library dict
########################################################################################################
if is_feature_bc:
    lib_csv['FB'] = f'{abs_path}/data/clean,{sample}_FB,Custom'

if is_cell_hashing:
    lib_csv['CH'] = f'{abs_path}/data/clean,{sample}_CH,Antibody Capture'

elif lib_type == 'GEX':
    lib_csv['GEX'] = f'{abs_path}/data/clean,{sample}_GEX,Gene Expression'

elif lib_type == 'ATAC':
    lib_csv['ATAC'] = f'{abs_path}/data/clean,{sample}_ATAC,Chromatin Accessibility'

elif lib_type == 'ARC' and not is_feature_bc:
    lib_csv['ATAC'] = f'{abs_path}/data/clean,{sample}_ATAC,Chromatin Accessibility'
    lib_csv['GEX']  = f'{abs_path}/data/clean,{sample}_GEX,Gene Expression'

elif lib_type == 'ARC' and is_feature_bc:
    lib_csv['GEX']  = f'{abs_path}/data/clean,{sample}_GEX,Gene Expression'

# Save library dict to csv
out_csv = '\n'.join(lib_csv.values())
with open(snakemake.output["library"], 'wt') as output_handle:
    output_handle.write("fastqs,sample,library_type\n")
    output_handle.write(out_csv)


########################################################################################################
# Create library dict for arc
########################################################################################################
# If the library is multiome and there is feature barcode data, the pipeline must be run 2 times
# One for rna + larry and the other for rna+atac. Due to this, we need 2 different library csv files.
if lib_type == 'ARC' and is_feature_bc:

    lib_csv2 = dict()
    lib_csv2['ATAC'] = f'{abs_path}/data/clean,{sample}_ATAC,Chromatin Accessibility'
    lib_csv2['GEX']  = f'{abs_path}/data/clean,{sample}_GEX,Gene Expression'

    # Save library (arc) dict to csv
    out_csv2 = '\n'.join(lib_csv2.values())
    with open(snakemake.output["library_arc"], 'wt') as output_handle:
        output_handle.write("fastqs,sample,library_type\n")
        output_handle.write(out_csv2)

else:
    lib_csv2 = "If library type is not ARC, ignore this file."
    with open(snakemake.output["library_arc"], 'wt') as output_handle:
        output_handle.write(lib_csv2)
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
import gzip
import re
from Bio.SeqIO.QualityIO import FastqGeneralIterator

#------------------------------------------------------------------------------------------------------------------------------------
# Declare input/output files
#------------------------------------------------------------------------------------------------------------------------------------
input_fb  = snakemake.input["fb"]
input_cb  = snakemake.input["cb"]
output_fb = snakemake.output["filt_fb"]
output_cb = snakemake.output["filt_cb"]
barcode_patterns = snakemake.params["barcode_dict"]


#------------------------------------------------------------------------------------------------------------------------------------
# Declare functions
#------------------------------------------------------------------------------------------------------------------------------------
def extract_barcodes(input_file, barcode_patterns):
    """
    This function will take a fastq file from larry barcode enrichment and a dictionary in which the
    keys are the barcode patterns and the corresponding larry library name/color  (i.e: {...TG...AG... : GFP}).

    It will parse the fastq file, look for reads that contain the barcode and extract the barcode sequence
    from the read. All the fastq records containing barcodes will be stored in a dictionary, as a list. The
    keys of the dictionary are the larry colors, and the values are a list of the fastq records containing each
    specific barcode color.
    """

    patterns      = [re.compile(r'{}'.format(barcode)) for barcode in barcode_patterns.keys()]
    patterns_dict = {key: value for key, value in zip(patterns, barcode_patterns.values())}
    barcode_reads = {key: [] for key in barcode_patterns.values()}

    with gzip.open(input_file, 'rt') as input_handle:
        # Iterate over each record in the fastq file
        for title, seq, qual in FastqGeneralIterator(input_handle):
            # Look for barcode patterns
            for pattern in patterns:
                match = pattern.search(seq)
                if match:
                    # Update record to contain just matched sequence 
                    seq  = seq[match.start() : match.end()]
                    qual = qual[match.start() : match.end()]
                    # Save updated records to dictionary. Every key is a different barcode color, the content are all the records
                    # corresponding to that color.
                    barcode_reads[patterns_dict[pattern]] += [title, seq, qual],
                    break

    return(barcode_reads)


def extracted_bc_to_fq(output_fastqs, barcode_reads):
    """
    Take the dictionary of larry colors and fastq records containing barcodes and save it to multiple fastq
    files, one for each larry color.
    """
    # Order of output files is the same as the keys of the dictionary since both of them are taken from the same config variable
    for i, key in enumerate(barcode_reads.keys()):
        with gzip.open(output_fastqs[i], 'wt') as output_handle:
            for title, seq, qual in barcode_reads[key]:
                _ = output_handle.write(f"@{title}\n{seq}\n+\n{qual}\n")


def subset_cb_fastq(input_fastq, output_fastq, barcode_reads):
    """
    Subset the fastq file that contains the cellular barcodes (instead of larry barcodes) to contain the same read ids
    of the larry barcode fastq, which has been filtered and now does not contain all the initial fastq entries.

    Also, since the larry bc fq is split in different colors (if there is sequential barcoding), the order of fastq
    reads will be different. For this, the cellular barcode fastq must be filtered and then sorted to match the larry
    fastq.
    """
    read_primer      = re.compile(r"\s.*$")
    filtered_ids     = [read_primer.sub('', fastq_record[0]) for larry_color in barcode_reads.values() for fastq_record in larry_color]
    filtered_ids_set = set(filtered_ids)
    fastq_records    = {}

    with gzip.open(input_fastq, 'rt') as input_handle, gzip.open(output_fastq, 'wt') as output_handle:
        # Parse fastq and store records in dictionary using read_id as key
        for title, seq, qual in FastqGeneralIterator(input_handle):
            title_no_read_id = read_primer.sub('', title)
            if title_no_read_id in filtered_ids_set:
                fastq_records[title_no_read_id] = [title, seq, qual]

        # Sort the keys (read_id) of the dict to match the order of read_ids from the larry fastq
        index_map = {v: i for i, v in enumerate(filtered_ids)}
        fastq_records = dict( sorted(fastq_records.items(), key=lambda pair: index_map[pair[0]]) )

        # Save to fastq
        for title, seq, qual in fastq_records.values():
                _ = output_handle.write(f"@{title}\n{seq}\n+\n{qual}\n")


#------------------------------------------------------------------------------------------------------------------------------------
# Main
#------------------------------------------------------------------------------------------------------------------------------------
# Filter reads containing barcodes from feature barcoding read and write to new fastq file
barcode_reads = extract_barcodes(input_fb, barcode_patterns) 
extracted_bc_to_fq(output_fb, barcode_reads)

# Subset the other fastq (the one containing cellular barcodes) based on the read ids filtered before
subset_cb_fastq(input_cb, output_cb, barcode_reads) 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def generate_cellhash_ref_csv(cell_hashing_dict):
    """Generate cmo-set csv file indicating the totalseq names and barcode sequences + positions"""
    cmo_csv = "id,name,read,pattern,sequence,feature_type\n"
    for key, value in cell_hashing_dict.items():
        cmo_csv += f"{key},{key},{value[0]},{value[1]},{value[2]},Antibody Capture\n"

    return cmo_csv

cell_hashing_Abs  = snakemake.params["cellhash_ab_names"]
cell_hashing_dict = snakemake.params["cell_hashing"]
cell_hashing_dict = dict((Ab, cell_hashing_dict[Ab]) for Ab in cell_hashing_Abs) # Use just cellhash Abs corresponding to this sample

cellhash_csv = generate_cellhash_ref_csv(cell_hashing_dict)

with open(snakemake.output[0], 'wt') as output_handle:
    output_handle.write(cellhash_csv)
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")

### Libraries
library(Seurat)
library(tidyverse)
library(DropletUtils)
source("workflow/scripts/R/functions.R")

#-----------------------------------------------------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------------------------------------------------
get_larry_molinfo <- function(molinfo) {

    larry_bc_pos <- which(molinfo$feature.type == "Custom")

    larry_molinfo <- molinfo$data %>% 
        data.frame() %>% 
        dplyr::filter(gene %in% larry_bc_pos) %>% 
        mutate(larry_bc = molinfo$genes[gene]) %>% # Create col with larry bc name instead of idx from molinfo$genes
        mutate(larry_color = str_replace(larry_bc, "_.*$", "")) %>% # Add color information to split barcodes
        dplyr::select(-gene)

    return(larry_molinfo)

}


filter_umi_reads <- function(df_molinfo, read_threshold) {

    df_molinfo <- df_molinfo %>% 
        dplyr::filter(reads >= read_threshold)

    return(df_molinfo)

}


filter_bc_umis <- function(df_molinfo, umi_threshold) {

    df_molinfo <- df_molinfo %>% 
        dplyr::group_by(cell, larry_bc, larry_color) %>% 
        dplyr::count() %>% 
        dplyr::rename(n_umi = n) %>% 
        dplyr::filter(n_umi >= umi_threshold) %>% 
        dplyr::ungroup()

    return(df_molinfo)

}


#-----------------------------------------------------------------------------------------------------------------------
# Data laoding
#-----------------------------------------------------------------------------------------------------------------------
seurat_rds    <- snakemake@input[[1]]
molec_info_h5 <- snakemake@params[["molecule_info"]]
output_rds    <- snakemake@output[[1]]

umi_cutoff  <- snakemake@params[["umi_cutoff"]]
read_cutoff <- snakemake@params[["reads_cutoff"]]

seurat      <- readRDS(seurat_rds)
molinfo     <- read10xMolInfo(molec_info_h5,
                              get.cell    = TRUE,
                              get.umi     = TRUE,
                              get.gem     = FALSE,
                              get.gene    = TRUE,
                              get.reads   = TRUE,
                              get.library = FALSE
)

# Modify cell names form molinfo file to match those from seurat (basically add whatever is)
# before and after the cellular barcode (which consists in random 16 nucleotides, by now)
cell_prefix <- Cells(seurat) %>% str_replace("[AGTC]{16}-.*", "")
cell_suffix <- Cells(seurat) %>% str_replace(".*_[AGTC]{16}", "")

molinfo$data <- molinfo$data %>% 
    data.frame() %>%
    dplyr::mutate(cell = paste0(cell_prefix, cell, cell_suffix)) %>% 
    filter(cell %in% Cells(seurat)) %>% 
    DataFrame()

molinfo_larry <- get_larry_molinfo(molinfo)


#-----------------------------------------------------------------------------------------------------------------------
# Barcode calling
#-----------------------------------------------------------------------------------------------------------------------
larry_filt <- molinfo_larry %>% 
    filter_umi_reads(read_cutoff) %>% 
    filter_bc_umis(umi_cutoff)

larry_bc_calls <- larry_filt %>% 
    dplyr::group_by(cell, larry_color) %>% 
    dplyr::filter(n_umi == max(n_umi)) %>% 
    dplyr::filter(n() == 1) %>% 
    dplyr::ungroup() %>% 
    dplyr::select(cell, larry_bc) %>% 
    dplyr::group_by(cell) %>% 
    dplyr::arrange(larry_bc) %>% 
    dplyr::summarise(larry_bc = paste(larry_bc, collapse = "__")) %>% 
    tibble::deframe()

seurat$larry <- larry_bc_calls


#-----------------------------------------------------------------------------------------------------------------------
# Filter larry matrix and save to new rds
#-----------------------------------------------------------------------------------------------------------------------
# Add barcode matrix to seurat object. Since not all cells are present in the barcode matrix, we will have to manually
# add the missing cells and set 0 to all barcode UMIs.
# The matrix added is the matrix filtered by reads, not by UMIs. In this way it is always possible to go back to the matrix
# without read filtering or read filtered (larry_filt) in order to call the barcodes again later on in a different way
# and always having the original data.
larry_filt_reads <- molinfo_larry %>% 
    filter_umi_reads(read_cutoff) %>% 
    filter_bc_umis(0)

larry_filt_mat <- larry_filt_reads %>% 
    mutate(cell = factor(cell, levels = Cells(seurat))) %>% 
    dplyr::select(cell, larry_bc, n_umi) %>% 
    pivot_wider(values_from = n_umi, names_from = cell, values_fill = 0) %>% 
    column_to_rownames("larry_bc") %>% 
    as.matrix()

# Create empty matrix for cells without larry barcodes
barcode_names <- unique(larry_filt_reads$larry_bc)
cell_names_noLarry <- Cells(seurat)[!Cells(seurat) %in% larry_filt_reads$cell]

mtx_noLarry_cells <- matrix(0, 
                            length(barcode_names),
                            length(cell_names_noLarry),
                            dimnames = list(
                                barcode_names,
                                cell_names_noLarry
                            )
)

# Merge both matrices
final_larry_mtx <- cbind(larry_filt_mat, mtx_noLarry_cells) %>% 
    as("dgCMatrix")

# Add filtered matrix to seurat object
seurat[["Larry_filt"]] <- CreateAssayObject(counts = final_larry_mtx)

saveRDS(seurat, file = output_rds)
20
21
22
23
24
25
26
27
28
knitr::opts_chunk$set(
    echo           = TRUE,
    error          = FALSE,
    fig.align      = "center",
    message        = FALSE,
    warning        = FALSE,
    fig.width      = 10,
    fig.height     = 8
)
32
33
34
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")
38
39
40
41
library(Seurat)
library(tidyverse)
library(DropletUtils)
source("workflow/scripts/R/functions.R")
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
get_larry_molinfo <- function(molinfo) {

  larry_bc_pos <- which(molinfo$feature.type == "Custom")

  larry_molinfo <- molinfo$data %>% 
    data.frame() %>% 
    dplyr::filter(gene %in% larry_bc_pos) %>% 
    mutate(larry_bc = molinfo$genes[gene]) %>% # Create col with larry bc name instead of idx from molinfo$genes
    mutate(larry_color = str_replace(larry_bc, "_.*$", "")) %>% # Add color information to split barcodes
    dplyr::select(-gene)

    return(larry_molinfo)

}


filter_umi_reads <- function(df_molinfo, read_threshold) {

  df_molinfo <- df_molinfo %>% 
    dplyr::filter(reads >= read_threshold)

  return(df_molinfo)

}


filter_bc_umis <- function(df_molinfo, umi_threshold) {

  df_molinfo <- df_molinfo %>% 
    dplyr::group_by(cell, larry_bc, larry_color) %>% 
    dplyr::count() %>% 
    dplyr::rename(n_umi = n) %>% 
    dplyr::filter(n_umi >= umi_threshold) %>% 
    dplyr::ungroup()

  return(df_molinfo)

}


efficiency_larry <- function(df_molinfo, umi_threshold, n_cells) {

  efficiency <- df_molinfo %>% 
    filter_bc_umis(umi_threshold) %>% 
    dplyr::group_by(larry_color) %>% 
    dplyr::distinct(cell) %>% 
    dplyr::count() %>% 
    dplyr::mutate(efficiency    = n/n_cells,
                  umi_threshold = umi_threshold
                  ) %>% 
    dplyr::ungroup()

  return(efficiency)

}


plot_larry_efficiency <- function(molinfo_larry, read_threshold, n_cells, umi_thresholds) {

  larry_molinfo_read_filt <- molinfo_larry %>% 
    filter_umi_reads(read_threshold)

  larry_eficiencies <- purrr::map_df(umi_thresholds,
             \(umi_threshold) efficiency_larry(larry_molinfo_read_filt, umi_threshold, n_cells)
             )

  p <- larry_eficiencies %>%
    ggplot2::ggplot(aes( x = umi_threshold, y = efficiency)) +
    geom_line() +
    facet_wrap(~ larry_color) +
    theme_bw() +
    ggtitle(paste0(read_threshold, " read threshold"))

  return(p)

}

prop_integrations_larry <- function(df_molinfo, umi_threshold) {

  integrtions <- df_molinfo %>% 
    filter_bc_umis(umi_threshold) %>% 
    dplyr::group_by(larry_color) %>% 
    dplyr::count(cell) %>% 
    dplyr::summarise(
      p_cells_multiple_integrations = sum(n > 1)/n()
    ) %>% 
    dplyr::mutate(umi_threshold = umi_threshold) %>% 
    dplyr::ungroup()

  return(integrtions)

}

plot_larry_mult_int <- function(molinfo_larry, read_threshold, umi_thresholds) {

  larry_molinfo_read_filt <- molinfo_larry %>% 
    filter_umi_reads(read_threshold)

  larry_eficiencies <- purrr::map_df(umi_thresholds,
             \(umi_threshold) prop_integrations_larry(larry_molinfo_read_filt, umi_threshold)
             )

  p <- larry_eficiencies %>%
    ggplot2::ggplot(aes( x = umi_threshold, y = p_cells_multiple_integrations)) +
    geom_line() +
    facet_wrap(~ larry_color) +
    theme_bw() +
    ggtitle(paste0(read_threshold, " read threshold")) +
    scale_x_continuous(breaks = umi_thresholds)

  return(p)

}
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
seurat_rds    <- snakemake@input[[1]]
molec_info_h5 <- snakemake@params[["molecule_info"]]

seurat      <- readRDS(seurat_rds)
molinfo     <- read10xMolInfo(molec_info_h5,
                              get.cell    = TRUE,
                              get.umi     = TRUE,
                              get.gem     = FALSE,
                              get.gene    = TRUE,
                              get.reads   = TRUE,
                              get.library = FALSE
                              )

# Modify cell names form molinfo file to match those from seurat (basically add whatever is)
# before and after the cellular barcode (which consists in random 16 nucleotides, by now)
cell_prefix <- Cells(seurat) %>% str_replace("[AGTC]{16}-.*", "")
cell_suffix <- Cells(seurat) %>% str_replace(".*_[AGTC]{16}", "")

molinfo$data <- molinfo$data %>% 
  data.frame() %>%
  dplyr::mutate(cell = paste0(cell_prefix, cell, cell_suffix)) %>% 
  filter(cell %in% Cells(seurat)) %>% 
  DataFrame()

molinfo_larry <- get_larry_molinfo(molinfo)
194
195
196
197
198
199
200
molinfo_larry %>% 
  ggplot(aes(reads)) + 
  geom_histogram(bins = 100) +
  scale_y_log10() +
  scale_x_log10() +
  theme_bw() +
  facet_wrap(~larry_color)
208
209
210
211
212
213
214
215
216
217
218
219
summary_larry_thresholds <- map(1:10,
    \(read_threshold) plot_larry_efficiency(
                      molinfo_larry  = molinfo_larry,
                      read_threshold = read_threshold,
                      n_cells        = length(Cells(seurat)),
                      umi_thresholds = 1:10
                      )
    )

names(summary_larry_thresholds) <- paste0(1:10, " reads")

in_tabs(summary_larry_thresholds, level = 1L)
228
229
230
231
232
233
234
235
236
237
238
summary_larry_integrations <- map(1:10,
    \(read_threshold) plot_larry_mult_int(
                      molinfo_larry  = molinfo_larry,
                      read_threshold = read_threshold,
                      umi_thresholds = 1:10
                      )
    )

names(summary_larry_integrations) <- paste0(1:10, " reads")

in_tabs(summary_larry_integrations, level = 1L)
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")

### Libraries
library(Seurat)
library(Signac)
library(tidyverse)
library(SingleCellExperiment)
library(scDblFinder)
library(BiocParallel)
library(DropletUtils)

#-----------------------------------------------------------------------------------------------------------------------
# Create seurat object
#-----------------------------------------------------------------------------------------------------------------------
create_seurat <- function(input_files, sample_name, cellhash_names, min_cells_gene = 1,
                          is_larry = FALSE, is_cell_hashing = FALSE, UMI_cutoff = 0) {
  # Load files
  names(input_files) <- sample_name
  data <- Read10X(data.dir = input_files)

  # Create seurat objects
  if (is.list(data)) {

    seurat <- CreateSeuratObject(counts = data$`Gene Expression`, min.cells = min_cells_gene)

    if (is_cell_hashing) {
      seurat[["Cellhashing"]] <- CreateAssayObject(counts = data$`Antibody Capture`)
    }

    if (is_larry) {
      seurat[["Larry"]] <- CreateAssayObject(counts = data$`Custom`)
    }

  } else {

    seurat <- CreateSeuratObject(counts = data, min.cells = min_cells_gene)

  }

  # Fix sample names. cellhashing column is added to be consistent with the structure of seurat objects
  # coming from libraries in which cellhashing has been performed.
  # Also a subsample entry is created to be consistent with samples with cellhashing.
  seurat$sample      <- sample_name
  seurat$subsample   <- sample_name
  Idents(seurat)     <- seurat$sample

  # Remove cells with less than UMI threshold
  seurat <- subset(seurat, subset = nCount_RNA >= UMI_cutoff)

  return(seurat)

}


create_seurat_arc <- function(input_files, input_fragments, input_larry = NULL, sample_name, min_cells_gene = 1,
                          is_larry = FALSE, UMI_cutoff = 0) {
  # Load files
  names(input_files) <- sample_name
  arc <- Read10X(data.dir = input_files)

  if (is_larry) {

    names(input_larry) <- sample_name
    larry <- Read10X(data.dir = input_larry)

    common_cells <- intersect(
      colnames(larry$Custom),
      colnames(arc$`Gene Expression`)
    )

    seurat            <- CreateSeuratObject(counts = arc$`Gene Expression`[,common_cells], min.cells = min_cells_gene)
    seurat[["ATAC"]]  <- CreateChromatinAssay(counts = arc$`Peaks`[,common_cells], fragments = input_fragments, sep = c(":", "-"))
    seurat[["Larry"]] <- CreateAssayObject(counts = larry$Custom[,common_cells])

  } else {

    seurat           <- CreateSeuratObject(counts = arc$`Gene Expression`, min.cells = min_cells_gene)
    seurat[["ATAC"]] <- CreateChromatinAssay(counts = arc$`Peaks`, fragments = input_fragments, sep = c(":", "-"))

  }

  # Fix sample names. cellhashing column is added to be consistent with the structure of seurat objects
  # coming from libraries in which cellhashing has been performed.
  # Also a subsample entry is created to be consistent with samples with cellhashing.
  seurat$sample      <- sample_name
  seurat$subsample   <- sample_name
  Idents(seurat)     <- seurat$sample

  # Remove cells with less than UMI threshold
  seurat <- subset(seurat, subset = nCount_RNA >= UMI_cutoff)

  return(seurat)

}

#-----------------------------------------------------------------------------------------------------------------------
# Remove cell doublets
#-----------------------------------------------------------------------------------------------------------------------
remove_doublets <- function(seurat, cores = 1) {

  sce <- NormalizeData(seurat) %>% as.SingleCellExperiment()
  sce <- scDblFinder(sce, samples = "sample", BPPARAM = MulticoreParam(cores))

  dblt_info <- sce$scDblFinder.class
  names(dblt_info) <- rownames(sce@colData)
  seurat$scDblFinder.class <- dblt_info

  print("Total number of singlets and doublets")
  print(table(seurat$scDblFinder.class))

  return(seurat)

}


#-----------------------------------------------------------------------------------------------------------------------
# Cellhashing assignment functions
#-----------------------------------------------------------------------------------------------------------------------
cell_hashing_assignment <- function(seurat, cellhash_names, sample_name) {

  sce               <- as.SingleCellExperiment(seurat)
  hash.stats        <- hashedDrops( counts(altExp(sce, "Cellhashing")), constant.ambient=TRUE)
  cellhash_ab_names <- metadata(hash.stats)$ambient %>% names()

  cell_hash_assignment <- hash.stats %>% 
    as.data.frame() %>% 
    tibble::rownames_to_column("cell_id") %>% 
    dplyr::mutate(subsample = cellhash_names[cellhash_ab_names[Best]]) %>% 
    dplyr::mutate(subsample = ifelse(Confident, subsample, paste0("Unassigned_", sample_name))) %>% 
    dplyr::select(cell_id, subsample) %>% 
    tibble::deframe() %>% 
    unlist()

  seurat$subsample <- cell_hash_assignment

  return(seurat)

}

cell_hashing_assignment_seurat <- function(seurat, cellhash_names, sample_name) {

  seurat <- NormalizeData(seurat, assay = "Cellhashing", normalization.method = "CLR")
  seurat <- HTODemux(seurat, assay = "Cellhashing", positive.quantile = 0.99)

  return(seurat)

}

summary_cellhashing <- function(seurat, cellhash_names) {

  # Plots based on seurat and dropletutils cell hashing assignment
  Idents(seurat) <- "Cellhashing_classification"
  p1 <- RidgePlot(seurat, assay = "Cellhashing", features = rownames(seurat[["Cellhashing"]]), ncol = 1)
  p2 <- VlnPlot(seurat, features = "nCount_RNA", pt.size = 0.1, log = TRUE)
  Idents(seurat) <- "subsample"
  p3 <- RidgePlot(seurat, assay = "Cellhashing", features = rownames(seurat[["Cellhashing"]]), ncol = 1)
  p4 <- VlnPlot(seurat, features = "nCount_RNA", pt.size = 0.1, log = TRUE)

  print(p1)
  print(p2)
  print(p3)
  print(p4)

  # scatter plot of all pairwise combinations of Abs used for cellhashing.
  # First with emprydrops annotation, then with seurat annotation
  ab_combs <- snakemake@params[["cellhash_names"]] %>% names() %>% combn(2)

  for (i in ncol(ab_combs)) {
    comb <- ab_combs[,i]
    p <- FeatureScatter(seurat, feature1 = comb[1], feature2 = comb[2], raster = TRUE)
    print(p)
  }

  Idents(seurat) <- "Cellhashing_classification"
  for (i in ncol(ab_combs)) {
    comb <- ab_combs[,i]
    p <- FeatureScatter(seurat, feature1 = comb[1], feature2 = comb[2], raster = TRUE)
    print(p)
  }

}

#-----------------------------------------------------------------------------------------------------------------------
# Main & save output
#-----------------------------------------------------------------------------------------------------------------------
# Create seurat object & calculate doublets
if (snakemake@params[["library_type"]] == "ARC") {

  seurat <- create_seurat_arc(
    input_files     = snakemake@input[["arc"]],
    input_fragments = snakemake@input[["fragments"]],
    input_larry     = snakemake@input[["counts"]],
    sample_name     = snakemake@wildcards[["sample"]],
    min_cells_gene  = snakemake@params[["min_cells_gene"]],
    is_larry        = snakemake@params[["is_larry"]],
    UMI_cutoff      = snakemake@params[["umi_cutoff"]]
  )

} else {

  seurat <- create_seurat(
    input_files     = snakemake@input[["counts"]],
    sample_name     = snakemake@wildcards[["sample"]],
    min_cells_gene  = snakemake@params[["min_cells_gene"]],
    is_larry        = snakemake@params[["is_larry"]],
    is_cell_hashing = snakemake@params[["is_cell_hashing"]],
    cellhash_names  = snakemake@params[["cellhash_names"]],
    UMI_cutoff      = snakemake@params[["umi_cutoff"]]
  )

}

# Remove doublets
seurat <- remove_doublets(seurat, cores = snakemake@threads[[1]])

# Add mitochondrial and ribosomal RNA metrics
mito_pattern             <- snakemake@params[["mito_pattern"]]
ribo_pattern             <- snakemake@params[["ribo_pattern"]]
seurat[["percent.mt"]]   <- PercentageFeatureSet(seurat, pattern = mito_pattern)
seurat[["percent.ribo"]] <- PercentageFeatureSet(seurat, pattern = ribo_pattern)

# Filter doublets and save object
seurat_clean <- subset(seurat, subset = scDblFinder.class == "singlet")

# If the library has been processed with cell hashing, assign cells to subsamples in seurat without doublets
if (snakemake@params[["is_cell_hashing"]]) {

  seurat_clean <- cell_hashing_assignment(
    seurat         = seurat_clean,
    cellhash_names = snakemake@params[["cellhash_names"]],
    sample_name    = snakemake@wildcards[["sample"]]
  )

  seurat_clean <- cell_hashing_assignment_seurat(
    seurat         = seurat_clean,
    cellhash_names = snakemake@params[["cellhash_names"]],
    sample_name    = snakemake@wildcards[["sample"]]
  )

  pdf(paste0("results/02_createSeurat/", snakemake@wildcards[["sample"]], "_cellhash.pdf"), width = 7.5, height = 5)
  summary_cellhashing(seurat_clean, snakemake@params[["cellhash_names"]])
  dev.off()

}

# Save to rds
saveRDS(seurat_clean, snakemake@output[["no_doublets"]])
saveRDS(seurat, snakemake@output[["raw"]])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")

library(tidyverse)

#------------------------------------------------------------------------------------------
# Load feature ref from every sample and merge it into 1
#------------------------------------------------------------------------------------------
feature_ref <- snakemake@input %>%
  purrr::map(read_csv) %>% 
  bind_rows() %>% 
  mutate(
    id    = str_replace(id, "_.*$", ""),
    name = id
  ) %>% 
  distinct() %>% 
  group_by(id) %>% 
  mutate(
    id   = paste0(id, "_", 1:n()),
    name = id
  ) %>%
  select(id, name, read, pattern, sequence, feature_type)

write_csv(feature_ref, snakemake@output[[1]])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")

library(tidyverse)

#------------------------------------------------------------------------------------------
# Load feature ref from larry/cellhashing
#------------------------------------------------------------------------------------------
if (length(snakemake@input[[1]]) == 1) {

	# If just cellhash or larry are set, return the same csv
	feature_ref <- read_csv(snakemake@input[[1]])
	write_csv(feature_ref, snakemake@output[[1]])

} else { # Otherwise combine both larry and cellhash references into 1

	larry_ref    <- read_csv(snakemake@input[["larry_ref"]])
	cellhash_ref <- read_csv(snakemake@input[["cell_hash_ref"]])

	combined_ref <- bind_rows(larry_ref, cellhash_ref)
	write_csv(combined_ref, snakemake@output[[1]])

}
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")

### Libraries
library(Seurat)
library(tidyverse)

### Read and merge seurat objects if there are multiple samples
if (length(snakemake@input)  == 1) {
    seurat <- readRDS(snakemake@input[[1]])
} else {
    seurat_objects <- map(snakemake@input, \(x) readRDS(x))
    seurat         <- merge(seurat_objects[[1]], seurat_objects[2:length(seurat_objects)] %>% unlist())
}

saveRDS(seurat, snakemake@output[["seurat"]])
20
21
22
23
24
25
26
27
28
knitr::opts_chunk$set(
    echo           = TRUE,
    error          = FALSE,
    fig.align      = "center",
    message        = FALSE,
    warning        = FALSE,
    fig.width      = 10,
    fig.height     = 8
)
32
33
34
log <- file(snakemake@log[[1]], open = "wt")
sink(log)
sink(log, type = "message")
38
39
40
41
library(Seurat)
library(tidyverse)
library(viridis)
source("workflow/scripts/R/functions.R")
45
46
47
48
49
input_file   <- snakemake@input[[1]]
marker_genes <- snakemake@params[["marker_genes"]]
species      <- snakemake@params[["species"]]
cluster_degs <- snakemake@params[["cluster_degs"]]
sample_degs  <- snakemake@params[["sample_degs"]]
53
seurat <- readRDS(input_file)
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# CC genes
data(cc.genes.updated.2019)
if (species == "mouse") {
  s.genes   <- str_to_title(cc.genes.updated.2019$s.genes)
  g2m.genes <- str_to_title(cc.genes.updated.2019$g2m.genes)
} else {
  s.genes   <- cc.genes.updated.2019$s.genes
  g2m.genes <- cc.genes.updated.2019$g2m.genes
}

# Pipeline params
n_pcs <- 25
k     <- 20

# Seurat pipeline
seurat <- seurat %>%
  NormalizeData() %>%
  FindVariableFeatures() %>%
  ScaleData() %>%
  RunPCA(npcs = n_pcs) %>%
  FindNeighbors(dims = 1:n_pcs, k.param = k) %>%
  FindClusters() %>%
  RunUMAP(dims = 1:n_pcs, n.neighbors = k, min.dist = 0.3) %>%
  CellCycleScoring(s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)

Idents(seurat) <- seurat$seurat_clusters
90
VlnPlot(seurat, features = c("percent.mt"), pt.size = 0, group.by = "sample") + theme(legend.position = "none")
96
VlnPlot(seurat, features = c("percent.ribo"), pt.size = 0, group.by = "sample") + theme(legend.position = "none")
105
VlnPlot(seurat, features = c("percent.mt"), pt.size = 0, group.by = "seurat_clusters") + theme(legend.position = "none")
111
VlnPlot(seurat, features = c("percent.ribo"), pt.size = 0, group.by = "seurat_clusters") + theme(legend.position = "none")
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
seurat_sample_plt  <- DimPlot(seurat, group.by = "sample", raster=FALSE)
seurat_cluster_plt <- DimPlot(seurat, group.by = "seurat_clusters", raster=FALSE)
seurat_cc_plt      <- DimPlot(seurat, group.by = "Phase", raster=FALSE)
seurat_RNA_plt     <- FeaturePlot(seurat, features = "nFeature_RNA", max.cutoff = "q99", raster=FALSE) + scale_color_viridis()
seurat_Count_plt   <- FeaturePlot(seurat, features = "nCount_RNA", max.cutoff = "q99", raster=FALSE) + scale_color_viridis()
seurat_mt_plt      <- FeaturePlot(seurat, features = "percent.mt", max.cutoff = "q99", raster=FALSE) + scale_color_viridis()
seurat_ribo_plt    <- FeaturePlot(seurat, features = "percent.ribo", max.cutoff = "q99", raster=FALSE) + scale_color_viridis()

l <- list(
  UMAP_sample    = seurat_sample_plt,
  UMAP_cluster   = seurat_cluster_plt,
  UMAP_CellCycle = seurat_cc_plt,
  UMAP_nGenes    = seurat_RNA_plt,
  UMAP_nCounts   = seurat_Count_plt,
  UMAP_mt        = seurat_mt_plt,
  UMAP_ribo      = seurat_ribo_plt
)

in_tabs(l, level = 1L)
142
143
144
145
146
147
148
149
detected_genes <- GetAssayData(object = seurat, slot = "data") %>% rownames()

plots <- map(
  marker_genes,
  \(gene) plot_detected_genes(seurat, detected_genes, gene)
)

in_tabs(plots, labels = marker_genes, level = 1L)
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
cluster_markers <- FindAllMarkers(seurat, only.pos = T, logfc.threshold = 0.25)
write_tsv(cluster_markers, cluster_degs)

top_9_markers <- cluster_markers %>% 
  filter(p_val_adj < 0.05) %>%
  group_by(cluster) %>%
  slice(1:9) %>%
  split(f = as.factor(paste0("Cluster ", .$cluster))) %>%
  map(pull, gene)

plots <- map(
  top_9_markers,
  \(genes) FeaturePlot(seurat, features = genes, ncol = 3, raster=FALSE) & scale_color_viridis()
)

in_tabs(plots, level = 1L)
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
Idents(seurat)  <- seurat$sample

if (length(unique(seurat$sample)) == 1) {
    print("Only 1 sample present in the seurat object, markers by sample can't be calculated.")
} else {
    sample_markers <- FindAllMarkers(seurat, only.pos = T, logfc.threshold = 0.25)
    write_tsv(sample_markers, sample_degs)
    Idents(seurat)  <- seurat$seurat_clusters

    top_9_markers <- sample_markers %>% 
      filter(p_val_adj < 0.05) %>%
      group_by(cluster) %>%
      slice(1:9) %>%
      split(f = as.factor(.$cluster)) %>%
      map(pull, gene)

    plots <- map(
      top_9_markers,
      \(genes) FeaturePlot(seurat, features = genes, ncol = 3, raster=FALSE) & scale_color_viridis()
    )

    in_tabs(plots, level = 1L)
}
ShowHide 50 more snippets with no or duplicated tags.

Login to post a comment if you would like to share your experience with this workflow.

Do you know this workflow well? If so, you can request seller status , and start supporting this workflow.

Free

Created: 1yr ago
Updated: 1yr ago
Maitainers: public
URL: https://github.com/dfernandezperez/scRNAseq-snakemake
Name: scrnaseq-snakemake
Version: v0.0.1
Badge:
workflow icon

Insert copied code into your website to add a link to this workflow.

Accessed: 1
Downloaded: 0
Copyright: Public Domain
License: None
  • Future updates

Related Workflows

cellranger-snakemake-gke
snakemake workflow to run cellranger on a given bucket using gke.
A Snakemake workflow for running cellranger on a given bucket using Google Kubernetes Engine. The usage of this workflow ...