Snakefile 24 KB
Newer Older
Sander Bollen's avatar
Sander Bollen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#   hutspot - a DNAseq variant calling pipeline
#   Copyright (C) 2017-2019, Sander Bollen, Leiden University Medical Center
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""
17
Main Snakefile for the pipeline.
Sander Bollen's avatar
Sander Bollen committed
18
19
20
21
22
23

:copyright: (c) 2017-2019 Sander Bollen
:copyright: (c) 2017-2019 Leiden University Medical Center
:license: AGPL-3.0
"""

Sander Bollen's avatar
Sander Bollen committed
24
import json
Sander Bollen's avatar
Sander Bollen committed
25
from functools import partial
Sander Bollen's avatar
Sander Bollen committed
26
from os.path import join, basename
27
from pathlib import Path
28
import itertools
Sander Bollen's avatar
Sander Bollen committed
29
30

from pyfaidx import Fasta
Sander Bollen's avatar
Sander Bollen committed
31
32

REFERENCE = config.get("REFERENCE")
33
34
if REFERENCE is None:
    raise ValueError("You must set --config REFERENCE=<path>")
Sander Bollen's avatar
Sander Bollen committed
35
if not Path(REFERENCE).exists():
Sander Bollen's avatar
Sander Bollen committed
36
37
    raise FileNotFoundError("Reference file {0} "
                            "does not exist.".format(REFERENCE))
Sander Bollen's avatar
Sander Bollen committed
38
DBSNP = config.get("DBSNP")
39
40
if DBSNP is None:
    raise ValueError("You must set --config DBSNP=<path>")
Sander Bollen's avatar
Sander Bollen committed
41
42
if not Path(DBSNP).exists():
    raise FileNotFoundError("{0} does not exist".format(DBSNP))
43

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
SCONFIG = config.get("SAMPLE_CONFIG")
if SCONFIG is None:
    raise ValueError("You must set --config SAMPLE_CONFIG=<path>")
if not Path(SCONFIG).exists():
    raise FileNotFoundError("{0} does not exist".format(SCONFIG))

KNOWN_SITES = config.get("KNOWN_SITES")
if KNOWN_SITES is None:
    raise ValueError("You must set --config KNOWN_SITES=<path>")

# The user can specify multiple known sites
KNOWN_SITES = KNOWN_SITES.split(',')
for filename in KNOWN_SITES:
    if not Path(filename).exists():
        raise FileNotFoundError("{0} does not exist".format(filename))

60
61

# these are all optional
62
63
BED = config.get("BED", "")  # comma-separated list of BED files
REFFLAT = config.get("REFFLAT", "")  # comma-separated list of refFlat files
Sander Bollen's avatar
Sander Bollen committed
64
FEMALE_THRESHOLD = config.get("FEMALE_THRESHOLD", 0.6)
Sander Bollen's avatar
Sander Bollen committed
65
MAX_BASES = config.get("MAX_BASES", "")
Sander Bollen's avatar
Sander Bollen committed
66

67
# Generate the input string for basrecalibration
68
69
70
BSQR_known_sites = ''
for argument, filename in zip(itertools.repeat('-knownSites'), KNOWN_SITES):
    BSQR_known_sites +=' {} {}'.format(argument, filename)
71

72
73
74
75
76
def fsrc_dir(*args):
    """Wrapper around snakemake's srcdir to work like os.path.join"""
    if len(args) == 1:
        return srcdir(args[0])
    return srcdir(join(*args))
Sander Bollen's avatar
Sander Bollen committed
77

78
79
80
covpy = fsrc_dir("src", "covstats.py")
colpy = fsrc_dir("src", "collect_stats.py")
mpy = fsrc_dir("src", "merge_stats.py")
Sander Bollen's avatar
Sander Bollen committed
81
seq = fsrc_dir("src", "seqtk.sh")
Sander Bollen's avatar
Sander Bollen committed
82
fqpy = fsrc_dir("src", "fastqc_stats.py")
Sander Bollen's avatar
Sander Bollen committed
83
tsvpy = fsrc_dir("src", "stats_to_tsv.py")
Sander Bollen's avatar
Sander Bollen committed
84
fqsc = fsrc_dir("src", "safe_fastqc.sh")
85
pywc = fsrc_dir("src", "pywc.py")
Sander Bollen's avatar
Sander Bollen committed
86

Sander Bollen's avatar
Sander Bollen committed
87
# sample config parsing
Sander Bollen's avatar
Sander Bollen committed
88
89
90
91
with open(config.get("SAMPLE_CONFIG")) as handle:
    SAMPLE_CONFIG = json.load(handle)
SAMPLES = SAMPLE_CONFIG['samples'].keys()

Sander Bollen's avatar
Sander Bollen committed
92
93
94
95
96
97
98
99
100
if BED != "":
    BEDS = BED.split(",")
else:
    BEDS = []

if REFFLAT != "":
    REFFLATS = REFFLAT.split(",")
else:
    REFFLATS = []
Sander Bollen's avatar
Sander Bollen committed
101
102

BASE_BEDS = [basename(x) for x in BEDS]
Sander Bollen's avatar
Sander Bollen committed
103
BASE_REFFLATS = [basename(x) for x in REFFLATS]
Sander Bollen's avatar
Sander Bollen committed
104

