rogge_12231_data_compilation.R 48.5 KB
Newer Older
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
1
2
3
4
5
6
7
8
9
10
11
12

################################ Initialization

erase.objects <- TRUE # write TRUE to erase all the existing objects in R before starting the algorithm and FALSE otherwise. Beginners should use TRUE
if(erase.objects == TRUE){
    rm(list=ls())
    erase.objects = TRUE
}
erase.graphs <- TRUE # write TRUE to erase all the graphic windows in R before starting the algorithm and FALSE otherwise

################################ End Initialization

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
13
sink(stdout(), type = "message") # diverts R output to a connection
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
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
script <- commandArgs(trailingOnly = FALSE)[1]  # recover script name, e.g., r_341_conf $check_lod_gael_conf 
args <- commandArgs(trailingOnly = TRUE)  # recover arguments written after the call of the Rscript, ie after r_341_conf $check_lod_gael_conf 
tempo.arg.names <- c("path.lib", "path.in", "path.out", "path.function1", "project.name", "activate.pdf", "label.size", "optional.text", "slurm.loop.nb", "analysis.kind") # objects names exactly in the same order as in the bash code and recovered in args
if(length(args) != length(tempo.arg.names)){
    tempo.cat <- paste0("\n\n================\n\nERROR: THE NUMBER OF ELEMENTS IN args (", length(args),") IS DIFFERENT FROM THE NUMBER OF ELEMENTS IN tempo.arg.names (", length(tempo.arg.names),")\nargs:", paste0(args, collapse = ","), "\ntempo.arg.names:", paste0(tempo.arg.names, collapse = ","), "\n\n================\n\n")
    stop(tempo.cat)
}
for(i in 1:length(tempo.arg.names)){
    assign(tempo.arg.names[i], args[i])
    if(is.character(get(tempo.arg.names[i])) == TRUE & grepl(x = get(tempo.arg.names[i]), pattern = "^[1234567890]+$")){  # convert into numeric
        assign(tempo.arg.names[i], as.integer(get(tempo.arg.names[i])))
    }else if(is.character(get(tempo.arg.names[i])) == TRUE & grepl(x = get(tempo.arg.names[i]), pattern = "^[1234567890.+e-]+$")){
        assign(tempo.arg.names[i], as.numeric(get(tempo.arg.names[i])))
    }else if(is.character(get(tempo.arg.names[i])) == TRUE & grepl(x = get(tempo.arg.names[i]), pattern = "^(TRUE|FALSE)$")){  # convert into logical
        assign(tempo.arg.names[i], as.logical(get(tempo.arg.names[i])))
    }
}

################################ Recording of the initial parameters
param.list <- c(
    "script", 
    "args",
    "tempo.arg.names",
    tempo.arg.names
)
if(any(duplicated(param.list))){
    stop(paste0("\n\n================\n\nERROR: THE param.list OBJECT CONTAINS DUPLICATED ELEMENTS\n\n================\n\n")) # message for developers
}
char.length <- nchar(param.list)
space.add <- max(char.length) - char.length + 5
param.ini.settings <- NULL
for(i in 1:length(param.list)){
    param.ini.settings <- c(param.ini.settings, paste0("\n", param.list[i], paste0(rep(" ", space.add[i]), collapse = ""), paste0(get(param.list[i]), collapse = ",")))
}
################################ End Recording of the initial parameters

################################ DEBUG


debug2 <- '
rm(list = ls())
erase.objects <- TRUE
erase.graphs <- TRUE
script <- "code ini v1.0.0"
project.name <-"rogge12231"
path.lib <- "C:/Users/Gael/Documents/R/win-library/3.5/" # absolute path of the library folder. Write "none" if not required
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
60
path.in <- "Z:/rogge12231/rogge_12231_1550076020/" # absolute path of the data folder
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
61
path.out <- "C:/Users/Gael/Desktop/" # absolute path of the output folder
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
62
63
path.function1 <- "C:/Users/Gael/Documents/Git_versions_to_use/cute_little_R_functions-v4.5.0/cute_little_R_functions.R" # Define the absolute pathway of the folder containing functions created by Gael Millot
project.name <- "rogge_project"
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
64
activate.pdf = FALSE
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
65
label.size <-12
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
66
optional.text <- ""
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
67
68
slurm.loop.nb <- 3
analysis.kind <- "full_cross_validation"
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
69
'
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
70
eval(parse(text = debug2)) ; cat(paste0("\n\n================\n\nERROR: ACTIVE DEBUG VALUES\n\n================\n\n")) ; stop()
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
71
72
73
74
75
76

# data.frame(PARAM = tempo.arg.names, ARG = args) # for debug mode

################################ End DEBUG

################################ Packages verification and import
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
77

Gael  MILLOT's avatar
interm  
Gael MILLOT committed
78
79
80
81
82
83
# packages are imported even if functions are used using package.name::function()
req.package.list <- c(
    "pheatmap",
    "corrplot",
    "ggplot2",
    "gridExtra",
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
84
85
    "lubridate",
    "RCurl" # for url.exists
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
86
87
)
if(path.lib == "none"){
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
88
    path.lib <- .libPaths() #
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
89
}else{
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
90
91
    # .libPaths(new = ) add path to default path
  .libPaths(new = sub(x = path.lib, pattern = "/$|\\\\$", replacement = "")) # .libPaths() does not support / at the end of a submitted path. Thus check and replace last / or \\ in path
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
92
93
94
95
96
97
98
99
}
for(i0 in 1:length(req.package.list)){
    if( ! req.package.list[i0] %in% rownames(installed.packages(lib.loc =  path.lib))){
        stop(paste0("\n\n================\n\nERROR: PACKAGE ", req.package.list[i0], " MUST BE INSTALLED IN THE MENTIONNED DIRECTORY:\n", paste(path.lib, collapse = "\n"), "\n CHECK ALSO IN :\n", paste(.libPaths(), collapse = "\n"), "\n\n================\n\n"))
    }else{
        suppressPackageStartupMessages(library(req.package.list[i0], lib.loc = path.lib, quietly = TRUE, character.only = TRUE))
    }
}
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
100

