iCLIP.snakefile 32.4 KB
Newer Older
Blaise Li's avatar
Blaise Li committed
1
2
3
4
5
6
7
8
9
10
11
12
"""
Snakefile to process iCLIP data.
"""
import sys
major, minor = sys.version_info[:2]
if major < 3 or (major == 3 and minor < 6):
    sys.exit("Need at least python 3.6\n")


import os
OPJ = os.path.join
from glob import glob
13
from subprocess import CalledProcessError
Blaise Li's avatar
Blaise Li committed
14
15

from collections import defaultdict
16
from itertools import product
Blaise Li's avatar
Blaise Li committed
17
18
19
20
21
22
23
24
25
26
27
28

import matplotlib as mpl
# To be able to run the script without a defined $DISPLAY
mpl.use("PDF")
#mpl.rcParams["figure.figsize"] = 2, 4
mpl.rcParams["font.sans-serif"] = [
    "Arial", "Liberation Sans", "Bitstream Vera Sans"]
mpl.rcParams["font.family"] = "sans-serif"
#mpl.rcParams["figure.figsize"] = [16, 30]
import pandas as pd
import matplotlib.pyplot as plt

29
from libhts import make_empty_bigwig, median_ratio_to_pseudo_ref_size_factors, plot_histo
30
from libworkflows import get_chrom_sizes, cleanup_and_backup
31
32
from libworkflows import last_lines, ensure_relative, SHELL_FUNCTIONS, warn_context
from libworkflows import feature_orientation2stranded, read_feature_counts, sum_feature_counts
Blaise Li's avatar
Blaise Li committed
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
from smincludes import rules as irules

# Define functions to be used in shell portions
shell.prefix(SHELL_FUNCTIONS)

aligner = config["aligner"]
genome_dict = config["genome_dict"]
genome = genome_dict["name"]
chrom_sizes = get_chrom_sizes(genome_dict["size"])
genomelen = sum(chrom_sizes.values())
genome_db = genome_dict["db"][aligner]
# bed file binning the genome in 10nt bins
genome_binned = genome_dict["binned"]
annot_dir = genome_dict["annot_dir"]
# TODO: figure out the difference between OPJ(convert_dir, "wormid2name.pickle") and genome_dict["converter"]
convert_dir = genome_dict["convert_dir"]
gene_lists_dir = genome_dict["gene_lists_dir"]
avail_id_lists = set(glob(OPJ(gene_lists_dir, "*_ids.txt")))

merged_fastq = config["merged_fastq"]
barcode_dict = config["barcode_dict"]
BARCODES = list(barcode_dict.keys())
MAX_DIFF = config["max_diff"]
output_dir = config["output_dir"]
log_dir = OPJ(output_dir, "logs")
data_dir = OPJ(output_dir, "data")
demux_dir = OPJ(data_dir, f"demultiplexed_{MAX_DIFF}")
lib2raw = defaultdict(dict)
REPS = set()
for (barcode, lib_info) in barcode_dict.items():
    REPS.add(lib_info["rep"])
    lib2raw[lib_info["lib"]][lib_info["rep"]] = OPJ(demux_dir, f"{barcode}.fastq.gz")
LIBS = list(lib2raw.keys())
REPS = sorted(REPS)
67
68
69
70
71
72
73
74
75
76
77
CONDITIONS = [{
    "lib" : lib,
    "rep" : rep} for rep in REPS for lib in LIBS]
# We use this for various things in order to have always the same library order:
COND_NAMES = ["_".join((
    cond["lib"],
    cond["rep"])) for cond in CONDITIONS]
COND_COLUMNS = pd.DataFrame(CONDITIONS).assign(
    cond_name=pd.Series(COND_NAMES).values).set_index("cond_name")

LIB_TYPE = config["lib_type"]
Blaise Li's avatar
Blaise Li committed
78
#TRIMMERS = ["fastx_clipper"]
79
TRIMMERS = ["cutadapt"]
80
#COUNTERS = ["feature_count"]
81
82
83
84
85
ORIENTATIONS = ["fwd", "rev", "all"]
WITH_ADAPT = ["adapt_deduped", "adapt_nodedup"]
POST_TRIMMING = ["noadapt_deduped"] + WITH_ADAPT
SIZE_RANGES = ["12-18", "21-24", "26-40", "48-52"]
SIZE_SELECTED = [f"{read_type}_{size_range}" for (read_type, size_range) in product(WITH_ADAPT, SIZE_RANGES)]
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

# TODO: Have different settings for different size ranges
# recommended k-mer length for D. melanogaster is 20
# However, reads shorter thant the k-mer length will be ignored.
# http://crac.gforge.inria.fr/documentation/crac/#sec-2
alignment_settings = {
    #"bowtie2": "-L 6 -i S,1,0.8 -N 0",
    "bowtie2": "-L 6 -i S,1,0.8 -N 1",
    # Small RNA-seq parameters may not be compatible with --local
    #"bowtie2": "--local -L 6 -i S,1,0.8 -N 0",
    "crac": "-k 20 --stranded --use-x-in-cigar"}