105
106
107
containers = {
    "bcftools": "docker://quay.io/biocontainers/bcftools:1.9--ha228f0b_4",
    "bedtools-2.26-python-2.7": "docker://quay.io/biocontainers/mulled-v2-3251e6c49d800268f0bc575f28045ab4e69475a6:4ce073b219b6dabb79d154762a9b67728c357edb-0",
van den Berg's avatar
van den Berg committed
108
    "biopet-scatterregions": "docker://quay.io/biocontainers/biopet-scatterregions:0.2--0",
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    "bwa-0.7.17-picard-2.18.7": "docker://quay.io/biocontainers/mulled-v2-002f51ea92721407ef440b921fb5940f424be842:43ec6124f9f4f875515f9548733b8b4e5fed9aa6-0",
    "cutadapt": "docker://quay.io/biocontainers/cutadapt:1.14--py36_0",
    "debian": "docker://debian:buster-slim",
    "fastq-count": "docker://quay.io/biocontainers/fastq-count:0.1.0--h14c3975_0",
    "fastqc": "docker://quay.io/biocontainers/fastqc:0.11.7--4",
    "gatk": "docker://broadinstitute/gatk3:3.7-0",
    "multiqc": "docker://quay.io/biocontainers/multiqc:1.5--py36_0",
    "picard-2.14": "docker://quay.io/biocontainers/picard:2.14--py36_0",
    "python3": "docker://python:3.6-slim",
    "samtools-1.7-python-3.6": "docker://quay.io/biocontainers/mulled-v2-eb9e7907c7a753917c1e4d7a64384c047429618a:1abf1824431ec057c7d41be6f0c40e24843acde4-0",
    "seqtk-1.2-jq-1.6": "docker://quay.io/biocontainers/mulled-v2-13686261ac0aa5682c680670ff8cda7b09637943:d143450dec169186731bb4df6f045a3c9ee08eb6-0",
    "sickle": "docker://quay.io/biocontainers/sickle-trim:1.33--ha92aebf_4",
    "tabix": "docker://quay.io/biocontainers/tabix:0.2.6--ha92aebf_0",
    "vtools": "docker://quay.io/biocontainers/vtools:1.0.0--py37h3010b51_0"
}
Sander Bollen's avatar
Sander Bollen committed
124

Sander Bollen's avatar
Sander Bollen committed
125
126
def get_r(strand, wildcards):
    """Get fastq files on a single strand for a sample"""
Sander Bollen's avatar
Sander Bollen committed
127
    s = SAMPLE_CONFIG['samples'].get(wildcards.sample)
Sander Bollen's avatar
Sander Bollen committed
128
    rs = []
129
    for l in sorted(s['libraries'].keys()):
Sander Bollen's avatar
Sander Bollen committed
130
131
        rs.append(s['libraries'][l][strand])
    return rs
Sander Bollen's avatar
Sander Bollen committed
132

Sander Bollen's avatar
Sander Bollen committed
133
134
get_r1 = partial(get_r, "R1")
get_r2 = partial(get_r, "R2")
Sander Bollen's avatar
Sander Bollen committed
135
136


Sander Bollen's avatar
Sander Bollen committed
137
def get_bedpath(wildcards):
Sander Bollen's avatar
Sander Bollen committed
138
139
    """Get absolute path of a bed file"""
    return next(x for x in BEDS if basename(x) == wildcards.bed)
Sander Bollen's avatar
Sander Bollen committed
140
141
142


def get_refflatpath(wildcards):
Sander Bollen's avatar
Sander Bollen committed
143
    """Get absolute path of a refflat file"""
Sander Bollen's avatar
Sander Bollen committed
144
    return next(x for x in REFFLATS if basename(x) == wildcards.ref)
Sander Bollen's avatar
Sander Bollen committed
145
146


Sander Bollen's avatar
Sander Bollen committed
147
def sample_gender(wildcards):
Sander Bollen's avatar
Sander Bollen committed
148
    """Get sample gender"""
Sander Bollen's avatar
Sander Bollen committed
149
150
151
152
    sam = SAMPLE_CONFIG['samples'].get(wildcards.sample)
    return sam.get("gender", "null")


Sander Bollen's avatar
Sander Bollen committed
153
154
155
156
def metrics(do_metrics=True):
    if not do_metrics:
        return ""

Sander Bollen's avatar
Sander Bollen committed
157
158
159
160
161
162
    fqcr = expand("{sample}/pre_process/raw_fastqc/.done.txt",
                  sample=SAMPLES)
    fqcm = expand("{sample}/pre_process/merged_fastqc/{sample}.merged_R1_fastqc.zip",
                  sample=SAMPLES)
    fqcp = expand("{sample}/pre_process/postqc_fastqc/{sample}.cutadapt_R1_fastqc.zip",
                  sample=SAMPLES)
163
    if len(REFFLATS) >= 1:
Sander Bollen's avatar
Sander Bollen committed
164
165
        coverage_stats = expand("{sample}/coverage/{ref}.coverages.tsv",
                                sample=SAMPLES, ref=BASE_REFFLATS)
166
167
    else:
        coverage_stats = []
Sander Bollen's avatar
Sander Bollen committed
168
    stats = "stats.json"
Sander Bollen's avatar
Sander Bollen committed
169
    return  fqcr + fqcm + fqcp + coverage_stats + [stats]
Sander Bollen's avatar
Sander Bollen committed
170
171


Sander Bollen's avatar
Sander Bollen committed
172
173
rule all:
    input:
174
175
        #combined="multisample/genotyped.vcf.gz",
        #report="multiqc_report/multiqc_report.html",
Sander Bollen's avatar
Sander Bollen committed
176
        bais=expand("{sample}/bams/{sample}.markdup.bam.bai",sample=SAMPLES),
177
178
        vcfs=expand("{sample}/vcf/{sample}.vcf.gz",sample=SAMPLES),
        #stats=metrics()
Sander Bollen's avatar
Sander Bollen committed
179

Sander Bollen's avatar
Sander Bollen committed
180
181
182

rule create_markdup_tmp:
    """Create tmp directory for mark duplicates"""
183
    output: directory("tmp")
184
    singularity: containers["debian"]
Sander Bollen's avatar
Sander Bollen committed
185
186
    shell: "mkdir -p {output}"

Sander Bollen's avatar
Sander Bollen committed
187
rule genome:
Sander Bollen's avatar
Sander Bollen committed
188
    """Create genome file as used by bedtools"""
Sander Bollen's avatar
Sander Bollen committed
189
    input: REFERENCE
Sander Bollen's avatar
Sander Bollen committed
190
    output: "current.genome"
