-
Notifications
You must be signed in to change notification settings - Fork 7
/
looper_runtime_plot.R
executable file
·462 lines (427 loc) · 17.9 KB
/
looper_runtime_plot.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
#! /usr/bin/env Rscript
###############################################################################
#06/04/18
#Last Updated 07/03/18
#Original Author: Jason Smith
#looper_runtime_plot.R
#
#This program is meant to plot a comparison of total runtime to a breakdown
#of the runtime for each pipeline subcommand
#
#NOTES:
#usage: Rscript /path/to/Rscript/looper_runtime_plot.R
# /path/to/project_config.yaml
#
#requirements: argparser, dplyr, ggplot2, grid, stringr, pepr
#
###############################################################################
#### DEPENDENCIES ####
###############################################################################
##### LOAD ARGUMENTPARSER #####
loadLibrary <- tryCatch (
{
suppressWarnings(suppressPackageStartupMessages(library(argparser)))
},
error=function(e) {
message("Error: Install the \"argparser\"",
" library before proceeding.")
return(NULL)
},
warning=function(e) {
message(e)
return(TRUE)
}
)
if (length(loadLibrary)!=0) {
suppressWarnings(library(argparser))
} else {
quit()
}
# Create a parser
p <- arg_parser("Produce an ATACseq pipeline (PEPATAC) runtime plot")
# Add command line arguments
p <- add_argument(p, "config",
help="PEPATAC project_config.yaml")
# p <- add_argument(p, "--output",
# help="PNG or PDF",
# default = "PDF")
# Parse the command line arguments
argv <- parse_args(p)
##### LOAD ADDITIONAL DEPENDENCIES #####
required_libraries <- c("dplyr", "ggplot2", "grid", "stringr", "pepr")
for (i in required_libraries) {
loadLibrary <- tryCatch (
{
suppressPackageStartupMessages(
suppressWarnings(library(i, character.only=TRUE)))
},
error=function(e) {
message("Error: Install the \"", i,
"\" R library before proceeding.")
return(NULL)
},
warning=function(e) {
message(e)
return(1)
}
)
if (length(loadLibrary)!=0) {
suppressWarnings(library(i, character.only=TRUE))
} else {
quit()
}
}
###############################################################################
#### FUNCTIONS ####
###############################################################################
# Convert Hours:Minutes:Seconds to Seconds
toSeconds <- function(HMS){
if (!is.character(HMS)) {
stop("HMS must be a character string of the form H:M:S")
}
if (length(HMS)<=0){
return(HMS)
}
unlist(
lapply(HMS,
function(i){
i <- as.numeric(strsplit(i,':',fixed=TRUE)[[1]])
if (length(i) == 3) {i[1]*3600 + i[2]*60 + i[3]}
else if (length(i) == 2) {i[1]*60 + i[2]}
else if (length(i) == 1) {i[1]}
}))
}
# Convert seconds back to HMS format
secondsToString <- function(secs, digits=2){
unlist(
lapply(secs,
function(i){
# includes fractional seconds
fs <- as.integer(round((i - round(i))*(10^digits)))
fmt <- ''
if (i >= 3600) {fmt <- '%H:%M:%S'}
else if (i >= 60) {fmt <- '%M:%S'}
else {fmt <- '%OS'}
i <- format(as.POSIXct(strptime("0:0:0","%H:%M:%S")) +
i, format=fmt)
if (fs > 0) {sub('[0]+$','',paste(i,fs,sep='.'))}
else {i}
}))
}
# Taken from https://github.com/baptiste/egg/blob/master/R/set_panel_size.r
set_panel_size <- function(p=NULL, g=ggplotGrob(p), file=NULL,
margin=unit(1, "in"),
width=unit(4, "in"),
height=unit(4, "in")){
panels <- grep("panel", g$layout$name)
panel_index_w <- unique(g$layout$l[panels])
panel_index_h <- unique(g$layout$t[panels])
nw <- length(panel_index_w)
nh <- length(panel_index_h)
if(getRversion() < "3.3.0"){
# the following conversion is necessary
# because there is no `[<-`.unit method
# so promoting to unit.list allows standard list indexing
g$widths <- grid:::unit.list(g$widths)
g$heights <- grid:::unit.list(g$heights)
g$widths[panel_index_w] <- rep(list(width), nw)
g$heights[panel_index_h] <- rep(list(height), nh)
} else {
g$widths[panel_index_w] <- rep(width, nw)
g$heights[panel_index_h] <- rep(height, nh)
}
if(!is.null(file))
ggsave(file, g, limitsize = FALSE,
width=convertWidth(sum(g$widths) + margin,
unitTo="in", valueOnly=TRUE),
height=convertHeight(sum(g$heights) + margin,
unitTo="in", valueOnly=TRUE))
invisible(g)
}
# Helper function to build a file path to the correct output folder using a
# specified suffix
buildFilePath = function(sampleName, suffix, pep=prj) {
invisible(capture.output(outputDir <- config(pep)$metadata$output_dir))
file.path(outputDir, "results_pipeline", sampleName,
paste(sampleName, suffix, sep=""))
}
# Remove sequentially duplicated values in a column, summing the values
# in the other
dedupSequential = function(dupDF) {
dupList <- dupDF[c(tail(dupDF[,1],-1) != head(dupDF[,1],-1), TRUE),][,1]
dedupDF <- data.frame(cmd=character(length(dupList)),
val=numeric(length(dupList)),
stringsAsFactors=FALSE)
currentPos <- 1
counter <- 1
while (counter <= nrow(dupDF)) {
currentCmd <- dupDF[counter, 1]
total <- dupDF[counter, 2]
if (counter + 1 <= nrow(dupDF)) {
nextCmd <- dupDF[counter + 1, 1]
while (nextCmd == currentCmd) {
counter <- counter + 1
total <- total + dupDF[counter, 2]
nextCmd <- dupDF[counter + 1, 1]
if (is.na(nextCmd)) {break}
}
}
dedupDF[currentPos, 1] <- currentCmd
dedupDF[currentPos, 2] <- total
currentPos <- currentPos + 1
counter <- counter + 1
}
return (dedupDF)
}
# Produce a runtime plot for a sample
getRuntime = function(timeFile, sampleName, createPlot=TRUE) {
# Get just the first line to get pipeline start time
if (length(timeFile) == 0 || !file.exists(timeFile)) {
fileMissing <<- TRUE
return(data.frame(cmd=as.character(),
time=as.numeric(),
order=as.numeric()))
} else {
fileMissing <<- FALSE
startTime <- readLines(timeFile, n=1)
}
# Extract just the starting time timestamp
startTime <- word(startTime, -1, sep=" ")
# Get the run times for each pipeline command
# Ignore any lines containing '#'
# TODO: Handle an empty file for a still running or failed sample
timeStamps <- tryCatch(
{
read.delim2(timeFile, skip=2, header = FALSE,
as.is=TRUE, comment.char = '#')
},
error=function(e) {
message("The profile.tsv file for ", sampleName, " contains no ",
"commands. Check if ", sampleName, " has yet to be run.")
timeStamps <- data.frame(cmd=as.character(),
time=as.numeric(),
order=as.numeric())
return(timeStamps)
},
warning=function(e) {
message("The profile.tsv file for ", sampleName, " is incomplete.")
message("WARNING: ", e)
}
)
if (nrow(timeStamps) == 0 ) {
# The profile.tsv contains no commands
return(timeStamps)
}
# Remove leading directory structure
for (i in 1:nrow(timeStamps)) {
timeStamps[i,1] <- sub('.*\\/', '', timeStamps[i,1])
}
timeStamps <- timeStamps[,-c(2,4)]
colnames(timeStamps) <- c("cmd","time")
timeStamps$time <- toSeconds(timeStamps$time)
# Combine any of the same commands to get total time spent per command
# Eliminate only sequentially duplicated commands
combinedTime <- dedupSequential(timeStamps)
colnames(combinedTime) <- c("cmd", "time")
totalTime <- sum(combinedTime$time)
finishTime <- secondsToString(toSeconds(startTime) + totalTime)
num.rows <- nrow(combinedTime)
combinedTime[num.rows+1, 1] <- "totalTime"
combinedTime[num.rows+1, 2] <- as.character(totalTime)
combinedTime$time <- as.numeric(combinedTime$time)
combinedTime$cmd <- as.character(combinedTime$cmd)
# Set order for plotting purposes
combinedTime$order <- as.factor(as.numeric(row.names(combinedTime)))
# Create plot
if (createPlot) {
p <- ggplot(data=combinedTime, aes(x=order, y=time)) +
geom_bar(stat="identity", position=position_dodge())+
scale_fill_brewer(palette="Paired")+
theme_minimal() +
coord_flip() +
labs(y = paste("Time (s)\n", "[Start: ", startTime, " | ",
"End: ", finishTime, "]", sep=""),
x = "PEPATAC Command") +
scale_x_discrete(labels=combinedTime$cmd) +
theme(plot.title = element_text(hjust = 0.5))
# Produce both PDF and PNG
set_panel_size(
p,
file=buildFilePath(sampleName, "_Runtime.pdf", prj),
width=unit(8,"inches"),
height=unit(5.5,"inches"))
set_panel_size(
p,
file=buildFilePath(sampleName, "_Runtime.png", prj),
width=unit(8,"inches"),
height=unit(5.5,"inches"))
}
return(combinedTime)
}
joinTimes = function (new, preexist) {
combined <- sort(union(levels(preexist$order), levels(new$order)))
if (length(new$cmd) == length(preexist$cmd) &&
all(is.element(new$cmd, preexist$cmd))) {
#message("A")
# Both data.frames have the same commands in number and value
preexist <- full_join(preexist, new, by=c("cmd", "order"))
return (preexist)
} else if (length(new$cmd) < length(preexist$cmd)) {
#message("B")
# The to-be-added data.frame contains less commands than the
# pre-existing data.frame
rebuiltNew <- data.frame(cmd=preexist$cmd,
time=rep(0, nrow(preexist)),
order=rep(1:nrow(preexist)),
stringsAsFactors=FALSE)
uniqueCmds <- data.frame(cmd=as.character(), time=as.numeric(),
order=as.numeric(), stringsAsFactors=FALSE)
for (i in 1:nrow(new)) {
if (new$cmd[i] %in% preexist$cmd) {
rowPos <- grep(new$cmd[i], preexist$cmd)
rebuiltNew[rowPos, ] <- data.frame(cmd=new$cmd[i],
time=new$time[i],
order=rowPos,
stringsAsFactors=FALSE)
} else {
uniqueCmds <- rbind(uniqueCmds, new[i, ])
}
}
uniqueCmds$order <- as.factor(uniqueCmds$order)
joinedTimes <- left_join(
mutate(preexist, order=factor(order, levels=combined)),
mutate(rebuiltNew,
order=factor(order, levels=combined)),
by=c("cmd","order"))
joinedTimes$order <- as.factor(rep(1:nrow(joinedTimes)))
return(joinedTimes)
} else if (length(new$cmd) > length(preexist$cmd)) {
#message("C")
# The to-be-added data.frame contains more commands than are present
# in the pre-existing data.frame
rebuiltPre <- data.frame(cmd=new$cmd,
time=rep(0, nrow(new)),
order=rep(1:nrow(new)),
stringsAsFactors=FALSE)
uniqueCmds <- data.frame(cmd=as.character(), time=as.numeric(),
order=as.numeric(), stringsAsFactors=FALSE)
for (i in 1:nrow(preexist)) {
if (preexist$cmd[i] %in% new$cmd) {
rowPos <- grep(preexist$cmd[i], new$cmd)
rebuiltPre[rowPos, ] <- data.frame(cmd=preexist$cmd[i],
time=preexist$time[i],
order=rowPos,
stringsAsFactors=FALSE)
} else {
uniqueCmds <- rbind(uniqueCmds, preexist[i, ])
}
}
uniqueCmds$order <- as.factor(uniqueCmds$order)
joinedTimes <- left_join(
mutate(new, order=factor(order, levels=combined)),
mutate(rebuiltPre,
order=factor(order, levels=combined)),
by=c("cmd","order"))
joinedTimes <- suppressWarnings(full_join(
joinedTimes, uniqueCmds,by=c("cmd","order")))
joinedTimes$order <- as.factor(rep(1:nrow(joinedTimes)))
return(joinedTimes)
} else {
#message("D")
# Both data.frames are the same length but contain different cmds
rebuiltNew <- data.frame(cmd=preexist$cmd,
time=rep(0, nrow(preexist)),
order=rep(1:nrow(preexist)),
stringsAsFactors=FALSE)
uniqueCmds <- data.frame(cmd=as.character(), time=as.numeric(),
order=as.numeric(), stringsAsFactors=FALSE)
for (i in 1:nrow(new)) {
if (new$cmd[i] %in% preexist$cmd) {
rowPos <- grep(new$cmd[i], preexist$cmd)
rebuiltNew[rowPos, ] <- data.frame(cmd=new$cmd[i],
time=new$time[i],
order=rowPos,
stringsAsFactors=FALSE)
} else {
uniqueCmds <- rbind(uniqueCmds, new[i, ])
}
}
uniqueCmds$order <- as.factor(uniqueCmds$order)
joinedTimes <- left_join(
mutate(preexist, order=factor(order, levels=combined)),
mutate(rebuiltNew,
order=factor(order, levels=combined)),
by=c("cmd","order"))
joinedTimes <- suppressWarnings(full_join(
joinedTimes, uniqueCmds,by=c("cmd","order")))
joinedTimes$order <- as.factor(rep(1:nrow(joinedTimes)))
return(joinedTimes)
}
}
###############################################################################
#### OPEN FILE ####
###############################################################################
configFile <- argv$config
prj = Project(configFile)
###############################################################################
#### MAIN ####
###############################################################################
# For each sample in the project, produce a runtime summary plot
if (!is.null(config(prj)$name)) {
accumName <- file.path(config(prj)$metadata$output_dir,
paste(config(prj)$name, "average_runtime.csv",
sep="_"))
} else {
accumName <- file.path(config(prj)$metadata$output_dir,
"average_runtime.csv")
}
invisible(capture.output(outputDir <- config(prj)$metadata$output_dir))
invisible(capture.output(numSamples <- length(samples(prj)$sample_name)))
accumulated <- data.frame(cmd=as.character(), time=as.numeric(),
order=as.numeric())
for (i in 1:numSamples) {
invisible(capture.output(sampleName <- samples(prj)$sample_name[i]))
timeFile <- Sys.glob(file.path(outputDir, "results_pipeline",
sampleName, "*_profile.tsv"))
if (length(timeFile) != 0) {
write(paste("Plotting runtime: ", sampleName, sep=""), stdout())
combinedTime <- getRuntime(timeFile, sampleName)
if (nrow(accumulated) == 0) {
accumulated <- combinedTime
} else {
accumulated <- joinTimes(combinedTime, accumulated)
}
} else {
write(paste("Could not find the profile.tsv file for \'", sampleName,
"\' at location:", file.path(outputDir, "results_pipeline",
sampleName), sep=""), stdout())
}
}
accumulated <- accumulated[order(as.numeric(row.names(accumulated))), ]
accumulated <- subset(accumulated, select=-c(order))
final <- data.frame(cmd=as.character(), average_time=as.numeric())
if (nrow(accumulated) == 0) {
# Do nothing
final <- NULL
} else {
for (i in 1:nrow(accumulated)) {
cmd <- accumulated$cmd[i]
tmp <- subset(accumulated, select=-c(cmd))
average_time <- as.numeric(sum(tmp[i,], na.rm=TRUE))/numSamples
average <- data.frame(cbind(cmd, average_time))
final <- rbind(final, average)
}
}
if (is.null(final)) {
if (fileMissing) {
write("WARNING: Profile.tsv file(s) was/were missing.",
stdout())
} else {
write("WARNING: Profile.tsv file(s) contained no commands.",
stdout())
}
} else {
write.csv(final, accumName, row.names=FALSE)
write(paste("Average command runtime (n=", numSamples, "): ",
accumName, sep=""), stdout())
}