# Lower stringency settings, to remap the unmapped
realignment_settings = {
    # Try with almost-default settings
    "bowtie2": "-N 1",
    # Allow more mismatches in the seed
    # Reduce minimal mismatch and gap open penalties
    #"bowtie2": "--local -L 6 -i S,1,0.8 -N 1 --mp 6,1 --rdg 4,3",
    # TODO: Find how to be less stringent with crac
    "crac": "-k 20 --stranded --use-x-in-cigar"}
#test_alignment_settings = {
#    "bowtie2": {
#        "": "-L 6 -i S,1,0.8 -N 1",
#        "": "-L 6 -i S,1,0.8 -N 1",
#        "": "-L 6 -i S,1,0.8 -N 1",
#        "": "-L 6 -i S,1,0.8 -N 1",
#        "": "-L 6 -i S,1,0.8 -N 1",
#        "": "-L 6 -i S,1,0.8 -N 1"}
#    }


Blaise Li's avatar
Blaise Li committed
117
118
119
120
# For compatibility with trim_and_dedup as used in PRO-seq pipeline
lib2adapt = defaultdict(lambda: config["adapter"])
MAX_ADAPT_ERROR_RATE = config["max_adapt_error_rate"]

121
122
123
124
125
126
COUNT_BIOTYPES = ["protein_coding", "DNA_transposons_rmsk_families", "RNA_transposons_rmsk_families"]
SIZE_FACTORS = ["protein_coding", "median_ratio_to_pseudo_ref"]
assert set(SIZE_FACTORS).issubset(set(COUNT_BIOTYPES) | {"median_ratio_to_pseudo_ref"})
NORM_TYPES = ["protein_coding", "median_ratio_to_pseudo_ref"]
assert set(NORM_TYPES).issubset(set(SIZE_FACTORS))

Blaise Li's avatar
Blaise Li committed
127
128
wildcard_constraints:
    lib="|".join(LIBS),
129
130
    rep="\d+",
    orientation="|".join(ORIENTATIONS),
Blaise Li's avatar
Blaise Li committed
131
    norm="|".join(SIZE_FACTORS),
132
    #size_range="\d+-\d+"
Blaise Li's avatar
Blaise Li committed
133
134

preprocessing = [
135
136
137
138
139
140
141
    ## Will be pulled in as dependencies of other needed results:
    # expand(OPJ(demux_dir, "{barcode}.fastq.gz"), barcode=BARCODES),
    # expand(OPJ(data_dir, "{lib}_{rep}.fastq.gz"), lib=LIBS, rep=REPS),
    # expand(OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}.fastq.gz"), trimmer=TRIMMERS, lib=LIBS, rep=REPS, read_type=POST_TRIMMING + SIZE_SELECTED),
    ##
    expand(OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}_fastqc.html"), trimmer=TRIMMERS, lib=LIBS, rep=REPS, read_type=POST_TRIMMING + SIZE_SELECTED),
    expand(OPJ(data_dir, "trimmed_{trimmer}", "read_stats", "{lib}_{rep}", "{read_type}_size_distribution.pdf"), trimmer=TRIMMERS, lib=LIBS, rep=REPS, read_type=POST_TRIMMING),
Blaise Li's avatar
Blaise Li committed
142
143
144
]

mapping = [
145
146
147
    ## Will be pulled in as dependencies of other needed results:
    # expand(OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_sorted.bam" % genome), trimmer=TRIMMERS, lib=LIBS, rep=REPS, read_type=POST_TRIMMING + SIZE_SELECTED),
    ##
148
149
150
151
    expand(
        OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_samtools_stats.txt" % genome),
        trimmer=TRIMMERS, lib=LIBS, rep=REPS,
        read_type=POST_TRIMMING + SIZE_SELECTED + [f"{to_map}_unmapped" for to_map in POST_TRIMMING + SIZE_SELECTED]),
152
153
154
155
156
157
]

