-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrough-draft_run-analyses_rlog-PCA_write-rds.R
3045 lines (2762 loc) · 108 KB
/
rough-draft_run-analyses_rlog-PCA_write-rds.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
#!/usr/bin/env Rscript
# rough-draft_run-analyses_rlog-TPM-PCA_write_rds.R
# KA
# Initialize arguments =======================================================
#TODO Parser
# type <- "mRNA" #ARGUMENT
# type <- "pa-ncRNA" #ARGUMENT
# type <- "Trinity-Q" #ARGUMENT
# type <- "Trinity-G1" #ARGUMENT
type <- "Trinity-Q-unique" #ARGUMENT
# type <- "Trinity-G1-unique" #ARGUMENT
# type <- "representation" #TODO
samples <- "Ovation" #ARGUMENT #FIG1.5
# samples <- "test.Ovation_Rrp6∆" #ARGUMENT #TODO Remove
# samples <- "test.Ovation_Tecan" #ARGUMENT #TODO Remove
# samples <- "Rrp6∆.G1-Q.N-SS" #ARGUMENT
# samples <- "Rrp6∆.G1-Q.SS" #ARGUMENT
# samples <- "Rrp6∆.Q.N-SS" #ARGUMENT
# samples <- "Rrp6∆.timecourse" #ARGUMENT
# samples <- "Rrp6∆.timecourse-G1-Q.SS" #ARGUMENT #FIG5
# samples <- "Rrp6∆.timecourse-G1.SS" #ARGUMENT
# samples <- "Rrp6∆.timecourse-G1-Q.N-SS" #ARGUMENT
# samples <- "Rrp6∆.timecourse.G1-SS.Q-N" #ARGUMENT
# samples <- "Nab3AID.Q.N-SS" #ARGUMENT
# samples <- "Nab3AID.Q.N-SS_Rrp6∆.Q.N-SS" #ARGUMENT
# samples <- "Nab3AID.Q.SS_Rrp6∆.Q.SS"
# samples <- "Nab3AID.Q.N-SS_Rrp6∆.timecourse-G1-Q.N-SS" #ARGUMENT
# run_norm <- "rlog" #ARGUMENT
run_norm <- "tpm" #ARGUMENT
run_batch_correction <- FALSE #ARGUMENT
run_PCA <- FALSE #ARGUMENT
date <- "2023-0704" #ARGUMENT
# write_norm_counts_rds <- TRUE #ARGUMENT
write_norm_counts_rds <- TRUE #ARGUMENT
# write_PCA_results <- TRUE #ARGUMENT
write_PCA_results <- FALSE #ARGUMENT
# write_pdfs <- TRUE #ARGUMENT
write_pdfs <- FALSE #ARGUMENT
# Load libraries, set options ================================================
suppressMessages(library(DESeq2))
# suppressMessages(library(limma))
suppressMessages(library(PCAtools))
suppressMessages(library(tidyverse))
options(scipen = 999)
options(ggrepel.max.overlaps = Inf)
# Initialize functions and ggplot2 themes ====================================
`%notin%` <- base::Negate(`%in%`)
filter_process_counts_matrix <- function(
counts_matrix,
named_character_vector
) {
# ...
#
# :param counts_matrix: counts matrix from htseq-count
# :param named_character_vector: ...
# :return df: counts matrix as tibble
# Perform debugging
debug <- FALSE
if(base::isTRUE(debug)) {
counts_matrix <- t_cm
named_character_vector <- col_cor
}
df <- dplyr::bind_cols(
counts_matrix[, 1],
counts_matrix[
, colnames(counts_matrix) %in% named_character_vector
]
)
df <- dplyr::bind_cols(
df[, 1],
df[, 2:ncol(df)][
, match(named_character_vector, colnames(df)[2:ncol(df)])
]
)
names(df)[2:ncol(df)] <- names(named_character_vector)
return(df)
}
get_name_of_var <- function(v) {
# ...
#
# :param v: ...
# :return v: ...
return(deparse(substitute(v)))
}
get_top_loadings <- function(x, y, z, a) {
# ...
#
# :param x: dataframe of PC loadings <data.frame>
# :param y: character element for column in dataframe x <chr>
# :param z: whether to select all loadings sorted from largest to smallest
# absolute value ("all"), positive loadings sorted from largest
# to smallest value ("pos"), or negative loadings sorted from
# largest to smallest absolute value ("neg") <str>
# :param a: whether or not to keep "sign" and "abs" columns added in the
# course of processing the dataframe <logical>
# :return b: ...
b <- as.data.frame(x[[y]])
rownames(b) <- rownames(x)
colnames(b) <- y
b[["sign"]] <- ifelse(
b[[y]] > 0,
"pos",
ifelse(
b[[y]] == 0,
"zero",
"neg"
)
)
b[["abs"]] <- abs(b[[y]])
if(z == "all") {
b <- dplyr::arrange(b, by = desc(abs))
} else if(z == "pos") {
b <- b[b[[y]] > 0, ] %>% dplyr::arrange(., by = desc(abs))
} else if(z == "neg") {
b <- b[b[[y]] < 0, ] %>% dplyr::arrange(., by = desc(abs))
} else {
stop(paste("Stopping: param z must be either 'all', 'pos', or 'neg'"))
}
if(isTRUE(a)) {
paste0("Retaining 'sign' and 'abs' columns")
} else if(isFALSE(a)) {
b <- b %>% dplyr::select(-c(sign, abs))
} else {
stop(paste("Stopping: param a must be either 'TRUE' or 'FALSE'"))
}
return(b)
}
plot_biplot <- function(
pca, PC_x, PC_y,
loadings_show, loadings_n,
meta_color, meta_shape, shape_key = NULL,
point_size = 6, encircle = FALSE,
x_min, x_max, y_min, y_max
) {
# ...
#
# :param pca: "pca" list object obtained by running PCAtools::pca()
# :param PC_x: PC to plot on the x axis <chr>
# :param PC_y: PC to plot on the y axis <chr>
# :param loadings_show: whether to overlay component loadings or not <lgl>
# :param loadings_n: number of top loadings to show <int >= 0>
# :param meta_color: column in "pca" list metadata to color by <chr>
# :param meta_shape: column in "pca" list metadata to shape by <chr>
# :param shape_key: vector of name-value pairs relating to value passed to
# "shape" <...>
# :param point_size: size of plotted points <int>
# :param encircle: draw a polygon around groups specified by "colby" <lgl>
# :param x_min: minimum value on x axis <dbl>
# :param x_max: maximum value on x axis <dbl>
# :param y_min: minimum value on y axis <dbl>
# :param y_max: maximum value on y axis <dbl>
# :param title: title of biplot <dbl>
# :return image: ...
if(is.null(shape_key)) {
image <- pca %>%
PCAtools::biplot(
x = PC_x,
y = PC_y,
lab = NULL,
showLoadings = loadings_show,
ntopLoadings = loadings_n,
boxedLoadingsNames = TRUE,
colby = meta_color,
shape = meta_shape,
pointSize = point_size,
encircle = FALSE,
ellipse = FALSE,
max.overlaps = Inf,
xlim = c(x_min, x_max),
ylim = c(y_min, y_max)
)
} else {
image <- pca %>%
PCAtools::biplot(
x = PC_x,
y = PC_y,
lab = NULL,
showLoadings = loadings_show,
ntopLoadings = loadings_n,
boxedLoadingsNames = TRUE,
colby = meta_color,
shape = meta_shape,
shapekey = shape_key,
pointSize = point_size,
encircle = FALSE,
ellipse = FALSE,
max.overlaps = Inf,
xlim = c(x_min, x_max),
ylim = c(y_min, y_max)
)
}
image <- image + theme_AG_boxed
return(image)
}
plot_loadings <- function(x, y, z, a, b, d, e, f, g, h, i, j, k) {
# ...
#
# :param x: dataframe of PC loadings w/gene names as rownames <data.frame>
# :param y: column in dataframe to plot on x axis <dbl>
# :param z: column in dataframe to plot on y axis <dbl>
# :param a: minimum value on x axis <dbl>
# :param b: maximum value on x axis <dbl>
# :param d: minimum value on y axis <dbl>
# :param e: maximum value on y axis <dbl>
# :param f: amount to nudge labels on the x axis <dbl>
# :param g: amount to nudge labels on the y axis <dbl>
# :param h: x axis label <chr>
# :param i: y axis label <chr>
# :param j: color of line and arrow <chr>
# :param k: color of segment connecting arrowhead and text bubble <chr>
# :return l: ...
# Perform debugging
debug <- FALSE
if(base::isTRUE(debug)) {
# x = loadings_etc
# y = coords_PC1
# z = coords_PC2
# a = x_min
# b = x_max
# d = y_min
# e = y_max
# f = x$nudge_x
# g = x$nudge_y
# h = x_label
# i = y_label
# j = x$color
# k = col_seg_pos
x = loadings_filter_pos_1
y = loadings_filter_pos_1[[PC_x]]
z = loadings_filter_pos_1[[PC_y]]
a = x_min
b = x_max
d = y_min
e = y_max
f = loadings_etc[loadings_etc$label == "x_pos", ]$nudge_x[1]
g = loadings_etc[loadings_etc$label == "x_pos", ]$nudge_y[1]
h = x_label
i = y_label
j = loadings_etc[loadings_etc$label == "x_pos", ]$color[1]
k = col_seg_pos
}
l <- ggplot2::ggplot(x, ggplot2::aes(x = y, y = z)) +
ggplot2::coord_cartesian(xlim = c(a, b), ylim = c(d, e)) +
ggplot2::geom_segment(
aes(xend = 0, yend = 0, alpha = 0.5),
color = j,
arrow = ggplot2::arrow(
ends = "first",
type = "open",
length = unit(0.125, "inches")
)
) +
ggrepel::geom_label_repel(
mapping = ggplot2::aes(
fontface = 1, segment.color = k, segment.size = 0.25
),
label = x[["feature_names"]],
label.size = 0.05,
direction = "both",
nudge_x = f,
nudge_y = g,
force = 4,
force_pull = 1,
hjust = 0
) +
ggplot2::xlab(h) +
ggplot2::ylab(i) +
theme_slick_no_legend
if(base::isTRUE(debug)) l
return(l)
}
plot_pos_neg_loadings_each_axis <- function(
df_all, df_pos, df_neg,
PC_x, PC_y,
row_start, row_end,
x_min, x_max, y_min, y_max,
x_pos_nudge_x, y_pos_nudge_x,
x_neg_nudge_x, y_neg_nudge_x,
x_pos_nudge_y, y_pos_nudge_y,
x_neg_nudge_y, y_neg_nudge_y,
x_label, y_label,
col_x_pos = "#440154", col_y_pos = "#3B528B",
col_x_neg = "#21918C", col_y_neg = "#5EC962",
col_seg_pos, col_seg_neg
) {
# ...
#
# :param df_all: dataframe: all loadings (from, e.g., PCAtools)
# :param df_pos: dataframe: positive loadings ordered largest to smallest
# :param df_neg: dataframe: negative loadings ordered smallest to largest
# :param PC_x: PC to plot on the x axis
# :param PC_y: PC to plot on the y axis
# :param row_start: row from which to begin subsetting the PCs on x and y
# :param row_end: row at which to end subsetting the PCs on x and y
# :param x_min: minimum value on x axis <dbl>
# :param x_max: maximum value on x axis <dbl>
# :param y_min: minimum value on y axis <dbl>
# :param y_max: maximum value on y axis <dbl>
# :param x_pos_nudge_x: amount to nudge labels for x positive loadings on x
# axis <dbl>
# :param y_pos_nudge_x: amount to nudge labels for y positive loadings on x
# axis <dbl>
# :param x_neg_nudge_x: amount to nudge labels for x negative loadings on x
# axis <dbl>
# :param y_neg_nudge_x: amount to nudge labels for y negative loadings on x
# axis <dbl>
# :param x_pos_nudge_y: amount to nudge labels for x positive loadings on y
# axis <dbl>
# :param y_pos_nudge_y: amount to nudge labels for y positive loadings on y
# axis <dbl>
# :param x_neg_nudge_y: amount to nudge labels for x negative loadings on y
# axis <dbl>
# :param y_neg_nudge_y: amount to nudge labels for y negative loadings on y
# axis <dbl>
# :param x_label: x axis label <chr>
# :param y_label: y axis label <chr>
# :param col_x_pos: color: lines, arrows for x positive loadings <chr>
# :param col_y_pos: color: lines, arrows for y positive loadings <chr>
# :param col_x_neg: color: lines, arrows for x negative loadings <chr>
# :param col_y_neg: color: lines, arrows for y negative loadings <chr>
# :param col_seg_pos: color: segments connecting arrowhead and text bubble
# for positive loadings <chr>
# :param col_seg_neg: color: segments connecting arrowhead and text bubble
# for negative loadings <chr>
# :return image: ...
# Perform debugging
debug <- FALSE
if(base::isTRUE(debug)) {
df_all = loadings
df_pos = top_loadings_pos
df_neg = top_loadings_neg
PC_x = PC_x
PC_y = PC_y
row_start = 1
row_end = n_loadings
x_min = x_min_loadings_plot
x_max = x_max_loadings_plot
y_min = y_min_loadings_plot
y_max = y_max_loadings_plot
x_pos_nudge_x = 0.04
y_pos_nudge_x = 0
x_neg_nudge_x = -0.04
y_neg_nudge_x = -0.02
x_pos_nudge_y = 0
y_pos_nudge_y = 0.04
x_neg_nudge_y = 0
y_neg_nudge_y = -0.04
x_label = x_label
y_label = y_label
col_x_pos = "#440154"
col_y_pos = "#3B528B"
col_x_neg = "#21918C"
col_y_neg = "#5EC962"
col_seg_pos = "grey"
col_seg_neg = "grey"
}
filter_pos_1 <- rownames(df_pos[[PC_x]][row_start:row_end, ])
filter_pos_2 <- rownames(df_pos[[PC_y]][row_start:row_end, ])
filter_neg_1 <- rownames(df_neg[[PC_x]][row_start:row_end, ])
filter_neg_2 <- rownames(df_neg[[PC_y]][row_start:row_end, ])
loadings_filter_pos_1 <- df_all[rownames(df_all) %in% filter_pos_1, ]
loadings_filter_pos_2 <- df_all[rownames(df_all) %in% filter_pos_2, ]
loadings_filter_neg_1 <- df_all[rownames(df_all) %in% filter_neg_1, ]
loadings_filter_neg_2 <- df_all[rownames(df_all) %in% filter_neg_2, ]
loadings_etc <- dplyr::bind_rows(
loadings_filter_pos_1,
loadings_filter_pos_2,
loadings_filter_neg_1,
loadings_filter_neg_2
)
loadings_etc$label <- c(
rep("x_pos", 10),
rep("y_pos", 10),
rep("x_neg", 10),
rep("y_neg", 10)
)
loadings_etc$color <- c(
rep(col_x_pos, 10), # x pos
rep(col_y_pos, 10), # y pos
rep(col_x_neg, 10), # x neg
rep(col_y_neg, 10) # y neg
)
loadings_etc$nudge_x <- c(
rep(x_pos_nudge_x, 10), # x pos
rep(y_pos_nudge_x, 10), # y pos
rep(x_neg_nudge_x, 10), # x neg
rep(y_neg_nudge_x, 10) # y neg
)
loadings_etc$nudge_y <- c(
rep(x_pos_nudge_y, 10), # x pos
rep(y_pos_nudge_y, 10), # y pos
rep(x_neg_nudge_y, 10), # x neg
rep(y_neg_nudge_y, 10) # y neg
)
# Move rownames to a column, then remove signs of duplicate rownames (but
#+ keep the duplicate entries (at least for now))
loadings_etc <- loadings_etc %>%
tibble::rownames_to_column("feature_names")
loadings_etc$feature_names <- loadings_etc$feature_names %>%
stringr::str_remove_all("\\.\\.\\.[0-9]{1,2}$")
loadings_filter_pos_1 <- loadings_filter_pos_1 %>%
tibble::rownames_to_column("feature_names")
loadings_filter_pos_1$feature_names <-
loadings_filter_pos_1$feature_names %>%
stringr::str_remove_all("\\.\\.\\.[0-9]{1,2}$")
loadings_filter_pos_2 <- loadings_filter_pos_2 %>%
tibble::rownames_to_column("feature_names")
loadings_filter_pos_2$feature_names <-
loadings_filter_pos_2$feature_names %>%
stringr::str_remove_all("\\.\\.\\.[0-9]{1,2}$")
loadings_filter_neg_1 <- loadings_filter_neg_1 %>%
tibble::rownames_to_column("feature_names")
loadings_filter_neg_1$feature_names <-
loadings_filter_neg_1$feature_names %>%
stringr::str_remove_all("\\.\\.\\.[0-9]{1,2}$")
loadings_filter_neg_2 <- loadings_filter_neg_2 %>%
tibble::rownames_to_column("feature_names")
loadings_filter_neg_2$feature_names <-
loadings_filter_neg_2$feature_names %>%
stringr::str_remove_all("\\.\\.\\.[0-9]{1,2}$")
if(base::isTRUE(debug)) {
loadings_etc %>% head()
loadings_filter_pos_1 %>% head()
loadings_filter_pos_2 %>% head()
loadings_filter_neg_1 %>% head()
loadings_filter_neg_2 %>% head()
}
coords_PC1 <- c(
loadings_filter_pos_1[[PC_x]],
loadings_filter_pos_2[[PC_x]],
loadings_filter_neg_1[[PC_x]],
loadings_filter_neg_2[[PC_x]]
)
coords_PC2 <- c(
loadings_filter_pos_1[[PC_y]],
loadings_filter_pos_2[[PC_y]],
loadings_filter_neg_1[[PC_y]],
loadings_filter_neg_2[[PC_y]]
)
images <- list()
images[["all"]] <- plot_loadings(
loadings_etc,
coords_PC1,
coords_PC2,
x_min,
x_max,
y_min,
y_max,
loadings_etc$nudge_x,
loadings_etc$nudge_y,
x_label,
y_label,
loadings_etc$color,
col_seg_pos
)
images[["PC_x_pos"]] <- plot_loadings(
loadings_filter_pos_1,
loadings_filter_pos_1[[PC_x]],
loadings_filter_pos_1[[PC_y]],
x_min,
x_max,
y_min,
y_max,
loadings_etc[loadings_etc$label == "x_pos", ]$nudge_x[1],
loadings_etc[loadings_etc$label == "x_pos", ]$nudge_y[1],
x_label,
y_label,
loadings_etc[loadings_etc$label == "x_pos", ]$color[1],
col_seg_pos
)
images[["PC_y_pos"]] <- plot_loadings(
loadings_filter_pos_2,
loadings_filter_pos_2[[PC_x]],
loadings_filter_pos_2[[PC_y]],
x_min,
x_max,
y_min,
y_max,
loadings_etc[loadings_etc$label == "y_pos", ]$nudge_x[1],
loadings_etc[loadings_etc$label == "y_pos", ]$nudge_y[1],
x_label,
y_label,
loadings_etc[loadings_etc$label == "y_pos", ]$color[1],
col_seg_pos
)
images[["PC_x_neg"]] <- plot_loadings(
loadings_filter_neg_1,
loadings_filter_neg_1[[PC_x]],
loadings_filter_neg_1[[PC_y]],
x_min,
x_max,
y_min,
y_max,
loadings_etc[loadings_etc$label == "x_neg", ]$nudge_x[1],
loadings_etc[loadings_etc$label == "x_neg", ]$nudge_y[1],
x_label,
y_label,
loadings_etc[loadings_etc$label == "x_neg", ]$color[1],
col_seg_neg
)
images[["PC_y_neg"]] <- plot_loadings(
loadings_filter_neg_2,
loadings_filter_neg_2[[PC_x]],
loadings_filter_neg_2[[PC_y]],
x_min,
x_max,
y_min,
y_max,
loadings_etc[loadings_etc$label == "y_neg", ]$nudge_x[1],
loadings_etc[loadings_etc$label == "y_neg", ]$nudge_y[1],
x_label,
y_label,
loadings_etc[loadings_etc$label == "y_neg", ]$color[1],
col_seg_neg
)
if(base::isTRUE(debug)) images[["all"]]
return(images)
}
draw_scree_plot <- function(pca, horn, elbow) {
# ...
#
# :param pca: "pca" list object obtained by running PCAtools::pca()
# :param horn: ...
# :param elbow: ...
# :return scree: ...
scree <- PCAtools::screeplot(
pca,
components = PCAtools::getComponents(pca),
vline = c(horn, elbow),
vlineWidth = 0.25,
sizeCumulativeSumLine = 0.5,
sizeCumulativeSumPoints = 1.5
) +
geom_text(aes(horn + 1, 50, label = "Horn's", vjust = 2)) +
geom_text(aes(elbow + 1, 50, label = "Elbow", vjust = -2)) +
theme_slick +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
return(scree)
}
#SHORTCUT
run_PCA_pipeline <- function(
counts,
metadata,
feat_id,
x_min_biplot = -100,
x_max_biplot = 100,
y_min_biplot = -100,
y_max_biplot = 100,
x_min_loadings_plot = -0.1,
x_max_loadings_plot = 0.1,
y_min_loadings_plot = -0.1,
y_max_loadings_plot = 0.1,
n_loadings = 10,
x_pos_nudge_x = 0.04,
y_pos_nudge_x = 0,
x_neg_nudge_x = -0.04,
y_neg_nudge_x = -0.02,
x_pos_nudge_y = 0,
y_pos_nudge_y = 0.04,
x_neg_nudge_y = 0,
y_neg_nudge_y = -0.04,
meta_color,
meta_shape,
shape_key = NULL,
point_size = 6,
encircle = FALSE,
plot_loadings_pct = FALSE,
drop_md_levels = NULL,
PCs_cor_plot = NULL
) {
# ...
#
# :param counts: ... <data.frame>
# :param metadata: ... <data.frame>
# :param feat_id: ... <chr>
# :param x_min_biplot: ... <dbl> [default: -100]
# :param x_max_biplot: ... <dbl> [default: 100]
# :param y_min_biplot: ... <dbl> [default: -100]
# :param y_max_biplot: ... <dbl> [default: 100]
# :param x_min_loadings_plot: ... <dbl> [default: -0.1]
# :param x_max_loadings_plot: ... <dbl> [default: 0.1]
# :param y_min_loadings_plot: ... <dbl> [default: -0.1]
# :param y_max_loadings_plot: ... <dbl> [default: 0.1]
# :param n_loadings: Number of loading vectors to show per positive and
# negative x and y axis <int> [default: 10L]
# :param x_pos_nudge_x: amount to nudge labels for x positive loadings on x
# axis <dbl>
# :param y_pos_nudge_x: amount to nudge labels for y positive loadings on x
# axis <dbl>
# :param x_neg_nudge_x: amount to nudge labels for x negative loadings on x
# axis <dbl>
# :param y_neg_nudge_x: amount to nudge labels for y negative loadings on x
# axis <dbl>
# :param x_pos_nudge_y: amount to nudge labels for x positive loadings on y
# axis <dbl>
# :param y_pos_nudge_y: amount to nudge labels for y positive loadings on y
# axis <dbl>
# :param x_neg_nudge_y: amount to nudge labels for x negative loadings on y
# axis <dbl>
# :param y_neg_nudge_y: amount to nudge labels for y negative loadings on y
# axis <dbl>
# :param meta_color: ... <chr>
# :param meta_shape: ... <chr>
# :param shape_key: ... <...>
# :param point_size: size of plotted points <int>
# :param encircle: draw a polygon around groups specified by "colby" <lgl>
# :param plot_loadings_pct: Plot top 2.5% loadings for elbow + 2 number of
# PCs <lgl> [default: FALSE]
# :param drop_md_levels: Metadata variables to drop from correlation plot
# <chr> [default: NULL]
# :param PCs_cor_plot: PCs to include in correlation plot <dbl>
# [default: NULL]
# :return results_list: ... <list>
# Perform debugging #SHORTCUT
debug <- FALSE
if(base::isTRUE(debug)) {
counts = input_counts
metadata = t_meta
feat_id = pca_feat_id
x_min_biplot = -150
x_max_biplot = 150
y_min_biplot = -150
y_max_biplot = 150
x_min_loadings_plot = -0.1
x_max_loadings_plot = 0.1
y_min_loadings_plot = -0.1
y_max_loadings_plot = 0.1
n_loadings = 10L
x_pos_nudge_x = 0.04
y_pos_nudge_x = 0
x_neg_nudge_x = -0.04
y_neg_nudge_x = -0.02
x_pos_nudge_y = 0
y_pos_nudge_y = 0.04
x_neg_nudge_y = 0
y_neg_nudge_y = -0.04
meta_color = meta_color
meta_shape = meta_shape
point_size = 6
shape_key = NULL
plot_loadings_pct = FALSE
drop_md_levels = c("gt_st", "gt_tx", "st_tx", "gt_st_tx", "tc", "day")
PCs_cor_plot = 3
}
# Check arguments
stopifnot(is.data.frame(counts))
stopifnot(is.data.frame(metadata))
stopifnot(isTRUE(tibble::has_rownames(metadata)))
stopifnot(is.character(feat_id))
#TODO Checks for {x,y}_{min,max}_*
stopifnot(is.logical(plot_loadings_pct))
if(!is.null(drop_md_levels)) stopifnot(is.character(drop_md_levels))
if(!is.null(PCs_cor_plot)) stopifnot(is.numeric(PCs_cor_plot))
# Create a PCAtools "pca" S4 object
pca <- PCAtools::pca(counts, metadata = metadata)
rownames(pca$loadings) <- feat_id
# Determine "significant" PCs with Horn's parallel analysis (see Horn,
#+ 1965)
horn <- PCAtools::parallelPCA(counts[, 2:ncol(counts)]) %>%
suppressWarnings()
if(base::isTRUE(debug)) print(horn$n)
# Determine "significant" principle components with the elbow method (see
#+ Buja and Eyuboglu, 1992)
elbow <- PCAtools::findElbowPoint(pca$variance)
if(base::isTRUE(debug)) print(elbow)
# Evaluate cumulative proportion of explained variance with a scree plot
p_scree <- draw_scree_plot(pca, horn = horn$n, elbow = elbow)
if(base::isTRUE(debug)) print(p_scree)
# Save component loading vectors in their own dataframe
loadings <- as.data.frame(pca$loadings)
# Evaluate the component loading vectors for the number of "significant"
#+ PCs identified via the elbow method plus two
PCs <- paste0("PC", 1:(as.numeric(elbow) + 2))
top_loadings_all <- lapply(
PCs, get_top_loadings, x = loadings, z = "all", a = TRUE
)
top_loadings_pos <- lapply(
PCs, get_top_loadings, x = loadings, z = "pos", a = TRUE
)
top_loadings_neg <- lapply(
PCs, get_top_loadings, x = loadings, z = "neg", a = TRUE
)
names(top_loadings_all) <-
names(top_loadings_pos) <-
names(top_loadings_neg) <-
PCs
if(base::isTRUE(debug)) print(names(top_loadings_all))
if(base::isTRUE(debug)) test_check <- top_loadings_all$PC1
# Evaluate positive and negative loadings on axes of biplots; look at the
#+ top n per axis
p_images <- list()
mat <- combn(PCs, 2)
for(l in 1:ncol(mat)) {
# l <- 1
m <- mat[, l]
PC_x <- x_label <- m[1]
PC_y <- y_label <- m[2]
p_images[[paste0("PCAtools.", PC_x, ".v.", PC_y)]] <-
plot_biplot(
pca = pca,
PC_x = PC_x,
PC_y = PC_y,
loadings_show = FALSE,
loadings_n = 0,
meta_color = meta_color, #DONE
meta_shape = meta_shape, #DONE
shape_key = shape_key,
point_size = point_size, #HERE
encircle = encircle,
x_min = x_min_biplot,
x_max = x_max_biplot,
y_min = y_min_biplot,
y_max = y_max_biplot
)
if(base::isTRUE(debug)) p_images[[
paste0("PCAtools.", PC_x, ".v.", PC_y)
]]
p_images[[paste0("KA.", PC_x, ".v.", PC_y)]] <-
plot_pos_neg_loadings_each_axis( #DEBUGFROMHERE
df_all = loadings,
df_pos = top_loadings_pos,
df_neg = top_loadings_neg,
PC_x = PC_x,
PC_y = PC_y,
row_start = 1,
row_end = n_loadings,
x_min = x_min_loadings_plot,
x_max = x_max_loadings_plot,
y_min = y_min_loadings_plot,
y_max = y_max_loadings_plot,
x_pos_nudge_x = x_pos_nudge_x,
y_pos_nudge_x = y_pos_nudge_x,
x_neg_nudge_x = x_neg_nudge_x,
y_neg_nudge_x = y_neg_nudge_x,
x_pos_nudge_y = x_pos_nudge_y,
y_pos_nudge_y = y_pos_nudge_y,
x_neg_nudge_y = x_neg_nudge_y,
y_neg_nudge_y = y_neg_nudge_y,
x_label = x_label,
y_label = y_label,
col_x_pos = "#440154",
col_y_pos = "#3B528B",
col_x_neg = "#21918C",
col_y_neg = "#5EC962",
col_seg_pos = "grey",
col_seg_neg = "grey"
)
if(base::isTRUE(debug)) p_images[[paste0("KA.", PC_x, ".v.", PC_y)]][1]
}
if(base::isTRUE(debug)) {
# p_images$PCAtools.PC3.v.PC4 %>% print()
# p_images$PCAtools.PC2.v.PC4 %>% print()
# p_images$PCAtools.PC2.v.PC3 %>% print()
# p_images$PCAtools.PC1.v.PC4 %>% print()
p_images$PCAtools.PC1.v.PC3 %>% print()
p_images$PCAtools.PC1.v.PC2 %>% print()
run <- TRUE
if(base::isTRUE(run)) p_images$KA.PC1.v.PC2 %>% print()
}
# Plot the top features on an axis of "component loading range" to
#+ visualize the top variables (features) that drive variance among
#+ PCs of interest
if(base::isTRUE(plot_loadings_pct)) {
p_loadings <- PCAtools::plotloadings(
pca,
components = PCAtools::getComponents(pca, 1:length(PCs)),
rangeRetain = 0.025,
absolute = FALSE,
col = c("#167C2875", "#FFFFFF75", "#7835AC75"),
title = "Loadings plot",
subtitle = "Top 2.5% of variables (i.e., features)",
borderColour = "#000000",
borderWidth = 0.2,
gridlines.major = TRUE,
gridlines.minor = TRUE,
axisLabSize = 10,
labSize = 3, # label_size
drawConnectors = TRUE,
widthConnectors = 0.2,
typeConnectors = "closed",
colConnectors = "black"
) +
# ggplot2::coord_flip() +
# theme_slick_no_legend
theme_bw() +
theme(
aspect.ratio = 1,
panel.grid.minor = element_line(linewidth = 0.5),
panel.grid.major = element_line(linewidth = 1),
axis.text = element_text(
size = 20, face = "bold", color = "black"
),
axis.title = element_text(size = 25, face = "bold")
) # +
# coord_obs_pred()
if(base::isTRUE(debug)) p_loadings %>% print()
#TODO Work up some logic for saving the plot
}
# Evaluate correlations between PCs and model variables; answer
#+ the question, "What is driving biologically significant variance
#+ in our data?"
metavars <- t_meta[stringr::str_detect(colnames(t_meta), "no_")]
metavars <- metavars[
, vapply(metavars, function(x) length(unique(x)) > 1, logical(1L))
]
colnames(metavars) <- colnames(metavars) %>% gsub("no_", "", .)
if(!is.null(drop_md_levels)) {
metavars <- metavars %>%
dplyr::select(-dplyr::any_of(drop_md_levels))
}
components <- if(is.null(PCs_cor_plot)) {
PCAtools::getComponents(pca, 1:(elbow + 2))
} else {
paste0("PC", c(1:PCs_cor_plot))
}
p_cor <- PCAtools::eigencorplot(
pca,
components = components,
metavars = colnames(metavars),
col = c("#FFFFFF", "#7835AC"),
scale = FALSE,
corFUN = "pearson",
corMultipleTestCorrection = "BH",
plotRsquared = TRUE,
colFrame = "#FFFFFF",
main = bquote(Pearson ~ r^2 ~ correlates),
fontMain = 1,
titleX = "Principal components",
fontTitleX = 1,
fontLabX = 1,
titleY = "Model variables",
rotTitleY = 90,
fontTitleY = 1,
fontLabY = 1
) %>%
suppressWarnings()
if(base::isTRUE(debug)) p_cor %>% print()
results_list <- list()
results_list[["01_pca"]] <- pca
results_list[["02_horn"]] <- horn
results_list[["03_elbow"]] <- elbow
results_list[["04_p_scree"]] <- p_scree
results_list[["05_loadings"]] <- loadings
results_list[["06_PCs"]] <- PCs
results_list[["07_top_loadings_all"]] <- top_loadings_all
results_list[["08_top_loadings_pos"]] <- top_loadings_pos
results_list[["09_top_loadings_neg"]] <- top_loadings_neg
results_list[["10_p_images"]]<- p_images
if(base::isTRUE(plot_loadings_pct)) {
results_list[["11_p_loadings"]] <- p_loadings
}
results_list[["12_p_cor"]] <- p_cor
return(results_list)
}
# Load custom ggplot2 themes -------------------------------------------------
theme_slick <- theme_classic() +
theme(
panel.grid.major = ggplot2::element_line(linewidth = 0.4),
panel.grid.minor = ggplot2::element_line(linewidth = 0.2),
axis.line = ggplot2::element_line(linewidth = 0.2),
axis.ticks = ggplot2::element_line(linewidth = 0.4),
axis.text = ggplot2::element_text(color = "black"),
axis.title.x = ggplot2::element_text(),
axis.title.y = ggplot2::element_text(),
plot.title = ggplot2::element_text(),
text = element_text(family = "")
)
theme_AG <- theme_classic() +
theme(
panel.grid.major = ggplot2::element_line(linewidth = 3),
panel.grid.minor = ggplot2::element_line(linewidth = 2),
axis.line = ggplot2::element_line(linewidth = 0.5),
axis.ticks = ggplot2::element_line(linewidth = 1.0),
axis.text = ggplot2::element_text(
color = "black", size = 20, face = "bold"
),
axis.title.x = ggplot2::element_text(size = 25, face = "bold"),
axis.title.y = ggplot2::element_text(size = 25, face = "bold"),
plot.title = ggplot2::element_text(size = 20),
text = element_text(family = "")
)
theme_AG_boxed <- theme_AG +
theme(
axis.line = ggplot2::element_line(linewidth = 0),
panel.border = element_rect(linewidth = 2, color = "black", fill = NA)
)
theme_slick_no_legend <- theme_slick + theme(legend.position = "none")
theme_AG_no_legend <- theme_AG + theme(legend.position = "none")
theme_AG_boxed_no_legend <- theme_AG_boxed + theme(legend.position = "none")
# Get situated, load counts matrix ===========================================
if(stringr::str_detect(getwd(), "kalavattam")) {
p_base <- "/Users/kalavattam/Dropbox/FHCC"
} else {
p_base <- "/Users/kalavatt/projects-etc"
}
p_exp <- "2022-2023_RRP6-NAB3/results/2023-0215"
# Set work dir
paste(p_base, p_exp, sep = "/") %>% setwd()
# getwd()
# Determine mRNA counts matrix to work with, then load it
# Check on "type" option
if(base::isTRUE(type %notin% c(
"mRNA", "pa-ncRNA", "Trinity-Q", "Trinity-G1", "Trinity-Q-unique",
"Trinity-G1-unique", "representation"
))) {
stop(paste(