utils.R 23.8 KB
Newer Older
1
2
#!/usr/bin/Rscript

Valentina Galata's avatar
Valentina Galata committed
3
## IMPORT
4

5
suppressMessages(library(UpSetR)) # subset plots
6
7
8
9
10
11
suppressMessages(library(ggplot2)) # plotting
suppressMessages(library(reshape2)) # reshaping dataframes
suppressMessages(library(scales)) # plot scales
suppressMessages(library(pheatmap)) # heatmaps
suppressMessages(library(grid)) # for heatmaps
suppressMessages(library(viridis)) # color palettes
12
suppressMessages(library(ggsci)) # color palettes
13

Valentina Galata's avatar
Valentina Galata committed
14
15
##############################
# INPUT
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#' Transform a molten data.frame into a squared data.frame
#' For lists of pairwise comparisons
#' @input df Molten data.frame w/ three columns (two w/ labels and one w/ values)
#' @input col1 Column name containing labels (1)
#' @input col2 Column name containing labels (2)
#' @return a data.frame with labels from two label columns as row and column names
dcast_sq <- function(df, col1, col2){
    # make sure the labels are identical
    testit::assert(all( sort(df[,col1]) == sort(df[,col2]) ))
    # reshape given data.frame using given formula
    df <- reshape2::dcast(df, as.formula(sprintf("%s ~ %s", col1, col2)))
    # use col. w/ tool names as rownames and remove from table
    rownames(df) <- df[,col1]
    df <- df[,setdiff(colnames(df), col1)]
    return(df)
} 

Valentina Galata's avatar
Valentina Galata committed
34
read_nanostats <- function(fname){
35
    print(sprintf("Reading: %s", fname))
Valentina Galata's avatar
Valentina Galata committed
36
37
38
39
40
41
42
43
44
45
46
47
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        check.names=FALSE,
        stringsAsFactors=FALSE
    )
    df_cols <- c("stat"="Statistic", "value"="Value")
    colnames(df) <- df_cols[colnames(df)]
    return(df)
}

48
read_fastp <- function(fname){
49
    print(sprintf("Reading: %s", fname))
50
51
52
53
54
55
56
57
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        row.names=1,
        check.names=FALSE,
        stringsAsFactors=FALSE
    )
58
    df <- df[,c("total_reads", "total_bases", "q20_rate", "q30_rate")]
59
60
61
    return(df)
}

62
read_mappability <- function(fname){
63
    print(sprintf("Reading: %s", fname))
64
65
66
67
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
68
69
        check.names=FALSE,
        stringsAsFactors=FALSE
70
71
72
73
74
75
    )
    testit::assert(all(df$tool %in% names(ASM_TOOL_NAMES)))
    df$tool <- ASM_TOOL_NAMES[df$tool]
    return(df)
}

76
read_prodigal <- function(fname){
77
    print(sprintf("Reading: %s", fname))
78
79
80
81
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
82
83
        check.names=FALSE,
        stringsAsFactors=FALSE
84
    )
85
86
    testit::assert(all(df$tool %in% names(ASM_TOOL_NAMES)))
    df$tool <- ASM_TOOL_NAMES[df$tool]
87
88
89
    return(df)
}

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
read_prodigal_gcounts <- function(fname){
    df <- read_prodigal(fname)
    df$partial_pct <- 100 * df$partial / df$total
    return(df)
}

read_prodigal_glength <- function(fname){
    df <- read_prodigal(fname)
    return(df)
}

read_quast <- function(fname){
    print(sprintf("Reading: %s", fname))
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        row.names=1,
        check.names=FALSE,
        stringsAsFactors=FALSE
    )
    testit::assert(all(colnames(df) %in% names(ASM_TOOL_NAMES)))
    colnames(df) <- ASM_TOOL_NAMES[colnames(df)]
    df <- df[QUAST_VARS, ASM_TOOL_NAMES]
    return(df)
}

read_plasflow <- function(fname){
118
119
120
121
122
123
124
125
126
127
    print(sprintf("Reading: %s", fname))
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        stringsAsFactors=FALSE,
        check.names=FALSE
    )
    testit::assert(all(df$tool %in% names(ASM_TOOL_NAMES)))
    df$tool <- ASM_TOOL_NAMES[df$tool]