Gael  MILLOT's avatar
interm  
Gael MILLOT committed
101
102
103
################################ End Packages verification and import

################################ Functions
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
104
105
106

if(length(path.function1) != 1){
    stop(paste0("\n\n============\n\nERROR: path.function1 PARAMETER MUST BE LENGTH 1: ", paste(path.function1, collapse = " "), "\n\n============\n\n"))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
107
108
109
110
111
112
113
114
115
116
117
118
}else if(grepl(x = path.function1, pattern = "^http")){
    if( ! RCurl::url.exists(path.function1)){
        stop(paste0("\n\n============\n\nERROR: HTTP INDICATED IN THE path.function1 PARAMETER DOES NOT EXISTS: ", path.function1, "\n\n============\n\n"))
    }else{
        source(path.function1) # source the fun_ functions used below
    }
}else if( ! grepl(x = path.function1, pattern = "^http")){
    if( ! file.exists(path.function1)){
        stop(paste0("\n\n============\n\nERROR: FILE INDICATED IN THE path.function1 PARAMETER DOES NOT EXISTS: ", path.function1, "\n\n============\n\n"))
    }else{
        source(path.function1) # source the fun_ functions used below
    }
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
119
}
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
120

Gael  MILLOT's avatar
interm  
Gael MILLOT committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
################################ End Functions

################################ Main code

################ Pre-ignition checking

arg.check <- NULL # for function debbuging
checked.arg.names <- NULL # for function debbuging
ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))

# initializations
tempo <- fun_param_check(data = erase.objects, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = erase.graphs, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = script, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = args, class = "character", length = length(tempo.arg.names)) ; eval(ee)
tempo <- fun_param_check(data = tempo.arg.names, class = "character", length = length(tempo.arg.names)) ; eval(ee)

# imported objects
tempo <- fun_param_check(data = path.lib, class = "character", length = 1) ; eval(ee)
if(tempo$problem == FALSE & path.lib != "none"){
    if( ! dir.exists(path.lib)){
        cat(paste0("\n\n============\n\nERROR: DIRECTORY PATH INDICATED IN THE path.in PARAMETER DOES NOT EXISTS: ", path.in, "\n\n============\n\n"))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
143
        arg.check <- TRUE
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
144
145
146
147
148
    }
}
tempo <- fun_param_check(data = path.in, class = "character", length = 1) ; eval(ee)
if(tempo$problem == FALSE & ! dir.exists(path.in)){
    cat(paste0("\n\n============\n\nERROR: DIRECTORY PATH INDICATED IN THE path.in PARAMETER DOES NOT EXISTS: ", path.in, "\n\n============\n\n"))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
149
    arg.check <- TRUE
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
150
}
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
151
152
153
if(tempo$problem == FALSE & ! ("loop1_res_data.RData" %in% list.files(paste0(path.in, "loop1/")))){
    cat(paste0("\n\n============\n\nERROR: loop1_res_data.RData SHOULD BE PRESENT IN ", paste0(path.in, "loop1/"), ":\nCHECK THE path.in PARAMETER\n\n============\n\n"))
    arg.check <- TRUE
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
154
155
156
157
}
tempo <- fun_param_check(data = path.out, class = "character", length = 1) ; eval(ee)
if(tempo$problem == FALSE & ! dir.exists(path.out)){
    cat(paste0("\n\n============\n\nERROR: DIRECTORY PATH INDICATED IN THE path.out PARAMETER DOES NOT EXISTS: ", path.out, "\n\n============\n\n"))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
158
    arg.check <- TRUE
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
159
}
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
160
161
# path.function1 fully tested above
tempo <- fun_param_check(data = path.function1, class = "character", length = 1) ; eval(ee)
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
162
163
tempo <- fun_param_check(data = project.name, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = activate.pdf, class = "logical", length = 1) ; eval(ee)
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
164
tempo <- fun_param_check(data = label.size, typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE) ; eval(ee)
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
165
166
167
168
169
170
171
172
173
174
175
tempo <- fun_param_check(data = optional.text, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = slurm.loop.nb, typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = analysis.kind, options = c("longit", "valid_boot", "full_cross_validation"), length = 1) ; eval(ee)
if(any(arg.check) == TRUE){
    stop()
}

################ Ignition

ini.time <- as.numeric(Sys.time()) # time of process begin, converted into seconds
analysis.nb <- trunc(ini.time) # to provide a specific number ot each analysis
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
176
log.file <- paste0("r_", project.name, "_", analysis.nb,"_report.txt")
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
177
178
179
180
181
182
183
184
# name.dir <- paste0(project.name, "_", analysis.nb)
# path.out<-paste0(path.out, name.dir)
# suppressWarnings(dir.create(path.out))
backup.name <- NULL # names of the object to save
fun_export_data(data = paste0("\n\n################################ ", log.file, " ################"), output = log.file, no.overwrite = FALSE, path = path.out, sep = 4)
fun_export_data(path = path.out, data = "################################ INITIAL DATA", output = log.file, sep = 4)
fun_export_data(path = path.out, data = paste0("SCRIPT USED: ", script), output = log.file)
fun_export_data(path = path.out, data = paste0("KIND OF ANALYSIS PERFORMED: ", analysis.kind), output = log.file)
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
185
fun_export_data(path = path.out, data = paste0("NUMBER OF LOOPS USED FOR COMPILATION: ", slurm.loop.nb), output = log.file)
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205

################ Graphical parameter ignition

zone.ini <- matrix(1, ncol=1) # to reset the layout if required
if(erase.graphs == TRUE){
    graphics.off()
}else{
    tempo.cat <- paste0("BEWARE: GRAPHICS HAVE NOT BEEN ERASED. GRAPHICAL PARAMETERS MAY HAVE NOT BEEN REINITIALIZED")
    fun_export_data(path = path.out, data = tempo.cat, output = log.file)
}
if(optional.text == "no.txt"){
    optional.text <- ""
}else{
    fun_export_data(path = path.out, data = paste0("OPTIONAL TEXT:\n", optional.text), output = log.file)
}
par.ini <- fun_open_window(pdf.disp = activate.pdf, path.fun = path.out, pdf.name.file = paste0("loop", slurm.loop.nb, "_graphs"), width.fun = 7, height.fun = 7, paper = "special", no.pdf.overwrite = TRUE, return.output = TRUE)$ini.par
pdf.nb <- dev.cur()

