-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhkev_utils.R
executable file
·10111 lines (9095 loc) · 378 KB
/
hkev_utils.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
vplot2 = function(dat,
y_field,
group_field,
facet1 = NULL,
facet2 = NULL,
transpose = FALSE,
scale = "width",
stat = "ydensity",
position = "dodge",
xlab = NULL,
ylab = NULL,
cex.scatter = 2,
alpha = 0.5,
trim = TRUE,
fill_by = NULL,
title = NULL)
{
## browser()
dat2 = setDT(copy(dat))
y_field = substitute(y_field)
group_field = substitute(group_field)
facet1 = substitute(facet1)
facet2 = substitute(facet2)
facet1 = dat2[, eval(facet1)]
facet2 = dat2[, eval(facet2)]
if (!is.null(facet1))
if (!is.factor(facet1))
facet1 = factor(facet1, unique(facet1))
if (!is.null(facet2))
if (!is.factor(facet2))
facet2 = factor(facet2, unique(facet2))
dat2[, y := eval(y_field)]
group = dat2[, eval(group_field)]
fill_by = substitute(fill_by)
if (is.null(fill_by)) {
fill_by = group
} else {
fill_by = dat2[, eval(fill_by)]
}
if (!is.factor(group))
group = as.factor(group)
suppressWarnings(dat2[, `:=`(facet1, facet1)])
suppressWarnings(dat2[, `:=`(facet2, facet2)])
dat2 = dat2[rowSums(is.na(dat2)) == 0, ]
dat2$vgroup = paste(dat2$group, dat2$facet1, dat2$facet2)
vgroup = NULL
vfilter = TRUE
good = as.data.table(dat2)[, list(var = var(y)), keyby = vgroup][var >
0, vgroup]
dat2 = dat2[, `:=`(vfilter, dat2$vgroup %in% as.character(good))]
v = ggplot(data = dat2, aes(y = y, x = group)) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_blank(), axis.line = element_line(colour = "black"))
v = v + geom_violin(mapping = aes(fill = fill_by), stat = stat, position = position,
trim = trim, scale = scale)
v = v + geom_jitter(mapping = aes(fill = fill_by), shape = 21, size = cex.scatter, alpha = alpha, position = position_jitter(height = 0))
if (!is.null(ylab)) v = v + ylab(ylab)
if (!is.null(title)) v = v + ggtitle(title)
if (!is.null(dat2$facet1)) {
if (!is.null(dat2$facet2)) {
if (transpose)
v = v + facet_grid(facet2 ~ facet1)
else v = v + facet_grid(facet1 ~ facet2)
}
else {
if (transpose)
v = v + facet_grid(. ~ facet1)
else v = v + facet_grid(facet1 ~ .)
}
}
return(v)
}
vplot = function(y, group = 'x', facet1 = NULL, facet2 = NULL, transpose = FALSE, flip = FALSE, mapping = NULL,
stat = "ydensity",
position = "dodge",
trim = TRUE, sample = NA, scale = "width", log = FALSE, count = TRUE, xlab = NULL, ylim = NULL, ylab = NULL, minsup = NA,
scatter = FALSE,
text = NULL,
reorder = FALSE,
reorder.fun = mean,
cex.scatter = 1,
col.scatter = NULL, alpha = 0.3, title = NULL, legend.ncol = NULL, legend.nrow = NULL, vfilter = TRUE, vplot = TRUE, dot = FALSE, stackratio = 1, binwidth = 0.1, plotly = FALSE, print = TRUE,
base_size = 11,
blank_theme = TRUE,
col = NULL,
flip_x = TRUE,
drop = FALSE,
facet_scales = c("fixed", "free_y", "free_x", "free"))
{
# require(ggplot2)
if (!is.factor(group))
group = as.factor(group)
dat = data.table(y = suppressWarnings(as.numeric(y)), group)
if (reorder)
{
newlev = dat[, reorder.fun(y, na.rm = TRUE), by = group][order(V1), group]
dat[, group := factor(group, levels = newlev)]
}
if (!is.na(sample))
if (sample>0)
{
if (sample<1)
dat = dat[sample(nrow(dat), round(sample*nrow(sample))), ]
else
dat = dat[sample(nrow(dat), round(sample)), ]
}
if (is.null(facet1))
{
facet1 = facet2
facet2 = NULL
}
if (!is.null(facet1))
if (!is.factor(facet1))
facet1 = factor(facet1, unique(facet1))
if (!is.null(facet2))
if (!is.factor(facet2))
facet2 = factor(facet2, unique(facet2))
suppressWarnings(dat[, facet1 := facet1])
suppressWarnings(dat[, facet2 := facet2])
dat = dat[rowSums(is.na(dat))==0, ]
## remove 0 variance groups
dat$vgroup = paste(dat$group, dat$facet1, dat$facet2)
## if (vfilter)
## {
vgroup = NULL ## NOTE fix
good = as.data.table(dat)[, list(var = var(y)), keyby = vgroup][var>0, vgroup]
dat = dat[, vfilter := dat$vgroup %in% as.character(good)]
## }
if (!is.na(minsup))
{
num = NULL ## NOTE fix
good = as.data.table(dat)[, list(num = length(y)), keyby = vgroup][num>minsup, vgroup]
dat = dat[(dat$vgroup %in% as.character(good)), ]
}
if (nrow(dat)==0)
stop('No groups exist with >0 variance')
if (count)
{
tmp = table(dat$group)
ix = match(levels(dat$group), names(tmp))
levels(dat$group) = paste(names(tmp)[ix], '\n(', tmp[ix], ')', sep = '')
}
if (is.null(mapping))
mapping = aes(fill=group)
if (!is.null(col)) {
dat[, col := col]
}
## g = ggplot(dat[vfilter!=0, ], aes(y = y, x = group, group = group))
g = ggplot(dat, aes(y = y, x = group, group = group))
g = g + theme_bw(base_size = base_size)
if (blank_theme) {
if (flip_x) {
g = g + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_blank(), axis.line = element_line(colour = "black"), axis.text.x = element_text(angle = 90, vjust = .5))
} else {
g = g + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), plot.background = element_blank(), axis.line = element_line(colour = "black"))
}
}
if (vplot)
g = g + geom_violin(mapping = mapping, stat = stat, position = position, trim = trim, scale = scale)
if (scatter) {
if (dot)
{
if (is.null(text))
g = g + geom_dotplot(data = dat, mapping = aes(x = group, y = y, fill = group), binaxis = 'y', position = 'identity', col = NA, alpha = alpha, method = 'dotdensity', dotsize = cex.scatter, stackratio = stackratio, binwidth = binwidth, stackdir = 'center')
else
g = g + geom_dotplot(data = dat, mapping = aes(x = group, y = y, fill = group, text = text), binaxis = 'y', position = 'identity', col = NA, alpha = alpha, method = 'dotdensity', dotsize = cex.scatter, stackratio = stackratio, binwidth = binwidth, stackdir = 'center')
}
else
{
if (is.null(text))
{
if (is.null(col.scatter)) {
g = g + geom_jitter(data = dat, mapping = aes(fill = group), shape = 21, size = cex.scatter, alpha = alpha, position = position_jitter(height = 0))
## g = g + geom_jitter(data = dat, shape = 21, size = cex.scatter, alpha = alpha, position = position_jitter(height = 0))
}
else
g = g + geom_jitter(data = dat, fill = alpha(col.scatter, alpha), shape = 21, position = position_jitter(height = 0))
}
else
{
if (is.null(col.scatter)) {
g = g + geom_jitter(data = dat, mapping = aes(fill = group, text = text), shape = 21, size = cex.scatter, alpha = alpha, position = position_jitter(height = 0))
}
else
g = g + geom_jitter(data = dat, mapping = aes(text = text), fill = alpha(col.scatter, alpha), shape = 21, position = position_jitter(height = 0))
}
}
}
if (log)
{
if (!is.null(ylim))
if (length(ylim)!=2)
ylim = NULL
if (is.null(ylim))
g = g + scale_y_log10()
# g = g + coord_trans(y = 'log10')
else
g = g+ scale_y_log10(limits = ylim)
# g = g + coord_trans(y = 'log10', limits = ylim)
}
else
{
if (!is.null(ylim))
if (length(ylim)==1)
g = g+ ylim(ylim[1])
else if (length(ylim)==2)
g = g+ ylim(ylim[1], ylim[2])
}
if (!is.null(xlab))
g = g+ xlab(xlab)
if (!is.null(ylab))
g = g+ ylab(ylab)
if (!is.null(title))
g = g + ggtitle(title)
if (!is.null(legend.ncol))
g = g + guides(fill = guide_legend(ncol = legend.ncol, byrow = TRUE))
if (!is.null(legend.nrow))
g = g + guides(fill = guide_legend(nrow = legend.nrow, byrow = TRUE))
if (flip)
g = g + coord_flip()
if (!is.null(dat$facet1)) {
if (length(facet_scales) > 1) {
message("length > 1 arg provided to facet_scales\ndefaulting to facet_scales[1]")
facet_scales = facet_scales[facet_scales %in% c("fixed", "free_y", "free_x", "free")][1]
if (length(facet_scales) == 0) {
stop("facet_scales argument incorrect, must be one of\n", c("fixed", "free_y", "free_x", "free"))
}
}
if (!is.null(dat$facet2)) {
if (transpose) {
g = g + facet_grid(facet2 ~ facet1, drop = drop, scales = facet_scales)
} else {
g = g + facet_grid(facet1 ~ facet2, drop = drop, scales = facet_scales)
}
} else {
if (transpose) {
g = g + facet_grid(. ~ facet1, drop = drop, scales = facet_scales)
} else {
g = g + facet_grid(facet1 ~ ., drop = drop, scales = facet_scales)
}
}
}
if (plotly)
return(ggplotly(g))
if (print)
print(g)
else
g
}
#' match x indices in terms of y
#'
#' @param x A vector
#' @param y A vector
#' @return a vector of indices of \code(x) ordered by \code(y)
#' @examples
#' match_s(c(1,3,5,7,9), c(9, 5, 3))
#' match_s(c(1,3,5,7,9), c(3, 5, 9))
match_s = function(x, y) {
## x_tmp = factor(as.character(x), levels = as.character(y))
## y_tmp = factor(as.character(y), levels = as.character(x))
## y_tmp[which(y_tmp %in% x_tmp)]
x_tmp = setNames(as.character(x), as.character(x))
x_ind = setNames(1:length(x), as.character(x))
y_tmp = setNames(as.character(y), as.character(y))
y_ind = setNames(1:length(y), as.character(y))
## return(x_ind[names(y_tmp)[which(y_tmp %in% x_tmp)]])
these_idx = which(y_tmp %in% x_tmp)
find_in_x = names(y_tmp)[these_idx]
names(find_in_x) = y_ind[these_idx]
return(setNames(x_ind[find_in_x], names(find_in_x)))
}
#' matches x in terms of y
#'
#' returns vector of indices of matches in x with length of vector = length(y)
#' non matches are NA
match2 = function(x, y) {
## x_tmp = factor(as.character(x), levels = as.character(y))
## y_tmp = factor(as.character(y), levels = as.character(x))
## y_tmp[which(y_tmp %in% x_tmp)]
x_tmp = setNames(as.character(x), as.character(x))
x_ind = setNames(1:length(x), as.character(x))
y_tmp = setNames(as.character(y), as.character(y))
y_ind = setNames(1:length(y), as.character(y))
## return(x_ind[names(y_tmp)[which(y_tmp %in% x_tmp)]])
these_idx = which(y_tmp %in% x_tmp)
find_in_x = names(y_tmp)[these_idx]
names(find_in_x) = y_ind[these_idx]
new_index = rep(NA, length(y_tmp))
new_index[y_ind[these_idx]] = x_ind[find_in_x]
return(new_index)
}
match3 = function(x, table, nomatch = NA_integer_) {
dx = within(data.frame(x), {id.x = seq_along(x)})
dtb = within(data.frame(table), {id.tb = seq_along(table)})
res = merge(dx, dtb, by.x = "x", by.y = "table", all.x = TRUE,
allow.cartesian = TRUE)
return(res$id.tb[order(res$id.x)])
}
brew = function (x, palette = "Accent")
{
if (!is.factor(x))
x = factor(x)
ucols = structure(brewer.master(length(levels(x)), palette = palette), names = levels(x))
return(ucols[x])
}
#' find all duplicates in a vector
#'
#' @param vec A vector
#' @return a logical vector with all positions marked TRUE being duplicates
#' @examples
#' find_dups(c(1,1,1,3,5))
#' find_dups(c(1,3,1,3,1))
#' find_dups(c(3,1,5,4,4))
find_dups = function(..., re_sort = FALSE, sep = " ") {
lst = as.list(match.call())[-1]
ix = setdiff(seq_along(lst), which(names(lst) %in% c("re_sort", "sep")))
## cl = sapply(lst[ix], class)
if (length(ix) > 1)
vec = do.call(function(...) paste(..., sep = sep), alist(...))
else
vec = unlist(list(...))
dupix = which(duplicated(vec))
if (!re_sort) {
return(which(vec %in% vec[dupix]))
} else {
matching_idx = match2(sort(vec[dupix]), vec)
return(which(!is.na(matching_idx))[order(na.omit(matching_idx))])
}
}
## find_dups = function(vec, re_sort = FALSE) {
## dups = unique(vec[ duplicated(vec)])
## if (!re_sort) {
## return(vec %in% dups)
## } else {
## matching_idx = match2(sort(dups), vec)
## return(which(!is.na(matching_idx))[order(na.omit(matching_idx))])
## }
## }
#' @name undup
#' @title an alternative to base::unique() that preserves names
#'
#' @param obj an R vector
#' @return unique values of obj with names preserved
undup = function(obj, fromLast = FALSE, nmax = NA) {
obj[!duplicated(obj, fromLast = fromLast, nmax = NA)]
}
selfname = function(char) {setNames(char, char)}
#' @title check_lst
#' checking a list for any elements that are try-errors
#' usually from an lapply(..., function(x) try({})) call
#'
#' @param lst A list
#' @return a logical vector marking which elements are try-errors"
check_lst = function(lst, class_condition = c("try-error", "error", "errored", "err"))
{
unlist(lapply(lst, function(x) class(x)[1])) %in% class_condition
}
iderr = function(lst, class_condition = c("try-error", "error", "errored", "err")) {
which(check_lst(lst))
}
#' a wrapper around check_lst
#'
#' @param lst A list (usually the output of lapply(... , function(x) try({}))
#' @return only returns the non-errors in the list
ret_no_err = function(lst, class_condition = c("try-error", "error", "errored", "err"))
{
return(lst[!check_lst(lst, class_condition = class_condition)])
}
#' a wrapper around check_lst
#'
#' @param lst A list (usually the output of lapply(... , function(x) try({}))
#' @return only returns the errors in the list
ret_err = function(lst, class_condition = c("try-error", "error", "errored", "err"))
{
return(lst[check_lst(lst, class_condition = class_condition)])
}
#' using check_lst to return
#'
#' @param lst A list (usually the output of lapply(... , function(x) try({}))
#' @return returns full length list with errored elements changed to NA
ret_na_err = function(lst, class_condition = c("try-error", "error", "errored", "err"))
{
lst[check_lst(lst, class_condition = class_condition)] = NA
return(lst)
}
ret_ind = function(x, ix = 1)
{
if (class(x)[1] == "try-error")
{
return(x)
} else
{
x[[ix]]
}
}
#' convenience function to set column names
#'
#' @param object tabled object
#' @param nm names of the new columns
#' @return colnamed object
setColnames = function(object = nm, nm = NULL, pattern = NULL, replacement = "") {
if (!is.null(nm)) {
if (is.null(names(nm)))
colnames(object) = nm
else {
ix = match3(names(nm), colnames(object))
colnames(object)[ix] = nm
}
} else if (!is.null(pattern)) {
colnames(object) = gsub(pattern, replacement, colnames(object))
}
return(object)
}
#' convenience function to set row names
#'
#' @param object tabled object
#' @param nm names of the new columns
#' @return rownamed object
setRownames = function(object = nm, nm) {
base::rownames(object) = nm
object
}
#' a convenience function that unlists the output of lapply
#'
#' @param ... An expression call to lapply
#' @return An unlisted output of a lapply call
unlapply = function(...) {
return(unlist(lapply(...)))
}
#' label the quantiles in a numeric vector
#'
#' @param x A vector
#' @param g number of quantiles to bin the vector x
#' @return a factor labeling the quantile for each value in x
#' @examples
#' label_quantiles(1:100, 4)
#' label_quantiles(1:100, 10)
label_quantiles = function(x, g = 4, ordered = FALSE) {
is.hmisc = require(Hmisc)
if (! is.hmisc) {
stop("this function requires Hmisc")
}
quant = as.integer(Hmisc::cut2(x, g = g))
lev = levels(cut(0:100, quantile(0:100, prob = 0:g/g), include.lowest = T))
labels = factor(lev[quant], levels = lev, ordered = ordered)
return(labels)
}
#' find out if the list is nested
#'
#' @param x A list
#' @return a logical vector indicating if the list is nested
isNested <- function(x) {
if (class(x) != "list") {
stop("Expecting 'x' to be a list")
}
out <- any(sapply(x, is.list))
return(out)
}
#' collate two vectors together
#'
#' @param ... A set of vectors to collate
#' @return a vector with values of inputs collated together
#' @examples
#' intercalate(c("a","d","f"), c("b", "e", "g", "z"))
#' @export
intercalate = function(...) {
args = list(...)
if (isNested(args)) {
args = unlist(args, recursive = F)
}
s_along = lapply(args, seq_along)
ord = order(do.call(c, s_along))
conc = do.call(c, args)
return(conc[ord])
}
#' convenience function to convert to matrix
#' and optionally filter out the first column
#' which may be rownames that are not relevant to further data analysis
#'
#' @param obj a data.frame or matrix
#' @param rm_col1 a logical vector specifying if the 1st column should be removed
#' @return a matrix
#' @export
matrify = function(obj, rm_col1 = TRUE, use.c1.rownames = TRUE) {
if (rm_col1) {
if (use.c1.rownames) {
rn = as.matrix(obj[,1])[,1, drop = TRUE]
} else {
rn = NULL
}
setRownames(as.matrix(obj[,-1]), rn)
} else {
as.matrix(obj)
}
}
#' collate lists together
#'
#' @param ... A set of lists to collate
#' @return a lists with elements collated together
#' @examples
#' intercalate(list(paste0(1:5, "_A")), list(paste0(1:3, "_B")), list(paste0(1:6, "_C")))
intercalate_lst = function(...) {
args = list(...)
s_along = lapply(args, seq_along)
ord = order(do.call(c, s_along))
conc = do.call(c, args)
return(conc[ord])
}
#' utility function for removing multiple parantheses
#' probably not necessary
#'
#' @param str a path string
#' @return a string with multiple parentheses replaced with a single parenthesis
rm_mparen = function(str) {
return(gsub('\\/{2,}', "/", str))
}
normpath = function(p) {
bn = basename(p)
d = dirname(normalizePath(p))
return(paste0(d, "/", bn))
}
#' qstat parsing
#'
#' @param query a string of additional switches provided to qstat
#' @return NULL
make_qstat_query = function(query = "", tmpdir = '~/tmp/qstat_query/') {
tmpfn = gsub('\\/{2,}', "/", paste0(tmpdir, "/q.xml"))
system(paste0("mkdir -p ", tmpdir))
cmd = paste0("qstat -xml ", query, " > ", tmpfn)
system(cmd)
}
#' qstat query parsing
#'
#' @param query String that is either empty or -u <username>
#' @param tmpdir temporary directory path where the qstat info is dumped for reading into R
#'
#' @return a data table containing the full queue information at time of calling this function
qstat_query = function(query = "", tmpdir = "~/tmp/qstat_query/") {
library(XML)
make_qstat_query(query = query, tmpdir = tmpdir)
tmpfn = gsub('\\/{2,}', "/", paste0(tmpdir, "/q.xml"))
this_xml = xmlToList(tmpfn, simplify = F)
qinfo = rbindlist(lapply(this_xml$queue_info, function(x) as.data.table(t(x))))
if (! nchar(trimws(unlist(as.data.frame(qinfo[1,1])))) == 0) {
qinfo[, jclass_name := sapply(jclass_name, function(x) switch(is.null(NULL), NULL = NA, x))][, queue_name := sapply(queue_name, function(x) switch(is.null(NULL), NULL = NA, x))]
} else {
qinfo = NULL
}
jinfo = rbindlist(lapply(this_xml$job_info, function(x) as.data.table(t(x))))
if ( ! nchar(trimws(unlist(as.data.frame(jinfo[1,1])))) == 0) {
jinfo[, jclass_name := sapply(jclass_name, function(x) switch(is.null(NULL), NULL = NA, x))][, queue_name := sapply(queue_name, function(x) switch(is.null(NULL), NULL = NA, x))]
} else {
jinfo = NULL
}
fullinfo = rrbind(qinfo, jinfo, as.data.table = TRUE)
fullinfo = as.data.table(lapply(fullinfo, unlist))
system(paste0('rm ', tmpfn))
return(fullinfo)
}
#' qstat job id querying
#' INCOMPLETE
#'
#' @param jid job id numbers, usually gotten from qstat_query
#' @param tmpdir temporary directory path where the qstat info is dumped for reading into R
#'
#' @return a data table containing job information
qstat_jquery = function(jid, tmpdir = "~/tmp/qstat_query/") {
tmpfn = gsub('\\/{2,}', "/", paste0(tmpdir, "/q.xml"))
these_j = rbindlist(lapply(jid, function(j) {
make_qstat_query((paste0("-j ", j)))
this_xml = xmlToList(tmpfn)
this_j = rbindlist(lapply(this_xml$djob_info, function(x) as.data.table(t(x))))[, JB_preemption := sapply(JB_preemption, function(x) ifelse(is.null(x), NA, x))]
return(this_j)
}))
## browser()
## these_j = as.data.table(lapply(these_j, function(x) unlist(x, recursive = FALSE)))
return(these_j)
}
#' @name ix_sdiff
#'
#' A function that subsets out indices and is robust to
#' if filt_out indices are integer(0)
#'
#' @return obj with indices indicated in filt_out taken out
ix_sdiff = function(obj, filt_out) {
if (is.null(nrow(obj))) {
ix = 1:length(obj)
} else {
ix = 1:nrow(obj)
}
obj[! ix %in% filt_out]
}
slide_every_n = function(vec, every = 2) {
lst_to_inter = lapply(c(0, seq_len(every-1)), function(i) {
seq_along(vec) + i
})
these_ids = vec[intercalate(lst_to_inter)]
return(these_ids)
}
label_every_n = function(sliding_vec, every = 2) {
return(rep(seq_len(ceiling(length(sliding_vec)/2)), each = every))
}
map_integer_to_junc_match = function(ids) {
if (ids[1] < 0) {
ids = rev(-ids) ## now positive is always first
}
if (sign(ids[1]) * sign(ids[2]) < 0) { ## if signs of adjacent ids are different, inversion
if (abs(ids[1]) < abs(ids[2])) {
return(-sort(abs(ids)))
} else if (abs(ids[1]) > abs(ids[2])) {
return(sort(abs(ids) - 1))
}
} else if (sign(ids[1]) * sign(ids[2]) > 0) { ## if signs of adjacent ids are same
if (abs(ids[1]) < abs(ids[2])) {
## ids[2] = ids[2] - 1
ids[1] = -abs(ids[1])
return(ids)
} else if (abs(ids[1]) > abs(ids[2])) {
## ids[2] = ids[2] - 1
ids[1] = -abs(ids[1])
return(rev(ids))
}
}
}
diff_every_n = function(vec, every = 2) {
slide_every = slide_every_n(vec, every = every)
lst = split(slide_every, label_every_n(slide_every))
mat = as.matrix(do.call("rbind", lst))
return(mat)
}
name_dtlst = function(lst) {
lapply(lst, function(x) {
all.x = eval.parent(substitute(x)[[2]])
this.i = eval.parent(substitute(x)[[3]])
nm = names(all.x[this.i])
x$pair = nm
x
})
}
#' parse the output of gGnome::fusion()
#'
#' Take the fusion outputs and separate into 5' and 3' partners
#'
#' @param fus GRangeslist object output of gGnome::fusion()
#' @return data table containing breakpoints and the name of fusion partners
parse_pair_fus = function(fus, only_unique = TRUE)
{
tmp_dt = gr2dt(grl.unlist(fus))
star_formatted = tmp_dt[,
{
this_iix = .SD[, grl.iix][-.N]
ids_by_2 = intercalate(c(this_iix, this_iix + 1))
names(ids_by_2) = rep(1:(length(ids_by_2)/2), each = 2)
dt = copy(.SD)[ids_by_2]
dt[, split_by := names(ids_by_2)]
dt2 = dt[,{
left = copy(.SD)[1]
right = copy(.SD)[2]
#' be careful here
#' it seems like the star breakpoints are specified
#' as reference coordinate junctions (the fused sides)
#' the fusions are in walk format...
#' so need to specify the actual fused breakpoints
left_bp = ifelse(left$strand == "+", left$end, left$start-1)
left_strand = ifelse(left$strand == "+", "-", "+")
right_bp = ifelse(right$strand == "+", right$start-1, right$end)
right_strand = ifelse(right$strand == "+", "+", "-")
list(Left_Gene = left$gene_name,
Right_Gene = right$gene_name,
Left_Breakpoint = paste0(left$seqnames, ":", left_bp, ":", left_strand),
Right_Breakpoint = paste0(right$seqnames, ":", right_bp, ":", right_strand),
Left_InFrame = left$in.frame,
Right_InFrame = right$in.frame,
Fusion = left$alteration)
}, by = split_by]
dt2[, Fusion_Name := paste0(Left_Gene, "--", Right_Gene)]
dt2
## bla = matrix(intercalate(c(this_iix, this_iix + 1)), nrow = length(this_iix), ncol = 2, dimnames = list(NULL, c("left_idx", "right_idx")))
}, by = grl.ix]
if (only_unique) {
star_formatted = star_formatted[!duplicated(Fusion_Name)]
}
return(star_formatted)
}
parse_pair_fus2 = function(fus) {
fus_dt = gr2dt(unlist(fus))
possible_fus_pairs = fus_dt[, {
possible_fus = do.call(rbind, combn(gene_name, 2, simplify = FALSE))
possible_fus = unique(as.data.table(possible_fus[!matrixStats::rowAnyNAs(possible_fus),,drop = FALSE]))
possible_fus
}, by = grl.ix]
setnames(possible_fus_pairs, c("V1", "V2"), c("left_gene", "right_gene"))
possible_fus_pairs[, fusion_name := paste(left_gene, right_gene, sep = "--")]
## possible_fus_pairs[, pair := this_id]
possible_fus_pairs = merge(possible_fus_pairs, as.data.table(mcols(fus)), by = "grl.ix", all.x = TRUE)
## indiv_fus = parse_pair_fus(individual_fus, only_unique = FALSE)
## indiv_fus[, called_by := nm]
## indiv_fus[, pair := this_row$pair]
## return(indiv_fus)
return(possible_fus_pairs)
}
run_complex = function(gg) {
gg = gg %>%
pyrgo(mark = TRUE) %>%
rigma(mark = TRUE) %>%
chromothripsis(mark = TRUE) %>%
## tornado(mark = TRUE) %>%
tyfonas(mark = TRUE) %>%
chromoplexy(mark = TRUE) %>%
tic(mark = TRUE) %>%
qrp(mark = TRUE) %>%
bfb() %>%
dm()
gg
}
#' splitting a uniform string
#'
#' Splits a uniform string (i.e. a strings that when split, give a list of all equal sized elements
#'
#' @param str string to split
#' @param split regex to split by
#' @return a matrix of the strings
str_mat = function(str, split = "\\:")
{
tmp_mat = do.call(rbind, strsplit(str, split = split))
}
#' making na's false
#'
na2false = function(v)
{
## v = ifelse(is.na(v), v, FALSE)
v[is.na(v)] = FALSE
as.logical(v)
}
na2true = function(v)
{
## v = ifelse(is.na(v), v, FALSE)
v[is.na(v)] = TRUE
as.logical(v)
}
na2zero = function(v) {
## v = ifelse(is.na(v), v, FALSE)
v[is.na(v)] = 0
return(v)
}
nan2zero = function(v) {
v[is.nan(v)] = 0
return(v)
}
#' making na's empty characters
na2empty = function(v) {
## v = ifelse(is.na(v), v, FALSE)
v[is.na(v)] = ""
as.character(v)
}
#' making empty characters into na's
empty2na = function(v) {
## v = ifelse(is.na(v), v, FALSE)
v[nchar(v) == 0] = as.character(NA)
v
}
#' make data.frame or data.table column name whitespaces into underscores and remove end whitespaces
#'
ws2und = function(df)
{
data.table::setnames(df, gsub("^_|_$", "", gsub("_{2,}", "_", gsub("(\\/)|(\\.)|( )|\\(|\\)|\\#", "_", trimws(colnames(df))))))
return(df)
}
#' test if all elements of object are the same
#'
#' This may not work with numeric
#'
allsame = function(obj)
{
all(obj == obj[1])
}
.filter_sv = function(ent, overwrite = FALSE) {
if (file.exists(ent$svaba_unfiltered_somatic_vcf)) {
outpath = paste0(file_path_sans_ext(ent$svaba_unfiltered_somatic_vcf), ".pon.filtered.rds")
if (isTRUE(overwrite) || isFALSE(file.exists(outpath))) {
sv = JaBbA::read.junctions(ent$svaba_unfiltered_somatic_vcf)
if (!exists("sv_pon")) {
sv_pon = gr.noval(readRDS('~/lab/projects/CCLE/db/tcga_and_1kg_sv_pon.rds'))
}
sv = sv_filter(sv, sv_pon, pad = 1000)
outpath = paste0(file_path_sans_ext(ent$svaba_unfiltered_somatic_vcf), ".pon.filtered.rds")
saveRDS(sv, outpath, compress = FALSE)
message(ent$pair, " finished")
message("\n")
data.table(pair = ent$pair, svaba_unfiltered_somatic_vcf_sv_pon_filtered = outpath)
} else if (isTRUE(file.exists(outpath))) {
data.table(pair = ent$pair, svaba_unfiltered_somatic_vcf_sv_pon_filtered = outpath)
}
} else {
data.table(pair = ent$pair, svaba_unfiltered_somatic_vcf_sv_pon_filtered = NA_character_)
}
}
pairs.filter.sv = function(tbl, id.field, sv.field = "svaba_unfiltered_somatic_vcf", mc.cores = 1, pon.path = '~/lab/projects/CCLE/db/tcga_and_1kg_sv_pon.rds') {
if (missing(id.field))
id.field = key(tbl)
if (is.null(id.field))
stop("please specify an id field")
if (!exists("sv_pon")) {
message("no sv_pon variable found...", "\n",
"loading ", pon.path)
sv_pon = gr.noval(readRDS(pon.path))
}
iter.fun = function(pr, tbl) {
try2({
ent = tbl[get(id.field) == pr]
return(.filter_sv(ent))
})
}
out = mclapply(mc.cores = mc.cores,
tbl[[id.field]], iter.fun, tbl = tbl)
out = tryCatch(rbindlist(out), error = function(e) {
message("error at rbindlist, returning list"); out
})
return(out)
}
#################### Inspecting jabbas
gt.plot = function(gtrack, win, filename ="plot.png", title = "", h = 10, w = 10, ...) {
if (missing(win))
win = si2gr(gtrack) %>% keepStandardChromosomes(pruning.mode = "coarse") %>% gr.sort
ppng({par(mar = c(1, 1.5, 2, 3)); plot(gtrack, win = win, ...)}, filename = filename, res = 200, title = title, h = h, w = w)
}
plot.jabba = function(pairs, win, filename, use.jab.cov = TRUE, field.name = "jabba_rds", cov.field.name = "cbs_cov_rds", cov.y.field = "ratio", title = "", doplot = TRUE, rel2abs = FALSE, gt, plotfun = "ppng", h = 10, w = 10, rebin = FALSE, binwidth = 1e3, lwd.border = 0.0001, ...) {
lst.args = list(...)
if (!all(c("purity", "ploidy") %in% names(lst.args)))
lst.args = c(lst.args,
with(readRDS(pairs[["jabba_rds"]]),
list(purity = purity, ploidy = ploidy)))
if (is.character(plotfun)) {
plotfun = get(plotfun)
} else if (!is.function(plotfun)) {
stop("plotfun needs to be a function")
}
if (missing(gt)) {
gg = gG(jabba = pairs[[field.name]])
if (isTRUE(use.jab.cov))
cov = readRDS(inputs(readRDS(pairs[[field.name]] %>% dig_dir("Job.rds$")))$CovFile)
else
cov = readRDS(pairs[[cov.field.name]])
if (rebin)
cov = rebin(cov, binwidth = binwidth, FUN = median)
if (rel2abs) {
mcols(cov)[[cov.y.field]] =
skitools::rel2abs(cov, field = cov.y.field,
purity = lst.args$purity,
ploidy = lst.args$ploidy)
}
gcov = gTrack(cov, cov.y.field, circles = TRUE, lwd.border = lwd.border, y0 = 0)
gt = within(c(gcov, gg$gtrack()), {y0 = 0})
}
if (missing(win))
win = si2gr(hg_seqlengths()) %>% keepStandardChromosomes(pruning.mode = "coarse") %>% gr.sort
if (isTRUE(doplot)) {
if (missing(filename))
plotfun(plot(gt, win = win, ...), res = 200, title = title, h = h, w = w)
else
plotfun(plot(gt, win = win, ...), filename = filename, res = 200, title = title, h = h, w = w)
}
return(gt)
}
pairs.plot.jabba = function(pairs, dirpath = "~/public_html/jabba_output", ftitle.field = "pair", jabba.field = "jabba_rds", cov.y.field = "foreground", id.field = "pair", mc.cores = 1, cov.field.name = "cbs_cov_rds", use.jab.cov = TRUE) {
paths = subset2(pairs[[jabba.field]], file.exists(x))
iter.fun = function(x, tbl) {
ent = tbl[get(jabba.field) == x]
ttl = ent[[id.field]]
plot.jabba(ent, use.jab.cov = use.jab.cov, field.name = jabba.field, filename = paste0(dirpath, "/", ent[[ftitle.field]], ".png"), cov.y.field = cov.y.field, cov.field.name = cov.field.name, y.quantile = 0.01, title = ttl)
}
mclapply(paths, iter.fun, tbl = pairs, mc.cores = mc.cores)
NULL
}
pairs.process.events = function(pairs, events.field = "complex", id.field = "pair", mc.cores = 1) {