128
129
    df <- df[df$label %in% names(PLASFLOW_NAMES$labels),]
    df$label <- PLASFLOW_NAMES$labels[df$label]
130
131
132
    return(df)
}

133
read_rgi <- function(fname){
134
    print(sprintf("Reading: %s", fname))
135
136
137
138
139
140
141
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        stringsAsFactors=FALSE,
        check.names=FALSE
    )
142
143
144
    colnames(df) <- sapply(colnames(df), function(x){ ifelse(x %in% names(ASM_TOOL_NAMES), ASM_TOOL_NAMES[x], x) })
    testit::assert(all(df$col %in% names(RGI_NAMES$col)))
    df$col <- RGI_NAMES$col[df$col]
145
146
147
    return(df)
}

148
149
150
151
152
153
154
proc_rgi <- function(df){
    df_melted <- reshape2::melt(df, id.vars=c("label", "col", "type"), variable.name="tool", value.name="count")
    df_aggr   <- df_melted[df_melted$col == "ARO",]
    df_aggr   <- aggregate(df_aggr$count, by=list(tool=df_aggr$tool, type=df_aggr$type), FUN=sum)
    return(list(melted=df_melted, aggr=df_aggr))
}

155
read_barrnap <- function(fname){
156
    print(sprintf("Reading: %s", fname))
157
158
159
160
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
161
162
        stringsAsFactors=FALSE,
        check.names=FALSE
163
    )
164
165
    testit::assert(all(df$tool %in% names(ASM_TOOL_NAMES)))
    df$tool <- ASM_TOOL_NAMES[df$tool]
166
167
    testit::assert(all(df$kingdom %in% names(BARRNAP_KINGDOM_NAMES)))
    df$kingdom <- BARRNAP_KINGDOM_NAMES[df$kingdom]
168
169
170
    return(df)
}

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
proc_barrnap <- function(df){
    # total counts per tool, kingdom and partial/complete categories
    df_total <- aggregate(
        df$count,
        by=list(tool=df$tool, kingdom=df$kingdom, partial=grepl("partial", df$gene)),
        FUN=sum
    )
    # partial: FALSE/TRUE -> label
    df_total$partial <- c("complete", "partial")[df_total$partial + 1]
    # add partial + complete = total
    df_total <- rbind(
        df_total,
        aggregate(
            df_total$x,
            by=list(tool=df_total$tool, kingdom=df_total$kingdom, partial=rep("total", nrow(df_total))),
            FUN=sum
        )
    )
    return(df_total)
}

read_crispr <- function(fname){
193
    print(sprintf("Reading: %s", fname))
194
195
196
197
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
198
199
        stringsAsFactors=FALSE,
        check.names=FALSE
200
    )
201
202
203
    # testit::assert(all(df$crispr_tool %in% names(CRISPR_TOOL_NAMES)))
    testit::assert(all(df$tool    %in% names(ASM_TOOL_NAMES)))
    # df$crispr_tool <- CRISPR_TOOL_NAMES[df$crispr_tool]
204
205
206
207
    df$tool <- ASM_TOOL_NAMES[df$tool]
    return(df)
}

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
aggr_crispr <- function(df){
    df_spacers <- aggregate(
        x=df$spacers,
        by=list(tool=df$tool),
        FUN=sum
    )
    rownames(df_spacers) <- df_spacers$tool
    df_arrays <- aggregate(
        x=df$seq_id,
        by=list(tool=df$tool),
        FUN=length
    )
    rownames(df_arrays) <- df_arrays$tool
    return(list(spacers=df_spacers, arrays=df_arrays))
}

224
read_diamondDB <- function(fname){
225
    print(sprintf("Reading: %s", fname))
226
227
228
229
230
231
232
233
234
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        check.names=FALSE,
        stringsAsFactors=FALSE
    )
    testit::assert(all(df$tool %in% names(ASM_TOOL_NAMES)))
    df$tool <- ASM_TOOL_NAMES[df$tool]
235
236
237
    return(df)
}

238
read_ugenes <- function(fname){
239
    print(sprintf("Reading: %s", fname))
240
241
242
243
244
245
246
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        check.names=FALSE,
        stringsAsFactors=FALSE
    )