################ Data import

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
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
for(i0 in 1:slurm.loop.nb){
    load(paste0(path.in, "loop", i0, "/loop", i0, "_res_data.RData"))
}

# > class(loop1_ttab)
# [1] "data.frame"
# > class(mod.gene.names)
# [1] "character"
# > class(confmat1.genes.logreg$result)
# [1] "matrix"
# class(data.pred1.genes.logreg)
# [1] "data.frame"
# class(data.roc1.genes.rpart)
# [1] "data.frame"

# > class(final.gene.list)
# [1] "data.frame"

################ Data compilation

backup.name <- NULL
# ttab
if(analysis.kind == "full_cross_validation"){
    final.ttab <- data.frame(NULL, stringsAsFactors = FALSE)
    for(i0 in 1:slurm.loop.nb){
        if(nrow(get(paste0("loop", i0, "_ttab"))) > 0){
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
232
            final.ttab <- rbind(final.ttab, data.frame(get(paste0("loop", i0, "_ttab")), LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
233
234
235
236
237
238
239
240
241
242
        }else{
            final.ttab <- rbind(final.ttab, data.frame(logFC = NA, AveExpr = NA, t = NA, P.Value = NA, adj.P.Val = NA, B = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }
    }
}else{
    final.ttab <- get(paste0("loop1_ttab"))
    fun_export_data(path = path.out, data = paste0("final.ttab OBJECT CONTAINS ONLY LOOP1 RESULTS BECAUSE NO LOOP PERFORMED FOR THIS USING ", analysis.kind, " ANALYSIS"), output = log.file)
}
backup.name <- c(backup.name, "final.ttab")

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# select.gene.curve
if(analysis.kind == "full_cross_validation"){
    final.select.gene.curve <- data.frame(NULL, stringsAsFactors = FALSE)
    for(i0 in 1:slurm.loop.nb){
        if(nrow(get(paste0("loop", i0, "_select.gene.curve"))) > 0){
            final.select.gene.curve <- rbind(final.select.gene.curve, data.frame(get(paste0("loop", i0, "_select.gene.curve")), LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }else{
            final.select.gene.curve <- rbind(final.select.gene.curve, data.frame(x = NA, y = NA, PANEL = NA, group = NA, shape = NA, colour = NA, size = NA, fill = NA, alpha = NA, stroke = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }
    }
}else{
    final.select.gene.curve <- get(paste0("loop1_select.gene.curve"))
    fun_export_data(path = path.out, data = paste0("final.select.gene.curve OBJECT CONTAINS ONLY LOOP1 RESULTS BECAUSE NO LOOP PERFORMED FOR THIS USING ", analysis.kind, " ANALYSIS"), output = log.file)
}
backup.name <- c(backup.name, "final.select.gene.curve")

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# mod.gene.names
if(analysis.kind == "full_cross_validation"){
    final.mod.gene.names <- data.frame(NULL, stringsAsFactors = FALSE)
    for(i0 in 1:slurm.loop.nb){
        if(length(get(paste0("loop", i0, "_mod.gene.names"))) > 0){
            final.mod.gene.names <- rbind(final.mod.gene.names, data.frame(GENE = get(paste0("loop", i0, "_mod.gene.names")), LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }else{
            final.mod.gene.names <- rbind(final.mod.gene.names, data.frame(GENE = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }
    }
}else{
    final.mod.gene.names <- data.frame(GENE = get(paste0("loop1_mod.gene.names")), LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE)
    fun_export_data(path = path.out, data = paste0("final.mod.gene.names OBJECT CONTAINS ONLY LOOP1 RESULTS BECAUSE NO LOOP PERFORMED FOR THIS USING ", analysis.kind, " ANALYSIS"), output = log.file)
}
backup.name <- c(backup.name, "final.mod.gene.names")

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# gene.importance
if(analysis.kind == "full_cross_validation"){
    final.gene.importance <- data.frame(NULL, stringsAsFactors = FALSE)
    for(i0 in 1:slurm.loop.nb){
        if(nrow(get(paste0("loop", i0, "_gene.importance"))) > 0){
            final.gene.importance <- rbind(final.gene.importance, data.frame(get(paste0("loop", i0, "_gene.importance")), LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }else{
            final.gene.importance <- rbind(final.gene.importance, data.frame(features = NA, importance = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
        }
    }
}else{
    final.gene.importance <- get(paste0("loop1_gene.importance"))
    fun_export_data(path = path.out, data = paste0("final.gene.importance OBJECT CONTAINS ONLY LOOP1 RESULTS BECAUSE NO LOOP PERFORMED FOR THIS USING ", analysis.kind, " ANALYSIS"), output = log.file)
}
backup.name <- c(backup.name, "final.gene.importance")

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
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
# loop1_confmat1.genes.rf, data.pred1.genes.logreg, data.roc1.genes.logreg
data.kind <- c("genes", "crp", "genes.crp") # beware, the order is important
ana.kind <- c("rf", "logreg", "rpart")
for(i0 in 1:length(data.kind)){
    for(i1 in 1:length(ana.kind)){
        assign(paste0("final.confmat", i0, ".", data.kind[i0], ".", ana.kind[i1]), data.frame(NULL, stringsAsFactors = FALSE))
        assign(paste0("final.data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1]), data.frame(NULL, stringsAsFactors = FALSE))
        assign(paste0("final.data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1]), data.frame(NULL, stringsAsFactors = FALSE))
        for(i2 in 1:slurm.loop.nb){
            # matrix confusion
            if(nrow(get(paste0("loop", i2, "_confmat", i0, ".", data.kind[i0], ".", ana.kind[i1]))$result) > 0){
                # transform the table into a 1 line data frame
                tempo1 <- get(paste0("loop", i2, "_confmat", i0, ".", data.kind[i0], ".", ana.kind[i1]))
                tempo2 <- c(c(tempo1$result[1:2, 1:2]), tempo1$task.desc$size)
                tempo3 <- c("TRUE_NR_PRED_NR", "TRUE_R_PRED_NR", "TRUE_NR_PRED_R", "TRUE_R_PRED_R", "SIZE")
                tempo4 <- eval(parse(text = paste0("data.frame(", paste(tempo3, tempo2, sep = "=", collapse = ","), ", LOOP_NB = 'loop", i2, "', stringsAsFactors = FALSE)")))
                assign(paste0("final.confmat", i0, ".", data.kind[i0], ".", ana.kind[i1]), rbind(get(paste0("final.confmat", i0, ".", data.kind[i0], ".", ana.kind[i1])), tempo4))
            }else{
                assign(paste0("final.confmat", i0, ".", data.kind[i0], ".", ana.kind[i1]), rbind(get(paste0("final.confmat", i0, ".", data.kind[i0], ".", ana.kind[i1])), data.frame(TRUE_NR_PRED_NR = NA, TRUE_R_PRED_NR = NA, TRUE_NR_PRED_R = NA, TRUE_R_PRED_R = NA, SIZE = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE)))
            }
            # predictions
            if(nrow(get(paste0("loop", i2, "_data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1]))) > 0){
                assign(paste0("final.data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1]), rbind(get(paste0("final.data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1])), data.frame(get(paste0("loop", i2, "_data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1])), LOOP_NB = paste0("loop", i2), stringsAsFactors = FALSE)))
            }else{
                assign(paste0("final.data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1]), rbind(get(paste0("final.data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1])), data.frame(truth = NA, prob.NR = NA, prob.R = NA, response = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE)))
            }
            # roc curves
            if(nrow(get(paste0("loop", i2, "_data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1]))) > 0){
                assign(paste0("final.data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1]), rbind(get(paste0("final.data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1])), data.frame(get(paste0("loop", i2, "_data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1])), LOOP_NB = paste0("loop", i2), stringsAsFactors = FALSE)))
            }else{
                assign(paste0("final.data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1]), rbind(get(paste0("final.data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1])), data.frame(x = NA, y = NA, PANEL = NA, group = NA, coloup = NA, sizep = NA, linetypep = NA, alphap = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE)))
            }
        }
        backup.name <- c(backup.name, paste0("final.confmat", i0, ".", data.kind[i0], ".", ana.kind[i1]))
        backup.name <- c(backup.name, paste0("final.data.pred", i0, ".", data.kind[i0], ".", ana.kind[i1]))
        backup.name <- c(backup.name, paste0("final.data.roc", i0, ".", data.kind[i0], ".", ana.kind[i1]))
    }
}

# final.gene.list
final.gene.list <- data.frame(NULL, stringsAsFactors = FALSE)
for(i0 in 1:slurm.loop.nb){
    if(length(get(paste0("loop", i0, "_final.gene.list"))) > 0){
        final.gene.list <- rbind(final.gene.list, data.frame(get(paste0("loop", i0, "_final.gene.list")), LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
    }else{
        final.gene.list <- rbind(final.gene.list, data.frame(sfeats = NA, Freq = NA, LOOP_NB = paste0("loop", i0), stringsAsFactors = FALSE))
    }
}
backup.name <- c(backup.name, "final.gene.list")
save(list=c(backup.name), file = paste0(path.out, "compiled_data.RData"))
fun_export_data(path = path.out, data = paste0("THE COMPILED DATA ARE SAVED IN: ", paste0(path.out, "compiled_data.RData")), output = log.file)

################ 3 Differential analysis with limma
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
344

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
fun_export_data(path = path.out, data = "################################ LIMMA ANALYSIS", output = log.file, sep = 4)

if(nrow(final.ttab) == 0 | nrow(na.omit(final.ttab)) == 0){
    fun_export_data(path = path.out, data = paste0("NO GENE LIST RESULTS FROM THE LIMMA ANALYSIS (P VALUES ABOVE 0.05 AFTER CORRECTION FOR INSTANCE)"), output = log.file)
    fun_export_data(path = path.out, data = final.ttab, output = log.file)
}else if(analysis.kind == "valid_boot"){
    fun_export_data(path = path.out, data = paste0("BEWARE: NO LOOP FOR THE LIMMA ANALYSIS (", analysis.kind, " KIND OF ANALYSIS)"), output = log.file)
    fun_export_data(path = path.out, data = final.ttab, output = log.file)
}else{
    tempo1 <- c(table(rownames(final.ttab)))
    tempo2 <- data.frame(
        ADJ_P_VALUE_MEDIAN = quantile(final.ttab$adj.P.Val, probs = 0.5, na.rm = TRUE),
        ADJ_P_VALUE_CI95_INF = quantile(final.ttab$adj.P.Val, probs = 0.025, na.rm = TRUE),
        ADJ_P_VALUE_CI95_SUP = quantile(final.ttab$adj.P.Val, probs = 0.975, na.rm = TRUE)
    )
    final.ttab.freq <- data.frame(GENE = names(tempo1), NB = unname(tempo1), FREQ = unname(tempo1)/sum(tempo1), tempo2)
    rownames(final.ttab.freq) <- NULL
    fun_export_data(path = path.out, data = "FREQUENCIES AND P VALUES MEDIANS & CI: ", output = log.file)
    fun_export_data(path = path.out, data = final.ttab.freq, output = log.file)
    
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
365
    # horiz barplot
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
366
367
368
369
370
    bar.width <- 0.5
    log.scale <- FALSE
    amplif <- label.size
    tempo.gg.name <- "gg.indiv.plot."
    tempo.gg.count <- 0
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
371
372
373
374
375
376
377
378
379
380
381
382
    if(nrow(final.ttab.freq) > 20){
        tempo1 <- table(final.ttab.freq$FREQ)
        tempo2 <- tempo1[order(names(tempo1), decreasing = TRUE)]
        tempo3 <- as.numeric(names(cumsum(tempo2)[cumsum(tempo2) <= 20]))
        tempo.plot <- final.ttab.freq[round(final.ttab.freq$FREQ, 7) %in% round(tempo3, 7), ]
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data = tempo.plot, mapping = ggplot2::aes(x = reorder(GENE, FREQ), y = FREQ))) # reorder from higher to lower
        tempo.txt <- paste0("BEWARE: ONLY THE ", nrow(tempo.plot), " MOST FREQUENT GENES PLOTTED, AMONG ", nrow(final.ttab.freq))
    }else{
        tempo.plot <- final.ttab.freq
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data =  tempo.plot, mapping = ggplot2::aes(x = reorder(GENE, FREQ), y = FREQ))) # reorder from higher to lower
        tempo.txt <- ""
    }
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
383
384
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_bar(stat = "identity", position = "dodge", color = "black", fill = grey(0.8), width = bar.width))
    # assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_errorbar(ggplot2::aes(ymin = PROP.CI95.inf, ymax = PROP.CI95.sup), position = ggplot2::position_dodge(width = bar.width), color = "black", width = 0))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
385
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggtitle(paste0("LIMMA GENE LIST\n(PROP OF TIMES THE GENE IS SIGNIFICANT FOR ", slurm.loop.nb, " LOOPS)\n", tempo.txt)))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::xlab(""))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ylab("PROPORTION"))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), m.gg <- ggplot2::theme_classic(base_size = amplif))
    coord <- ggplot2::ggplot_build(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))$data # to have the summary statistics of the plot. is interesting: x = coord[[2]]$x, y = coord[[2]]$ymax_final
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1),  ggplot2::annotate(geom = "text", x = coord[[1]]$x, y = coord[[1]]$ymax, label = round(coord[[1]]$y, 3), size = amplif/2, color = "black", vjust = "center", hjust = "right")) # beware: no need of order() for labels because coord[[1]]$x set the order
    if(log.scale == TRUE){
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::annotation_logticks(sides = "l"))
    }else{
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::scale_y_continuous(expand = c(0,0), breaks = scales::extended_breaks(10)))
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::coord_flip(ylim = c(0, max(final.ttab.freq$FREQ, na.rm = TRUE) * 1.02))) # fix limits
    }
    if(activate.pdf == TRUE){
        tempo <- dev.set(pdf.nb) # assign to avoid the message
    }else{
        windows(5, 5)
    }
    print(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))
}
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
404
backup.name <- c(backup.name, "final.ttab.freq")
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
405
406
407
408
409
410
411
412
413
414
415
416

################ 4 Machine Learning based analysis

######## 4.1 Discovery: Learning the Random Forest

fun_export_data(path = path.out, data = "################################ RANDOM FOREST LEARNING USING THE DISCOVERY SET", output = log.file, sep = 4)

#mod.gene.names

fun_export_data(path = path.out, data = "################ LIST OF GENES SELECTED DURING THE MODEL ELABORATION", output = log.file, sep = 4)

if(nrow(final.mod.gene.names) == 0 | nrow(na.omit(final.mod.gene.names)) == 0){
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
417
    fun_export_data(path = path.out, data = paste0("NO GENE LIST RESULTS FROM THE RANDOM FOREST TRAINING"), output = log.file)
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
418
419
    fun_export_data(path = path.out, data = final.mod.gene.names, output = log.file)
}else if(analysis.kind == "valid_boot"){
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
420
    fun_export_data(path = path.out, data = paste0("BEWARE: NO LOOP FOR THE THE RANDOM FOREST TRAINING (", analysis.kind, " KIND OF ANALYSIS)"), output = log.file)
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
421
422
423
424
425
    fun_export_data(path = path.out, data = final.mod.gene.names, output = log.file)
}else{
    tempo1 <- c(table(final.mod.gene.names$GENE))
    final.mod.gene.names.freq <- data.frame(GENE = names(tempo1), NB = unname(tempo1), FREQ = unname(tempo1)/sum(tempo1))
    rownames(final.mod.gene.names.freq) <- NULL
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
426
    fun_export_data(path = path.out, data = "FREQUENCIES: ", output = log.file)
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
427
428
    fun_export_data(path = path.out, data = final.mod.gene.names.freq, output = log.file)
    
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
429
    # horiz barplot
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
430
431
432
433
434
    bar.width <- 0.5
    log.scale <- FALSE
    amplif <- label.size
    tempo.gg.name <- "gg.indiv.plot."
    tempo.gg.count <- 0
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
435
436
437
438
439
440
441
442
443
444
445
446
    if(nrow(final.mod.gene.names.freq) > 20){
        tempo1 <- table(final.mod.gene.names.freq$FREQ)
        tempo2 <- tempo1[order(names(tempo1), decreasing = TRUE)]
        tempo3 <- as.numeric(names(cumsum(tempo2)[cumsum(tempo2) <= 20]))
        tempo.plot <- final.mod.gene.names.freq[round(final.mod.gene.names.freq$FREQ, 7) %in% round(tempo3, 7), ]
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data = tempo.plot, mapping = ggplot2::aes(x = reorder(GENE, FREQ), y = FREQ))) # reorder from higher to lower
        tempo.txt <- paste0("BEWARE: ONLY THE ", nrow(tempo.plot), " MOST FREQUENT GENES PLOTTED, AMONG ", nrow(final.mod.gene.names.freq))
    }else{
        tempo.plot <- final.mod.gene.names.freq
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data =  tempo.plot, mapping = ggplot2::aes(x = reorder(GENE, FREQ), y = FREQ))) # reorder from higher to lower
        tempo.txt <- ""
    }
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
447
448
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_bar(stat = "identity", position = "dodge", color = "black", fill = grey(0.8), width = bar.width))
    # assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_errorbar(ggplot2::aes(ymin = PROP.CI95.inf, ymax = PROP.CI95.sup), position = ggplot2::position_dodge(width = bar.width), color = "black", width = 0))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
449
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggtitle(paste0("RANDOM FOREST MODELISATION GENE LIST\n(PROP OF TIMES THE GENES HAVE BEEN SELECTED FOR ", slurm.loop.nb, " LOOPS)\n", tempo.txt)))
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::xlab(""))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ylab("PROPORTION"))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), m.gg <- ggplot2::theme_classic(base_size = amplif))
    coord <- ggplot2::ggplot_build(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))$data # to have the summary statistics of the plot. is interesting: x = coord[[2]]$x, y = coord[[2]]$ymax_final
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1),  ggplot2::annotate(geom = "text", x = coord[[1]]$x, y = coord[[1]]$ymax, label = round(coord[[1]]$y, 3), size = amplif/2, color = "black", vjust = "center", hjust = "right")) # beware: no need of order() for labels because coord[[1]]$x set the order
    if(log.scale == TRUE){
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::annotation_logticks(sides = "l"))
    }else{
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::scale_y_continuous(expand = c(0,0), breaks = scales::extended_breaks(10)))
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::coord_flip(ylim = c(0, max(final.mod.gene.names.freq$FREQ, na.rm = TRUE) * 1.02))) # fix limits
    }
    if(activate.pdf == TRUE){
        tempo <- dev.set(pdf.nb) # assign to avoid the message
    }else{
        windows(5, 5)
    }
    print(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))
}
Gael  MILLOT's avatar
interm    
Gael MILLOT committed
468
backup.name <- c(backup.name, "final.mod.gene.names.freq")
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
469
470