191
    singularity: containers["debian"]
Sander Bollen's avatar
Sander Bollen committed
192
193
194
    shell: "awk -v OFS='\t' {{'print $1,$2'}} {input}.fai > {output}"

rule merge_r1:
Sander Bollen's avatar
Sander Bollen committed
195
    """Merge all forward fastq files into one"""
Sander Bollen's avatar
Sander Bollen committed
196
    input: get_r1
Sander Bollen's avatar
Sander Bollen committed
197
    output: temp("{sample}/pre_process/{sample}.merged_R1.fastq.gz")
198
    singularity: containers["debian"]
Sander Bollen's avatar
Sander Bollen committed
199
200
201
    shell: "cat {input} > {output}"

rule merge_r2:
Sander Bollen's avatar
Sander Bollen committed
202
    """Merge all reverse fastq files into one"""
Sander Bollen's avatar
Sander Bollen committed
203
    input: get_r2
Sander Bollen's avatar
Sander Bollen committed
204
    output: temp("{sample}/pre_process/{sample}.merged_R2.fastq.gz")
205
    singularity: containers["debian"]
Sander Bollen's avatar
Sander Bollen committed
206
207
    shell: "cat {input} > {output}"

Sander Bollen's avatar
Sander Bollen committed
208
209

rule seqtk_r1:
Sander Bollen's avatar
Sander Bollen committed
210
    """Either subsample or link forward fastq file"""
Sander Bollen's avatar
Sander Bollen committed
211
    input:
Sander Bollen's avatar
Sander Bollen committed
212
213
        stats="{sample}/pre_process/{sample}.preqc_count.json",
        fastq="{sample}/pre_process/{sample}.merged_R1.fastq.gz",
Sander Bollen's avatar
Sander Bollen committed
214
        seqtk=seq
Sander Bollen's avatar
Sander Bollen committed
215
    params:
Sander Bollen's avatar
Sander Bollen committed
216
        max_bases=str(MAX_BASES)
Sander Bollen's avatar
Sander Bollen committed
217
    output:
Sander Bollen's avatar
Sander Bollen committed
218
        fastq=temp("{sample}/pre_process/{sample}.sampled_R1.fastq.gz")
219
    singularity: containers["seqtk-1.2-jq-1.6"]
Sander Bollen's avatar
Sander Bollen committed
220
221
    shell: "bash {input.seqtk} {input.stats} {input.fastq} {output.fastq} "
           "{params.max_bases}"
Sander Bollen's avatar
Sander Bollen committed
222
223
224


rule seqtk_r2:
Sander Bollen's avatar
Sander Bollen committed
225
    """Either subsample or link reverse fastq file"""
Sander Bollen's avatar
Sander Bollen committed
226
    input:
Sander Bollen's avatar
Sander Bollen committed
227
228
        stats = "{sample}/pre_process/{sample}.preqc_count.json",
        fastq = "{sample}/pre_process/{sample}.merged_R2.fastq.gz",
Sander Bollen's avatar
Sander Bollen committed
229
        seqtk=seq
Sander Bollen's avatar
Sander Bollen committed
230
    params:
Sander Bollen's avatar
Sander Bollen committed
231
        max_bases =str(MAX_BASES)
Sander Bollen's avatar
Sander Bollen committed
232
    output:
Sander Bollen's avatar
Sander Bollen committed
233
        fastq = temp("{sample}/pre_process/{sample}.sampled_R2.fastq.gz")
234
    singularity: containers["seqtk-1.2-jq-1.6"]
Sander Bollen's avatar
Sander Bollen committed
235
236
    shell: "bash {input.seqtk} {input.stats} {input.fastq} {output.fastq} "
           "{params.max_bases}"
Sander Bollen's avatar
Sander Bollen committed
237
238


239
# contains original merged fastq files as input to prevent them from being prematurely deleted
Sander Bollen's avatar
Sander Bollen committed
240
rule sickle:
Sander Bollen's avatar
Sander Bollen committed
241
    """Trim fastq files"""
Sander Bollen's avatar
Sander Bollen committed
242
    input:
Sander Bollen's avatar
Sander Bollen committed
243
244
245
246
        r1 = "{sample}/pre_process/{sample}.sampled_R1.fastq.gz",
        r2 = "{sample}/pre_process/{sample}.sampled_R2.fastq.gz",
        rr1 = "{sample}/pre_process/{sample}.merged_R1.fastq.gz",
        rr2 = "{sample}/pre_process/{sample}.merged_R2.fastq.gz"
Sander Bollen's avatar
Sander Bollen committed
247
    output:
Sander Bollen's avatar
Sander Bollen committed
248
249
        r1 = temp("{sample}/pre_process/{sample}.trimmed_R1.fastq"),
        r2 = temp("{sample}/pre_process/{sample}.trimmed_R2.fastq"),
Sander Bollen's avatar
Sander Bollen committed
250
        s = "{sample}/pre_process/{sample}.trimmed_singles.fastq"
251
    singularity: containers["sickle"]
Sander Bollen's avatar
Sander Bollen committed
252
    shell: "sickle pe -f {input.r1} -r {input.r2} -t sanger -o {output.r1} "
Sander Bollen's avatar
Sander Bollen committed
253
254
255
           "-p {output.r2} -s {output.s}"

rule cutadapt:
Sander Bollen's avatar
Sander Bollen committed
256
    """Clip fastq files"""
Sander Bollen's avatar
Sander Bollen committed
257
    input:
Sander Bollen's avatar
Sander Bollen committed
258
259
        r1 = "{sample}/pre_process/{sample}.trimmed_R1.fastq",
        r2 = "{sample}/pre_process/{sample}.trimmed_R2.fastq"
Sander Bollen's avatar
Sander Bollen committed
260
    output:
Sander Bollen's avatar
Sander Bollen committed
261
262
        r1 = temp("{sample}/pre_process/{sample}.cutadapt_R1.fastq"),
        r2 = temp("{sample}/pre_process/{sample}.cutadapt_R2.fastq")