counting = [
    ## Will be pulled in as dependencies of other needed results:
    # expand(OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "{lib}_{rep}_{read_type}_on_%s" % genome, "{biotype}_{orientation}_counts.txt"), trimmer=TRIMMERS, lib=LIBS, rep=REPS, read_type=POST_TRIMMING + SIZE_SELECTED, biotype=COUNT_BIOTYPES, orientation=ORIENTATIONS),
    ##
Blaise Li's avatar
Blaise Li committed
158
159
160
    expand(OPJ(output_dir, "{trimmer}", aligner, f"mapped_{genome}", "feature_count", "summaries", "all_{read_type}_on_%s_{orientation}_counts.txt" % genome), trimmer=TRIMMERS, read_type=POST_TRIMMING + SIZE_SELECTED, orientation=ORIENTATIONS),
    expand(OPJ(output_dir, "{trimmer}", aligner, f"mapped_{genome}", "feature_count", "all_{read_type}_on_%s" % genome, "{biotype}_{orientation}_counts.txt"), trimmer=TRIMMERS, read_type=POST_TRIMMING + SIZE_SELECTED, biotype=COUNT_BIOTYPES, orientation=ORIENTATIONS),
    expand(OPJ(output_dir, "{trimmer}", aligner, f"mapped_{genome}", "{lib}_{rep}_{read_type}_on_%s_by_{norm}_{orientation}.bw" % genome), trimmer=TRIMMERS, lib=LIBS, rep=REPS, read_type=POST_TRIMMING + SIZE_SELECTED, norm=NORM_TYPES, orientation=["all"]),
Blaise Li's avatar
Blaise Li committed
161
162
163
]

#TODO:
164
165
166
# - Plot histogram of read type counts at successive processing steps
# - Remap unmapped with less stringency to check if we are too stringent
# (- remove deduplication step ?)
167
# - map and featureCount rev/fwd: fwd -> mRNA, rev -> smallRNA
168
# - map with CRAC, detect chimera and crosslink-induced sequencing errors
Blaise Li's avatar
Blaise Li committed
169
# - find cross-link sites on genes: should be 5' of antisense reads
170
171
# (otherwise, we expect mismatches at the cross-link sites: distribution of mismatch positions in the reads)
# see also https://genomebiology.biomedcentral.com/articles/10.1186/s13059-016-1130-x
Blaise Li's avatar
Blaise Li committed
172
173
174
175
176
rule all:
    """This top rule is used to drive the whole workflow by taking as input its final products."""
    input:
        preprocessing,
        mapping,
177
        counting,
Blaise Li's avatar
Blaise Li committed
178
179
180
181
182
183
184
185
186
187
188
189
190


#################
# Preprocessing #
#################
rule demultiplex:
    input:
        fq_in = merged_fastq,
    output:
        expand(OPJ(demux_dir, "{barcode}.fastq.gz"), barcode=BARCODES),
    params:
        demux_dir = demux_dir,
        bc_start = config["bc_start"],
191
        barcodes = " -b ".join(BARCODES),
Blaise Li's avatar
Blaise Li committed
192
193
194
195
196
197
198
        max_diff = MAX_DIFF
    log:
        err = OPJ(log_dir, "demultiplex.err")
    benchmark:
        OPJ(log_dir, "demultiplex_benchmark.txt")
    shell:
        """
199
        qaf_demux \\
200
            -i {input.fq_in} -g -o {params.demux_dir} \\
Blaise Li's avatar
Blaise Li committed
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
            -s {params.bc_start} -b {params.barcodes} -m {params.max_diff} \\
            2> {log.err} || error_exit "qaf_demux failed"
        """


include: ensure_relative(irules["link_raw_data"], workflow.basedir)


rule trim_and_dedup:
    """The adaptor is trimmed, then reads are treated in two groups depending
    on whether the adapter was found or not. For each group the reads are
    sorted, deduplicated, and the random k-mers that helped identify
    PCR duplicates are removed at both ends"""
    input:
        rules.link_raw_data.output,
    output:
        noadapt = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_noadapt_deduped.fastq.gz"),
        adapt = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_adapt_deduped.fastq.gz"),
        adapt_nodedup = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_adapt_nodedup.fastq.gz"),
        nb_raw =  OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_nb_raw.txt"),
        nb_adapt =  OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_nb_adapt.txt"),
        nb_adapt_deduped =  OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_nb_adapt_deduped.txt"),
        nb_noadapt =  OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_nb_noadapt.txt"),
        nb_noadapt_deduped =  OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_nb_noadapt_deduped.txt"),
    params:
        adapter = lambda wildcards : lib2adapt[wildcards.lib],
        max_adapt_error_rate = MAX_ADAPT_ERROR_RATE,
        process_type = "iCLIP",
        trim5 = 8,
        trim3 = 4,
    threads: 4 # Actually, to avoid too much IO
    message:
        "Trimming adaptor from raw data using {wildcards.trimmer}, deduplicating reads, and removing 5' and 3' random n-mers for {wildcards.lib}_{wildcards.rep}."
    benchmark:
        OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_trim_benchmark.txt")
    log:
        trim = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_trim.log"),
        log = OPJ(log_dir, "{trimmer}", "trim_and_dedup", "{lib}_{rep}.log"),
        err = OPJ(log_dir, "{trimmer}", "trim_and_dedup", "{lib}_{rep}.err"),
    run:
        shell_commands = """
MAX_ERROR_RATE="{params.max_adapt_error_rate}" THREADS="{threads}" {params.process_type}_trim_and_dedup.sh {wildcards.trimmer} {input} \\
    {params.adapter} {params.trim5} {params.trim3} \\
    {output.adapt} {output.noadapt} {output.adapt_nodedup} {log.trim} \\
    {output.nb_raw} {output.nb_adapt} {output.nb_adapt_deduped} \\
    {output.nb_noadapt} {output.nb_noadapt_deduped} 1> {log.log} 2> {log.err}
"""
        shell(shell_commands)