Gael  MILLOT's avatar
interm    
Gael MILLOT committed
471
#gene.importance
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
472

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
473
fun_export_data(path = path.out, data = "################ GENE IMPORTANCE DURING THE MODEL ELABORATION", output = log.file, sep = 4)
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
474

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
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
if(nrow(final.gene.importance) == 0 | nrow(na.omit(final.gene.importance)) == 0){
    fun_export_data(path = path.out, data = paste0("NO GENE IMPORTANCE RESULTS FROM THE RANDOM FOREST TRAINING"), output = log.file)
    fun_export_data(path = path.out, data = final.gene.importance, output = log.file)
}else if(analysis.kind == "valid_boot"){
    fun_export_data(path = path.out, data = paste0("BEWARE: NO LOOP FOR THE THE RANDOM FOREST TRAINING (", analysis.kind, " KIND OF ANALYSIS)"), output = log.file)
    fun_export_data(path = path.out, data = final.gene.importance, output = log.file)
}else{
    tempo1 <- aggregate(final.gene.importance$importance, list(final.gene.importance$features), median, na.rm = TRUE)
    names(tempo1) <- c("GENE", "MEDIAN")
    tempo2 <- aggregate(final.gene.importance$features, list(final.gene.importance$features), function(x){length(x[ ! is.na(x)])}) # nb
    if(identical(tempo1$GENE, tempo2$Group.1)){
        tempo1 <- data.frame(tempo1, NB = tempo2$x)
    }else{
        cat(paste0("\n\n============\n\nERROR: IN THE PLOT OF THE final.gene.importance OBJECT, tempo1 AND tempo2 SHOULD HAVE THE SAME GENE COLUMN: \n\n============\n\n"))
        tempo1
        tempo2
        cat("\n\n============\n\n")
        stop()
    }
    final.gene.importance.median <- cbind(tempo1,
                    CI95.inf = aggregate(final.gene.importance$importance, list(final.gene.importance$features), quantile, probs = 0.025, na.rm = TRUE)[, 2],
                    CI95.sup = aggregate(final.gene.importance$importance, list(final.gene.importance$features), quantile, probs = 0.975, na.rm = TRUE)[, 2],
                    stringsAsFactors = FALSE
    )
    fun_export_data(path = path.out, data = "IMPORTANCE: ", output = log.file)
    fun_export_data(path = path.out, data = final.gene.importance.median, output = log.file)
    
    # horiz barplot + CI
    bar.width <- 0.5
    log.scale <- FALSE
    amplif <- label.size
    tempo.gg.name <- "gg.indiv.plot."
    tempo.gg.count <- 0
    if(nrow(final.gene.importance.median) > 20){
        tempo1 <- table(final.gene.importance.median$MEDIAN)
        tempo2 <- tempo1[order(names(tempo1), decreasing = TRUE)]
        tempo3 <- as.numeric(names(cumsum(tempo2)[cumsum(tempo2) <= 20]))
        tempo.plot <- final.gene.importance.median[round(final.gene.importance.median$MEDIAN, 7) %in% round(tempo3, 7), ]
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data = tempo.plot, mapping = ggplot2::aes(x = reorder(GENE, -MEDIAN), y = MEDIAN))) # reorder from higher to lower
        tempo.txt <- paste0("BEWARE: ONLY THE ", nrow(tempo.plot), " MOST IMPORTANT GENES PLOTTED, AMONG ", nrow(final.gene.importance.median))
    }else{
        tempo.plot <- final.gene.importance.median
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data =  tempo.plot, mapping = ggplot2::aes(x = reorder(GENE, -MEDIAN), y = MEDIAN))) # reorder from higher to lower
        tempo.txt <- ""
    }
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_bar(stat = "identity", position = "dodge", color = "black", fill = grey(0.8), width = bar.width))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_errorbar(ggplot2::aes(ymin = CI95.inf, ymax = CI95.sup), position = ggplot2::position_dodge(width = bar.width), color = "black", width = 0))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggtitle(paste0("GENE IMPORTANCE (NUMBERS ARE NUMBER OF TIMES THE GENE IS SEEN FOR ", slurm.loop.nb, " LOOPS)")))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::xlab(""))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ylab("MEDIAN +/- 95CI"))
#     assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), m.gg <- ggplot2::theme_classic(base_size = amplif))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), m.gg <- ggplot2::theme(
        # plot.margin = margin(up.space.mds, right.space.mds, down.space.mds, left.space.mds, "inches"), 
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = amplif * 0.5), 
        axis.text.x = element_text(angle = 90, hjust = 1),
        axis.text = ggplot2::element_text(size = amplif * 0.75), 
        axis.title = ggplot2::element_text(size = amplif), 
        legend.text = ggplot2::element_text(size = amplif), 
        legend.title = ggplot2::element_text(size = amplif), 
        strip.text = ggplot2::element_text(size = amplif), 
        legend.key = ggplot2::element_blank(), 
        panel.background = ggplot2::element_rect(fill = "grey95"), 
        panel.border = ggplot2::element_rect(colour = "black", fill = NA), 
        panel.grid.major.x = ggplot2::element_line(colour = "grey75"), 
        panel.grid.major.y = ggplot2::element_line(colour = "grey75"), 
        panel.grid.minor.x = ggplot2::element_blank(), 
        panel.grid.minor.y = ggplot2::element_blank(), 
        strip.background = ggplot2::element_rect(fill = "white", colour = "black")
    ))
    coord <- ggplot2::ggplot_build(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))$data # to have the summary statistics of the plot. is interesting: x = coord[[2]]$x, y = coord[[2]]$ymax_final
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1),  ggplot2::annotate(geom = "text", x = coord[[1]]$x, y = coord[[1]]$ymax, label = tempo.plot$NB, size = amplif/2, color = "black", vjust = "center", hjust = "right", angle = 90)) # beware: no need of order() for labels because coord[[1]]$x set the order
    if(log.scale == TRUE){
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::annotation_logticks(sides = "l"))
    }else{
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::scale_y_continuous(expand = c(0,0), breaks = scales::extended_breaks(10)))
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::coord_cartesian(ylim = c(0, max(final.gene.importance.median$CI95.sup, na.rm = TRUE) * 1.02))) # fix limits
    }
    if(activate.pdf == TRUE){
        tempo <- dev.set(pdf.nb) # assign to avoid the message
    }else{
        windows(5, 5)
    }
    print(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))
}
backup.name <- c(backup.name, "final.gene.importance.median")
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
560
561


