-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathUpset.R
More file actions
1829 lines (1671 loc) · 51.3 KB
/
Copy pathUpset.R
File metadata and controls
1829 lines (1671 loc) · 51.3 KB
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
# special case: the matrix can have no row names
make_comb_mat_from_matrix = function(x, mode, top_n_sets = Inf, min_set_size = -Inf,
universal_set = NULL, complement_size = NULL, set_on_rows = TRUE) {
# check whether x is a binary matrix
if(is.data.frame(x)) {
lc = sapply(x, function(x) {
if(is.numeric(x)) {
all(x == 0 | x == 1)
} else if(is.logical(x)) {
TRUE
} else {
FALSE
}
})
} else if(is.matrix(x)) {
lc = apply(x, 2, function(x) {
if(is.numeric(x)) {
all(x == 0 | x == 1)
} else if(is.logical(x)) {
TRUE
} else {
FALSE
}
})
} else {
stop_wrap("The input should be a matrix or in a format that can be converted to a matrix.")
}
if(sum(lc) < 1) {
stop_wrap("Can not find columns which are logical or only contain 0 or 1.")
} else {
x = x[, lc, drop = FALSE]
}
if(is.null(colnames(x))) {
stop_wrap("The matrix or the data frame must have column names.")
}
x = as.matrix(x) + 0
if(any(is.na(x))) {
warning_wrap("The matrix contains NA values. Convert to 0/FALSE.")
x[is.na(x)] = 0
}
if(is.null(rownames(x))) {
x_has_rownames = FALSE
} else {
x_has_rownames = TRUE
}
# when there is no row name in x, there is no universal_set
if(!is.null(universal_set)) {
if(!x_has_rownames) {
stop_wrap("`x` should have row names when `universal_set` is set.")
}
}
if(is.null(complement_size)) {
k = sum(rowSums(x) == 0)
if(k) {
complement_size = k
}
}
if(!is.null(universal_set)) {
x = x[intersect(rownames(x), universal_set), , drop = FALSE]
if(nrow(x) == 0) {
stop_wrap("There is no combination set left after intersecting to `universal_set`.")
}
complement_size = length(setdiff(universal_set, rownames(x)))
}
set_size = colSums(x)
l = set_size >= min_set_size & rank(max(set_size) - set_size) <= top_n_sets
set_size = set_size[l]
x = x[, l, drop = FALSE]
# universal_set has higher priority than complement_size
x0 = x
x = x[rowSums(x) > 0, , drop = FALSE]
if(mode == "distinct") {
comb_size = table(apply(x, 1, binaryToInt))
} else {
comb_size = table(unlist(apply(x, 1, function(code) {
code2 = expand_mode(code, mode)
apply(code2, 1, binaryToInt)
})))
}
class(comb_size) = NULL
n_set = ncol(x)
comb_mat = sapply(names(comb_size), function(x) intToBinary(as.integer(x), n_set))
if(!is.matrix(comb_mat)) comb_mat = matrix(comb_mat, ncol = 1)
rownames(comb_mat) = colnames(x)
colnames(comb_mat) = NULL
if(!is.null(complement_size)) {
comb_mat = cbind(rep(0, nrow(comb_mat)), comb_mat)
comb_size = c(complement_size, comb_size)
}
attributes(comb_size) = NULL
if(!set_on_rows) {
comb_mat = t.default(comb_mat)
}
attr(comb_mat, "set_size") = unname(set_size)
attr(comb_mat, "comb_size") = comb_size
attr(comb_mat, "data") = x0
param = list(mode = mode,
universal_set = universal_set,
set_on_rows = set_on_rows)
attr(comb_mat, "param") = param
class(comb_mat) = c("comb_mat", "matrix")
comb_mat = comb_mat[order.comb_mat(comb_mat)]
return(comb_mat)
}
# code: a vector of 0 or 1, from distinct mode
expand_mode = function(code, mode = c("intersect", "union")) {
mode = match.arg(mode)[1]
if(mode == "intersect") {
l_one = which(code == 1)
n = length(l_one)
code2 = matrix(0, nrow = 2^n - 1, ncol = length(code))
k = 0
for(i in seq_len(n)) {
cm = combn(l_one, i, x_is_set = TRUE)
for(j in seq_len(ncol(cm))) {
k = k + 1
code2[k, cm[, j]] = 1
}
}
} else if(mode == "union") {
l_one = which(code == 1)
n = length(l_one)
all_n = length(code)
code2 = matrix(0, nrow = 2^(all_n-1)*n, ncol = length(code))
k = 0
for(i in seq_len(n)) {
# any combination of the remaining all_n - 1
other = setdiff(1:all_n, l_one[1:i])
for(i2 in 0:(all_n - i)) {
cm = combn(other, i2, x_is_set = TRUE)
for(j in seq_len(ncol(cm))) {
k = k + 1
code2[k, l_one[i]] = 1
code2[k, cm[, j]] = 1
}
}
}
code2 = code2[seq_len(k), , drop = FALSE]
}
return(code2)
}
combn = function(x, m, x_is_set = FALSE) {
if(length(x) == 1 && x_is_set) {
if(m == 0) {
return(utils::combn(1, 0))
} else {
return(matrix(x, nrow = 1))
}
} else {
utils::combn(x, m)
}
}
make_comb_mat_from_list = function(lt, mode, value_fun = length, top_n_sets = Inf,
min_set_size = -Inf, universal_set = NULL, complement_size = NULL,
set_on_rows = TRUE) {
n = length(lt)
if(n > 15) {
stop_wrap("Currently number of sets <= 15 is only supported when the input is a list.")
}
nm = names(lt)
if(is.null(nm)) {
stop_wrap("The list must have names.")
}
if(inherits(lt, "GRangesList")) {
lt = as.list(lt)
}
if(inherits(lt[[1]], "GRanges")) {
union = getFromNamespace("union", ns = "BiocGenerics")
intersect = getFromNamespace("intersect", ns = "BiocGenerics")
setdiff = getFromNamespace("setdiff", ns = "BiocGenerics")
} else if(inherits(lt[[1]], "IRanges")) {
union = getFromNamespace("union", ns = "BiocGenerics")
intersect = getFromNamespace("intersect", ns = "BiocGenerics")
setdiff = getFromNamespace("setdiff", ns = "BiocGenerics")
}
if(!is.null(universal_set)) {
lt = lapply(lt, function(x) intersect(x, universal_set))
complement_set = universal_set
for(i in seq_along(lt)) {
complement_set = setdiff(complement_set, lt[[i]])
}
complement_size = value_fun(complement_set)
}
if(inherits(lt[[1]], "GRanges")) {
set_size = sapply(lt, function(x) {
value_fun(union(x, x[NULL]))
})
} else if(inherits(lt[[1]], "IRanges")) {
set_size = sapply(lt, function(x) {
value_fun(union(x, x[NULL]))
})
} else {
set_size = sapply(lt, function(x) {
value_fun(union(x, NULL))
})
}
l = set_size >= min_set_size & rank(max(set_size) - set_size) <= top_n_sets
set_size = set_size[l]
lt = lt[l]
n = length(lt)
nm = names(lt)
comb_mat = matrix(FALSE, nrow = n, ncol = sum(choose(n, 1:n)))
rownames(comb_mat) = nm
j = 1
for(k in 1:n) {
comb = combn(n, k)
for(i in 1:ncol(comb)) {
comb_mat[comb[, i], j] = TRUE
j = j + 1
}
}
get_comb_size = function(lt, mode, do = rep(TRUE, length(lt)), value_fun = length) {
set1_index = which(do)
set2_index = which(!do)
s = lt[[ set1_index[1] ]]
if(mode == "distinct") {
for(i in set1_index[-1]) {
s = intersect(s, lt[[ i ]])
}
for(i in set2_index) {
s = setdiff(s, lt[[ i ]])
}
} else if(mode == "intersect") {
for(i in set1_index[-1]) {
s = intersect(s, lt[[ i ]])
}
} else if(mode == "union") {
for(i in set1_index[-1]) {
s = union(s, lt[[ i ]])
}
}
value_fun(s)
}
comb_size = numeric(ncol(comb_mat))
for(i in seq_len(ncol(comb_mat))) {
comb_size[i] = get_comb_size(lt, mode = mode, comb_mat[, i], value_fun = value_fun)
}
comb_mat = comb_mat + 0
l = comb_size > 0
comb_mat = comb_mat[, l, drop = FALSE]
comb_size = comb_size[l]
if(!is.null(complement_size)) {
comb_mat = cbind(rep(0, nrow(comb_mat)), comb_mat)
comb_size = c(complement_size, comb_size)
}
attributes(comb_size) = NULL
if(!set_on_rows) {
comb_mat = t.default(comb_mat)
}
attr(comb_mat, "set_size") = unname(set_size)
attr(comb_mat, "comb_size") = comb_size
attr(comb_mat, "data") = lt
param = list(mode = mode,
value_fun = value_fun,
universal_set = universal_set,
set_on_rows = set_on_rows)
attr(comb_mat, "param") = param
class(comb_mat) = c("comb_mat", "matrix")
comb_mat = comb_mat[order.comb_mat(comb_mat)]
return(comb_mat)
}
# == title
# Convert a List of Sets to a Binary Matrix
#
# == param
# -lt A list of vectors.
# -universal_set The universal set.
#
# == details
# It converts the list which have m sets to a binary matrix with n rows and m columns
# where n is the size of universal set.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 5),
# b = sample(letters, 10),
# c = sample(letters, 15))
# list_to_matrix(lt)
# list_to_matrix(lt, universal_set = letters)
list_to_matrix = function(lt, universal_set = NULL) {
if(!is.null(universal_set)) {
lt = lapply(lt, function(x) intersect(x, universal_set))
} else {
universal_set = unique(unlist(lt))
}
mat = matrix(0, nrow = length(universal_set), ncol = length(lt))
rownames(mat) = sort(universal_set)
colnames(mat) = names(lt)
for(i in seq_along(lt)) {
mat[as.character(unique(lt[[i]])), i] = 1
}
return(mat)
}
# == title
# Make a Combination Matrix for UpSet Plot
#
# == param
# -... The input sets. If it is represented as a single variable, it should be a matrix/data frame
# or a list. If it is multiple variables, it should be name-value pairs, see Input section for explanation.
# -mode The mode for forming the combination set, see Mode section.
# -top_n_sets Number of sets with largest size.
# -min_set_size Ths minimal set size that is used for generating the combination matrix.
# -universal_set The universal set. If it is set, the size of the complement set of all sets is also calculated.
# It if is specified, ``complement_size`` is ignored.
# -complement_size The size for the complement of all sets. If it is specified, the combination
# set name will be like "00...".
# -value_fun For each combination set, how to calculate the size? If it is a scalar set,
# the length of the vector is the size of the set, while if it is a region-based set,
# (i.e. ``GRanges`` or ``IRanges`` object), the sum of widths of regions in the set is
# calculated as the size of the set.
# -set_on_rows Used internally.
#
# == Input
# To represent multiple sets, the variable can be represented as:
#
# 1. A list of sets where each set is a vector, e.g.:
#
# list(set1 = c("a", "b", "c"),
# set2 = c("b", "c", "d", "e"),
# ...)
#
# 2. A binary matrix/data frame where rows are elements and columns are sets, e.g.:
#
# a b c
# h 1 1 1
# t 1 0 1
# j 1 0 0
# u 1 0 1
# w 1 0 0
# ...
#
# If the variable is a data frame, the binary columns (only contain 0 and 1) and the logical
# columns are only kept.
#
# The set can be genomic regions, then it can only be represented as a list of ``GRanges`` objects.
#
# == Mode
# E.g. for three sets (A, B, C), the UpSet approach splits the combination of selecting elements
# in the set or not in the set and calculates the sizes of the combination sets. For three sets,
# all possible combinations are:
#
# A B C
# 1 1 1
# 1 1 0
# 1 0 1
# 0 1 1
# 1 0 0
# 0 1 0
# 0 0 1
#
# A value of 1 means to select that set and 0 means not to select that set. E.g., "1 1 0"
# means to select set A, B while not set C. Note there is no "0 0 0", because the background
# size is not of interest here. With the code of selecting and not selecting the sets, next
# we need to define how to calculate the size of that combination set. There are three modes:
#
# 1. ``distinct`` mode: 1 means in that set and 0 means not in that set, then "1 1 0" means a
# set of elements also in set A and B, while not in C (i.e. ``setdiff(intersect(A, B), C)``). Under
# this mode, the seven combination sets are the seven partitions in the Venn diagram and they
# are mutually exclusive.
#
# 2. ``intersect`` mode: 1 means in that set and 0 is not taken into account, then, "1 1 0" means
# a set of elements in set A and B, and they can also in C or not in C (i.e. ``intersect(A, B)``).
# Under this mode, the seven combination sets can overlap.
#
# 3. ``union`` mode: 1 means in that set and 0 is not taken into account. When there are multiple
# 1, the relationship is OR. Then, "1 1 0" means a set of elements in set A or B, and they can also in C or not in C (i.e. ``union(A, B)``).
# Under this mode, the seven combination sets can overlap.
#
# == value
# A matrix also in a class of ``comb_mat``.
#
# Following functions can be applied to it: `set_name`, `comb_name`, `set_size`, `comb_size`, `comb_degree`,
# `extract_comb` and `t.comb_mat`.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
#
# mat = list_to_matrix(lt)
# mat
# m = make_comb_mat(mat)
#
# \dontrun{
# require(circlize)
# require(GenomicRanges)
# lt = lapply(1:4, function(i) generateRandomBed())
# lt = lapply(lt, function(df) GRanges(seqnames = df[, 1],
# ranges = IRanges(df[, 2], df[, 3])))
# names(lt) = letters[1:4]
# m = make_comb_mat(lt)
# }
make_comb_mat = function(..., mode = c("distinct", "intersect", "union"),
top_n_sets = Inf, min_set_size = -Inf,
universal_set = NULL, complement_size = NULL,
value_fun = NULL, set_on_rows = TRUE) {
lt = list(...)
if("remove_complement_set" %in% names(lt)) {
stop_wrap("Argument `remove_complement_set` has been removed.")
}
mode = match.arg(mode)[1]
if(length(lt) == 1) {
lt = lt[[1]]
if(length(dim(lt)) == 2) { # a matrix
if(ncol(lt) > 31) {
stop_wrap("Only support number of sets <= 31.")
}
m = make_comb_mat_from_matrix(lt, mode = mode, top_n_sets = top_n_sets,
min_set_size = min_set_size, universal_set = universal_set, complement_size = complement_size,
set_on_rows = set_on_rows)
return(m)
}
}
if(is.null(value_fun)) {
if(inherits(lt[[1]], "GRanges")) {
value_fun = function(x) sum(as.numeric(getFromNamespace("width", ns = "BiocGenerics")(x)))
} else if(inherits(lt[[1]], "IRanges")) {
value_fun = function(x) sum(as.numeric(getFromNamespace("width", ns = "BiocGenerics")(x)))
} else {
value_fun = length
}
}
if(length(lt) > 31) {
stop_wrap("Only support number of sets <= 31.")
}
# if lt is a list of atomic sets, convert to the matrix because it is more efficient
if(is.atomic(lt[[1]])) {
m = make_comb_mat_from_matrix(list_to_matrix(lt), mode = mode, top_n_sets = top_n_sets,
min_set_size = min_set_size, universal_set = universal_set, complement_size = complement_size,
set_on_rows = set_on_rows)
return(m)
}
m = make_comb_mat_from_list(lt, value_fun, mode = mode, top_n_sets = top_n_sets, min_set_size = min_set_size,
universal_set = universal_set, complement_size = complement_size, set_on_rows = set_on_rows)
return(m)
}
# == title
# Full set of code of combination sets
#
# == param
# -n Number of sets
# -complement Whether include the code for complement set?
#
# == example
# full_comb_code(2)
# full_comb_code(3)
# full_comb_code(4)
# full_comb_code(4, TRUE)
full_comb_code = function(n, complement = FALSE) {
comb_mat = matrix(0, nrow = n, ncol = sum(choose(n, (!complement + 0):n)))
j = 1
for(k in 1:n) {
comb = combn(n, k)
for(i in 1:ncol(comb)) {
comb_mat[comb[, i], j] = 1
j = j + 1
}
}
lt = list(colSums(comb_mat))
lt = c(lt, as.list(as.data.frame(t(comb_mat))))
lt$decreasing = TRUE
od = do.call(order, lt)
apply(comb_mat[, od, drop = FALSE], 2, paste, collapse = "")
}
binaryToInt = function(x) {
sum(x * 2^(rev(seq_along(x)) - 1))
}
intToBinary = function(x, len) {
rev(as.integer(intToBits(x))[1:len])
}
# == title
# Set Names
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
#
# == value
# A vector of set names.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# set_name(m)
set_name = function(m) {
set_on_rows = attr(m, "param")$set_on_rows
if(set_on_rows) {
rownames(m)
} else {
colnames(m)
}
}
# == title
# Modify Set Names
#
# == param
# -x A combination matrix returned by `make_comb_mat`.
# -value New set names.
# -... Other arguments.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# set_name(m) = c("A", "B", "C")
# m
"set_name<-" = function (x, ..., value) {
old_set_name = set_name(x)
n1 = length(old_set_name)
n2 = length(value)
param = attr(x, "param")
set_on_rows = param$set_on_rows
data = attr(x, "data")
if(n1 != n2) {
stop_wrap("New set names should have the same length as the old ones.")
}
if(set_on_rows) {
attr(x, "dimnames")[[1]] = value
} else {
attr(x, "dimnames")[[2]] = value
}
if(is.matrix(data)) {
colnames(data) = value
} else {
names(data) = value
}
attr(x, "data") = data
return(x)
}
# == title
# Set Sizes
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
#
# == value
# A vector of set sizes.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# set_size(m)
set_size = function(m) {
structure(attr(m, "set_size"), names = set_name(m))
}
# == title
# Complement Set Size
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
#
# == value
# If there is no complement set, it returns zero.
#
complement_size = function(m) {
sz = comb_size(m)
l = grepl("^0+$", names(sz))
if(any(l)) {
return(unname(sz[l]))
} else {
return(0)
}
}
# == title
# Sizes of the Combination sets
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
# -degree degree of the intersection. The value can be a vector.
#
# == value
# A vector of sizes of the combination sets.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# comb_size(m)
comb_size = function(m, degree = NULL) {
x = structure(attr(m, "comb_size"), names = comb_name(m))
if(is.null(degree)) {
return(x)
} else {
x[comb_degree(m) %in% degree]
}
}
# == title
# Names of the Combination sets
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
# -readable Whether the combination represents as e.g. "A&B&C".
#
# == details
# The name of the combination sets are formatted as a string
# of binary bits. E.g. for three sets of "a", "b", "c", the combination
# set with name "101" corresponds to select set a, not select set b
# and select set c. The definition of "select" depends on the value of
# ``mode`` from `make_comb_mat`.
#
# == value
# A vector of names of the combination sets.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# comb_name(m)
# comb_name(m, readable = TRUE)
comb_name = function(m, readable = FALSE) {
set_on_rows = attr(m, "param")$set_on_rows
if(set_on_rows) {
nm = apply(m, 2, paste, collapse = "")
} else {
nm = apply(m, 1, paste, collapse = "")
}
if(readable) {
mode = attr(m, "param")$mode
sn = set_name(m)
if(mode == "distinct") {
nm = sapply(strsplit(nm, ""), function(x) {
x = as.numeric(x)
sn2 = paste(ifelse(x, "", "(!"), sn, ifelse(x, "", ")"), sep = "")
paste(sn2, collapse = "&")
})
} else if(mode == "intersect") {
nm = sapply(strsplit(nm, ""), function(x) {
l = as.logical(as.numeric(x))
paste(sn[l], collapse = "&")
})
} else if(mode == "union") {
nm = sapply(strsplit(nm, ""), function(x) {
l = as.logical(as.numeric(x))
paste(sn[l], collapse = "|")
})
}
}
return(nm)
}
# == title
# Degrees of the Combination sets
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
#
# == details
# The degree for a combination set is the number of sets that are selected.
#
# == value
# A vector of degrees of the combination sets.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# comb_degree(m)
comb_degree = function(m) {
set_on_rows = attr(m, "param")$set_on_rows
if(set_on_rows) {
d = colSums(m)
} else {
d = rowSums(m)
}
structure(d, names = comb_name(m))
}
# == title
# Extract Elements in a Combination set
#
# == param
# -m A combination matrix returned by `make_comb_mat`.
# -comb_name The valid combination set name should be from `comb_name`.
#
# == details
# It returns the combination set.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# extract_comb(m, "110")
extract_comb = function(m, comb_name) {
if(length(comb_name) != 1) {
stop_wrap('`comb_name` should be length one.')
}
all_comb_names = comb_name(m)
if((!comb_name %in% all_comb_names) && comb_name %in% full_comb_code(length(set_size(m)))) {
return(NULL)
} else if(!comb_name %in% all_comb_names) {
stop_wrap(paste0("Cannot find a combination name: ", comb_name, ", valid combination name should be in `comb_name(m)`."))
}
query = as.numeric(strsplit(comb_name, "")[[1]])
data = attr(m, "data")
param = attr(m, "param")
universal_set = param$universal_set
mode = param$mode
is_complement_set = function(comb_name) {
grepl("^0+$", comb_name)
}
if(is.matrix(data)) {
x = data
if(!is.null(universal_set)) {
if(is_complement_set(comb_name)) {
return(setdiff(universal_set, rownames(x)))
}
}
if(mode == "distinct") {
l = apply(x, 1, function(y) all(y == query))
} else if(mode == "intersect") {
l_subset = query == 1
l = apply(x, 1, function(y) all(y[l_subset] == 1))
} else if(mode == "union") {
l_subset = query == 1
l = apply(x, 1, function(y) {
any(y[l_subset] == 1)
})
}
rn = rownames(x)
if(is.null(universal_set)) {
if(is.null(rn)) {
return(seq_len(nrow(x))[l])
} else {
return(rn[l])
}
} else {
return(rn[l])
}
} else if(is.list(data)) {
lt = data
if(inherits(lt[[1]], "GRanges")) {
union = getFromNamespace("union", ns = "BiocGenerics")
intersect = getFromNamespace("intersect", ns = "BiocGenerics")
setdiff = getFromNamespace("setdiff", ns = "BiocGenerics")
} else if(inherits(lt[[1]], "IRanges")) {
union = getFromNamespace("union", ns = "BiocGenerics")
intersect = getFromNamespace("intersect", ns = "BiocGenerics")
setdiff = getFromNamespace("setdiff", ns = "BiocGenerics")
}
if(is_complement_set(comb_name)) {
s = universal_set
for(i in seq_along(lt)) {
s = setdiff(s, lt[[i]])
}
return(s)
}
do_comb = function(lt, mode, do = rep(TRUE, length(lt))) {
set1_index = which(do)
set2_index = which(!do)
s = lt[[ set1_index[1] ]]
if(mode == "distinct") {
for(i in set1_index[-1]) {
s = intersect(s, lt[[ i ]])
}
for(i in set2_index) {
s = setdiff(s, lt[[ i ]])
}
} else if(mode == "intersect") {
for(i in set1_index[-1]) {
s = intersect(s, lt[[ i ]])
}
} else if(mode == "union") {
for(i in set1_index[-1]) {
s = union(s, lt[[ i ]])
}
}
s
}
do = as.logical(as.numeric(strsplit(comb_name, "")[[1]]))
do_comb(lt, mode, do)
}
}
# == title
# Transpost the Combination Matrix
#
# == param
# -x A combination matrix returned by `make_comb_mat`.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# t(m)
t.comb_mat = function(x) {
x2 = t.default(x)
attr(x2, "param")$set_on_rows = !attr(x, "param")$set_on_rows
x2
}
# == title
# Subset the Combination Matrix
#
# == param
# -x A combination matrix returned by `make_comb_mat`.
# -i Indices on rows.
# -j Indices on columns.
# -drop It is always reset to ``FALSE`` internally.
#
# == details
# If sets are on rows of the combination matrix, the row indices correspond
# to sets and column indices correspond to combination sets, and if sets are
# on columns of the combination matrix, rows correspond to the combination sets.
#
# If the index is one-dimension, e.g. ``x[i]``, the index always corresponds to the combination sets.
#
# You should not subset by the sets. It will give you wrong combination set size. The subsetting
# on sets are only used internally.
#
# This subsetting method is mainly for subsetting combination sets, i.e., users
# can first use `comb_size` to get the size of each combination set, and filter them
# by the size.
#
# == example
# set.seed(123)
# lt = list(a = sample(letters, 10),
# b = sample(letters, 15),
# c = sample(letters, 20))
# m = make_comb_mat(lt)
# m2 = m[, comb_size(m) >= 3]
# comb_size(m2)
# m[comb_size(m) >= 3]
"[.comb_mat" = function(x, i, j, drop = FALSE) {
set_on_rows = attr(x, "param")$set_on_rows
if(set_on_rows) {
if(nargs() == 2) {
x2 = subset_by_comb_ind(x, i, 2)
} else if(missing(i)) {
x2 = subset_by_comb_ind(x, j, 2)
} else if(missing(j)) {
x2 = subset_by_set_ind(x, i, 1)
} else {
if(can_both_subset(x, i)) {
x2 = subset_by_comb_ind(x, j, 2)
x2 = subset_by_set_ind(x2, i, 1)
} else {
stop_wrap("Cannot apply subsetting on combination sets and sets simultaneously.")
}
}
} else {
if(nargs() == 2) {
x2 = subset_by_comb_ind(x, i, 1)
} else if(missing(i)) {
x2 = subset_by_set_ind(x, j, 2)
} else if(missing(j)) {
x2 = subset_by_comb_ind(x, i, 1)
} else {
if(can_both_subset(x, j)) {
x2 = subset_by_comb_ind(x, i, 1)
x2 = subset_by_set_ind(x2, j, 2)
} else {
stop_wrap("Cannot apply subsetting on combination sets and sets simultaneously.")
}
}
}
return(x2)
}
can_both_subset = function(x, set_selected) {
set_name = set_name(x)
set_size = set_size(x)
if(is.numeric(set_selected)) set_selected = set_name[set_selected]
non_empty_set = set_name[set_size > 0]
length(setdiff(non_empty_set, set_selected)) == 0
}
# when comb_set changes, set does not need to change
# it should also allow new empty comb sets
subset_by_comb_ind = function(x, ind, margin = 2) {
comb_size = comb_size(x)
set_size = set_size(x)
class(x) = "matrix"
n = nrow(x)
if(is.numeric(ind) || is.logical(ind)) {
if(margin == 1) {
x2 = x[ind, , drop = FALSE]
} else {
x2 = x[, ind, drop = FALSE]
}
comb_size = unname(comb_size[ind])
} else if(is.character(ind)) {
ind = unique(ind)
if(!all(grepl("^(0|1)+$", ind))) {
stop_wrap("code for combination set should only contain 0 and 1.")
}
code = strsplit(ind, "")
if(any(sapply(code, length) != n)) {
stop_wrap(qq("code should have @{n} digits."))
}