-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathdimension_reduction.R
1920 lines (1537 loc) · 67.7 KB
/
dimension_reduction.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
# * Dimension Reduction Object Creation #
# ! Moved to classes.R
## * PCA ####
# ---------- #
#' @title pca_giotto
#' @name pca_giotto
#' @description performs PCA based on Rfast
#' @param mymatrix matrix or object that can be converted to matrix
#' @param center center data
#' @param scale scale features
#' @param k number of principal components to calculate
#' @keywords internal
#' @return list of eigenvalues, eigenvectors and pca coordinates
pca_giotto = function(mymatrix, center = T, scale = T, k = 50) {
if(!is.null(k) & k > ncol(mymatrix)) {
warning('k > ncol(matrix), will be set to ncol(matrix)')
k = ncol(mymatrix)
}
if(!is.matrix(mymatrix)) mymatrix = as.matrix(mymatrix)
my_t_matrix = t_flex(mymatrix)
pca_f = Rfast::hd.eigen(x = my_t_matrix, center = center, scale = scale, k = k, vectors = TRUE)
# calculate pca coordinates
rotated_mat = standardise_flex(x = my_t_matrix, center = center, scale = scale)
coords = rotated_mat %*% pca_f$vectors
colnames(coords) = paste0('Dim.', 1:ncol(coords))
return(list(eigenvalues = pca_f$values, eigenvectors = pca_f$vectors, coords = coords))
}
#' @title runPCA_prcomp_irlba
#' @name runPCA_prcomp_irlba
#' @description performs PCA based on the irlba package
#' @param x matrix or object that can be converted to matrix
#' @param ncp number of principal components to calculate
#' @param center center data
#' @param scale scale features
#' @param rev reverse PCA
#' @param set_seed use of seed
#' @param seed_number seed number to use
#' @keywords internal
#' @return list of eigenvalues, loadings and pca coordinates
runPCA_prcomp_irlba = function(x,
ncp = 100,
center = TRUE,
scale = TRUE,
rev = FALSE,
set_seed = TRUE,
seed_number = 1234,
...) {
min_ncp = min(dim(x))
if(ncp >= min_ncp) {
warning("ncp >= minimum dimension of x, will be set to minimum dimension of x - 1")
ncp = min_ncp-1
}
if(isTRUE(rev)) {
x = t_flex(x)
# start seed
if(isTRUE(set_seed)) {
set.seed(seed = seed_number)
}
pca_res = irlba::prcomp_irlba(x = x, n = ncp, center = center, scale. = scale, ...)
# exit seed
if(isTRUE(set_seed)) {
set.seed(seed = Sys.time())
}
# eigenvalues
eigenvalues = pca_res$sdev^2
# PC loading
loadings = pca_res$x
rownames(loadings) = rownames(x)
colnames(loadings) = paste0('Dim.', 1:ncol(loadings))
# coordinates
coords = pca_res$rotation
rownames(coords) = colnames(x)
colnames(coords) = paste0('Dim.', 1:ncol(coords))
result = list(eigenvalues = eigenvalues, loadings = loadings, coords = coords)
} else {
# start seed
if(isTRUE(set_seed)) {
set.seed(seed = seed_number)
}
pca_res = irlba::prcomp_irlba(x = x, n = ncp, center = center, scale. = scale, ...)
# exit seed
if(isTRUE(set_seed)) {
set.seed(seed = Sys.time())
}
# eigenvalues
eigenvalues = pca_res$sdev^2
# PC loading
loadings = pca_res$rotation
rownames(loadings) = colnames(x)
colnames(loadings) = paste0('Dim.', 1:ncol(loadings))
# coordinates
coords = pca_res$x
rownames(coords) = rownames(x)
colnames(coords) = paste0('Dim.', 1:ncol(coords))
result = list(eigenvalues = eigenvalues, loadings = loadings, coords = coords)
}
return(result)
}
#' @title runPCA_factominer
#' @name runPCA_factominer
#' @description performs PCA based on the factominer package
#' @param x matrix or object that can be converted to matrix
#' @param ncp number of principal components to calculate
#' @param scale scale features
#' @param rev reverse PCA
#' @param set_seed use of seed
#' @param seed_number seed number to use
#' @keywords internal
#' @return list of eigenvalues, loadings and pca coordinates
runPCA_factominer = function(x,
ncp = 100,
scale = TRUE,
rev = FALSE,
set_seed = TRUE,
seed_number = 1234,
...) {
# verify if optional package is installed
package_check(pkg_name = "FactoMineR", repository = "CRAN")
if(!methods::is(x, 'matrix')) {
x = as.matrix(x)
}
if(isTRUE(rev)) {
x = t_flex(x)
if(ncp > nrow(x)) {
warning("ncp > nrow(x), will be set to nrow(x)")
ncp = nrow(x)
}
# start seed
if(isTRUE(set_seed)) {
set.seed(seed = seed_number)
}
pca_res = FactoMineR::PCA(X = x, ncp = ncp, scale.unit = scale, graph = F, ...)
# exit seed
if(isTRUE(set_seed)) {
set.seed(seed = Sys.time())
}
# eigenvalues
eigenvalues = pca_res$eig[,1]
# PC loading
loadings = pca_res$ind$coord
rownames(loadings) = rownames(x)
colnames(loadings) = paste0('Dim.', 1:ncol(loadings))
# coordinates
coords = sweep(pca_res$var$coord, 2, sqrt(eigenvalues[1:ncp]), FUN = "/")
rownames(coords) = colnames(x)
colnames(coords) = paste0('Dim.', 1:ncol(coords))
result = list(eigenvalues = eigenvalues, loadings = loadings, coords = coords)
} else {
if(ncp > ncol(x)) {
warning("ncp > ncol(x), will be set to ncol(x)")
ncp = ncol(x)
}
# start seed
if(isTRUE(set_seed)) {
set.seed(seed = seed_number)
}
pca_res = FactoMineR::PCA(X = x, ncp = ncp, scale.unit = scale, graph = F, ...)
# exit seed
if(isTRUE(set_seed)) {
set.seed(seed = Sys.time())
}
# eigenvalues
eigenvalues = pca_res$eig[,1]
# PC loading
loadings = sweep(pca_res$var$coord, 2, sqrt(eigenvalues[1:ncp]), FUN = "/")
rownames(loadings) = colnames(x)
colnames(loadings) = paste0('Dim.', 1:ncol(loadings))
# coordinates
coords = pca_res$ind$coord
rownames(coords) = rownames(x)
colnames(coords) = paste0('Dim.', 1:ncol(coords))
result = list(eigenvalues = eigenvalues, loadings = loadings, coords = coords)
}
return(result)
}
#' @title runPCA_BiocSingular
#' @name runPCA_BiocSingular
#' @description Performs PCA based on the biocSingular package
#' @param x matrix or object that can be converted to matrix
#' @param ncp number of principal components to calculate
#' @param center center the matrix before pca
#' @param scale scale features
#' @param rev reverse PCA
#' @param set_seed use of seed
#' @param seed_number seed number to use
#' @param BSPARAM method to use
#' @param BSParameters additonal parameters for method
#' @keywords internal
#' @return list of eigenvalues, loadings and pca coordinates
runPCA_BiocSingular = function(x,
ncp = 100,
center = TRUE,
scale = TRUE,
rev = FALSE,
set_seed = TRUE,
seed_number = 1234,
BSPARAM = c('irlba', 'exact', 'random'),
BSParameters = list(NA),
...) {
BSPARAM = match.arg(BSPARAM, choices = c('irlba', 'exact', 'random'))
min_ncp = min(dim(x))
if(ncp >= min_ncp) {
warning("ncp >= minimum dimension of x, will be set to minimum dimension of x - 1")
ncp = min_ncp-1
}
# start seed
if(isTRUE(set_seed)) {
set.seed(seed = seed_number)
}
if(isTRUE(rev)) {
x = t_flex(x)
if(BSPARAM == 'irlba') {
pca_res = BiocSingular::runPCA(x = x, rank = ncp,
center = center, scale = scale,
BSPARAM = BiocSingular::IrlbaParam(BSParameters),
...)
} else if(BSPARAM == 'exact') {
pca_res = BiocSingular::runPCA(x = x, rank = ncp,
center = center, scale = scale,
BSPARAM = BiocSingular::ExactParam(BSParameters),
...)
} else if(BSPARAM == 'random') {
pca_res = BiocSingular::runPCA(x = x, rank = ncp,
center = center, scale = scale,
BSPARAM = BiocSingular::RandomParam(BSParameters),
...)
}
# eigenvalues
eigenvalues = pca_res$sdev^2
# PC loading
loadings = pca_res$x
rownames(loadings) = rownames(x)
colnames(loadings) = paste0('Dim.', 1:ncol(loadings))
# coordinates
coords = pca_res$rotation
rownames(coords) = colnames(x)
colnames(coords) = paste0('Dim.', 1:ncol(coords))
result = list(eigenvalues = eigenvalues, loadings = loadings, coords = coords)
} else {
if(BSPARAM == 'irlba') {
pca_res = BiocSingular::runPCA(x = x, rank = ncp,
center = center, scale = scale,
BSPARAM = BiocSingular::IrlbaParam(BSParameters),
...)
} else if(BSPARAM == 'exact') {
pca_res = BiocSingular::runPCA(x = x, rank = ncp,
center = center, scale = scale,
BSPARAM = BiocSingular::ExactParam(BSParameters),
...)
} else if(BSPARAM == 'random') {
pca_res = BiocSingular::runPCA(x = x, rank = ncp,
center = center, scale = scale,
BSPARAM = BiocSingular::RandomParam(BSParameters),
...)
}
# eigenvalues
eigenvalues = pca_res$sdev^2
# PC loading
loadings = pca_res$rotation
rownames(loadings) = colnames(x)
colnames(loadings) = paste0('Dim.', 1:ncol(loadings))
# coordinates
coords = pca_res$x
rownames(coords) = rownames(x)
colnames(coords) = paste0('Dim.', 1:ncol(coords))
result = list(eigenvalues = eigenvalues, loadings = loadings, coords = coords)
}
# exit seed
if(isTRUE(set_seed)) {
set.seed(seed = Sys.time())
}
return(result)
}
#' @title create_genes_to_use_matrix
#' @name create_genes_to_use_matrix
#' @description subsets matrix based on vector of genes or hvf column
#' @param gobject giotto object
#' @param feat_type feature type
#' @param spat_unit spatial unit
#' @param sel_matrix selected expression matrix
#' @param feats_to_use feats to use, character or vector of features
#' @param verbose verbosity
#' @keywords internal
#' @return subsetted matrix based on selected genes
create_feats_to_use_matrix = function(gobject,
feat_type = NULL,
spat_unit = NULL,
sel_matrix,
feats_to_use,
verbose = FALSE) {
# Set feat_type and spat_unit
spat_unit = set_default_spat_unit(gobject = gobject,
spat_unit = spat_unit)
feat_type = set_default_feat_type(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type)
# cell metadata
feat_metadata = fDataDT(gobject,
spat_unit = spat_unit,
feat_type = feat_type)
# for hvf features
if(is.character(feats_to_use) & length(feats_to_use) == 1) {
if(feats_to_use %in% colnames(feat_metadata)) {
if(verbose == TRUE) {
wrap_msg('"', feats_to_use, '" was found in the feats metadata information and will be used to select highly variable features',
sep = '')
}
feats_to_use = feat_metadata[get(feats_to_use) == 'yes'][['feat_ID']]
sel_matrix = sel_matrix[rownames(sel_matrix) %in% feats_to_use, ]
} else {
if(verbose == TRUE) wrap_msg('"', feats_to_use, '" was not found in the gene metadata information, all genes will be used',
sep = '')
}
} else {
if(verbose == TRUE) wrap_msg('a custom vector of genes will be used to subset the matrix')
sel_matrix = sel_matrix[rownames(sel_matrix) %in% feats_to_use, ]
}
if(verbose == TRUE) cat('class of selected matrix: ', class(sel_matrix), '\n')
return(sel_matrix)
}
#' @title runPCA
#' @name runPCA
#' @description runs a Principal Component Analysis
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param expression_values expression values to use
#' @param reduction cells or genes
#' @param name arbitrary name for PCA run
#' @param feats_to_use subset of features to use for PCA
#' @param genes_to_use deprecated use feats_to_use
#' @param return_gobject boolean: return giotto object (default = TRUE)
#' @param center center data first (default = TRUE)
#' @param scale_unit scale features before PCA (default = TRUE)
#' @param ncp number of principal components to calculate
#' @param method which implementation to use
#' @param method_params additional parameters
#' @param rev do a reverse PCA
#' @param set_seed use of seed
#' @param seed_number seed number to use
#' @param verbose verbosity of the function
#' @param ... additional parameters for PCA (see details)
#' @return giotto object with updated PCA dimension recuction
#' @details See \code{\link[BiocSingular]{runPCA}} and \code{\link[FactoMineR]{PCA}} for more information about other parameters.
#' \itemize{
#' \item feats_to_use = NULL: will use all features from the selected matrix
#' \item feats_to_use = <hvg name>: can be used to select a column name of
#' highly variable features, created by (see \code{\link{calculateHVF}})
#' \item feats_to_use = c('geneA', 'geneB', ...): will use all manually provided features
#' }
#' @export
runPCA <- function(gobject,
spat_unit = NULL,
feat_type = NULL,
expression_values = c('normalized', 'scaled', 'custom'),
reduction = c('cells', 'feats'),
name = NULL,
feats_to_use = 'hvf',
genes_to_use = NULL,
return_gobject = TRUE,
center = TRUE,
scale_unit = TRUE,
ncp = 100,
method = c('irlba', 'exact', 'random','factominer'),
method_params = list(NA),
rev = FALSE,
set_seed = TRUE,
seed_number = 1234,
verbose = TRUE,
...) {
# Set feat_type and spat_unit
spat_unit = set_default_spat_unit(gobject = gobject,
spat_unit = spat_unit)
feat_type = set_default_feat_type(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type)
# specify name to use for pca
if(is.null(name)) {
if(feat_type == 'rna') {
name = 'pca'
} else {
name = paste0(feat_type,'.','pca')
}
}
## deprecated arguments
if(!is.null(genes_to_use)) {
feats_to_use = genes_to_use
warning('genes_to_use is deprecated, use feats_to_use in the future \n')
}
# expression values to be used
values = match.arg(expression_values, unique(c('normalized', 'scaled', 'custom', expression_values)))
expr_values = get_expression_values(gobject = gobject,
feat_type = feat_type,
spat_unit = spat_unit,
values = values,
output = 'exprObj')
provenance = prov(expr_values)
if(!is.null(slot(gobject, 'h5_file'))) {
expr_path = slot(expr_values, 'exprMat')
expr_values = HDF5Array::h5mread(filepath = slot(gobject, 'h5_file'),
name = paste0('expression/',
feat_type,'/',
values))
expr_dimnames = HDF5Array::h5readDimnames(filepath = slot(gobject, 'h5_file'),
name = paste0('expression/',
feat_type,'/',
values))
rownames(expr_values) = expr_dimnames[[1]]
colnames(expr_values) = expr_dimnames[[2]]
} else {
expr_values = expr_values[] # extract matrix
}
## subset matrix
if(!is.null(feats_to_use)) {
expr_values = create_feats_to_use_matrix(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
sel_matrix = expr_values,
feats_to_use = feats_to_use,
verbose = verbose)
}
# do PCA dimension reduction
reduction = match.arg(reduction, c('cells', 'feats'))
# PCA implementation
method = match.arg(method, c('irlba', 'exact', 'random','factominer'))
if(reduction == 'cells') {
# PCA on cells
if(method %in% c('irlba', 'exact', 'random')) {
pca_object = runPCA_BiocSingular(x = t_flex(expr_values),
center = center,
scale = scale_unit,
ncp = ncp,
rev = rev,
set_seed = set_seed,
seed_number = seed_number,
BSPARAM = method,
BSParameters = method_params,
...)
} else if(method == 'factominer') {
pca_object = runPCA_factominer(x = t_flex(expr_values),
scale = scale_unit,
ncp = ncp, rev = rev,
set_seed = set_seed,
seed_number = seed_number,
...)
} else {
stop('only PCA methods from the BiocSingular and factominer package have been implemented \n')
}
} else {
# PCA on genes
if(method %in% c('irlba', 'exact', 'random')) {
pca_object = runPCA_BiocSingular(x = expr_values,
center = center,
scale = scale_unit,
ncp = ncp,
rev = rev,
set_seed = set_seed,
seed_number = seed_number,
BSPARAM = method,
BSParameters = method_params,
...)
} else if(method == 'factominer') {
pca_object = runPCA_factominer(x = expr_values,
scale = scale_unit, ncp = ncp, rev = rev,
set_seed = set_seed, seed_number = seed_number, ...)
} else {
stop('only PCA methods from the irlba and factominer package have been implemented \n')
}
}
print("finished runPCA_factominer, method == factominer")
if(return_gobject == TRUE) {
pca_names = list_dim_reductions_names(gobject = gobject,
data_type = reduction,
spat_unit = spat_unit,
feat_type = feat_type,
dim_type = 'pca')
if(name %in% pca_names) {
cat('\n ', name, ' has already been used, will be overwritten \n')
}
if (reduction == "cells") {
my_row_names = colnames(expr_values)
} else {
my_row_names = rownames(expr_values)
}
dimObject = create_dim_obj(name = name,
feat_type = feat_type,
spat_unit = spat_unit,
provenance = provenance,
reduction = reduction,
reduction_method = 'pca',
coordinates = pca_object$coords,
misc = list(eigenvalues = pca_object$eigenvalues,
loadings = pca_object$loadings),
my_rownames = my_row_names)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
gobject = set_dimReduction(gobject = gobject, dimObject = dimObject)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
## update parameters used ##
gobject = update_giotto_params(gobject, description = '_pca')
return(gobject)
} else {
return(pca_object)
}
}
## * PC estimates ####
# ------------------ #
#' @title create_screeplot
#' @name create_screeplot
#' @description create screeplot with ggplot
#' @param pca_obj pca dimension reduction object
#' @param ncp number of principal components to calculate
#' @param ylim y-axis limits on scree plot
#' @return ggplot
#' @keywords internal
create_screeplot = function(pca_obj, ncp = 20, ylim = c(0, 20)) {
# data.table: set global variable
PC = NULL
eigs = slot(pca_obj, 'misc')$eigenvalues
# variance explained
var_expl = eigs/sum(eigs)*100
var_expl_cum = cumsum(eigs)/sum(eigs)*100
# create data.table
screeDT = data.table::data.table('PC' = paste0('PC.', 1:length(var_expl)),
'var_expl' = var_expl,
'var_expl_cum' = var_expl_cum)
screeDT[, PC := factor(PC, levels = PC)]
max_ncp = length(eigs)
ncp = ifelse(ncp > max_ncp, max_ncp, ncp)
pl = ggplot2::ggplot()
pl = pl + ggplot2::theme_bw()
pl = pl + ggplot2::geom_bar(data = screeDT[1:ncp], ggplot2::aes(x = PC, y = var_expl), stat = 'identity')
pl = pl + ggplot2::coord_cartesian(ylim = ylim)
pl = pl + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1, vjust = 1))
pl = pl + ggplot2::labs(x = '', y = '% of variance explained per PC')
cpl = ggplot2::ggplot()
cpl = cpl + ggplot2::theme_bw()
cpl = cpl + ggplot2::geom_bar(data = screeDT[1:ncp], ggplot2::aes(x = PC, y = var_expl_cum), stat = 'identity')
cpl = cpl + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1, vjust = 1))
cpl = cpl + ggplot2::labs(x = '', y = 'cumulative % of variance explained')
savelist = list(pl, cpl)
## combine plots with cowplot
combo_plot <- cowplot::plot_grid(plotlist = savelist,
ncol = 1,
rel_heights = c(1),
rel_widths = c(1),
align = 'v')
return(combo_plot)
}
#' @title screePlot
#' @name screePlot
#' @description identify significant principal components (PCs) using an screeplot (a.k.a. elbowplot)
#' @param gobject giotto object
#' @param spat_unit spatial unit
#' @param feat_type feature type
#' @param name name of PCA object if available
#' @param expression_values expression values to use
#' @param reduction cells or features
#' @param method which implementation to use
#' @param rev do a reverse PCA
#' @param feats_to_use subset of features to use for PCA
#' @param genes_to_use deprecated, use feats_to_use
#' @param center center data before PCA
#' @param scale_unit scale features before PCA
#' @param ncp number of principal components to calculate
#' @param ylim y-axis limits on scree plot
#' @param verbose verobsity
#' @param show_plot show plot
#' @param return_plot return ggplot object
#' @param save_plot directly save the plot [boolean]
#' @param save_param list of saving parameters from all_plots_save_function()
#' @param default_save_name default save name for saving, don't change, change save_name in save_param
#' @param ... additional arguments to pca function, see \code{\link{runPCA}}
#' @return ggplot object for scree method
#' @details
#' Screeplot works by plotting the explained variance of each
#' individual PC in a barplot allowing you to identify which PC provides a significant
#' contribution (a.k.a 'elbow method'). \cr
#' Screeplot will use an available pca object, based on the parameter 'name', or it will
#' create it if it's not available (see \code{\link{runPCA}})
#' @export
screePlot = function(gobject,
spat_unit = NULL,
feat_type = NULL,
name = NULL,
expression_values = c('normalized', 'scaled', 'custom'),
reduction = c('cells', 'feats'),
method = c('irlba', 'exact', 'random','factominer'),
rev = FALSE,
feats_to_use = NULL,
genes_to_use = NULL,
center = F,
scale_unit = F,
ncp = 100,
ylim = c(0, 20),
verbose = T,
show_plot = NA,
return_plot = NA,
save_plot = NA,
save_param = list(),
default_save_name = 'screePlot',
...) {
# Set feat_type and spat_unit
spat_unit = set_default_spat_unit(gobject = gobject,
spat_unit = spat_unit)
feat_type = set_default_feat_type(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type)
# specify name to use for screeplot
if(is.null(name)) {
if(feat_type == 'rna') {
name = 'pca'
} else {
name = paste0(feat_type,'.','pca')
}
}
## deprecated arguments
if(!is.null(genes_to_use)) {
feats_to_use = genes_to_use
warning('genes_to_use is deprecated, use feats_to_use in the future \n')
}
# select direction of reduction
reduction = match.arg(reduction, c('cells', 'feats'))
pca_obj = get_dimReduction(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
reduction = reduction,
reduction_method = 'pca',
name = name,
output = 'dimObj')
#gobject@dimension_reduction[[reduction]][[spat_unit]]$pca[[name]]
# print, return and save parameters
show_plot = ifelse(is.na(show_plot), readGiottoInstructions(gobject, param = 'show_plot'), show_plot)
save_plot = ifelse(is.na(save_plot), readGiottoInstructions(gobject, param = 'save_plot'), save_plot)
return_plot = ifelse(is.na(return_plot), readGiottoInstructions(gobject, param = 'return_plot'), return_plot)
# if pca already exists plot
if(!is.null(pca_obj)) {
if(verbose == TRUE) cat('PCA with name: ', name, ' already exists and will be used for the screeplot \n')
screeplot = create_screeplot(pca_obj = pca_obj, ncp = ncp, ylim = ylim)
} else {
# if pca doesn't exists, then create pca and then plot
if(verbose == TRUE) cat('PCA with name: ', name, ' does NOT exists, PCA will be done first \n')
# expression values to be used
values = match.arg(expression_values, unique(c('normalized', 'scaled', 'custom', expression_values)))
expr_values = get_expression_values(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
values = values,
output = 'exprObj')
provenance = prov(expr_values)
expr_values = expr_values[] # extract matrix
# PCA implementation
method = match.arg(method, c('irlba', 'exact', 'random','factominer'))
## subset matrix
if(!is.null(feats_to_use)) {
expr_values = create_feats_to_use_matrix(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
sel_matrix = expr_values,
feats_to_use = feats_to_use,
verbose = verbose)
}
# reduction of cells
if(reduction == 'cells') {
# PCA on cells
if(method == 'irlba') {
pca_object = runPCA_prcomp_irlba(x = t_flex(expr_values), center = center, scale = scale_unit, ncp = ncp, rev = rev, ...)
} else if(method == 'factominer') {
pca_object = runPCA_factominer(x = t_flex(expr_values), scale = scale_unit, ncp = ncp, rev = rev, ...)
} else {
stop('only PCA methods from the irlba and factominer package have been implemented \n')
}
dimObject = create_dim_obj(name = name,
feat_type = feat_type,
spat_unit = spat_unit,
provenance = provenance,
reduction = reduction,
reduction_method = 'pca',
coordinates = pca_object$coords,
misc = list(eigenvalues = pca_object$eigenvalues,
loadings = pca_object$loadings),
my_rownames = colnames(expr_values))
screeplot = create_screeplot(pca_obj = dimObject, ncp = ncp, ylim = ylim)
}
}
## print plot
if(show_plot == TRUE) {
print(screeplot)
}
## save plot
if(save_plot == TRUE) {
do.call('all_plots_save_function', c(list(gobject = gobject, plot_object = screeplot, default_save_name = default_save_name), save_param))
}
## return plot
if(return_plot == TRUE) {
return(screeplot)
}
}
#' @title create_jackstrawplot
#' @name create_jackstrawplot
#' @description create jackstrawplot with ggplot
#' @param jackstraw_data result from jackstraw function
#' @param ncp number of principal components to calculate
#' @param ylim y-axis limits on jackstraw plot
#' @param threshold p.value threshold to call a PC significant
#' @keywords internal
#' @return ggplot
create_jackstrawplot = function(jackstraw_data,
ncp = 20,
ylim = c(0, 1),
threshold = 0.01) {
# data.table variables
PC = p.val = NULL
testDT = data.table(PC = paste0('PC.', 1:length(jackstraw_data)),
p.val = jackstraw_data)
testDT[, PC := factor(PC, levels = PC)]
testDT[, sign := ifelse(p.val <= threshold, 'sign', 'n.s.')]
pl = ggplot2::ggplot()
pl = pl + ggplot2::theme_bw()
pl = pl + ggplot2::geom_point(data = testDT[1:ncp], ggplot2::aes(x = PC, y = p.val, fill = sign), shape = 21)
pl = pl + ggplot2::scale_fill_manual(values = c('n.s.' = 'lightgrey', 'sign' = 'darkorange'))
pl = pl + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1, vjust = 1))
pl = pl + ggplot2::coord_cartesian(ylim = ylim)
pl = pl + ggplot2::theme(panel.grid.major.x = ggplot2::element_blank())
pl = pl + ggplot2::labs(x = '', y = 'p-value per PC')
return(pl)
}
#' @title jackstrawPlot
#' @name jackstrawPlot
#' @description identify significant prinicipal components (PCs)
#' @param gobject giotto object
#' @param feat_type feature type
#' @param spat_unit spatial unit
#' @param expression_values expression values to use
#' @param reduction cells or genes
#' @param feats_to_use subset of features to use for PCA
#' @param genes_to_use deprecated, use feats_to_use
#' @param center center data before PCA
#' @param scale_unit scale features before PCA
#' @param ncp number of principal components to calculate
#' @param ylim y-axis limits on jackstraw plot
#' @param iter number of interations for jackstraw
#' @param threshold p-value threshold to call a PC significant
#' @param verbose show progress of jackstraw method
#' @param show_plot show plot
#' @param return_plot return ggplot object
#' @param save_plot directly save the plot [boolean]
#' @param save_param list of saving parameters from all_plots_save_function()
#' @param default_save_name default save name for saving, don't change, change save_name in save_param
#' @return ggplot object for jackstraw method
#' @details
#' The Jackstraw method uses the \code{\link[jackstraw]{permutationPA}} function. By
#' systematically permuting genes it identifies robust, and thus significant, PCs.
#' \cr
#' @export
jackstrawPlot = function(gobject,
spat_unit = NULL,
feat_type = NULL,
expression_values = c('normalized', 'scaled', 'custom'),
reduction = c('cells', 'feats'),
feats_to_use = NULL,
genes_to_use = NULL,
center = FALSE,
scale_unit = FALSE,
ncp = 20,
ylim = c(0, 1),
iter = 10,
threshold = 0.01,
verbose = TRUE,
show_plot = NA,
return_plot = NA,
save_plot = NA,
save_param = list(),
default_save_name = 'jackstrawPlot') {
# Set feat_type and spat_unit
spat_unit = set_default_spat_unit(gobject = gobject,
spat_unit = spat_unit)
feat_type = set_default_feat_type(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type)
## deprecated arguments
if(!is.null(genes_to_use)) {
feats_to_use = genes_to_use
warning('genes_to_use is deprecated, use feats_to_use in the future \n')
}
package_check(pkg_name = "jackstraw", repository = "CRAN")
# print message with information #
if(verbose) message("using 'jackstraw' to identify significant PCs If used in published research, please cite:
Neo Christopher Chung and John D. Storey (2014).
'Statistical significance of variables driving systematic variation in high-dimensional data. Bioinformatics")
# select direction of reduction
reduction = match.arg(reduction, c('cells', 'feats'))
# print, return and save parameters
show_plot = ifelse(is.na(show_plot), readGiottoInstructions(gobject, param = 'show_plot'), show_plot)
save_plot = ifelse(is.na(save_plot), readGiottoInstructions(gobject, param = 'save_plot'), save_plot)
return_plot = ifelse(is.na(return_plot), readGiottoInstructions(gobject, param = 'return_plot'), return_plot)
# expression values to be used
values = match.arg(expression_values, unique(c('normalized', 'scaled', 'custom', expression_values)))
expr_values = get_expression_values(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
values = values,
output = 'matrix')
## subset matrix
if(!is.null(feats_to_use)) {
expr_values = create_feats_to_use_matrix(gobject = gobject,
spat_unit = spat_unit,
feat_type = feat_type,
sel_matrix = expr_values,
feats_to_use = feats_to_use,
verbose = verbose)
}
# reduction of cells
if(reduction == 'cells') {