263
    singularity: containers["cutadapt"]
Sander Bollen's avatar
Sander Bollen committed
264
    shell: "cutadapt -a AGATCGGAAGAG -A AGATCGGAAGAG -m 1 -o {output.r1} "
Sander Bollen's avatar
Sander Bollen committed
265
266
267
           "{input.r1} -p {output.r2} {input.r2}"

rule align:
Sander Bollen's avatar
Sander Bollen committed
268
    """Align fastq files"""
Sander Bollen's avatar
Sander Bollen committed
269
    input:
Sander Bollen's avatar
Sander Bollen committed
270
271
        r1 = "{sample}/pre_process/{sample}.cutadapt_R1.fastq",
        r2 = "{sample}/pre_process/{sample}.cutadapt_R2.fastq",
Sander Bollen's avatar
Sander Bollen committed
272
        ref = REFERENCE,
273
        tmp = ancient("tmp")
Sander Bollen's avatar
Sander Bollen committed
274
275
    params:
        rg = "@RG\\tID:{sample}_lib1\\tSM:{sample}\\tPL:ILLUMINA"
Sander Bollen's avatar
Sander Bollen committed
276
    output: temp("{sample}/bams/{sample}.sorted.bam")
277
    singularity: containers["bwa-0.7.17-picard-2.18.7"]
Sander Bollen's avatar
Sander Bollen committed
278
    shell: "bwa mem -t 8 -R '{params.rg}' {input.ref} {input.r1} {input.r2} "
279
280
           "| picard -Xmx4G -Djava.io.tmpdir={input.tmp} SortSam "
           "CREATE_INDEX=TRUE TMP_DIR={input.tmp} "
Sander Bollen's avatar
Sander Bollen committed
281
282
283
           "INPUT=/dev/stdin OUTPUT={output} SORT_ORDER=coordinate"

rule markdup:
Sander Bollen's avatar
Sander Bollen committed
284
    """Mark duplicates in BAM file"""
Sander Bollen's avatar
Sander Bollen committed
285
    input:
Sander Bollen's avatar
Sander Bollen committed
286
        bam = "{sample}/bams/{sample}.sorted.bam",
Sander Bollen's avatar
Sander Bollen committed
287
        tmp = ancient("tmp")
Sander Bollen's avatar
Sander Bollen committed
288
    output:
Sander Bollen's avatar
Sander Bollen committed
289
290
291
        bam = "{sample}/bams/{sample}.markdup.bam",
        bai = "{sample}/bams/{sample}.markdup.bai",
        metrics = "{sample}/bams/{sample}.markdup.metrics"
292
    singularity: containers["picard-2.14"]
293
294
    shell: "picard -Xmx4G -Djava.io.tmpdir={input.tmp} MarkDuplicates "
           "CREATE_INDEX=TRUE TMP_DIR={input.tmp} "
Sander Bollen's avatar
Sander Bollen committed
295
296
           "INPUT={input.bam} OUTPUT={output.bam} "
           "METRICS_FILE={output.metrics} "
Sander Bollen's avatar
Sander Bollen committed
297
298
           "MAX_FILE_HANDLES_FOR_READ_ENDS_MAP=500"

Sander Bollen's avatar
Sander Bollen committed
299
300
301
rule bai:
    """Copy bai files as some genome browsers can only .bam.bai files"""
    input:
Sander Bollen's avatar
Sander Bollen committed
302
        bai = "{sample}/bams/{sample}.markdup.bai"
Sander Bollen's avatar
Sander Bollen committed
303
    output:
Sander Bollen's avatar
Sander Bollen committed
304
        bai = "{sample}/bams/{sample}.markdup.bam.bai"
305
    singularity: containers["debian"]
Sander Bollen's avatar
Sander Bollen committed
306
307
    shell: "cp {input.bai} {output.bai}"

Sander Bollen's avatar
Sander Bollen committed
308
rule baserecal:
Sander Bollen's avatar
Sander Bollen committed
309
    """Base recalibrated BAM files"""
Sander Bollen's avatar
Sander Bollen committed
310
    input:
Sander Bollen's avatar
Sander Bollen committed
311
        bam = "{sample}/bams/{sample}.markdup.bam",
Sander Bollen's avatar
Sander Bollen committed
312
313
        ref = REFERENCE,
    output:
Sander Bollen's avatar
Sander Bollen committed
314
        grp = "{sample}/bams/{sample}.baserecal.grp"
315
    params:
316
        known_sites = BSQR_known_sites
317
    singularity: containers["gatk"]
318
    shell: "java -XX:ParallelGCThreads=1 -jar /usr/GenomeAnalysisTK.jar -T "
Sander Bollen's avatar
Sander Bollen committed
319
320
           "BaseRecalibrator -I {input.bam} -o {output.grp} -nct 8 "
           "-R {input.ref} -cov ReadGroupCovariate -cov QualityScoreCovariate "
321
           "-cov CycleCovariate -cov ContextCovariate {params.known_sites}"
Sander Bollen's avatar
Sander Bollen committed
322

van den Berg's avatar
van den Berg committed
323
324
325
326
327
rule scatterregions:
    """Scatter the reference genome"""
    input:
        ref = REFERENCE,
    output:
van den Berg's avatar
van den Berg committed
328
        regions = dynamic("scatter/scatter-{chunk}.bed")
van den Berg's avatar
van den Berg committed
329
330
331
332
333
334
    singularity: containers["biopet-scatterregions"]
    shell: "mkdir -p scatter && "
           "biopet-scatterregions "
           "--referenceFasta {input.ref} --scatterSize 1000 "
           "--outputDir scatter"

Sander Bollen's avatar
Sander Bollen committed
335
rule gvcf_scatter:
Sander Bollen's avatar
Sander Bollen committed
336
    """Run HaplotypeCaller in GVCF mode by chunk"""