251
252
253
254
255
256
257
258
259
260
261
262
263
264
def source_trimmed_fastq(wildcards):
    """Determine the fastq file corresponding to a given read type."""
    # remove size range
    read_type = "_".join(wildcards.read_type.split("_")[:-1])
    if read_type == "adapt_deduped":
        return rules.trim_and_dedup.output.adapt
    elif read_type == "noadapt_deduped":
        return rules.trim_and_dedup.output.noadapt
    elif read_type == "adapt_nodedup":
        return rules.trim_and_dedup.output.adapt_nodedup
    else:
        raise NotImplementedError("Unknown read type: %s" % read_type)


Blaise Li's avatar
Blaise Li committed
265
266
267
268
269
def source_fastq(wildcards):
    """Determine the fastq file corresponding to a given read type."""
    read_type = wildcards.read_type
    if read_type == "raw":
        return rules.link_raw_data.output
270
271
    elif read_type in SIZE_SELECTED:
        return rules.select_size_range.output.selected
Blaise Li's avatar
Blaise Li committed
272
273
274
275
276
277
    elif read_type == "adapt_deduped":
        return rules.trim_and_dedup.output.adapt
    elif read_type == "noadapt_deduped":
        return rules.trim_and_dedup.output.noadapt
    elif read_type == "adapt_nodedup":
        return rules.trim_and_dedup.output.adapt_nodedup
278
279
    elif read_type.endswith("unmapped"):
        return rules.map_on_genome.output.nomap_fastq
Blaise Li's avatar
Blaise Li committed
280
281
282
283
    else:
        raise NotImplementedError("Unknown read type: %s" % read_type)


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def awk_size_filter(wildcards):
    """Returns the bioawk filter to select reads of type *wildcards.read_type*."""
    size_range = wildcards.read_type.split("_")[-1]
    (min_len, max_len) = size_range.split("-")
    return f"{min_len} <= length($seq) && length($seq) <= {max_len}"


rule select_size_range:
    """Select (and count) reads in the correct size range."""
    input:
        source_trimmed_fastq,
    output:
        selected = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}.fastq.gz"),
        nb_selected = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_nb_{read_type}.txt"),
    wildcard_constraints:
        read_type = "|".join(SIZE_SELECTED)
    params:
        awk_filter = awk_size_filter,
    message:
        "Selecting {wildcards.read_type} for {wildcards.lib}_{wildcards.rep}_{wildcards.read_type}."
    shell:
        """
        bioawk -c fastx '{params.awk_filter} {{print "@"$name" "$4"\\n"$seq"\\n+\\n"$qual}}' {input} \\
            | tee >(count_fastq_reads {output.nb_selected}) \\
            | gzip > {output.selected}
        """


# for with_size_selection in [True, False]:
#     if with_size_selection:
#         rule do_fastqc_on_size_selected:
#             input:
#                 fastq = source_fastq
#             output:
#                 fastqc_out = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}_{size_range}_fastqc.html")
#             shell:
#                 """
#                 fastqc {input.fastq}
#                 """
#     else:
#         rule do_fastqc:
#             input:
#                 fastq = source_fastq
#             output:
#                 fastqc_out = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}_fastqc.html")
#             shell:
#                 """
#                 fastqc {input.fastq}
#                 """

Blaise Li's avatar
Blaise Li committed
334
335
rule do_fastqc:
    input:
336
        fastq = source_fastq,
Blaise Li's avatar
Blaise Li committed
337
338
339
340
341
342
    output:
        fastqc_out = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}_fastqc.html")
    shell:
        """
        fastqc {input.fastq}
        """
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# rule do_fastqc_on_trimmed:
#     input:
#         fastq = source_fastq,
#     output:
#         fastqc_out = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}_fastqc.html")
#     shell:
#         """
#         fastqc {input.fastq}
#         """
# 
# 
# rule do_fastqc_on_size_selected:
#     input:
#         fastq = source_fastq,
#         #fastq = rules.select_size_range.output.selected,
#     output:
#         fastqc_out = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}_{size_range}_fastqc.html")
#     shell:
#         """
#         fastqc {input.fastq}
#         """
Blaise Li's avatar
Blaise Li committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390


rule compute_size_distribution:
    input:
        source_fastq
    output:
        OPJ(data_dir, "trimmed_{trimmer}", "read_stats", "{lib}_{rep}", "{read_type}_size_distribution.txt"),
    message:
        "Computing read size distribution for {wildcards.lib}_{wildcards.rep}_{wildcards.read_type}."
    shell:
        """
        zcat {input} | compute_size_distribution {output}
        """