Gael  MILLOT's avatar
interm    
Gael MILLOT committed
562
#select.gene.curve
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
563

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
564
fun_export_data(path = path.out, data = "################ OPTIMAL NUMBER OF GENES DURING THE MODEL ELABORATION", output = log.file, sep = 4)
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
565

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
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
if(nrow(final.select.gene.curve) == 0 | nrow(na.omit(final.select.gene.curve)) == 0){
    fun_export_data(path = path.out, data = paste0("NO OPTIMAL RESULTS FROM THE RANDOM FOREST TRAINING"), output = log.file)
    fun_export_data(path = path.out, data = final.select.gene.curve, output = log.file)
}else if(analysis.kind == "valid_boot"){
    fun_export_data(path = path.out, data = paste0("BEWARE: NO LOOP FOR THE THE RANDOM FOREST TRAINING (", analysis.kind, " KIND OF ANALYSIS)"), output = log.file)
    fun_export_data(path = path.out, data = final.select.gene.curve, output = log.file)
}else{
    tempo1 <- aggregate(final.select.gene.curve$y, list(final.select.gene.curve$x), median, na.rm = TRUE)
    names(tempo1) <- c("X", "MEDIAN")
    final.select.gene.curve.median <- cbind(tempo1,
                                          CI95.inf = aggregate(final.select.gene.curve$y, list(final.select.gene.curve$x), quantile, probs = 0.025, na.rm = TRUE)[, 2],
                                          CI95.sup = aggregate(final.select.gene.curve$y, list(final.select.gene.curve$x), quantile, probs = 0.975, na.rm = TRUE)[, 2],
                                          stringsAsFactors = FALSE
    )
    fun_export_data(path = path.out, data = "OPTIMAL NUMBER OF GENES: ", output = log.file)
    fun_export_data(path = path.out, data = final.select.gene.curve.median, output = log.file)
    
    # horiz barplot + CI
    bar.width <- 0.5
    log.scale <- FALSE
    amplif <- label.size
    tempo.gg.name <- "gg.indiv.plot."
    tempo.gg.count <- 0
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggplot(data = final.select.gene.curve.median, mapping = ggplot2::aes(x = X, y = MEDIAN))) # reorder from higher to lower
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_point(color = "red", shape = 16, size = 2))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_line(color = "red"))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::geom_errorbar(ggplot2::aes(ymin = CI95.inf, ymax = CI95.sup), position = ggplot2::position_dodge(), color = "black", width = 0))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ggtitle(paste0("OPTIMAL NUMBER OF GENES (n = ", slurm.loop.nb,")")))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::xlab("NUMBER OF GENES"))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::ylab("MEDIAN +/- 95CI"))
    assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), m.gg <- ggplot2::theme_classic(base_size = amplif))
    if(log.scale == TRUE){
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::annotation_logticks(sides = "l"))
    }else{
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::scale_y_continuous(expand = c(0,0), breaks = scales::extended_breaks(10)))
        assign(paste0(tempo.gg.name, tempo.gg.count <- tempo.gg.count + 1), ggplot2::coord_cartesian(ylim = c(0, max(final.select.gene.curve.median$CI95.sup, na.rm = TRUE) * 1.02))) # fix limits
    }
    if(activate.pdf == TRUE){
        tempo <- dev.set(pdf.nb) # assign to avoid the message
    }else{
        windows(5, 5)
    }
    print(eval(parse(text = paste(paste0(tempo.gg.name, 1:tempo.gg.count), collapse = " + "))))
}
backup.name <- c(backup.name, "final.select.gene.curve.median")
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
611

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
612
#gene heatmap and corrplot
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
613