Sander Bollen's avatar
Sander Bollen committed
337
    input:
Sander Bollen's avatar
Sander Bollen committed
338
339
        bam="{sample}/bams/{sample}.markdup.bam",
        bqsr="{sample}/bams/{sample}.baserecal.grp",
Sander Bollen's avatar
Sander Bollen committed
340
        dbsnp=DBSNP,
Sander Bollen's avatar
Sander Bollen committed
341
        ref=REFERENCE,
van den Berg's avatar
van den Berg committed
342
        region="scatter/scatter-{chunk}.bed"
Sander Bollen's avatar
Sander Bollen committed
343
    output:
Sander Bollen's avatar
Sander Bollen committed
344
345
        gvcf=temp("{sample}/vcf/{sample}.{chunk}.part.vcf.gz"),
        gvcf_tbi=temp("{sample}/vcf/{sample}.{chunk}.part.vcf.gz.tbi")
346
    singularity: containers["gatk"]
347
    shell: "java -jar -Xmx4G -XX:ParallelGCThreads=1 /usr/GenomeAnalysisTK.jar "
Sander Bollen's avatar
Sander Bollen committed
348
           "-T HaplotypeCaller -ERC GVCF -I "
Sander Bollen's avatar
Sander Bollen committed
349
           "{input.bam} -R {input.ref} -D {input.dbsnp} "
van den Berg's avatar
van den Berg committed
350
           "-L '{input.region}' -o '{output.gvcf}' "
Sander Bollen's avatar
Sander Bollen committed
351
           "-variant_index_type LINEAR -variant_index_parameter 128000 "
Sander Bollen's avatar
Sander Bollen committed
352
           "-BQSR {input.bqsr}"
Sander Bollen's avatar
Sander Bollen committed
353

Sander Bollen's avatar
Sander Bollen committed
354
rule gvcf_gather:
Sander Bollen's avatar
Sander Bollen committed
355
    """Gather all GVCF scatters"""
Sander Bollen's avatar
Sander Bollen committed
356
    input:
van den Berg's avatar
van den Berg committed
357
        gvcfs = dynamic("{sample}/vcf/{sample}.{chunk}.part.vcf.gz"),
Sander Bollen's avatar
Sander Bollen committed
358
    output:
Sander Bollen's avatar
Sander Bollen committed
359
        gvcf = "{sample}/vcf/{sample}.g.vcf.gz"
360
    singularity: containers["bcftools"]
van den Berg's avatar
van den Berg committed
361
    shell: "bcftools concat {input.gvcfs} -n > {output.gvcf}"
Sander Bollen's avatar
Sander Bollen committed
362
363
364
365
366
367
368
369


rule gvcf_gather_tbi:
    """Index GVCF"""
    input:
        gvcf = "{sample}/vcf/{sample}.g.vcf.gz"
    output:
        tbi = "{sample}/vcf/{sample}.g.vcf.gz.tbi"
370
    singularity: containers["tabix"]
Sander Bollen's avatar
Sander Bollen committed
371
    shell: "tabix -pvcf {input.gvcf}"
Sander Bollen's avatar
Sander Bollen committed
372
373
374


rule genotype_scatter:
Sander Bollen's avatar
Sander Bollen committed
375
    """Run GATK's GenotypeGVCFs by chunk"""
Sander Bollen's avatar
Sander Bollen committed
376
    input:
377
378
        gvcf = "{sample}/vcf/{sample}.g.vcf.gz",
        tbi = "{sample}/vcf/{sample}.g.vcf.gz.tbi",
van den Berg's avatar
van den Berg committed
379
        ref=REFERENCE,
380
        region=dynamic("scatter/scatter-{chunk}.bed")
Sander Bollen's avatar
Sander Bollen committed
381
    params:
382
        li=" -V ".join("{sample}/vcf/{sample}.g.vcf.gz")
Sander Bollen's avatar
Sander Bollen committed
383
    output:
384
385
        vcf=dynamic("{sample}/vcf/{sample}.genotype.{chunk}.part.vcf.gz"),
        vcf_tbi=dynamic("{sample}/vcf/{sample}.genotype.{chunk}.part.vcf.gz.tbi")
386
    singularity: containers["gatk"]
387
    shell: "java -jar -Xmx15G -XX:ParallelGCThreads=1 /usr/GenomeAnalysisTK.jar -T "
Sander Bollen's avatar
Sander Bollen committed
388
           "GenotypeGVCFs -R {input.ref} "
van den Berg's avatar
van den Berg committed
389
           "-V {params.li} -L '{input.region}' -o '{output.vcf}'"
390
391


Sander Bollen's avatar
Sander Bollen committed
392
rule genotype_gather:
393
    """Gather all genotyping VCFs"""
Sander Bollen's avatar
Sander Bollen committed
394
    input:
395
        vcfs = dynamic("{sample}/vcf/{sample}.genotype.{chunk}.part.vcf.gz"),
Sander Bollen's avatar
Sander Bollen committed
396
    output:
397
        vcf = "{sample}/vcf/{sample}.vcf.gz"
398
    singularity: containers["bcftools"]
van den Berg's avatar
van den Berg committed
399
    shell: "bcftools concat {input.vcfs} -n > {output.vcf}"
400
401
402
403
404


rule genotype_gather_tbi:
    """Index genotyped vcf file"""
    input:
405
        vcf = "{sample}/vcf/{sample}.vcf.gz"
406
    output:
407
        tbi = "{sample}/vcf/{sample}.vcf.gz.tbi"
408
    singularity: containers["tabix"]
409
    shell: "tabix -pvcf {input.vcf}"
Sander Bollen's avatar
Sander Bollen committed
410
411


Sander Bollen's avatar
Sander Bollen committed
412
## bam metrics
413
rule mapped_reads_bases:
Sander Bollen's avatar
Sander Bollen committed
414
    """Calculate number of mapped reads"""
Sander Bollen's avatar
Sander Bollen committed
415
    input:
416
417
        bam="{sample}/bams/{sample}.sorted.bam",
        pywc=pywc
Sander Bollen's avatar
Sander Bollen committed
418
    output:
419
420
        reads="{sample}/bams/{sample}.mapped.num",
        bases="{sample}/bams/{sample}.mapped.basenum"
421
    singularity: containers["samtools-1.7-python-3.6"]
422
423
    shell: "samtools view -F 4 {input.bam} | cut -f 10 | python {input.pywc} "
           "--reads {output.reads} --bases {output.bases}"
Sander Bollen's avatar
Sander Bollen committed
424
425


426
rule unique_reads_bases:
Sander Bollen's avatar
Sander Bollen committed
427
    """Calculate number of unique reads"""
Sander Bollen's avatar
Sander Bollen committed
428
    input:
429
430
        bam="{sample}/bams/{sample}.markdup.bam",
        pywc=pywc
Sander Bollen's avatar
Sander Bollen committed
431
    output:
432
433
        reads="{sample}/bams/{sample}.unique.num",
        bases="{sample}/bams/{sample}.usable.basenum"
434
    singularity: containers["samtools-1.7-python-3.6"]
435
436
    shell: "samtools view -F 4 -F 1024 {input.bam} | cut -f 10 | python {input.pywc} "
           "--reads {output.reads} --bases {output.bases}"
Sander Bollen's avatar
Sander Bollen committed
437
438
439
440


## fastqc

Sander Bollen's avatar
Sander Bollen committed
441
rule fastqc_raw:
442
443
    """
    Run fastqc on raw fastq files
444
    NOTE: singularity version uses 0.11.7 in stead of 0.11.5 due to
445
446
    perl missing in the container of 0.11.5
    """
Sander Bollen's avatar
Sander Bollen committed
447
    input:
Sander Bollen's avatar
Sander Bollen committed
448
        r1=get_r1,
Sander Bollen's avatar
Sander Bollen committed
449
450
        r2=get_r2
    params:
Sander Bollen's avatar
Sander Bollen committed
451
        odir="{sample}/pre_process/raw_fastqc"
Sander Bollen's avatar
Sander Bollen committed
452
    output:
Sander Bollen's avatar
Sander Bollen committed
453
        aux="{sample}/pre_process/raw_fastqc/.done.txt"
454
    singularity: containers["fastqc"]
van den Berg's avatar
van den Berg committed
455
    shell: "fastqc --threads 4 --nogroup -o {params.odir} {input.r1} {input.r2} "
Sander Bollen's avatar
Sander Bollen committed
456
           "&& echo 'done' > {output.aux}"
Sander Bollen's avatar
Sander Bollen committed
457
458


Sander Bollen's avatar
Sander Bollen committed
459
rule fastqc_merged:
460
    """
461
462
    Run fastqc on merged fastq files
    NOTE: singularity version uses 0.11.7 in stead of 0.11.5 due to
463
464
    perl missing in the container of 0.11.5
    """
Sander Bollen's avatar
Sander Bollen committed
465
    input:
Sander Bollen's avatar
Sander Bollen committed
466
467
        r1="{sample}/pre_process/{sample}.merged_R1.fastq.gz",
        r2="{sample}/pre_process/{sample}.merged_R2.fastq.gz",
Sander Bollen's avatar
Sander Bollen committed
468
        fq=fqsc
Sander Bollen's avatar
Sander Bollen committed
469
    params:
Sander Bollen's avatar
Sander Bollen committed
470
        odir="{sample}/pre_process/merged_fastqc"
Sander Bollen's avatar
Sander Bollen committed
471
    output:
Sander Bollen's avatar
Sander Bollen committed
472
473
        r1="{sample}/pre_process/merged_fastqc/{sample}.merged_R1_fastqc.zip",
        r2="{sample}/pre_process/merged_fastqc/{sample}.merged_R2_fastqc.zip"
474
    singularity: containers["fastqc"]
Sander Bollen's avatar
Sander Bollen committed
475
476
    shell: "bash {input.fq} {input.r1} {input.r2} "
           "{output.r1} {output.r2} {params.odir}"
Sander Bollen's avatar
Sander Bollen committed
477
478


Sander Bollen's avatar
Sander Bollen committed
479
rule fastqc_postqc:
480
481
    """
    Run fastqc on fastq files post pre-processing
482
483
    NOTE: singularity version uses 0.11.7 in stead of 0.11.5 due to
    perl missing in the container of 0.11.5
484
    """
Sander Bollen's avatar
Sander Bollen committed
485
    input:
Sander Bollen's avatar
Sander Bollen committed
486
487
        r1="{sample}/pre_process/{sample}.cutadapt_R1.fastq",
        r2="{sample}/pre_process/{sample}.cutadapt_R2.fastq",
Sander Bollen's avatar
Sander Bollen committed
488
        fq=fqsc
Sander Bollen's avatar
Sander Bollen committed
489
    params:
Sander Bollen's avatar
Sander Bollen committed
490
        odir="{sample}/pre_process/postqc_fastqc"
Sander Bollen's avatar
Sander Bollen committed
491
    output:
Sander Bollen's avatar
Sander Bollen committed
492
493
        r1="{sample}/pre_process/postqc_fastqc/{sample}.cutadapt_R1_fastqc.zip",
        r2="{sample}/pre_process/postqc_fastqc/{sample}.cutadapt_R2_fastqc.zip"
494
    singularity: containers["fastqc"]
Sander Bollen's avatar
Sander Bollen committed
495
496
    shell: "bash {input.fq} {input.r1} {input.r2} "
           "{output.r1} {output.r2} {params.odir}"
Sander Bollen's avatar
Sander Bollen committed
497
498
499
500
501


## fastq-count

rule fqcount_preqc:
Sander Bollen's avatar
Sander Bollen committed
502
    """Calculate number of reads and bases before pre-processing"""
Sander Bollen's avatar
Sander Bollen committed
503
    input:
Sander Bollen's avatar
Sander Bollen committed
504
505
        r1="{sample}/pre_process/{sample}.merged_R1.fastq.gz",
        r2="{sample}/pre_process/{sample}.merged_R2.fastq.gz"
Sander Bollen's avatar
Sander Bollen committed
506
    output:
Sander Bollen's avatar
Sander Bollen committed
507
        "{sample}/pre_process/{sample}.preqc_count.json"
508
    singularity: containers["fastq-count"]
Sander Bollen's avatar
Sander Bollen committed
509
    shell: "fastq-count {input.r1} {input.r2} > {output}"
Sander Bollen's avatar
Sander Bollen committed
510
511
512


rule fqcount_postqc:
Sander Bollen's avatar
Sander Bollen committed
513
    """Calculate number of reads and bases after pre-processing"""
Sander Bollen's avatar
Sander Bollen committed
514
    input:
Sander Bollen's avatar
Sander Bollen committed
515
516
        r1="{sample}/pre_process/{sample}.cutadapt_R1.fastq",
        r2="{sample}/pre_process/{sample}.cutadapt_R2.fastq"
Sander Bollen's avatar
Sander Bollen committed
517
    output:
Sander Bollen's avatar
Sander Bollen committed
518
        "{sample}/pre_process/{sample}.postqc_count.json"
519
    singularity: containers["fastq-count"]
Sander Bollen's avatar
Sander Bollen committed
520
    shell: "fastq-count {input.r1} {input.r2} > {output}"
Sander Bollen's avatar
Sander Bollen committed
521
522


Sander Bollen's avatar
Sander Bollen committed
523
524
525
526
# fastqc stats
rule fastqc_stats:
    """Collect fastq stats for a sample in json format"""
    input:
Sander Bollen's avatar
Sander Bollen committed
527
528
529
530
        preqc_r1="{sample}/pre_process/merged_fastqc/{sample}.merged_R1_fastqc.zip",
        preqc_r2="{sample}/pre_process/merged_fastqc/{sample}.merged_R2_fastqc.zip",
        postqc_r1="{sample}/pre_process/postqc_fastqc/{sample}.cutadapt_R1_fastqc.zip",
        postqc_r2="{sample}/pre_process/postqc_fastqc/{sample}.cutadapt_R2_fastqc.zip",
Sander Bollen's avatar
Sander Bollen committed
531
        sc=fqpy
532
    singularity: containers["python3"]
Sander Bollen's avatar
Sander Bollen committed
533
    output:
Sander Bollen's avatar
Sander Bollen committed
534
        "{sample}/pre_process/fastq_stats.json"
535
536
537
    shell: "python {input.sc} --preqc-r1 {input.preqc_r1} "
           "--preqc-r2 {input.preqc_r2} "
           "--postqc-r1 {input.postqc_r1} "
Sander Bollen's avatar
Sander Bollen committed
538
           "--postqc-r2 {input.postqc_r2} > {output}"
Sander Bollen's avatar
Sander Bollen committed
539

Sander Bollen's avatar
Sander Bollen committed
540
541
542
## coverages

rule covstats:
Sander Bollen's avatar
Sander Bollen committed
543
    """Calculate coverage statistics on bam file"""
Sander Bollen's avatar
Sander Bollen committed
544
    input:
Sander Bollen's avatar
Sander Bollen committed
545
546
        bam="{sample}/bams/{sample}.markdup.bam",
        genome="current.genome",
Sander Bollen's avatar
Sander Bollen committed
547
548
549
550
551
        covpy=covpy,
        bed=get_bedpath
    params:
        subt="Sample {sample}"
    output:
Sander Bollen's avatar
Sander Bollen committed
552
553
        covj="{sample}/coverage/{bed}.covstats.json",
        covp="{sample}/coverage/{bed}.covstats.png"
554
    singularity: containers["bedtools-2.26-python-2.7"]
Sander Bollen's avatar
Sander Bollen committed
555
556
557
558
    shell: "bedtools coverage -sorted -g {input.genome} -a {input.bed} "
           "-b {input.bam} -d  | python {input.covpy} - --plot {output.covp} "
           "--title 'Targets coverage' --subtitle '{params.subt}' "
           "> {output.covj}"
Sander Bollen's avatar
Sander Bollen committed
559
560


Sander Bollen's avatar
Sander Bollen committed
561
562
563
rule vtools_coverage:
    """Calculate coverage statistics per transcript"""
    input:
Sander Bollen's avatar
Sander Bollen committed
564
        gvcf="{sample}/vcf/{sample}.g.vcf.gz",
Sander Bollen's avatar
Sander Bollen committed
565
        tbi = "{sample}/vcf/{sample}.g.vcf.gz.tbi",
Sander Bollen's avatar
Sander Bollen committed
566
567
        ref=get_refflatpath
    output:
Sander Bollen's avatar
Sander Bollen committed
568
        tsv="{sample}/coverage/{ref}.coverages.tsv"
569
    singularity: containers["vtools"]
Sander Bollen's avatar
Sander Bollen committed
570
571
572
    shell: "vtools-gcoverage -I {input.gvcf} -R {input.ref} > {output.tsv}"


Sander Bollen's avatar
Sander Bollen committed
573
574
575
## vcfstats

rule vcfstats:
Sander Bollen's avatar
Sander Bollen committed
576
    """Calculate vcf statistics"""
Sander Bollen's avatar
Sander Bollen committed
577
    input:
578
579
        vcf="{sample}/vcf/{sample}.vcf.gz",
        tbi = "{sample}/vcf{sample}.vcf.gz.tbi"
Sander Bollen's avatar
Sander Bollen committed
580
    output:
581
        stats="{sampel}/vcf/{sample}.vcfstats.json"
582
    singularity: containers["vtools"]
Sander Bollen's avatar
Sander Bollen committed
583
    shell: "vtools-stats -i {input.vcf} > {output.stats}"