247
248
249
    df$uniq_pct                 <- 100 * df$uniq / df$total
    df$highcovuniq_pct_total    <- 100 * df$highcovuniq / df$total
    df$highcovuniq_pct_uniq     <- 100 * df$highcovuniq / df$uniq
250
251
    testit::assert(all(df$tool1 %in% names(ASM_TOOL_NAMES)))
    testit::assert(all(df$tool2 %in% names(ASM_TOOL_NAMES)))
252
    df$tool1 <- ASM_TOOL_NAMES[df$tool1]
253
254
255
256
    df$tool2 <- ASM_TOOL_NAMES[df$tool2]
    return(df)
}

257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
read_fastani_many2many <- function(fname){
    print(sprintf("Reading: %s", fname))
    proc_name <- function(x){
        x <- basename(dirname(x))
        testit::assert(x %in% names(ASM_TOOL_NAMES))
        return(ASM_TOOL_NAMES[x])
    }
    dm <- read.csv(file=fname, sep='\t', header=FALSE, check.names=FALSE, stringsAsFactors=FALSE, col.names=c("tool1", "tool2", "ani", "mappings", "queries"))
    dm <- dcast_sq(df=dm[,c("tool1", "tool2", "ani")], col1="tool1", col2="tool2")
    # proc. names
    colnames(dm) <- sapply(colnames(dm), proc_name)
    rownames(dm) <- sapply(rownames(dm), proc_name)
    return(dm)
}

read_mummer_dnadiff <- function(fname){
    print(sprintf("Reading: %s", fname))
    df <- read.csv(file=fname, sep='\t', header=TRUE, check.names=FALSE, stringsAsFactors=FALSE)
    df$seqs_pct  <- 100 * df$seqs_aligned  / df$seqs_total
    df$bases_pct <- 100 * df$bases_aligned / df$bases_total
    testit::assert(all(df$tool1 %in% names(ASM_TOOL_NAMES)))
    testit::assert(all(df$tool2 %in% names(ASM_TOOL_NAMES)))
    df$tool1 <- ASM_TOOL_NAMES[df$tool1]
    df$tool2 <- ASM_TOOL_NAMES[df$tool2]
    return(df)
}

284
read_mash_dist_reads <- function(fname){
285
    print(sprintf("Reading: %s", fname))
286
    proc_name <- function(x){
287
288
289
290
291
        rtype <- basename(dirname(x))
        mtype <- basename(dirname(dirname(x)))
        testit::assert(rtype %in% names(READ_TYPES))
        testit::assert(mtype %in% names(META_TYPES))
        return(sprintf("%s %s", META_TYPES[mtype], READ_TYPES[rtype]))
292
293
294
295
296
297
298
    }
    dm <- read.csv(file=fname, sep='\t', header=TRUE, row.names=1, check.names=FALSE)
    colnames(dm) <- sapply(colnames(dm), proc_name)
    rownames(dm) <- sapply(rownames(dm), proc_name)
    return(dm)
}

299
read_mash_dist_asm <- function(fname){
300
    print(sprintf("Reading: %s", fname))
301
302
303
304
305
306
307
308
309
310
    proc_name <- function(x){
        x <- basename(dirname(x))
        testit::assert(x %in% names(ASM_TOOL_NAMES))
        return(ASM_TOOL_NAMES[x])
    }
    dm <- read.csv(file=fname, sep='\t', header=TRUE, row.names=1, check.names=FALSE)
    colnames(dm) <- sapply(colnames(dm), proc_name)
    rownames(dm) <- sapply(rownames(dm), proc_name)
    return(dm)
}
311

312
313
314
315
316
317
318
319
read_covseg <- function(fname){
    print(sprintf("Reading: %s", fname))
    df <- read.csv(file=fname, sep='\t', header=TRUE, check.names=FALSE)
    testit::assert(all(df$tool %in% names(ASM_TOOL_NAMES)))
    df$tool <- ASM_TOOL_NAMES[df$tool]
    return(df)
}

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
read_mmseqs <- function(fname){
    print(sprintf("Reading: %s", fname))
    df <- read.csv(
        file=fname,
        sep="\t",
        header=TRUE,
        row.names=1,
        check.names=FALSE,
        stringsAsFactors=FALSE
    )
    rownames(df) <- sapply(
        rownames(df),
        function(x){
            # "&" separator for UpSetR plots
            paste(ASM_TOOL_NAMES[unlist(strsplit(x,","))], collapse="&")
        }
    )
    return(df)
}