rule plot_size_distribution:
    input:
        rules.compute_size_distribution.output
    output:
        OPJ(data_dir, "trimmed_{trimmer}", "read_stats", "{lib}_{rep}", "{read_type}_size_distribution.{fig_format}")
    message:
        "Plotting size distribution for trimmed {wildcards.lib}_{wildcards.rep}_{wildcards.read_type}."
    run:
        data = pd.read_table(input[0], header=None, names=("size", "count"), index_col=0)
        title = f"read size distribution for {wildcards.lib}_{wildcards.rep}_{wildcards.read_type}"
        plot_histo(output[0], data, title)

391

392
def set_alignment_settings(wildcards):
393
394
395
396
397
398
    return alignment_settings[aligner]


def set_realignment_settings(wildcards):
    return realignment_settings[aligner]

Blaise Li's avatar
Blaise Li committed
399
400
401
402
403
404
405
406
407
408
409
410

###########
# Mapping #
###########
rule map_on_genome:
    input:
        # fastq = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}.fastq.gz"),
        fastq = source_fastq,
    output:
        # sam files take a lot of space
        sam = temp(OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s.sam" % genome)),
        nomap_fastq = OPJ(output_dir, "{trimmer}", aligner, "info_mapping_%s" % genome, "{lib}_{rep}_{read_type}_unmapped_on_%s.fastq.gz" % genome),
411
412
    wildcard_constraints:
        read_type = "|".join(POST_TRIMMING + SIZE_SELECTED)
Blaise Li's avatar
Blaise Li committed
413
414
415
    params:
        aligner = aligner,
        index = genome_db,
416
417
        #settings = alignment_settings[aligner],
        settings = set_alignment_settings,
Blaise Li's avatar
Blaise Li committed
418
419
420
421
422
423
424
425
426
427
    message:
        "Mapping {wildcards.lib}_{wildcards.rep}_{wildcards.read_type} on C. elegans genome."
    log:
        log = OPJ(log_dir, "{trimmer}", aligner, "map_{read_type}_on_genome", "{lib}_{rep}.log"),
        err = OPJ(log_dir, "{trimmer}", aligner, "map_{read_type}_on_genome", "{lib}_{rep}.err"),
    threads: 12
    wrapper:
        "file:///pasteur/homes/bli/src/bioinfo_utils/snakemake_wrappers/map_on_genome"


428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
rule remap_on_genome:
    input:
        # fastq = OPJ(data_dir, "trimmed_{trimmer}", "{lib}_{rep}_{read_type}.fastq.gz"),
        #fastq = rules.map_on_genome.output.nomap_fastq,
        fastq = OPJ(output_dir, "{trimmer}", aligner, "info_mapping_%s" % genome, "{lib}_{rep}_{read_type}_unmapped_on_%s.fastq.gz" % genome),
    output:
        # sam files take a lot of space
        sam = temp(OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_unmapped_on_%s.sam" % genome)),
        nomap_fastq = OPJ(output_dir, "{trimmer}", aligner, "info_mapping_%s" % genome, "{lib}_{rep}_{read_type}_unmapped_unmapped_on_%s.fastq.gz" % genome),
    wildcard_constraints:
        read_type = "|".join(POST_TRIMMING + SIZE_SELECTED)
    #wildcard_constraints:
    #    read_type = "|".join([f"{to_map}_unmapped" for to_map in POST_TRIMMING + SIZE_SELECTED])
    params:
        aligner = aligner,
        index = genome_db,
444
445
        #settings = realignment_settings[aligner],
        settings = set_realignment_settings,
446
447
448
449
450
451
452
453
454
455
    message:
        "Re-mapping unmapped {wildcards.lib}_{wildcards.rep}_{wildcards.read_type} on C. elegans genome."
    log:
        log = OPJ(log_dir, "{trimmer}", aligner, "remap_{read_type}_unmapped_on_genome", "{lib}_{rep}.log"),
        err = OPJ(log_dir, "{trimmer}", aligner, "remap_{read_type}_unmapped_on_genome", "{lib}_{rep}.err"),
    threads: 12
    wrapper:
        "file:///pasteur/homes/bli/src/bioinfo_utils/snakemake_wrappers/map_on_genome"


Blaise Li's avatar
Blaise Li committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
rule sam2indexedbam:
    input:
        sam = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s.sam" % genome),
    output:
        sorted_bam = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_sorted.bam" % genome),
        index = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_sorted.bam.bai" % genome),
    message:
        "Sorting and indexing sam file for {wildcards.lib}_{wildcards.rep}_{wildcards.read_type}."
    log:
        log = OPJ(log_dir, "{trimmer}", "sam2indexedbam", "{lib}_{rep}_{read_type}.log"),
        err = OPJ(log_dir, "{trimmer}", "sam2indexedbam", "{lib}_{rep}_{read_type}.err"),
    threads:
        4
    wrapper:
        "file:///pasteur/homes/bli/src/bioinfo_utils/snakemake_wrappers/sam2indexedbam"


rule compute_mapping_stats:
    input:
        sorted_bam = rules.sam2indexedbam.output.sorted_bam,
    output:
        stats = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_samtools_stats.txt" % genome),
    shell:
        """samtools stats {input.sorted_bam} > {output.stats}"""


rule fuse_bams:
483
    """This rule fuses the two sorted bam files corresponding to the mapping
Blaise Li's avatar
Blaise Li committed
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
    of the reads containing the adaptor or not."""
    input:
        noadapt_sorted_bam = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_noadapt_on_%s_sorted.bam" % genome),
        adapt_sorted_bam = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_adapt_on_%s_sorted.bam" % genome),
    output:
        sorted_bam = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_on_%s_sorted.bam" % genome),
        bai = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_on_C_%s_sorted.bam.bai" % genome),
    message:
        "Fusing sorted bam files for {wildcards.lib}_{wildcards.rep}"
    log:
        log = OPJ(log_dir, "{trimmer}", "fuse_bams", "{lib}_{rep}.log"),
        err = OPJ(log_dir, "{trimmer}", "fuse_bams", "{lib}_{rep}.err"),
    shell:
        """
        samtools merge -c {output.sorted_bam} {input.noadapt_sorted_bam} {input.adapt_sorted_bam} 1> {log.log} 2> {log.err}
        indexed=""
        while [ ! ${{indexed}} ]
        do
            samtools index {output.sorted_bam} && indexed="OK"
            if [ ! ${{indexed}} ]
            then
                rm -f {output.bai}
                echo "Indexing failed. Retrying" 1>&2
            fi
        done 1>> {log.log} 2>> {log.err}
        """


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def biotype2annot(wildcards):
    if wildcards.biotype.endswith("_rmsk_families"):
        biotype = wildcards.biotype[:-9]
    else:
        biotype = wildcards.biotype
    return OPJ(annot_dir, f"{biotype}.gtf")


rule feature_count_reads:
    input:
        sorted_bam = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_sorted.bam" % genome),
        bai = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "{lib}_{rep}_{read_type}_on_%s_sorted.bam.bai" % genome),
    output:
        counts = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "{lib}_{rep}_{read_type}_on_%s" % genome, "{biotype}_{orientation}_counts.txt"),
        counts_converted = OPJ(output_dir, "{trimmer}", aligner, "mapped_C_elegans", "feature_count", "{lib}_{rep}_{read_type}_on_%s" % genome, "{biotype}_{orientation}_counts_gene_names.txt"),
    params:
        stranded = feature_orientation2stranded(LIB_TYPE),
        annot = biotype2annot,
    message:
        "Counting {wildcards.orientation} {wildcards.biotype} {wildcards.read_type} reads for {wildcards.lib}_{wildcards.rep} with featureCounts."
    log:
        log = OPJ(log_dir, "{trimmer}", "feature_count_reads", "{lib}_{rep}_{read_type}.log"),
        err = OPJ(log_dir, "{trimmer}", "feature_count_reads", "{lib}_{rep}_{read_type}.err")
    shell:
        """
        converter="/pasteur/entites/Mhe/Genomes/C_elegans/Caenorhabditis_elegans/Ensembl/WBcel235/Annotation/Genes/genes_id2name.pickle"
        tmpdir=$(mktemp -dt "feature_{wildcards.lib}_{wildcards.rep}_{wildcards.read_type}_{wildcards.biotype}_{wildcards.orientation}.XXXXXXXXXX")
        cmd="featureCounts -a {params.annot} -o {output.counts} -t transcript -g "gene_id" -O -M --primary -s {params.stranded} --fracOverlap 0 --tmpDir ${{tmpdir}} {input.sorted_bam}"
        featureCounts -v 2> {log.log}
        echo ${{cmd}} 1>> {log.log}
        eval ${{cmd}} 1>> {log.log} 2> {log.err} || error_exit "featureCounts failed"
        rm -rf ${{tmpdir}}
        cat {output.counts} | id2name.py ${{converter}} > {output.counts_converted}
        """