Gael  MILLOT's avatar
interm    
Gael MILLOT committed
614
615
616
print(loop1_heatmap.plot) # same for all the loops
corrplot(loop1_corr.plot, tl.col = "black", tl.cex = label.size / 10)  # same for all the loops
backup.name <- c(backup.name, "loop1_heatmap.plot", "loop1_corr.plot")
Gael  MILLOT's avatar
interm  
Gael MILLOT committed
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














######## 4.2 Validate the model
# 
fun_export_data(path = path.out, data = "################################ VALIDATION", output = log.file, sep = 4)


tempo <- dev.set(pdf.nb) # assign to avoid the message
roc1.genes.rf <- plotROCCurves(generateThreshVsPerfData(pred1.genes.rf, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 1.genes (only genes) \n AUC=%.2f", performance(pred1.genes.rf, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
roc2.crp.rf <- plotROCCurves(generateThreshVsPerfData(pred2.crp.rf, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 2.crp (only CRP) \n AUC=%.2f", performance(pred2.crp.rf, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
roc3.genes.crp.rf <- plotROCCurves(generateThreshVsPerfData(pred3.genes.crp.rf, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 3.genes.crp (genes + CRP) \n AUC=%.2f", performance(pred3.genes.crp.rf, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
data.roc1.genes.rf <- ggplot2::ggplot_build(roc1.genes.rf)$data[[1]]
data.roc2.crp.rf <- ggplot2::ggplot_build(roc2.crp.rf)$data[[1]]
data.roc3.genes.crp.rf <- ggplot2::ggplot_build(roc3.genes.crp.rf)$data[[1]]
backup.name <- c(backup.name, "data.roc1.genes.rf", "data.roc2.crp.rf", "data.roc3.genes.crp.rf")

gridExtra::grid.arrange(roc1.genes.rf, roc2.crp.rf, roc3.genes.crp.rf, nrow = 2)
# ```

######## 4.4 Logistic regression

fun_export_data(path = path.out, data = "################ LOGISTIC REGRESSION", output = log.file)



tempo <- dev.set(pdf.nb) # assign to avoid the message
roc1.genes.logreg <- plotROCCurves(generateThreshVsPerfData(pred1.genes.logreg, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 1.genes (only genes) \n AUC=%.2f", performance(pred1.genes.logreg, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
roc2.crp.logreg <- plotROCCurves(generateThreshVsPerfData(pred2.crp.logreg, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 2.crp (only CRP) \n AUC=%.2f", performance(pred2.crp.logreg, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
roc3.genes.crp.logreg <- plotROCCurves(generateThreshVsPerfData(pred3.genes.crp.logreg, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 3.genes.crp (genes + CRP) \n AUC=%.2f", performance(pred3.genes.crp.logreg, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
data.roc1.genes.logreg <- ggplot2::ggplot_build(roc1.genes.logreg)$data[[1]]
data.roc2.crp.logreg <- ggplot2::ggplot_build(roc2.crp.logreg)$data[[1]]
data.roc3.genes.crp.logreg <- ggplot2::ggplot_build(roc3.genes.crp.logreg)$data[[1]]
backup.name <- c(backup.name, "data.roc1.genes.logreg", "data.roc2.crp.logreg", "data.roc3.genes.crp.logreg")

gridExtra::grid.arrange(roc1.genes.logreg, roc2.crp.logreg, roc3.genes.crp.logreg, nrow = 2)
# ```
# 
######## 4.5 RPART

fun_export_data(path = path.out, data = "################ RPART", output = log.file)



tempo <- dev.set(pdf.nb) # assign to avoid the message
roc1.genes.rpart <- plotROCCurves(generateThreshVsPerfData(pred1.genes.rpart, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 1.genes (only genes) \n AUC=%.2f", performance(pred1.genes.rpart, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
roc2.crp.rpart <- plotROCCurves(generateThreshVsPerfData(pred2.crp.rpart, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 2.crp (only CRP) \n AUC=%.2f", performance(pred2.crp.rpart, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
roc3.genes.crp.rpart <- plotROCCurves(generateThreshVsPerfData(pred3.genes.crp.rpart, measures = list(fpr, tpr, mmce))) + theme_bw() + ggtitle(sprintf("Model 3.genes.crp (genes + CRP) \n AUC=%.2f", performance(pred3.genes.crp.rpart, auc))) +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
data.roc1.genes.rpart <- ggplot2::ggplot_build(roc1.genes.rpart)$data[[1]]
data.roc2.crp.rpart <- ggplot2::ggplot_build(roc2.crp.rpart)$data[[1]]
data.roc3.genes.crp.rpart <- ggplot2::ggplot_build(roc3.genes.crp.rpart)$data[[1]]
backup.name <- c(backup.name, "data.roc1.genes.rpart", "data.roc2.crp.rpart", "data.roc3.genes.crp.rpart")

gridExtra::grid.arrange(roc1.genes.rpart, roc2.crp.rpart, roc3.genes.crp.rpart, nrow = 2)


######## 4.6 Plot top feature boxplots


ggbox <- ggplot(data = boxdat_melt, aes(x=Y, y=value, colour=Y, shape = CV, linetype = CV)) +
    geom_beeswarm(dodge.width = 0.75, alpha = 0.7) +
    geom_boxplot(outlier.shape = NA, fill = NA) +
    facet_wrap(~ Gene, ncol = 5) +
    theme_bw() +
    theme(
        plot.title = ggplot2::element_text(hjust=1, vjust=1, size = label.size), 
        axis.text = ggplot2::element_text(size = label.size), 
        axis.title = ggplot2::element_text(size = label.size), 
        legend.text = ggplot2::element_text(size = label.size), 
        legend.title = ggplot2::element_text(size = label.size), 
        strip.text = ggplot2::element_text(size = label.size)
    )
tempo <- dev.set(pdf.nb) # assign to avoid the message
ggbox


######## 4.7 Frequencies associated to each predictor



################################ End Main code

################################ Post Main code

save(list=c(backup.name), file = paste0(path.out, "loop", slurm.loop.nb, "_res_data.RData"))

############ Pdf window closing

fun_close_specif_window()

############ total computing time

fin.time <- as.numeric(Sys.time()) # time of process end
cat("TOTAL COMPUTATION TIME: ", as.character(lubridate::seconds_to_period(round(fin.time - ini.time))), "\n\n")
fun_export_data(path = path.out, data = paste0("\n\n\n\n################################ TOTAL COMPUTING TIME\n\n", as.character(lubridate::seconds_to_period(round(fin.time - ini.time)))), output = log.file, sep = 4)

############ Parameter printing

fun_export_data("\n\n\n\n################################ INITIAL SETTINGS OF PARAMETERS", output = log.file, path = path.out)
fun_export_data(path = path.out, data = param.ini.settings, output = log.file, vector.cat = TRUE)
fun_export_data("\n\n\n\n################################ SYSTEM AND PACKAGES", output = log.file, path = path.out)
fun_export_data(path = path.out, data = sessionInfo(), output = log.file, vector.cat = TRUE)

################################ End Post Main code