-
Notifications
You must be signed in to change notification settings - Fork 1
/
AskoR_bootstrap.R
3482 lines (3129 loc) · 175 KB
/
AskoR_bootstrap.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
477
478
479
480
481
482
483
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
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
654
655
656
657
658
659
660
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
692
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' @title Asko_start
#'
#' @description Initialize and Scans parameters from command line in a python-like style:
#' \itemize{
#' \item declare options, their flags, types, default values and help messages,
#' \item read the arguments passed to the R script and parse them according to what has been declared in step 1.
#' }
#' Parameters can be called by their names as declared in opt object.
#'
#' @return List of parameters that contains all arguments.
#'
#' @examples
#' parameters <- Asko_start()
#' parameters$threshold_cpm <- 1 # Set parameters threshold cpm to new value
#'
#' @note All parameters were describe in README documentation
#'
#' @export
Asko_start <- function(){
# Loading libraries in silent mode (only error messages will be displayed)
pkgs<-c("limma","statmod","edgeR","VennDiagram","RColorBrewer","UpSetR","grid","topGO","ggfortify","gghalves","tidyverse",
"Rgraphviz","ggplot2","ggrepel","gplots","stringr","optparse","goSTAG","Glimma","ComplexHeatmap","cowplot","circlize","corrplot")
for(p in pkgs) suppressWarnings(suppressMessages(library(p, quietly=TRUE, character.only=TRUE, warn.conflicts=FALSE)))
# Specify desired options in a list
option_list = list(
optparse::make_option(c("-o", "--out"), type="character", default="AskoRanalysis",dest="analysis_name",
help="output directory name [default= %default]", metavar="character"),
optparse::make_option(c("-d", "--dir"), type="character", default=".",dest="dir_path",
help="data directory path [default= %default]", metavar="character"),
optparse::make_option(c("-O", "--org"), type="character", default="Asko", dest="organism",
help="Organism name [default= %default]", metavar="character"),
optparse::make_option(c("-f", "--fileofcount"), type="character", default=NULL, dest="fileofcount",
help="file of counts [default= %default]", metavar="character"),
optparse::make_option(c("-G", "--col_genes"), type="integer", default=1, dest="col_genes",
help="col of genes ids in count files [default= %default]", metavar="integer"),
optparse::make_option(c("-C", "--col_counts"), type="integer", default=7,dest="col_counts",
help="col of counts in count files [default= %default (featureCounts) ]", metavar="integer"),
optparse::make_option(c("-t", "--sep"), type="character", default="\t", dest="sep",
help="field separator for count files or count matrix [default= %default]", metavar="character"),
optparse::make_option(c("-a", "--annotation"), type="character", default=NULL, dest="annotation",
help="annotation file [default= %default]", metavar="character"),
optparse::make_option(c("-s", "--sample"), type="character", default="Samples.txt", dest="sample_file",
help="Samples file [default= %default]", metavar="character"),
optparse::make_option(c("-c", "--contrasts"), type="character", default="Contrasts.txt",dest="contrast_file",
help="Contrasts file [default= %default]", metavar="character"),
optparse::make_option(c("-k", "--mk_context"), type="logical", default=FALSE,dest="mk_context",
help="generate automatically the context names [default= %default]", metavar="logical"),
optparse::make_option(c("--palette"), type="character", default="Set2", dest="palette",
help="Color palette (ggplot)[default= %default]", metavar="character"),
optparse::make_option(c("-R", "--regex"), type="logical", default=FALSE, dest="regex",
help="use regex when selecting/removing samples [default= %default]", metavar="logical"),
optparse::make_option(c("-S", "--select"), type="character", default=NULL, dest="select_sample",
help="selected samples [default= %default]", metavar="character"),
optparse::make_option(c("-r", "--remove"), type="character", default=NULL, dest="rm_sample",
help="removed samples [default= %default]", metavar="character"),
optparse::make_option(c("--th_cpm"), type="double", default=0.5, dest="threshold_cpm",
help="CPM's threshold [default= %default]", metavar="double"),
optparse::make_option(c("--rep"), type="integer", default=3, dest="replicate_cpm",
help="Minimum number of replicates [default= %default]", metavar="integer"),
optparse::make_option(c("--th_FDR"), type="double", default=0.05, dest="threshold_FDR",
help="FDR threshold [default= %default]", metavar="double"),
optparse::make_option(c("-n", "--normalization"), type="character", default="TMM", dest="normal_method",
help="normalization method (TMM/RLE/upperquartile/none) [default= %default]", metavar="character"),
optparse::make_option(c("--adj"), type="character", default="fdr", dest="p_adj_method",
help="p-value adjust method (holm/hochberg/hommel/bonferroni/BH/BY/fdr/none) [default= %default]", metavar="character"),
optparse::make_option("--glm", type="character", default="qlf", dest="glm",
help="GLM method (lrt/qlf) [default= %default]", metavar="character"),
optparse::make_option("--glmDisp", type="logical", default=FALSE, dest="glm_disp",
help="Estimate Common, Trended and Tagwise Negative Binomial dispersions GLMs (TRUE/FALSE) [default= %default]", metavar="logical"),
optparse::make_option(c("--lfc"), type="logical", default=TRUE, dest="logFC",
help="logFC in the summary table [default= %default]", metavar="logical"),
optparse::make_option(c("--th_lfc"), type="double", default=0, dest="threshold_logFC",
help="logFC threshold [default= %default]", metavar="double"),
optparse::make_option("--CompleteHm", type="logical", default=FALSE, dest="CompleteHeatmap",
help="generation of the normalized expression heatmap on ALL genes (TRUE/FALSE) [default= %default]", metavar="logical"),
optparse::make_option("--fc", type="logical", default=TRUE, dest="FC",
help="FC in the summary table [default= %default]", metavar="logical"),
optparse::make_option(c("--lcpm"), type="logical", default=FALSE, dest="logCPM",
help="logCPm in the summary table [default= %default]", metavar="logical"),
optparse::make_option("--fdr", type="logical", default=TRUE, dest="FDR",
help="FDR in the summary table [default= %default]", metavar="logical"),
optparse::make_option("--lr", type="logical", default=FALSE, dest="LR",
help="LR in the summary table [default= %default]", metavar="logical"),
optparse::make_option(c("--sign"), type="logical", default=TRUE, dest="Sign",
help="Significance (1/0/-1) in the summary table [default= %default]", metavar="logical"),
optparse::make_option(c("--expr"), type="logical", default=TRUE, dest="Expression",
help="Significance expression in the summary table [default= %default]", metavar="logical"),
optparse::make_option(c("--mc"), type="logical", default=TRUE, dest="mean_counts",
help="Mean counts in the summary table [default= %default]", metavar="logical"),
optparse::make_option(c("--dclust"), type="character", default="euclidean", dest="distcluts",
help="The distance measure to be used : euclidean, maximum, manhattan, canberra, binary or minkowski [default= %default]", metavar="character"),
optparse::make_option(c("--hclust"), type="character", default="complete", dest="hclust",
help="The agglomeration method to be used : ward.D, ward.D2, single, complete, average, mcquitty, median or centroid [default= %default]", metavar="character"),
optparse::make_option(c("--hm"), type="logical", default=TRUE, dest="heatmap",
help="generation of the expression heatmap [default= %default]", metavar="logical"),
optparse::make_option(c("--nh"), type="integer", default="50", dest="numhigh",
help="number of genes in the heatmap [default= %default]", metavar="integer"),
optparse::make_option(c("--norm_factor"), type="logical", default=FALSE, dest="norm_factor",
help="generate file with normalize factor for each condition/sample [default= %default]", metavar="logical"),
optparse::make_option(c("--norm_counts"), type="logical", default=FALSE, dest="norm_counts",
help="Generate files with mormalized counts [default= %default]", metavar="logical"),
optparse::make_option(c("--VD"), type="character", default=NULL, dest="VD",
help="Plot VennDiagram, precise type of comparison: all, down, up or both [default=%default]", metavar = "character"),
optparse::make_option(c("--compaVD"), type="character", default=NULL, dest="compaVD",
help="Contrast comparison list to display in VennDiagram [default= %default]", metavar="character"),
optparse::make_option(c("--GO"), type="character", default=NULL, dest="GO",
help="GO enrichment analysis for gene expressed 'up', 'down' or 'both', NULL for no GO enrichment. [default= %default]", metavar="character"),
optparse::make_option(c("--ID2GO"), type="character", default=NULL, dest="geneID2GO_file",
help="GO annotation file [default= %default]", metavar="character"),
optparse::make_option(c("--GO_threshold"), type="numeric", default="0.05", dest="GO_threshold",
help="the significant threshold used to filter p-values [default=%default]", metavar="double"),
optparse::make_option(c("--GO_min_num_genes"), type="integer", default="10", dest="GO_min_num_genes",
help="the minimum number of genes for each GO terms [default=%default]", metavar="integer"),
optparse::make_option(c("--GO_min_sig_genes"), type="integer", default="0", dest="GO_min_sig_genes",
help="the minimum number of significant gene(s) behind the enriched GO-term [default=%default]", metavar="integer"),
optparse::make_option(c("--GO_max_top_terms"), type="integer", default="10", dest="GO_max_top_terms",
help="the maximum number of GO terms plot [default=%default]", metavar="integer"),
optparse::make_option(c("--GO_algo"), type="character", default="weight01", dest="GO_algo",
help="algorithms which are accessible via the runTest function: shown by the whichAlgorithms() function, [default=%default]", metavar="character"),
optparse::make_option(c("--GO_stats"), type="character", default="fisher", dest="GO_stats",
help = "statistical tests which are accessible via the runTest function: shown by the whichTests() function, [default=%default]", metavar = "character"),
optparse::make_option(c("--Ratio_threshold"), type="numeric", default="0", dest="Ratio_threshold",
help="the minimum ratio value to display GO in graph [default=%default]", metavar="double"),
optparse::make_option(c("--plotMD"),type="logical", default=FALSE, dest="plotMD", metavar="logical",
help="Mean-Difference Plot of Expression Data (aka MA plot) [default= %default]"),
optparse::make_option(c("--plotVO"),type="logical", default=FALSE, dest="plotVO", metavar="logical",
help="Volcano plot for a specified coefficient/contrast of a linear model [default= %default]"),
optparse::make_option(c("--glimMD"),type="logical", default=FALSE, dest="glimMD", metavar="logical",
help="Glimma - Interactif Mean-Difference Plot of Expression Data (aka MA plot) [default= %default]"),
optparse::make_option(c("--glimVO"),type="logical", default=FALSE, dest="glimVO", metavar="logical",
help="Glimma - Interactif Volcano plot for a specified coefficient/contrast of a linear model [default= %default]"),
optparse::make_option(c("--dens_bottom_mar"), type="integer", default="20", dest="densbotmar", metavar="integer",
help="Set bottom margin of density plot to help position the legend [default= %default]"),
optparse::make_option(c("--dens_inset"), type="double", default="0.45", dest="densinset", metavar="double",
help="Set position the legend in bottom density graphe [default= %default]"),
optparse::make_option(c("--legend_col"), type="integer", default="6", dest="legendcol", metavar="integer",
help="Set numbers of column for density plot legends [default= %default]"),
optparse::make_option(c("--upset_basic"),type="character", default=NULL, dest="upset_basic",
help="Display UpSetR charts for all contrasts, precise type of comparison: all, down, up, mixed [default=%default].", metavar = "character"),
optparse::make_option(c("--upset_type"),type="character", default=NULL, dest="upset_type",
help="Display UpSetR charts for list of contrasts, precise type of comparison: all, down, up, mixed [default=%default].", metavar = "character"),
optparse::make_option(c("--upset_list"), type="character", default=NULL, dest="upset_list",
help="Contrast comparison list to display in UpSetR chart. See documentation. [default=%default]", metavar="character"),
optparse::make_option("--coseq_data", type="character", default="ExpressionProfiles", dest="coseq_data",
help="Coseq data (ExpressionProfiles, LogScaledData) [default= %default]", metavar="character"),
optparse::make_option("--coseq_model", type="character", default="kmeans", dest="coseq_model",
help="Coseq model (kmeans, Normal) [default= %default]", metavar="character"),
optparse::make_option("--coseq_transformation", type="character", default="clr", dest="coseq_transformation",
help="Coseq tranformation (voom, logRPKM, arcsin, logit, logMedianRef, logclr, clr, alr, ilr, none) [default= %default]", metavar="character"),
optparse::make_option("--coseq_ClustersNb", type="double", default=2:25, dest="coseq_ClustersNb",
help="Coseq : number of clusters desired (2:25 (auto), number from 2 to 25) [default= %default]", metavar="double"),
optparse::make_option("--coseq_HeatmapOrderSample", type="logical", default=FALSE, dest="coseq_HeatmapOrderSample",
help="Choose TRUE if you prefer keeping your sample order than clusterizing samples in heatmap [default= %default]", metavar="logical")
)
# Get command line options
opt_parser = optparse::OptionParser(option_list=option_list)
parameters = optparse::parse_args(opt_parser)
if(is.null(parameters$rm_sample) == FALSE ) {
stringr::str_replace_all(parameters$rm_sample, " ", "")
parameters$rm_sample<-limma::strsplit2(parameters$rm_sample, ",")
}
if(is.null(parameters$select_sample) == FALSE ) {
stringr::str_replace_all(parameters$select_sample, " ", "")
parameters$select_sample<-limma::strsplit2(parameters$select_sample, ",")
}
return(parameters)
}
#' @title loadData
#'
#' @description
#' Function to load :
#' \itemize{
#' \item Count data (one of this below):
#' \itemize{
#' \item count matrix : 1 file with all counts for each samples/conditions or multiple
#' \item list of files : 1 file of count per conditions, files names contained in sample file
#' }
#' \item Metatdata :
#' \itemize{
#' \item sample file : file describing the samples and the experimental design
#' \item contrast file : matrix which specifies which comparisons you would like to make between the samples
#' \item (optional) annotation file : functional/genomic annotation for each genes
#' \item (optional) GO terms annotations files : GO annotations for each genes
#' }
#' }
#' Three output directory will be create :
#' \itemize{
#' \item images : contains all the images created when running this pipeline with the exception of the upsetR and Venn graphs.
#' \item vennDiagram : contain all venn diagrams created by VD function
#' \item UpSetR_graphs : contain all upset graphs created by UpSetGraph function
#' \item Askomics : files compatible with Askomics Software
#' }
#'
#' @param parameters, list that contains all arguments charged in Asko_start
#' @return data, list contain all data and metadata (DGEList, samples descriptions, contrast, design and annotations)
#'
#' @examples
#' \dontrun{
#' parameters<-Asko_start()
#' data<-loadData(parameters)
#' }
#'
#' @export
loadData <- function(parameters){
# Folders for output files
#---------------------------------------------------------
cat("\nCreated directories:\n")
study_dir = paste0(parameters$dir_path,"/", parameters$analysis_name, "/")
if(dir.exists(study_dir)==FALSE){ dir.create(study_dir) }
cat("\t",study_dir,"\n")
explo_dir = paste0(study_dir,"DataExplore/")
if(dir.exists(explo_dir)==FALSE){ dir.create(explo_dir) }
cat("\t",explo_dir,"\n")
de_dir = paste0(study_dir,"DEanalysis/")
if(dir.exists(de_dir)==FALSE){ dir.create(de_dir) }
cat("\t",de_dir,"\n")
image_dir = paste0(de_dir, "Images/")
if(dir.exists(image_dir)==FALSE){ dir.create(image_dir) }
cat("\t",image_dir,"\n")
asko_dir = paste0(de_dir, "AskoTables/")
if(dir.exists(asko_dir)==FALSE){ dir.create(asko_dir) }
cat("\t",asko_dir,"\n")
if(is.null(parameters$VD)==FALSE){
venn_dir = paste0(study_dir, "VennDiagrams/")
if(dir.exists(venn_dir)==FALSE){ dir.create(venn_dir) }
cat("\t",venn_dir,"\n")
}
if((is.null(parameters$upset_basic)==FALSE) || (is.null(parameters$upset_list)==FALSE && is.null(parameters$upset_type)==FALSE)){
upset_dir = paste0(study_dir, "UpsetGraphs/")
if(dir.exists(upset_dir)==FALSE){ dir.create(upset_dir) }
cat("\t",upset_dir,"\n")
}
# Management of input files
#---------------------------------------------------------
input_path = "/import/"
# Sample file
sample_path<-paste0(input_path, parameters$sample_file)
samples<-utils::read.csv(sample_path, header=TRUE, sep="\t", row.names=1)
# Selecting some sample (select_sample parameter)
if(is.null(parameters$select_sample)==FALSE){
if(parameters$regex==TRUE){
selected<-c()
for(sel in parameters$select_sample){
select<-grep(sel, rownames(samples))
if(is.null(selected)){selected=select}else{selected<-append(selected, select)}
}
samples<-samples[selected,]
}
else{ samples<-samples[parameters$select_sample,] }
}
# Deleting some samples (rm_sample parameter)
if(is.null(parameters$rm_sample)==FALSE){
if(parameters$regex==TRUE){
for(rm in parameters$rm_sample){
removed<-grep(rm, rownames(samples))
if(length(removed!=0)){samples<-samples[-removed,]}
}
}
else{
for (rm in parameters$rm_sample) {
rm2<-match(rm, rownames(samples))
samples<-samples[-rm2,]
}
}
}
# Conditions and colors
if(is.null(samples$color)==TRUE){
condition<-unique(samples$condition)
if(length(condition)<3){ color=c("#FF9999","#99CCFF") }
else{ color<-grDevices::colorRampPalette(RColorBrewer::brewer.pal(11,"Spectral"))(length(condition)) }
samples$color<-NA
j=0
for(name in condition){
j=j+1
samples$color[samples$condition==name]<-color[j]
}
}
else if(typeof(samples$colors)!="character"){
color<-as.character(unlist(samples$color))
samples$color<-color
}
# Count file(s).
# Two possibilities:
# - 1 count file per condition
# - a matrix of count for all samples/conditions
#----------------------------------------------------
# Multiple count files, 1 per conditions
if(is.null(parameters$fileofcount)){
cat("\nFiles of counts:\n")
print(samples$file)
cat("\nSamples:\n")
print(rownames(samples))
# creates a DGEList object from a table of counts
dge<-edgeR::readDGE(paste0(input_path,samples$file), labels=rownames(samples), columns=c(parameters$col_genes,parameters$col_counts), header=TRUE, comment.char="#")
dge<-edgeR::DGEList(counts=dge$counts, samples=samples)
}
# Matrix file with all counts for all conditions
else{
cat("\nSamples:\n")
print(rownames(samples))
count_path<-paste0(input_path, parameters$fileofcount)
if(grepl(".csv", parameters$fileofcount)==TRUE){
count<-utils::read.csv(count_path, header=TRUE, sep = "\t", row.names = parameters$col_genes, comment.char="#")
}
else{
count<-utils::read.table(count_path, header=TRUE, sep = "\t", row.names = parameters$col_genes, comment.char="#")
}
# If you ask for some samples were removed for analysis
select_counts<-row.names(samples)
countT<-count[,select_counts]
# Creates a DGEList object from a table of counts
dge<-edgeR::DGEList(counts=countT, samples=samples)
}
# Experimental design
#---------------------------------------------------------
Group<-factor(samples$condition)
cat("\nConditions :\n")
print(Group)
designExp<-stats::model.matrix(~0+Group)
rownames(designExp) <- row.names(samples)
colnames(designExp) <- levels(Group)
# Contrast for DE analysis
#---------------------------------------------------------
contrast_path<-paste0(input_path, parameters$contrast_file)
contrastab<-utils::read.table(contrast_path, sep="\t", header=TRUE, row.names = 1, comment.char="#", stringsAsFactors = FALSE)
# Verify if some colunms will be not use for analysis
rmcol<-list()
for(condition_name in row.names(contrastab)){
test<-match(condition_name, colnames(designExp),nomatch = 0)
if(test==0){
rm<-grep("0", contrastab[condition_name,], invert = TRUE)
if(is.null(rmcol)){rmcol=rm}else{rmcol<-append(rmcol, rm)}
}
}
# If it's the case then it delete them
if (length(rmcol)> 0){
rmcol<-unlist(rmcol)
rmcol<-unique(rmcol)
contrastab<-subset(contrastab, select=-rmcol)
}
contrastab2<-as.data.frame(contrastab[colnames(designExp),])
colnames(contrastab2)<-colnames(contrastab)
rownames(contrastab2)<-colnames(designExp)
# Sort contrast table if more than one contrast in contrastab
if(length(contrastab2)>1){
ord<-match(colnames(designExp),row.names(contrastab2), nomatch = 0)
contrast_table<-contrastab2[ord,]
}
else{
contrast_table<-contrastab2
}
cat("\nContrasts:\n")
print(contrast_table)
# Format contrast : convert "+" to "1" and - to "-1"
colnum<-c()
for(contrast in colnames(contrast_table)){
set_cond1<-row.names(contrast_table)[contrast_table[,contrast]=="+"]
set_cond2<-row.names(contrast_table)[contrast_table[,contrast]=="-"]
if(length(set_cond1)!=length(set_cond2)){
contrast_table[,contrast][contrast_table[,contrast]=="+"]=signif(1/length(set_cond1),digits = 2)
contrast_table[,contrast][contrast_table[,contrast]=="-"]=signif(-1/length(set_cond2),digits = 2)
}
else {
contrast_table[,contrast][contrast_table[,contrast]=="+"]=1
contrast_table[,contrast][contrast_table[,contrast]=="-"]=-1
}
contrast_table[,contrast]<-as.numeric(contrast_table[,contrast])
}
data<-list("dge"=dge, "samples"=samples, "contrast"=contrast_table, "design"=designExp)
# Annnotation file
if(is.null(parameters$annotation)==FALSE){
annot<-utils::read.csv(paste0(input_path, parameters$annotation), header = TRUE, row.names = 1, sep = '\t', quote = "")
data[["annot"]]=annot
}
return(data)
}
#' @title asko3c
#'
#' @description Create contrast/condition/context file in format readable by Askomics Software.
#'
#' @param data_list, list contain all data and metadata (DGEList, samples descriptions, contrast, design and annotations)
#' @param parameters, list that contains all arguments charged in Asko_start
#' @return asko, list of data.frame contain condition, contrast and context information
#'
#' @examples
#' \dontrun{
#' parameters <- Asko_start()
#' data<-loadData(parameters)
#' asko<-asko3c(data, parameters)
#' }
#'
#' @export
asko3c <- function(data_list, parameters){
study_dir = paste0(parameters$dir_path,"/", parameters$analysis_name, "/")
# Askomics directory
asko_dir = paste0(study_dir, "DEanalysis/AskoTables/")
asko<-list()
# Condition
#---------------
condition<-unique(data_list$samples$condition) # retrieval of different condition's names
col1<-which(colnames(data_list$samples)=="condition") # determination of number of the column "condition"
colcol<-which(colnames(data_list$samples)=="color")
if(is.null(parameters$fileofcount)){
col2<-which(colnames(data_list$samples)=="file") # determination of number of the column "replicate"
column_name<-colnames(data_list$samples[,c(-col1,-col2,-colcol)]) # retrieval of column names needful to create the file condition
}else{column_name<-colnames(data_list$samples[,c(-col1,-colcol)])}
condition_asko<-data.frame(row.names=condition) # initialization of the condition's data frame
for (name in column_name){ # for each experimental factor :
condition_asko$n<-NA # initialization of new column in the condition's data frame
colnames(condition_asko)[colnames(condition_asko)=="n"]<-name # to rename the new column with the name of experimental factor
for(condition_name in condition){ # for each condition's names
condition_asko[condition_name,name]<-as.character(unique(data_list$samples[data_list$samples$condition==condition_name, name]))
} # filling the condition's data frame
}
# Contrast + Context
#--------------------------
i=0
contrast_asko<-data.frame(row.names = colnames(data_list$contrast)) # initialization of the contrast's data frame
contrast_asko$Contrast<-NA # all columns are created et initialized with
contrast_asko$context1<-NA # NA values
contrast_asko$context2<-NA #
list_context<-list() # initialization of context and condition lists
list_condition<-list() # will be used to create the context data frame
if(parameters$mk_context==TRUE){
for (contrast in colnames(data_list$contrast)){ # for each contrast :
i=i+1 # contrast data frame will be filled line by line
set_cond1<-row.names(data_list$contrast)[data_list$contrast[,contrast]>0] # retrieval of 1st set of condition's names implicated in a given contrast
set_cond2<-row.names(data_list$contrast)[data_list$contrast[,contrast]<0] # retrieval of 2nd set of condition's names implicated in a given contrast
set_condition<-colnames(condition_asko) # retrieval of names of experimental factor
if(length(set_cond1)==1){complex1=FALSE}else{complex1=TRUE} # to determine if we have complex contrast (multiple conditions
if(length(set_cond2)==1){complex2=FALSE}else{complex2=TRUE} # compared to multiple conditions) or not
if(complex1==FALSE && complex2==FALSE){ # Case 1: one condition against one condition
contrast_asko[i,"context1"]<-set_cond1 # filling contrast data frame with the name of the 1st context
contrast_asko[i,"context2"]<-set_cond2 # filling contrast data frame with the name of the 2nd context
contrast_name<-paste(set_cond1,set_cond2, sep = "vs") # creation of contrast name by associating the names of contexts
contrast_asko[i,"Contrast"]<-contrast_name # filling contrast data frame with contrast name
list_context<-append(list_context, set_cond1) #
list_condition<-append(list_condition, set_cond1) # adding respectively to the lists "context" and "condition" the context name
list_context<-append(list_context, set_cond2) # and the condition name associated
list_condition<-append(list_condition, set_cond2) #
}
if(complex1==FALSE && complex2==TRUE){ # Case 2: one condition against multiple condition
contrast_asko[i,"context1"]<-set_cond1 # filling contrast data frame with the name of the 1st context
list_context<-append(list_context, set_cond1) # adding respectively to the lists "context" and "condition" the 1st context
list_condition<-append(list_condition, set_cond1) # name and the condition name associated
l=0
# "common_factor" will contain the common experimental factors shared by
common_factor=list() # conditions belonging to the complex context
for (param_names in set_condition){ # for each experimental factor
facteur<-unique(c(condition_asko[,param_names])) # retrieval of possible values for the experimental factor
l=l+1 #
for(value in facteur){ # for each possible values
verif<-unique(stringr::str_detect(set_cond2, value)) # verification of the presence of values in each condition contained in the set
if(length(verif)==1 && verif==TRUE){common_factor[l]<-value} # if verif contains only TRUE, value of experimental factor
} # is added as common factor
}
if(length(common_factor)>1){ # if there are several common factor
common_factor<-toString(common_factor) # the list is converted to string
contx<-stringr::str_replace(common_factor,", ","")
contx<-stringr::str_replace_all(contx, "NULL", "")}else{contx<-common_factor} # and all common factor are concatenated to become the name of context
contrast_asko[i,"context2"]<-contx # filling contrast data frame with the name of the 2nd context
contrast_name<-paste(set_cond1,contx, sep = "vs") # concatenation of context names to make the contrast name
contrast_asko[i,"Contrast"]<-contrast_name # filling contrast data frame with the contrast name
for(j in length(set_cond2)){ # for each condition contained in the complex context (2nd):
list_context<-append(list_context, contx) # adding condition name with the context name associated
list_condition<-append(list_condition, set_cond2[j]) # to their respective list
}
}
if(complex1==TRUE && complex2==FALSE){ # Case 3: multiple conditions against one condition
contrast_asko[i,"context2"]<-set_cond2 # filling contrast data frame with the name of the 2nd context
list_context<-append(list_context, set_cond2) # adding respectively to the lists "context" and "condition" the 2nd context
list_condition<-append(list_condition, set_cond2) # name and the 2nd condition name associated
l=0
# "common_factor" will contain the common experimental factors shared by
common_factor=list() # conditions belonging to the complex context
for (param_names in set_condition){ # for each experimental factor:
facteur<-unique(c(condition_asko[,param_names])) # retrieval of possible values for the experimental factor
l=l+1
for(value in facteur){ # for each possible values:
verif<-unique(stringr::str_detect(set_cond1, value)) # verification of the presence of values in each condition contained in the set
if(length(verif)==1 && verif==TRUE){common_factor[l]<-value} # if verif contains only TRUE, value of experimental factor
} # is added as common factor
}
if(length(common_factor)>1){ # if there are several common factor
common_factor<-toString(common_factor) # the list is converted to string
contx<-stringr::str_replace(common_factor,", ","")
contx<-stringr::str_replace_all(contx, "NULL", "")}else{contx<-common_factor} # and all common factor are concatenated to become the name of context
contrast_asko[i,"context1"]<-contx # filling contrast data frame with the name of the 1st context
contrast_name<-paste(contx,set_cond2, sep = "vs") # concatenation of context names to make the contrast name
contrast_asko[i,"Contrast"]<-contrast_name # filling contrast data frame with the contrast name
for(j in length(set_cond1)){ # for each condition contained in the complex context (1st):
list_context<-append(list_context, contx) # adding condition name with the context name associated
list_condition<-append(list_condition, set_cond1[j]) # to their respective list
}
}
if(complex1==TRUE && complex2==TRUE){ # Case 4: multiple conditions against multiple conditions
m=0 #
n=0 #
common_factor1=list() # list of common experimental factors shared by conditions of the 1st context
common_factor2=list() # list of common experimental factors shared by conditions of the 2nd context
w=1
for (param_names in set_condition){ # for each experimental factor:
print(w)
w=w+1
facteur<-unique(c(condition_asko[,param_names])) # retrieval of possible values for the experimental factor
for(value in facteur){ # for each possible values:
verif1<-unique(stringr::str_detect(set_cond1, value)) # verification of the presence of values in each condition contained in the 1st context
verif2<-unique(stringr::str_detect(set_cond2, value)) # verification of the presence of values in each condition contained in the 2nd context
if(length(verif1)==1 && verif1==TRUE){m=m+1;common_factor1[m]<-value} # if verif=only TRUE, value of experimental factor is added as common factor
if(length(verif2)==1 && verif2==TRUE){n=n+1;common_factor2[n]<-value} # if verif=only TRUE, value of experimental factor is added as common factor
}
}
if(length(common_factor1)>1){ # if there are several common factor for conditions in the 1st context
common_factor1<-toString(common_factor1) # conversion list to string
contx1<-stringr::str_replace(common_factor1,", ","")}else{contx1<-common_factor1}# all common factor are concatenated to become the name of context
contx1<-stringr::str_replace_all(contx1, "NULL", "")
if(length(common_factor2)>1){ # if there are several common factor for conditions in the 2nd context
common_factor2<-toString(common_factor2) # conversion list to string
contx2<-stringr::str_replace(common_factor2,", ","")}else{contx2<-common_factor2}# all common factor are concatenated to become the name of context
contx2<-stringr::str_replace_all(contx2, "NULL", "")
contrast_asko[i,"context1"]<-contx1 # filling contrast data frame with the name of the 1st context
contrast_asko[i,"context2"]<-contx2 # filling contrast data frame with the name of the 2nd context
contrast_asko[i,"Contrast"]<-paste(contx1,contx2, sep = "vs") # filling contrast data frame with the name of the contrast
for(j in seq_along(set_cond1)){ # for each condition contained in the complex context (1st):
list_context<-append(list_context, contx1) # verification of the presence of values in each condition
list_condition<-append(list_condition, set_cond1[j]) # contained in the 1st context
}
for(j in seq_along(set_cond2)){ # for each condition contained in the complex context (2nd):
list_context<-append(list_context, contx2) # verification of the presence of values in each condition
list_condition<-append(list_condition, set_cond2[j]) # contained in the 1st context
}
}
}
}
else{
for (contrast in colnames(data_list$contrast)){
i=i+1
contexts=limma::strsplit2(contrast,"vs")
contrast_asko[i,"Contrast"]<-contrast
contrast_asko[i,"context1"]=contexts[1]
contrast_asko[i,"context2"]=contexts[2]
set_cond1<-row.names(data_list$contrast)[data_list$contrast[,contrast]>0]
set_cond2<-row.names(data_list$contrast)[data_list$contrast[,contrast]<0]
for (cond1 in set_cond1){
list_context<-append(list_context, contexts[1])
list_condition<-append(list_condition, cond1)
}
for (cond2 in set_cond2){
list_context<-append(list_context, contexts[2])
list_condition<-append(list_condition, cond2)
}
}
}
list_context<-unlist(list_context)
list_condition<-unlist(list_condition) # conversion list to vector
context_asko<-data.frame(list_context,list_condition) # creation of the context data frame
context_asko<-unique(context_asko)
colnames(context_asko)[colnames(context_asko)=="list_context"]<-"context" # header formatting for askomics
colnames(context_asko)[colnames(context_asko)=="list_condition"]<-"condition" # header formatting for askomics
asko<-list("condition"=condition_asko, "contrast"=contrast_asko, "context"=context_asko) # adding context data frame to asko object
colnames(context_asko)[colnames(context_asko)=="context"]<-"Context" # header formatting for askomics
colnames(context_asko)[colnames(context_asko)=="condition"]<-"has@Condition" # header formatting for askomics
colnames(contrast_asko)[colnames(contrast_asko)=="context1"]<-paste("context1_of", "Context", sep="@") # header formatting for askomics
colnames(contrast_asko)[colnames(contrast_asko)=="context2"]<-paste("context2_of", "Context", sep="@") # header formatting for askomics
# Files creation
#-------------------
# creation of condition file for asko
utils::write.table(data.frame("Condition"=row.names(condition_asko),condition_asko),
paste0(asko_dir,"condition.asko.txt"),
sep = parameters$sep,
row.names = FALSE,
quote=FALSE)
# creation of context file for asko
utils::write.table(context_asko,
paste0(asko_dir, "context.asko.txt"),
sep=parameters$sep,
col.names = TRUE,
row.names = FALSE,
quote=FALSE)
# creation of contrast file for asko
utils::write.table(contrast_asko,
paste0(asko_dir, "contrast.asko.txt"),
sep=parameters$sep,
col.names = TRUE,
row.names = FALSE,
quote=FALSE)
return(asko)
}
#' @title GEfilt
#'
#' @description
#' \itemize{
#' \item Filter genes according to cpm threshold value and replicated cpm option value.
#' \item Plot different graphes to explore data before and after filtering.
#' }
#'
#' @param data_list, list contain all data and metadata (DGEList, samples descritions, contrast, design and annotations)
#' @param parameters, list that contains all arguments charged in Asko_start
#' @return filtered_counts, large DGEList with filtered counts and data descriptions.
#'
#' @examples
#' \dontrun{
#' filtered_counts<-GEfilt(data, parameters)
#' }
#'
#' @export
GEfilt <- function(data_list, parameters){
study_dir = paste0(parameters$dir_path,"/", parameters$analysis_name, "/")
image_dir = paste0(study_dir, "DataExplore/")
# plot density before filtering
#---------------------------------
cpm<-edgeR::cpm(data_list$dge)
logcpm<-edgeR::cpm(data_list$dge, log=TRUE)
colnames(logcpm)<-rownames(data_list$dge$samples)
nsamples <- ncol(data_list$dge$counts)
maxi<-c()
for (i in seq(nsamples)){
m=max(stats::density(logcpm[,i])$y)
maxi<-c(maxi,m)
}
ymax<-round(max(maxi),1) + 0.02
sizeImg=15*nsamples
if(sizeImg < 480){ sizeImg=480 }
btm=round((nsamples/6),0)+0.5
grDevices::png(paste0(image_dir, parameters$analysis_name, "_raw_data.png"), width=1024, height=1024)
graphics::par(oma=c(2,2,2,0), mar=c(parameters$densbotmar,5,5,5))
plot(stats::density(logcpm[,1]),
col=as.character(data_list$dge$samples$color[1]),
lwd=1,
las=2,
ylim=c(0,ymax),
main="A. Raw data",
xlab="Log-cpm")
graphics::abline(v=0, lty=3)
for (i in 2:nsamples){
den<-stats::density(logcpm[,i])
graphics::lines(den$x, col=as.character(data_list$dge$samples$color[i]), den$y, lwd=1)
}
graphics::legend("bottom", fill=data_list$dge$samples$color, bty="n", ncol=parameters$legendcol,
legend=rownames(data_list$dge$samples), xpd=TRUE, inset=-parameters$densinset)
grDevices::dev.off()
# plot density after filtering
#---------------------------------
keep.exprs <- rowSums(cpm>parameters$threshold_cpm)>=parameters$replicate_cpm
filtered_counts <- data_list$dge[keep.exprs,,keep.lib.sizes=FALSE]
filtered_cpm<-edgeR::cpm(filtered_counts$counts, log=TRUE)
maxi<-c()
for (i in seq(nsamples)){
m=max(stats::density(filtered_cpm[,i])$y)
maxi<-c(maxi,m)
}
ymax<-round(max(maxi),1) + 0.02
grDevices::png(paste0(image_dir,parameters$analysis_name,"_filtered_data.png"), width=1024, height=1024)
graphics::par(oma=c(2,2,2,0), mar=c(parameters$densbotmar,5,5,5))
plot(stats::density(filtered_cpm[,1]),
col=as.character(data_list$dge$samples$color[1]),
lwd=1,
ylim=c(0,ymax),
las=2,
main="B. Filtered data",
xlab="Log-cpm")
graphics::abline(v=0, lty=3)
for (i in 2:nsamples){
den <- stats::density(filtered_cpm[,i])
graphics::lines(den$x,col=as.character(data_list$dge$samples$color[i]), den$y, lwd=1)
}
graphics::legend("bottom", fill=data_list$dge$samples$color, bty="n", ncol=parameters$legendcol,
legend=rownames(data_list$dge$samples), xpd=TRUE, inset=-parameters$densinset)
grDevices::dev.off()
# histogram cpm values distribution before filtering
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_barplot_logcpm_before_filtering.png"), width=sizeImg, height=sizeImg)
graphics::hist(logcpm,
main= "A. Log2(cpm) distribution before filtering",
xlab = "log2(cpm)",
col = "grey")
grDevices::dev.off()
# histogram cpm values distribution after filtering
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_barplot_logcpm_after_filtering.png"), width=sizeImg, height=sizeImg)
graphics::hist(filtered_cpm,
main= "B. Log2(cpm) distribution after filtering",
xlab = "log2(cpm)",
col = "grey")
grDevices::dev.off()
# boxplot cpm values distribution before filtering
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_boxplot_logcpm_before_filtering.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(1,1,1,1))
graphics::boxplot(logcpm,
col=data_list$dge$samples$color,
main="A. Log2(cpm) distribution before filtering",
cex.axis=0.8,
las=2,
ylab="log2(cpm)")
grDevices::dev.off()
# boxplot cpm values distribution after filtering
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_boxplot_logcpm_after_filtering.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(1,1,1,1))
graphics::boxplot(filtered_cpm,
col=data_list$dge$samples$color,
main="B. Log2(cpm) distribution after filtering",
cex.axis=0.8,
las=2,
ylab="log2(cpm)")
grDevices::dev.off()
# barplot count distribution before filtering
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_barplot_SumCounts_before_filtering.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(1,1,1,1),mar=c(7, 7, 4, 2), mgp=c(5,0.7,0))
graphics::barplot(colSums(data_list$dge$counts),
col=data_list$dge$samples$color,
main=paste0("A. Sum of raw counts from ",nrow(data_list$dge$counts)," transcripts"),
cex.axis=0.8,
las=2,
ylab="Counts sum",
xlab="Samples")
grDevices::dev.off()
# barplot count distribution after filtering
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_barplot_SumCounts_after_filtering.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(1,1,1,1),mar=c(7, 7, 4, 2), mgp=c(5,0.7,0))
graphics::barplot(colSums(filtered_counts$counts),
col=data_list$dge$samples$color,
main=paste0("B. Sum of filtered counts from ",nrow(filtered_counts$counts)," transcripts"),
cex.axis=0.8,
las=2,
ylab="Counts sum",
xlab="Samples")
grDevices::dev.off()
return(filtered_counts)
}
#' @title GEnorm
#'
#' @description Normalize counts
#' \itemize{
#' \item Calculate normalization factors to scale the filtered library sizes.
#' \item Plot different graphes to explore data before and after normalization.
#' \item Optionally, write file with mean counts and normalized mean counts in Askomics format.
#' }
#'
#' @param filtered_GE, large DGEList with filtered counts by GEfilt function.
#' @param parameters, list that contains all arguments charged in Asko_start.
#' @param asko_list, list of data.frame contain condition, contrast and context informations made by asko3c.
#' @param data_list, list contain all data and metadata (DGEList, samples descritions, contrast, design and annotations)
#' @return norm_GE, large DGEList with normalized counts and data descriptions.
#'
#' @examples
#' \dontrun{
#' norm_GE<-GEnorm(filtered_counts, asko, parameters)
#' }
#'
#' @export
GEnorm <- function(filtered_GE, asko_list, data_list, parameters){
study_dir = paste0(parameters$dir_path,"/", parameters$analysis_name, "/")
image_dir = paste0(study_dir, "DataExplore/")
# for image size
nsamples <- ncol(filtered_GE$counts)
sizeImg=15*nsamples
if(sizeImg < 480){ sizeImg=480 }
# Normalization counts
norm_GE<-edgeR::calcNormFactors(filtered_GE, method = parameters$normal_method)
if(parameters$norm_factor == TRUE){
utils::write.table(norm_GE$samples, file=paste0(study_dir, parameters$analysis_name, "_normalization_factors.txt"), col.names=NA, row.names=TRUE, quote=FALSE, sep="\t", dec=".")
}
# boxplot log2(cpm) values after normalization
#----------------------------------------------------
logcpm_norm <- edgeR::cpm(norm_GE, log=TRUE)
colnames(logcpm_norm)<-rownames(filtered_GE$samples)
grDevices::png(paste0(image_dir,parameters$analysis_name,"_boxplot_logcpm_after_norm.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(1,1,1,1))
graphics::boxplot(logcpm_norm,
col=filtered_GE$samples$color,
main="C. Log2(cpm) distribution after normalization",
cex.axis=0.8,
las=2,
ylab="Log2(cpm)")
grDevices::dev.off()
dScaleFactors <- norm_GE$samples$lib.size * norm_GE$samples$norm.factors
normCounts <- t(t(filtered_GE$counts)/dScaleFactors)*mean(dScaleFactors)
# File with normalized counts
if (parameters$norm_counts == TRUE){
utils::write.table(normCounts, file=paste0(study_dir, parameters$analysis_name, "_NormCounts.txt"), col.names=NA, row.names=TRUE, quote=FALSE, sep="\t", dec=".")
}
# barplot counts after normalization
#------------------------------------------------------
grDevices::png(paste0(image_dir,parameters$analysis_name,"_barplot_SumCounts_after_norm.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(1,1,1,1),mar=c(7, 7, 4, 2), mgp=c(5,0.7,0))
graphics::barplot(colSums(normCounts),
col=data_list$dge$samples$color,
main=paste0("C. Sum of normalized counts from ",nrow(normCounts)," transcripts"),
cex.axis=0.8,
las=2,
ylab="Counts sum",
xlab="Samples")
grDevices::dev.off()
# heatmap visualisation
#----------------------------------------------------
if(parameters$CompleteHeatmap==TRUE)
{
# heatmap cpm value per sample
#----------------------------------------------------
cpm_norm <- edgeR::cpm(norm_GE, log=FALSE)
cpmscale <- scale(t(cpm_norm))
tcpmscale <- t(cpmscale)
d1 <- stats::dist(cpmscale, method = parameters$distcluts, diag = FALSE, upper = FALSE)
d2 <- stats::dist(tcpmscale, method = parameters$distcluts, diag = FALSE, upper = TRUE)
hc <- stats::hclust(d1, method = parameters$hclust, members = NULL)
hr <- stats::hclust(d2, method = parameters$hclust, members = NULL)
my_palette <- grDevices::colorRampPalette(c("green","black","red"), interpolate = "linear")
grDevices::png(paste0(image_dir,parameters$analysis_name,"_heatmap_CPMcounts_per_sample.png"), width=sizeImg*1.5, height=sizeImg*1.25)
graphics::par(oma=c(2,1,2,2))
gplots::heatmap.2(tcpmscale, Colv = stats::as.dendrogram(hc), Rowv = stats::as.dendrogram(hr), density.info="histogram",
trace = "none", dendrogram = "column", xlab = "samples", col = my_palette, labRow = FALSE,
cexRow = 0.1, cexCol = 1.25, ColSideColors = norm_GE$samples$color, margins = c(10,1),
main = paste0("CPM counts per sample\nGenes 1 to ",nrow(norm_GE)))
grDevices::dev.off()
# Normalized mean by conditions
#-------------------------------
# heatmap mean counts per condition
n_count <- NormCountsMean(norm_GE, ASKOlist = asko_list)
countscale <- scale(t(n_count))
tcountscale <- t(countscale)
d1 <- stats::dist(countscale, method = parameters$distcluts, diag = FALSE, upper = FALSE)
d2 <- stats::dist(tcountscale, method = parameters$distcluts, diag = FALSE, upper = TRUE)
hc <- stats::hclust(d1, method = parameters$hclust, members = NULL)
hr <- stats::hclust(d2, method = parameters$hclust, members = NULL)
my_palette <- grDevices::colorRampPalette(c("green","black","red"), interpolate = "linear")
grDevices::png(paste0(image_dir,parameters$analysis_name,"_heatmap_CPMmean_per_condi.png"), width=sizeImg*1.5, height=sizeImg*1.25)
graphics::par(oma=c(2,1,2,2))
gplots::heatmap.2(tcountscale, Colv = stats::as.dendrogram(hc), Rowv = stats::as.dendrogram(hr), density.info="histogram",
trace = "none", dendrogram = "column", xlab = "Condition", col = my_palette, labRow = FALSE,
cexRow = 0.1, cexCol = 1.5, ColSideColors = unique(norm_GE$samples$color), margins = c(10,1),
main = paste0("CPM counts per condition (mean)\nGenes 1 to ",nrow(norm_GE)))
grDevices::dev.off()
}
# File with normalized counts in CPM by sample
cpm_norm <- edgeR::cpm(norm_GE, log=FALSE)
utils::write.table(cpm_norm, file=paste0(study_dir, parameters$analysis_name, "_CPM_NormCounts.txt"), col.names=NA, row.names=TRUE, quote=FALSE, sep="\t", dec=".")
# File with normalized mean counts in CPM, grouped by condition
tempo<-as.data.frame(t(stats::aggregate(t(cpm_norm),list(data_list$samples$condition), mean)))
colnames(tempo)<-tempo["Group.1",]
meancpmDEGnorm<-tempo[-1,]
utils::write.table(meancpmDEGnorm,paste0(study_dir, parameters$analysis_name,"_CPM_NormMeanCounts.txt"), sep="\t", dec=".", row.names=TRUE, col.names=NA, quote=FALSE)
return(norm_GE)
}
#' @title GEcorr
#'
#' @description
#' Plot some graphes to see data correlation :
#' \itemize{
#' \item heatmap sample correslation
#' \item MDS plots
#' \item hierarchical clustering
#' }
#'
#' @param asko_norm, large DGEList with normalized counts by GEnorm function.
#' @param parameters, list that contains all arguments charged in Asko_start.
#' @return none
#'
#' @import ggfortify
#'
#' @examples
#' \dontrun{
#' GEcorr(asko_norm,parameters)
#' }
#'
#' @export
GEcorr <- function(asko_norm, parameters){
#library(ggfortify)
options(warn = -1)
study_dir = paste0(parameters$dir_path,"/", parameters$analysis_name, "/")
image_dir = paste0(study_dir, "DataExplore/")
# for image size
nsamples <- ncol(asko_norm$counts)
sizeImg=15*nsamples
if(sizeImg < 1024){ sizeImg=1024 }
lcpm<-edgeR::cpm(asko_norm, log=TRUE)
colnames(lcpm)<-rownames(asko_norm$samples)
# Heatmap sample correlation
#-----------------------------
cormat<-stats::cor(lcpm)
color<-grDevices::colorRampPalette(c("black","red","yellow","white"),space="rgb")(35)
grDevices::png(paste0(image_dir, parameters$analysis_name, "_heatmap_of_sample_correlation.png"), width=sizeImg, height=sizeImg)
graphics::par(oma=c(4,2,4,1))
stats::heatmap(cormat, col=color, symm=TRUE, RowSideColors=as.character(asko_norm$samples$color),
ColSideColors=as.character(asko_norm$samples$color), main="")
graphics::title("Sample Correlation Matrix", adj=0.5, outer=TRUE)
grDevices::dev.off()
corr<-stats::cor(edgeR::cpm(asko_norm, log=FALSE))
minCorr=min(corr)
maxCorr=max(corr)
grDevices::png(paste0(image_dir, parameters$analysis_name, "_correlogram.png"), width=sizeImg, height=sizeImg)
corrplot(corr, method="ellipse", type = "lower", tl.col = "black", tl.srt = 45, is.corr = FALSE, cl.lim=c(minCorr,maxCorr))
#corrplot.mixed(corr, lower = "number", upper = "ellipse", tl.col = "black",is.corr = FALSE, cl.lim=c(minCorr,maxCorr))
graphics::title("Sample Correlogram", adj=0.5)
grDevices::dev.off()
# MDS Plot
#-----------------------------
mds <- stats::cmdscale(stats::dist(t(lcpm)),k=3, eig=TRUE)
eigs<-round((mds$eig)*100/sum(mds$eig[mds$eig>0]),2)
dfmds<-as.data.frame(mds$points)
# Axe 1 and 2
grDevices::png(paste0(image_dir, parameters$analysis_name, "_MDS_corr_axe1_2.png"), width=sizeImg*1.25, height=sizeImg*1.25)
mds1<-ggplot2::ggplot(dfmds, ggplot2::aes(dfmds$V1, dfmds$V2, label=rownames(mds$points))) + ggplot2::labs(title="MDS Axes 1 and 2") +
ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5)) + ggplot2::theme(plot.margin=ggplot2::margin(20,30,20,15)) +
ggplot2::geom_point(ggplot2::aes(color=as.character(asko_norm$samples$condition)),shape=17,size=15 ) +
ggplot2::xlab(paste('dim 1 [', eigs[1], '%]')) + ggplot2::ylab(paste('dim 2 [', eigs[2], "%]")) +
ggrepel::geom_label_repel(ggplot2::aes(label = rownames(mds$points),fill = factor(as.character(asko_norm$samples$condition))), color = 'white',size = 7) +
ggplot2::theme(
axis.text.y = ggplot2::element_text(face="bold",size=30),
axis.text.x = ggplot2::element_text(face="bold",size=30),
legend.text = ggplot2::element_text(size = 30),
legend.title = ggplot2::element_text(size=30,face="bold"),
strip.text.y = ggplot2::element_text(size=30, face="bold"),
axis.title = ggplot2::element_text(size=30,face="bold"),
plot.title = ggplot2::element_text(size=35)) +
ggplot2::guides(color=FALSE, fill = ggplot2::guide_legend(title = "Condition", override.aes = ggplot2::aes(label = ""), ncol=parameters$legendcol)) +