rule summarize_feature_counts:
    """For a given library, compute the total counts for each biotype and write this in a summary table."""
    input:
        biotype_counts_files = expand(OPJ(output_dir, "{{trimmer}}", aligner, "mapped_%s" % genome, "feature_count", "{{lib}}_{{rep}}_{{read_type}}_on_%s" % genome, "{biotype}_{{orientation}}_counts.txt"), biotype=COUNT_BIOTYPES),
    output:
        summary = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "summaries", "{lib}_{rep}_{read_type}_on_%s_{orientation}_counts.txt" % genome),
    run:
        sum_counter = sum_feature_counts
        with open(output.summary, "w") as summary_file:
            header = "\t".join(COUNT_BIOTYPES)
            summary_file.write("%s\n" % header)
            sums = "\t".join((str(sum_counter(counts_file)) for counts_file in input.biotype_counts_files))
            summary_file.write("%s\n" % sums)


rule gather_read_counts_summaries:
    input:
        summary_tables = expand(OPJ(output_dir, "{{trimmer}}", aligner, "mapped_%s" % genome, "feature_count", "summaries", "{lib}_{rep}_{{read_type}}_on_%s_{{orientation}}_counts.txt" % genome), lib=LIBS, rep=REPS),
    output:
        summary_table = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "summaries", "all_{read_type}_on_%s_{orientation}_counts.txt" % genome),
    run:
        summary_files = (OPJ(
            output_dir,
            wildcards.trimmer,
            aligner,
            "mapped_%s" % genome,
            "feature_count",
            "summaries",
            f"{cond_name}_{wildcards.read_type}_on_%s_{wildcards.orientation}_counts.txt" % genome) for cond_name in COND_NAMES)
        summaries = pd.concat(
            (pd.read_table(summary_file).T.astype(int) for summary_file in summary_files),
            axis=1)
        summaries.columns = COND_NAMES
        summaries.to_csv(output.summary_table, sep="\t")