340
##############################
341
342
# PLOTS

343
344
345
346
draw_empty_plot <- function(text="no data"){
   return(ggplot(data=data.frame(x=0, y=0, text=text)) + geom_text(aes(x=x, y=y, label=text)) + theme_minimal())
}

347
set_tool_order <- function(df, cols, levels_before=c(), levels_behind=c()){
348
    for(cname in cols){
349
        df[,cname] <- factor(df[,cname], ordered=TRUE, levels=c(levels_before,ASM_TOOL_NAMES,levels_behind))
350
351
352
353
    }
    return(df)
}

354
plot_mappability <- function(df){
355
    df <- set_tool_order(df, c("tool"))
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    pp <- 
        ggplot(data=df, aes(x=tool, y=value, fill=tool)) +
        geom_col() +
        geom_text(aes(label=value, y=0.5*value), color="black", size=4, angle=90) +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        facet_wrap(vars(minlength), ncol=2, scales="fixed") +
        labs(
            x="",
            y="Mapped reads [%]"
        ) +
        mappability_theme
    return(pp)
}

plot_prodigal <- function(df_gc, df_gl){
    df_gcm <- reshape2::melt(df_gc[,c("tool", "total", "partial")], id.vars=c("tool"))
372
373
374
    df_gc  <- set_tool_order(df_gc,  c("tool"))
    df_gl  <- set_tool_order(df_gl,  c("tool"))
    df_gcm <- set_tool_order(df_gcm, c("tool"))
375
376
377
    pp1 <-
        ggplot(data=df_gcm, aes(x=variable, y=value, fill=tool)) +
        geom_col(position="dodge") +
378
        scale_fill_manual(values=ASM_TOOL_COLORS) +
379
380
381
382
383
384
385
386
387
        labs(
            x="",
            y="Gene count"
        ) +
        prodigal_theme
    
    pp2 <-
        ggplot(data=df_gc, aes(x=tool, y=partial_pct, fill=tool)) +
        geom_col() +
388
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        labs(
            x="",
            y="Percentage of partial genes"
        ) +
        prodigal_theme
    
    pp3 <-
        ggplot(data=df_gl, aes(x=tool, y=gene_length, fill=tool)) +
        geom_violin(draw_quantiles = c(0.25, 0.5, 0.75)) +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        labs(
            x="",
            y="Gene length [bp]"
        ) +
        diamondDB_theme
    
    pp4 <- pp3 + coord_cartesian(ylim=c(0, 2000))

    return(list(
        gcounts=pp1,
        gpct=pp2,
        glen=pp3,
        glen_zoom=pp4
    ))
}

plot_barrnap <- function(df){
416
    df <- set_tool_order(df, c("tool"))
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    pp <-
        ggplot(data=df, aes(x=tool, y=x, fill=tool)) +
        geom_col() +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        facet_grid(vars(partial), vars(kingdom), scales="fixed") +
        labs(
            x="",
            y=sprintf("rRNA gene hits")
        ) +
        barrnap_theme
    return(pp)
}

plot_barrnap_genes <- function(df, subtitle){
431
    df <- set_tool_order(df, c("tool"))
432
433
434
435
436
437
438
439
440
441
442
443
444
445
    pp <-
        ggplot(data=df, aes(x=tool, y=count, fill=tool)) +
        geom_col() +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        facet_wrap(vars(gene), ncol=1, scales="free_y") +
        labs(
            subtitle=subtitle,
            x="",
            y="rRNA gene hits"
        ) +
        barrnap_theme
    return(pp)
}

446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
plot_rgi_counts_total <- function(df){
    df <- set_tool_order(df, "tool")
    pp <-
        ggplot(data=df, aes(x=tool, y=x, fill=tool)) +
        geom_col() +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        facet_wrap(vars(type), ncol=3) +
        labs(
            x="",
            y="Total hits"
        ) +
        rgi_theme
    return(pp)
}