Sander Bollen's avatar
Sander Bollen committed
584
585


Sander Bollen's avatar
Sander Bollen committed
586
## collection
587
588
589
590
if len(BASE_BEDS) >= 1:
    rule collectstats:
        """Collect all stats for a particular sample with beds"""
        input:
Sander Bollen's avatar
Sander Bollen committed
591
592
593
594
595
596
597
            preqc="{sample}/pre_process/{sample}.preqc_count.json",
            postq="{sample}/pre_process/{sample}.postqc_count.json",
            mnum="{sample}/bams/{sample}.mapped.num",
            mbnum="{sample}/bams/{sample}.mapped.basenum",
            unum="{sample}/bams/{sample}.unique.num",
            ubnum="{sample}/bams/{sample}.usable.basenum",
            fastqc="{sample}/pre_process/fastq_stats.json",
Sander Bollen's avatar
Sander Bollen committed
598
599
            cov=expand("{{sample}}/coverage/{bed}.covstats.json",
                       bed=BASE_BEDS),
600
601
602
603
604
            colpy=colpy
        params:
            sample_name="{sample}",
            fthresh=FEMALE_THRESHOLD
        output:
Sander Bollen's avatar
Sander Bollen committed
605
            "{sample}/{sample}.stats.json"
606
        singularity: containers["vtools"]
607
608
609
610
        shell: "python {input.colpy} --sample-name {params.sample_name} "
               "--pre-qc-fastq {input.preqc} --post-qc-fastq {input.postq} "
               "--mapped-num {input.mnum} --mapped-basenum {input.mbnum} "
               "--unique-num {input.unum} --usable-basenum {input.ubnum} "
611
612
               "--female-threshold {params.fthresh} "
               "--fastqc-stats {input.fastqc} {input.cov} > {output}"
613
614
else:
    rule collectstats:
Sander Bollen's avatar
Sander Bollen committed
615
        """Collect all stats for a particular sample without beds"""
Sander Bollen's avatar
Sander Bollen committed
616
        input:
Sander Bollen's avatar
Sander Bollen committed
617
618
619
620
621
622
623
            preqc = "{sample}/pre_process/{sample}.preqc_count.json",
            postq = "{sample}/pre_process/{sample}.postqc_count.json",
            mnum = "{sample}/bams/{sample}.mapped.num",
            mbnum = "{sample}/bams/{sample}.mapped.basenum",
            unum = "{sample}/bams/{sample}.unique.num",
            ubnum = "{sample}/bams/{sample}.usable.basenum",
            fastqc="{sample}/pre_process/fastq_stats.json",
Sander Bollen's avatar
Sander Bollen committed
624
625
626
627
628
            colpy = colpy
        params:
            sample_name = "{sample}",
            fthresh = FEMALE_THRESHOLD
        output:
Sander Bollen's avatar
Sander Bollen committed
629
            "{sample}/{sample}.stats.json"
630
        singularity: containers["vtools"]
Sander Bollen's avatar
Sander Bollen committed
631
632
633
634
        shell: "python {input.colpy} --sample-name {params.sample_name} "
               "--pre-qc-fastq {input.preqc} --post-qc-fastq {input.postq} "
               "--mapped-num {input.mnum} --mapped-basenum {input.mbnum} "
               "--unique-num {input.unum} --usable-basenum {input.ubnum} "
635
636
               "--female-threshold {params.fthresh} "
               "--fastqc-stats {input.fastqc}  > {output}"
Sander Bollen's avatar
Sander Bollen committed
637
638

rule merge_stats:
Sander Bollen's avatar
Sander Bollen committed
639
    """Merge all stats of all samples"""
Sander Bollen's avatar
Sander Bollen committed
640
    input:
Sander Bollen's avatar
Sander Bollen committed
641
        cols=expand("{sample}/{sample}.stats.json", sample=SAMPLES),
642
        vstat="{sample}/vcf/{sample}.vcfstats.json",
Sander Bollen's avatar
Sander Bollen committed
643
644
        mpy=mpy
    output:
Sander Bollen's avatar
Sander Bollen committed
645
        stats="stats.json"
646
    singularity: containers["vtools"]
Sander Bollen's avatar
Sander Bollen committed
647
648
    shell: "python {input.mpy} --vcfstats {input.vstat} {input.cols} "
           "> {output.stats}"
Sander Bollen's avatar
Sander Bollen committed
649
650


Sander Bollen's avatar
Sander Bollen committed
651
652
653
rule stats_tsv:
    """Convert stats.json to tsv"""
    input:
Sander Bollen's avatar
Sander Bollen committed
654
        stats="stats.json",
Sander Bollen's avatar
Sander Bollen committed
655
656
        sc=tsvpy
    output:
Sander Bollen's avatar
Sander Bollen committed
657
        stats="stats.tsv"
658
    singularity: containers["python3"]
Sander Bollen's avatar
Sander Bollen committed
659
660
661
    shell: "python {input.sc} -i {input.stats} > {output.stats}"


Sander Bollen's avatar
Sander Bollen committed
662
663
664
rule multiqc:
    """
    Create multiQC report
Sander Bollen's avatar
Sander Bollen committed
665
    Depends on stats.tsv to forcefully run at end of pipeline
Sander Bollen's avatar
Sander Bollen committed
666
667
    """
    input:
Sander Bollen's avatar
Sander Bollen committed
668
        stats="stats.tsv"
Sander Bollen's avatar
Sander Bollen committed
669
    params:
Sander Bollen's avatar
Sander Bollen committed
670
        odir=".",
Sander Bollen's avatar
Sander Bollen committed
671
        rdir="multiqc_report"
Sander Bollen's avatar
Sander Bollen committed
672
    output:
Sander Bollen's avatar
Sander Bollen committed
673
        report="multiqc_report/multiqc_report.html"
674
    singularity: containers["multiqc"]
675
    shell: "multiqc -f -o {params.rdir} {params.odir} || touch {output.report}"