rule gather_counts:
    """For a given biotype, gather counts from all libraries in one table."""
    input:
        counts_tables = expand(OPJ(output_dir, "{{trimmer}}", aligner, "mapped_%s" % genome, "feature_count", "{lib}_{rep}_{{read_type}}_on_%s" % genome, "{{biotype}}_{{orientation}}_counts.txt"), lib=LIBS, rep=REPS),
    output:
        counts_table = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "all_{read_type}_on_%s" % genome, "{biotype}_{orientation}_counts.txt"),
    # wildcard_constraints:
    #     # Avoid ambiguity with join_all_counts
    #     biotype = "|".join(COUNT_BIOTYPES)
    run:
        # Gathering the counts data
        ############################
        counts_files = (OPJ(
            output_dir,
            wildcards.trimmer,
            aligner,
            "mapped_%s" % genome,
            "feature_count",
            f"{cond_name}_{wildcards.read_type}_on_%s" % genome,
            f"{wildcards.biotype}_{wildcards.orientation}_counts.txt") for cond_name in COND_NAMES)
        # if wildcards.counter == "htseq_count":
        #     counts_data = pd.concat(
        #         map(read_htseq_counts, counts_files),
        #         axis=1).fillna(0).astype(int)
        # elif wildcards.counter == "intersect_count":
        #     counts_data = pd.concat(
        #         map(read_intersect_counts, counts_files),
        #         axis=1).fillna(0).astype(int)
        # elif wildcards.counter == "feature_count":
        #     counts_data = pd.concat(
        #         map(read_feature_counts, counts_files),
        #         axis=1).fillna(0).astype(int)
        # else:
        #     raise NotImplementedError(f"{wilcards.counter} not handled (yet?)")
        counts_data = pd.concat(
            map(read_feature_counts, counts_files),
            axis=1).fillna(0).astype(int)
        counts_data.columns = COND_NAMES
        # Simple_repeat|Simple_repeat|(TTTTTTG)n:1
        # Simple_repeat|Simple_repeat|(TTTTTTG)n:2
        # Simple_repeat|Simple_repeat|(TTTTTTG)n:3
        # Simple_repeat|Simple_repeat|(TTTTTTG)n:4
        # -> Simple_repeat|Simple_repeat|(TTTTTTG)n
        if wildcards.biotype.endswith("_rmsk_families"):
            repeat_families = [":".join(name.split(":")[:-1]) for name in counts_data.index]
            # Sum the counts for a given repeat family
            counts_data = counts_data.assign(family=repeat_families).groupby("family").sum()
        counts_data.index.names = ["gene"]
        counts_data.to_csv(output.counts_table, sep="\t")


rule compute_median_ratio_to_pseudo_ref_size_factors:
    input:
        counts_table = rules.gather_counts.output.counts_table,
    output:
        median_ratios_file = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "all_{read_type}_on_%s" % genome, "{biotype}_{orientation}_median_ratios_to_pseudo_ref.txt"),
    run:
        counts_data = pd.read_table(
            input.counts_table,
            index_col=0,
            na_filter=False)
        # http://stackoverflow.com/a/21320592/1878788
        #median_ratios = pd.DataFrame(median_ratio_to_pseudo_ref_size_factors(counts_data)).T
        #median_ratios.index.names = ["median_ratio_to_pseudo_ref"]
        # Easier to grep when not transposed, actually:
        median_ratios = median_ratio_to_pseudo_ref_size_factors(counts_data)
        print(median_ratios)
        median_ratios.to_csv(output.median_ratios_file, sep="\t")


Blaise Li's avatar
Blaise Li committed
654
655
def source_norm_file(wildcards):
    if wildcards.norm == "median_ratio_to_pseudo_ref":