plot_rgi_counts <- function(df, ctype, col){
    df_ <- df[df$type == ctype & df$col == col,]
    df_ <- set_tool_order(df_, c("tool"))
    pp <-
        ggplot(data=df_, aes(x=tool, y=count, fill=tool)) +
        geom_col() +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        facet_wrap(vars(label), ncol=round(sqrt(length(unique(df_$label)))), scales="free_y") +
        labs(
            x="",
            y=sprintf("%s (%s hits)", col, ctype)
        ) +
        rgi_theme
    return(pp)
}

477
478
479
480
481
482
483
484
485
plot_rgi_overlap <- function(df, ctype, col){
    df <- df[df$type == ctype & df$col == col,]
    df_list <- lapply(ASM_TOOL_NAMES, function(x){ df[df[,x] > 0,"label"] })
    names(df_list) <- ASM_TOOL_NAMES[names(df_list)]
    UpSetR::upset(
        data=UpSetR::fromList(df_list),
        # overlap order
        order.by="degree",
        decreasing=FALSE,
486
487
        # number of sets to plot
        nsets=length(ASM_TOOL_NAMES),
488
489
        # y-label title
        mainbar.y.label=sprintf("Intersection size (%s hits, %s)", ctype, col),
490
        # text size: intersection size title, intersection size tick labels, set size title, set size tick labels, set names, numbers above bars
491
        text.scale = c(1.2, 1.2, 1.2, 1.2, 1.2, 1.2)#,
492
        # colors
493
494
495
496
497
498
499
500
        # set.metadata=list(
        #     data=data.frame(
        #         sets=names(df_list),
        #         Tool=names(df_list),
        #         stringsAsFactors=FALSE
        #     ), 
        #     plots=list(list(type="matrix_rows", column="Tool", colors=ASM_TOOL_COLORS, alpha=0.7))
        # )
501
502
503
    )
}

504
505
plot_crispr <- function(df){
    df_m <- reshape2::melt(df, id.vars="tool")
506
    df_m <- set_tool_order(df_m, c("tool"))
507
    pp <-
508
        ggplot(data=df_m, aes(x=tool, y=value, fill=tool)) +
509
510
        geom_col(position="dodge") +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
511
        facet_wrap(vars(variable), ncol=1, scales="free_y") +
512
513
        labs(
            x="",
514
            y="Number of features"
515
516
517
518
519
520
        ) +
        crispr_theme
    return(pp)
}

plot_plasflow <- function(df, ylab=""){
521
    df <- set_tool_order(df, c("tool"))
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
    pp <-
        ggplot(data=df, aes_string(x="tool", y="value", fill="label")) +
        geom_col(position="dodge") +
        scale_fill_manual(values=PLASFLOW_COLORS$labels, guide="legend") +
        labs(
            x="",
            y=ylab
        ) +
        plasflow_theme
    return(pp)
}

plot_quast <- function(df){
    df_m <- reshape2::melt(
        cbind(stat_vars=rownames(df), df),
        id.vars="stat_vars"
538
    )
539
    df_m <- set_tool_order(df_m, c("variable"))
540
541
542
543
544
545
546
547
548
549
550
    pp <-
        ggplot(data=df_m, aes(x=variable, y=value)) +
        geom_col(aes(fill=variable)) +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        facet_wrap(vars(stat_vars), ncol=2, scales="free_y") +
        labs(
            x="",
            y="QUAST statistic"
        ) +
        quast_theme
    return(pp)
551
552
}

553
plot_ugenes_barplots <- function(df, ycol, ylab="", subtitle=""){
554
    df <- set_tool_order(df, c("tool1", "tool2"))
555
    pp <-
556
        ggplot(data=df, aes_string(x="tool2", y=ycol, fill="tool2")) +
557
558
559
560
        geom_col() +
        facet_wrap(vars(tool1), ncol=1) +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        labs(
561
            subtitle=subtitle,
562
            x="Assembly 2",
563
            y=ylab
564
        ) +
565
        ugenes_theme
566
567
568
    return(pp)
}

569
plot_ugenes_scatterplot <- function(df, subtitle=""){
570
    df <- set_tool_order(df, c("tool1", "tool2"))
571
    pp <-
572
        ggplot(data=df, aes(x=uniq_pct, y=highcovuniq_pct_uniq, fill=tool2, shape=tool2)) +
573
        geom_point(colour="white", size=6) +
574
575
        scale_fill_manual(values=ASM_TOOL_COLORS, name="") +
        scale_shape_manual(values=ASM_TOOL_SHAPES, name="") +
576
        labs(
577
            subtitle=subtitle,
578
            x="Unique proteins [%, total]",
579
            y="Unique proteins w/ high mean cov. [% of unique]"
580
        ) +
581
582
583
584
585
        default_theme +
        theme(
            legend.position="bottom",
            legend.direction="horizontal"
        )
586
587
588
    return(pp)
}

589
plot_diamondDB_density <- function(df, col, xlim=NULL){
590
    df <- set_tool_order(df, c("tool"))
591
592
593
594
595
    pp <-
        ggplot(data=df, aes_string(x=col, colour="tool", fill="tool")) +
        geom_density(alpha=0.2) +
        scale_colour_manual(values=ASM_TOOL_COLORS, guide=NULL) +
        scale_fill_manual(values=ASM_TOOL_COLORS, guide=NULL) +
596
        facet_wrap(vars(tool), nrow=4, scales="fixed") +
597
        labs(
598
            subtitle=ifelse(!is.null(xlim), "zoomed in", ""),
599
600
601
            x=DIAMOND_VAR_LABELLER(col),
            y="Density"
        ) +
602
603
604
605
606
607
608
609
        diamondDB_theme
    if(!is.null(xlim)){
        pp <- pp + coord_cartesian(xlim=xlim)
    }
    return(pp)
}

plot_diamondDB_density2d <- function(df){
610
    df <- set_tool_order(df, c("tool"))
611
612
613
614
    pp <-
        ggplot(data=df, aes(x=qcov, y=scov)) +
        geom_bin2d(bins=25) +
        scale_fill_continuous(type="viridis") +
615
        facet_wrap(vars(tool), ncol=3, nrow=3) +
616
617
618
619
620
621
622
623
        labs(
            x=DIAMOND_VAR_LABELLER("qcov"),
            y=DIAMOND_VAR_LABELLER("scov")
        ) +
        diamondDB_theme
    return(pp)
}

624
plot_mmseqs2_overlap <- function(df, topN=20){
625
626
627
628
    # cluster summary: number of proteins in clusters grouped by represented tools
    upsetr_input <- UpSetR::fromExpression(t(df %>% select(members))[1,,drop=TRUE])
    testit::assert(all( colnames(upsetr_input) %in% ASM_TOOL_NAMES ))
    upsetr_input <- upsetr_input[,ASM_TOOL_NAMES,drop=FALSE]
629
    topN_combis <- rownames(df[with(df, order(-members)), ])[1:topN]
630
631
    UpSetR::upset(
        upsetr_input,
632
        keep.order=TRUE,
633
        nsets=ncol(upsetr_input),
634
635
        sets=ASM_TOOL_NAMES,
        nintersects=topN,
636
637
638
639
640
641
642
643
644
645
646
        order.by="freq",
        decreasing=TRUE,
        # titles
        mainbar.y.label="Total number of proteins in clusters",
        sets.x.label="Total number of proteins per assembly",
        # text size: intersection size title, intersection size tick labels, set size title, set size tick labels, set names, numbers above bars
        text.scale = c(1.2, 1.2, 1.2, 1.2, 1.2, 1),
        # highlight those w/ only one set
        queries=c(
            # unique proteins
            lapply(
647
                intersect(colnames(upsetr_input), topN_combis),
648
649
650
651
652
653
654
655
                function(x){ list(query=intersects, params=list(x), active=TRUE, color=MMSEQS2_UPSETR_HIGHLIGHTS["unique"]) }
            ),
            # all tools
            list(list(query=intersects, params=as.list(colnames(upsetr_input)), active=TRUE, color=MMSEQS2_UPSETR_HIGHLIGHTS["all"]))
        )
    )
}