656
        return OPJ(output_dir, f"{wildcards.trimmer}", aligner, f"mapped_{genome}", "feature_count", f"all_{wildcards.read_type}_on_%s" % genome, "protein_coding_fwd_median_ratios_to_pseudo_ref.txt")
Blaise Li's avatar
Blaise Li committed
657
658
659
660
    else:
        return rules.summarize_feature_counts.output.summary


661
662
663
664
rule make_normalized_bigwig:
    input:
        bam = rules.sam2indexedbam.output.sorted_bam,
        #bam = rules.fuse_bams.output.sorted_bam,
Blaise Li's avatar
Blaise Li committed
665
666
        # TODO: use sourcing function based on norm
        norm_file = source_norm_file,
667
        #size_factor_file = rules.compute_coverage.output.coverage
Blaise Li's avatar
Blaise Li committed
668
        #median_ratios_file = OPJ(output_dir, "{trimmer}", aligner, "mapped_%s" % genome, "feature_count", "all_{read_type}_on_%s" % genome, "protein_coding_fwd_median_ratios_to_pseudo_ref.txt"),
669
670
671
        # TODO: compute this
        #scale_factor_file = OPJ(output_dir, aligner, "mapped_C_elegans", "annotation", "all_%s_on_C_elegans" % size_selected, "pisimi_median_ratios_to_pseudo_ref.txt"),
    output:
Blaise Li's avatar
Blaise Li committed
672
        bigwig_norm = OPJ(output_dir, "{trimmer}", aligner, f"mapped_{genome}", "{lib}_{rep}_{read_type}_on_%s_by_{norm}_{orientation}.bw" % genome),
673
674
675
676
    #params:
    #    orient_filter = bamcoverage_filter,
    threads: 12  # to limit memory usage, actually
    benchmark:
Blaise Li's avatar
Blaise Li committed
677
        OPJ(log_dir, "{trimmer}", "make_normalized_bigwig", "{lib}_{rep}_{read_type}_by_{norm}_{orientation}_benchmark.txt")
678
679
680
    params:
        genome_binned = genome_binned,
    log:
Blaise Li's avatar
Blaise Li committed
681
682
        log = OPJ(log_dir, "{trimmer}", "make_normalized_bigwig", "{lib}_{rep}_{read_type}_by_{norm}_{orientation}.log"),
        err = OPJ(log_dir, "{trimmer}", "make_normalized_bigwig", "{lib}_{rep}_{read_type}_by_{norm}_{orientation}.err"),
683
    run:
Blaise Li's avatar
Blaise Li committed
684
685
686
687
688
689
690
691
692
        if wildcards.norm == "median_ratio_to_pseudo_ref":
            size = float(pd.read_table(
                input.norm_file, index_col=0, header=None).loc[
                    f"{wildcards.lib}_{wildcards.rep}"])
        else:
            # We normalize by million in order not to have too small values
            size = pd.read_table(input.norm_file).T.loc[wildcards.norm][0] / 1000000
            #scale = 1 / pd.read_table(input.summary, index_col=0).loc[
            #    wildcards.norm_file].loc[f"{wildcards.lib}_{wildcards.rep}"]
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
        assert size >= 0, f"{size} is not positive"
        if size == 0:
            make_empty_bigwig(output.bigwig_norm, chrom_sizes)
        else:
            # TODO: make this a function of deeptools version
            no_reads = """Error: The generated bedGraphFile was empty. Please adjust
    your deepTools settings and check your input files.
    """
            zero_bytes = """needLargeMem: trying to allocate 0 bytes (limit: 100000000000)
    bam2bigwig.sh: bedGraphToBigWig failed
    """
            try:
                shell("""
                    bam2bigwig.sh {input.bam} {params.genome_binned} \\
                        {wildcards.lib}_{wildcards.rep} {wildcards.orientation} %s \\
                        %f {output.bigwig_norm} \\
                        > {log.log} 2> {log.err} \\
                        || error_exit "bam2bigwig.sh failed"
                    """ % (LIB_TYPE[-1], size))
            except CalledProcessError as e:
                if last_lines(log.err, 2) in {no_reads, zero_bytes}:
                    make_empty_bigwig(output.bigwig_norm, chrom_sizes)
                    #with open(output.bigwig_norm, "w") as bwfile:
                    #    bwfile.write("")
                else:
                    raise
719
720


Blaise Li's avatar
Blaise Li committed
721
onsuccess:
722
    print("iCLIP data analysis finished.")
723
    cleanup_and_backup(output_dir, config, delete=True)
Blaise Li's avatar
Blaise Li committed
724
725

onerror:
726
727
728
729
    shell(f"rm -rf {output_dir}_err")
    shell(f"cp -rp {output_dir} {output_dir}_err")
    cleanup_and_backup(output_dir + "_err", config)
    print("iCLIP data analysis failed.")
Blaise Li's avatar
Blaise Li committed
730