656
657
658
659
#' Contig coverage and segmentation plot
#' @input df_cov Coverage data.frame incl. contig ID, base, coverage and state
#' @input cid Contig ID
#' @return ggplot2 object
660
plot_contig_covseg <- function(df_cov, cid){
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
    # subset cov.
    df_cov <- df_cov[df_cov$contig==cid,]
    # segments/states medians
    df_cov$state_median <- NA
    for(s in unique(df_cov$state)){
        df_cov$state_median[df_cov$state == s] <- median(df_cov[df_cov$state==s, "cov"])
    }
    # plot
    df_plot <-
        ggplot(data=df_cov, aes(x=base, y=cov)) +
        geom_line(colour="#666666") +
        geom_line(aes(x=base, y=state_median), colour="#0066CC", size=2) +
        scale_x_continuous(breaks=seq(0, max(df_cov$base), by=5000)) +
        scale_y_log10(breaks=trans_breaks("log10", function(x) 10^x), labels=trans_format("log10", math_format(10^.x))) +
        labs(
            title=cid,
            x="base",
            y="coverage"
        ) +
        theme_bw() +
        theme(
            axis.text.x=element_text(angle=90, vjust=0.5, hjust=1)
        )
    return(df_plot)
}

#' Coverage and segmentation scatter plot
#' @input df_states Coverage segmentation summary data.frame
#' @input title Title
#' @input subtitle Sub-title
#' @return ggplot object
692
693
plot_contig_covseg_scatterplot <- function(df_states){
    df_states <- set_tool_order(df_states, c("tool"))
694
695
696
697
698
699
700
701
702
703
704
705
    pp <-
        ggplot(data=df_states[df_states$states > 1,], aes(x=length, y=mean)) +
        geom_point(data=df_states[df_states$states < 2,], aes(x=length, y=mean), shape=4, color="#CCCCCC", size=0.5) +
        geom_point(aes(size=states_median_sd, fill=as.factor(states), color=as.factor(states)), shape=21, alpha=0.75) +
        scale_x_log10(
            breaks=trans_breaks("log10", function(x) 10^x),
            labels=trans_format("log10", math_format(10^.x))
        ) +
        scale_y_log10(
            breaks=trans_breaks("log10", function(x) 10^x),
            labels=trans_format("log10", math_format(10^.x))
        ) +
706
        facet_wrap(vars(tool), ncol=3, nrow=3) +
707
708
709
710
711
712
713
        labs(
            fill="Number of states",
            color="Number of states",
            size="State median SD",
            x="Contig length [bp]",
            y="Mean contig coverage"
        ) +
714
        covseg_theme
715
716
    return(pp)
}
Valentina Galata's avatar
Valentina Galata committed
717

718
719
720
721
722
723
# THEMES
default_theme <-
    # theme_bw() +
    theme_minimal(
        base_size=12
    ) +
Valentina Galata's avatar
Valentina Galata committed
724
    theme(
725
726
        plot.title=element_text(size=14, face="bold"),
        plot.subtitle=element_text(size=12, face="italic"),
Valentina Galata's avatar
Valentina Galata committed
727
        # legend
728
        legend.title=element_text(size=12, face="bold"),
729
        legend.text=element_text(size=12),
Valentina Galata's avatar
Valentina Galata committed
730
731
732
733
        # grid
        panel.grid=element_blank(),
        # strip
        strip.background=element_rect(fill="white"),
734
        strip.text=element_text(size=12),
Valentina Galata's avatar
Valentina Galata committed
735
        # axes
736
737
738
        axis.title=element_text(size=12, color="black"),
        axis.text.y=element_text(size=12, color="black"),
        axis.text.x=element_text(size=12, color="black")
Valentina Galata's avatar
Valentina Galata committed
739
740
    )

741
default_theme_axis_text_x <-
Valentina Galata's avatar
Valentina Galata committed
742
    theme(
743
        axis.text.x=element_text(size=12, color="black", angle=90, vjust=0.5, hjust=1)
Valentina Galata's avatar
Valentina Galata committed
744
745
    )

746
747
748
mappability_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())

crispr_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
Valentina Galata's avatar
Valentina Galata committed
749

750
plasflow_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
Valentina Galata's avatar
Valentina Galata committed
751

752
prodigal_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
Valentina Galata's avatar
Valentina Galata committed
753

754
diamondDB_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
755

756
rgi_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
Valentina Galata's avatar
Valentina Galata committed
757

758
barrnap_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
759

760
quast_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
761

762
ugenes_theme <- default_theme + default_theme_axis_text_x + theme(legend.title=element_blank())
763

764
covseg_theme <- default_theme