-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrwgcna_main_seurat3.0.R
2044 lines (1620 loc) · 96.8 KB
/
rwgcna_main_seurat3.0.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
#' @title robust Weighted Gene Co-expression Network Analysis
# export R_MAX_NUM_DLLS=999
######################################################################
########################### OptParse #################################
######################################################################
suppressPackageStartupMessages(library(optparse))
option_list <- list(
make_option("--pathDatExpr", type="character",
help = "Character, path to log-normalized expression data in delimited text form (readable by data.table::fread) with gene names in the first column"),
make_option("--pathMetadata", type="character",
help = "path to metadata containing celltype identities under the colIdents. File should be in one of the standard (compressed) character separated formats. First column should have barcode/cell names matching column names in datExpr [default %default]"),
make_option("--dirProject", type="character", default=NULL,
help = "Optional. Provide project directory. Must have subdirs RObjects, plots, tables. If not provided, assumed to be dir one level up from input data dir. [default %default]"),
make_option("--dirTmp", type="character", default=NULL,
help = "Directory for temporary files, defaults to creating a 'tmp' folder within the project directory, [default %default]"),
make_option("--prefixData", type="character",
help = "Dataset prefix for the project, [default %default]"),
make_option("--prefixRun", type="character", default="run1",
help = "Run prefix to distinguish runs e.g. with different parameters, [default %default]"),
make_option("--dataType", type="character", default="sc",
help = "Expression data type, one of 'sc' or 'bulk', [default %default]"),
make_option("--autosave", type="logical", default=T,
help = "Autosave session images at regular intervals to resume later? [default %default]."),
make_option("--resume", type="character", default=NULL,
help = "Resume from a checkpoint? Must have same path and prefixData as provided. Options are 'checkpoint_1' - '5' [default %default]"),
make_option("--colIdents", type="character", default=NULL,
help = "Specify a metadata column to use for subsetting the data by cell cluster. If NULL uses the @ident slot. [default %default]"),
make_option("--minGeneCells", type="integer", default=20L,
help="What is the minimum number of cells in each subset in the data in which a gene should be detected to not be filtered out? Integer, [default %default]."),
make_option("--minCellClusterSize", type="integer", default=50L,
help="What is the minimum number of cells in a subset to continue? Integer, [default %default]."),
make_option("--featuresUse", type="character", default="PCLoading",
help="One of 'var.features', 'PCLoading', 'JackStrawPCLoading' or 'JackStrawPCSignif'. PCLoading uses the top nFeatures PC loading genes; JackStrawPCLoading does the same but only on PCs retained after JackStraw significance testing; JackStrawPCSignif uses gene p-values instead of loadings [default %default]"),
make_option("--nFeatures", type="numeric", default=5000,
help="How many genes to select under the criteria set with the featuresUse argument, set to Inf to take all [default %default]"),
make_option("--nPC", type="integer", default=100L,
help = "Number of principal components to compute for selecting genes based on their loadings, [default %default]."),
make_option("--nRepJackStraw", type="integer", default=250L,
help = "Number of times to re-run PCA after permuting a small proportion of genes to perform empirical significance tests, i.e. the `JackStraw` procedure (see `featuresUse` above), [default %default]."),
make_option("--corFnc", type="character", default="cor",
help="Use 'cor' for Pearson or 'bicor' for midweighted bicorrelation function (https://en.wikipedia.org/wiki/Biweight_midcorrelation). [default %default]"),
make_option("--networkType", type="character", default = "c('signed hybrid')",
help="'signed' scales correlations to [0:1]; 'unsigned' takes the absolute value (but the TOM can still be 'signed'); ''c('signed hybrid')'' (quoted vector) sets negative correlations to zero. [default %default]"),
make_option("--nRepTOM", type="integer", default=100L,
help = "Number of times to resample the dataset when finding the consensus TOM [default %default]"),
make_option("--consensusQuantile", type="numeric", default=0.2,
help = "Gene-gene adjacency quantile to use when computing consensus TOM [default %default]"),
make_option("--hclustMethod", type="character", default="average",
help = "Hierarchical clustering agglomeration method. One of 'ward.D', 'ward.D2', 'single', 'complete', 'average' (= UPGMA), 'mcquitty' (= WPGMA), 'median' (= WPGMC) or 'centroid' (= UPGMC). See hclust() documentation for further information. [default %default]"),
make_option("--minClusterSize", type="character", default="15L",
help = "Minimum features needed to form a module, or an initial cluster before the Partitioning Around Medoids-like step. WGCNA authors recommend decreasing the minimum cluster size when using higher settings of deepSplit. Takes a character with a vector, without whitespace, of integer values to try 'c(15,20,25)' [default %default]"),
make_option("--deepSplit", type="character", default="2L",
help = "Controls the sensitivity of the cutreeDynamic/cutreeHybrid algorithm. Takes a character with a vector, without whitespace, of integer values between 0-4 to try, e.g. 'c(1,2,3)', [default %default]"),
make_option("--moduleMergeCutHeight", type="character", default="c(0.15)",
help = "Cut-off level for 1-cor(eigen-gene, eigen-gene) for merging modules. Takes a character with a vector, without whitespace, of double values to try, e.g. 'c(0.1, 0.2)', [default %default]"),
make_option("--pamStage", type="character", default="c(FALSE)",
help = "cutreeHybrid. Perform additional Partition Around Medroids step? Users favoring specificity over sensitivity (that is, tight clusters with few mis-classifications) should set pamStage = FALSE, or at least specify the maximum allowable object-cluster dissimilarity to be zero (in which case objects are assigned to clusters only if the object-cluster dissimilarity is smaller than the radius of the cluster). Takes a character with a vector, without whitespace, of logicals to try, e.g. 'c(TRUE,FALSE)', [default %default]"),
make_option("--kMReassign", type="logical", default="TRUE",
help = "Following hierarchical clustering, do additional k-means clustering to reassign features whose proximity to another module is >= 1.2 times the proximity to their own? [default %default]"),
make_option("--kMSignifFilter", type="logical", default="TRUE",
help = "Do a t test to filter out insignificant features from modules? If fuzzyModMembership=='kME', carries out a correlation t-test; if kIM, does a two-sample t-test between IntraModular and ExtraModular connectivities"),
make_option("--fuzzyModMembership", type="character", default="kIM",
help="Which 'fuzzy' measure of gene membership in a module should be used? Options are 'kME' (correlation between gene expression and module PC1 expression) and 'kIM' (sum of edges between a gene and genes in the module, normalized by number of genes in the module; i.e. average distance in the TOM between a gene and genes in the module [default %default]."),
make_option("--RAMGbMax", type="integer", default=400,
help = "Upper limit on Gb RAM available. Taken into account when setting up parallel processes. [default %default]")
)
######################################################################
########################## GET CURRENT DIR ###########################
######################################################################
LocationOfThisScript = function() # Function LocationOfThisScript returns the location of this .R script (may be needed to source other files in same dir)
{
this.file = NULL
# This file may be 'sourced'
for (i in -(1:sys.nframe())) {
if (identical(sys.function(i), base::source)) this.file = (normalizePath(sys.frame(i)$ofile))
}
if (!is.null(this.file)) return(dirname(this.file))
# But it may also be called from the command line
cmd.args = commandArgs(trailingOnly = FALSE)
cmd.args.trailing = commandArgs(trailingOnly = TRUE)
cmd.args = cmd.args[seq.int(from=1, length.out=length(cmd.args) - length(cmd.args.trailing))]
res = gsub("^(?:--file=(.*)|.*)$", "\\1", cmd.args)
# If multiple --file arguments are given, R uses the last one
res = tail(res[res != ""], 1)
if (0 < length(res)) return(dirname(res))
# Both are not the case. Maybe we are in an R GUI?
return(NULL)
}
current.dir = paste0(LocationOfThisScript(), "/")
######################################################################
############################## FUNCTIONS #############################
######################################################################
source(file = paste0(current.dir, "rwgcna_functions_seurat3.0.R"))
source(paste0(current.dir, "/perslab-sc-library/utility_functions.R"))
######################################################################
############################## PACKAGES ##############################
######################################################################
# load packages
suppressPackageStartupMessages(library("dplyr"))
suppressPackageStartupMessages(library("Biobase"))
suppressPackageStartupMessages(library("Matrix"))
suppressPackageStartupMessages(library("Seurat"))
suppressPackageStartupMessages(library("parallel"))
suppressPackageStartupMessages(library("reshape"))
suppressPackageStartupMessages(library("reshape2"))
suppressPackageStartupMessages(library("WGCNA"))
suppressPackageStartupMessages(library("data.table"))
message("Packages loaded")
######################################################################
################### GET COMMAND LINE OPTIONS #########################
######################################################################
# get command line options, if help option encountered print help and exit,
# otherwise if options not found on command line then set defaults,
opt <- parse_args(OptionParser(option_list=option_list))
resume <- opt$resume
prefixData <- opt$prefixData
dirTmp <- opt$dirTmp
prefixRun <- opt$prefixRun
# load saved image?
if (!is.null(resume)) {
message(paste0("loading from ", resume))
tryCatch({load(file=sprintf("%s%s_%s_%s_image.RData.gz", dirTmp, prefixData, prefixRun, resume))},
error = function(x) {stop(paste0(resume, " session image file not found in ", dirTmp))})
}
# get opt again because loading from checkpoint will have overwritten it..
opt <- parse_args(OptionParser(option_list=option_list))
pathDatExpr <- opt$pathDatExpr
pathMetadata <- opt$pathMetadata
dirProject <- opt$dirProject
dirTmp <- opt$dirTmp
dataType = opt$dataType
autosave <- opt$autosave
colIdents <- opt$colIdents
minGeneCells <- opt$minGeneCells
minCellClusterSize <- opt$minCellClusterSize
featuresUse <- opt$featuresUse
#genesPCA <- opt$genesPCA
nFeatures <- opt$nFeatures
corFnc <- opt$corFnc
networkType <- opt$networkType
if (grepl("hybrid", networkType)) networkType <- eval(parse(text=opt$networkType))
nRepTOM <- opt$nRepTOM
consensusQuantile <- opt$consensusQuantile
hclustMethod <- opt$hclustMethod
minClusterSize <- eval(parse(text=opt$minClusterSize))
deepSplit <- eval(parse(text=opt$deepSplit))
moduleMergeCutHeight <- eval(parse(text=opt$moduleMergeCutHeight))
pamStage <- eval(parse(text=opt$pamStage))
kMReassign <- opt$kMReassign
kMSignifFilter <- opt$kMSignifFilter
nPC <- opt$nPC
nRepJackStraw <- opt$nRepJackStraw
fuzzyModMembership <- opt$fuzzyModMembership
RAMGbMax <- opt$RAMGbMax
######################################################################
########################## FUNCTIONS (AGAIN) #########################
######################################################################
if (!is.null(resume)) {
source(file = paste0(current.dir, "rwgcna_functions_seurat3.0.R"))
source(paste0(current.dir, "/perslab-sc-library/utility_functions.R"))
}
######################################################################
############################## CONSTANTS #############################
######################################################################
if (!file.exists(pathDatExpr) & is.null(resume)) stop("Input data path not found and no previous session to resume")
# if no output directory provided, use the dir one level above that of the input file.
if (is.null(dirProject)) {
pos <- tail(gregexpr("/", pathDatExpr)[[1]],2)[1]
dirProject = substr(pathDatExpr, 1, pos)
}
# if specified output directory doesn't exist, create it
if (!file.exists(dirProject)) {
dir.create(dirProject)
message("Project directory not found, new one created")
}
dirPlots = paste0(dirProject,"plots/")
if (!file.exists(dirPlots)) dir.create(dirPlots)
dirTables = paste0(dirProject,"tables/")
if (!file.exists(dirTables)) dir.create(dirTables)
dirRObjects = paste0(dirProject,"RObjects/")
if (!file.exists(dirRObjects)) dir.create(dirRObjects)
dirLog = paste0(dirProject,"log/")
if (!file.exists(dirLog)) dir.create(dirLog)
if (is.null(dirTmp)) dirTmp <- paste0(dirProject,"tmp/")
if (!file.exists(dirTmp)) dir.create(dirTmp)
flagDate = substr(gsub("-","",as.character(Sys.Date())),3,1000)
tStart <- as.character(Sys.time())
# source parameter values
source(file = paste0(current.dir, "rwgcna_params_seurat3.0.R"))
set.seed(randomSeed)
######################################################################
########################## PREPROCESS DATA ###########################
######################################################################
if (is.null(resume)) {
######################################################################
############################ CHECK INPUT #############################
######################################################################
if (minGeneCells < 0) stop("minGeneCells must be a non-negative integer")
if (!featuresUse %in% c("var.features", "PCLoading", "JackStrawPCLoading", "JackStrawPCSignif")) stop('featuresUse must be one of "var.features", "PCLoading", "JackStrawPCLoading", "JackStrawPCSignif"')
if (nRepJackStraw < 1 & featuresUse %in% c("JackStrawPCLoading", "JackStrawPCSignif")) stop("nRepJackStraw must be 0 or higher")
if (!corFnc %in% c("cor", "bicor")) stop("corFnc must be one of 'cor' for Pearson's or 'bicor' for biweighted midcorrelation")
if (!networkType %in% c('signed', 'unsigned', 'signed hybrid')) stop("networkType must be one of 'signed', 'unsigned' or 'signed hybrid' (not 'signed_hybrid')")
if (! (nRepTOM >= 0)) stop("nRepTOM must be non-negative")
if (length(c(minClusterSize, deepSplit, pamStage, moduleMergeCutHeight))>4) warning("Comparing different parameters increases processing time")
if (min(minClusterSize) < 5) stop("minClusterSize must be a vector of integers over 5")
if (max(deepSplit) > 4 | min(deepSplit) < 0) stop("deepSplit must be a vector of integers between 0 and 4")
if (min(moduleMergeCutHeight) < 0 | max(moduleMergeCutHeight) > 1) stop("moduleMergeCutHeight must be a vector of doubles between 0 and 1, recommended range is between 0.1 and 0.2")
if (!fuzzyModMembership %in% c("kME", "kIM")) {
warning("Invalid fuzzeModuleMembership value - reset to kIM (default)")
fuzzyModMembership <- "kIM"
}
if (!dataType %in% c("sc", "bulk")) stop("dataType must be 'sc' or 'bulk'")
if (!RAMGbMax >= 1 | !RAMGbMax <= 1000) stop("verify RAMGbMax value")
######################################################################
######################## CREATE ERROR LOG ############################
######################################################################
pathLogCellClustersDropped <- paste0(dirLog, prefixData, "_", prefixRun, "_cellClustersDropped.txt")
######################################################################
################# LOAD AND SUBSET EXPRESSSION DATA ###################
######################################################################
message("Loading data..")
df_metadata <- fread(pathMetadata, data.table = F)
rownames(df_metadata) <- df_metadata[[1]]
df_metadata <- df_metadata[,-1]
dt_datExpr <- fread(pathDatExpr)
if (any(duplicated(dt_datExpr[[1]]))) stop("datExpr has duplicate feature names, please ensure they are unique")
spmat_datExpr <- as.sparse(dt_datExpr[,-1])
# check that data is log-normalized
if (!any(apply(X = spmat_datExpr[,0:100], MARGIN=2, FUN=function(vec) any(as.logical(vec%%1))))) {
stop("Data does not appear to be log-normalized!")
}
rownames(spmat_datExpr) <- dt_datExpr[[1]]
rm(dt_datExpr)
seurat_obj <- CreateSeuratObject(counts = spmat_datExpr,
project = paste0(prefixData, "_", prefixRun),
assay = "RNA",
meta.data = df_metadata)
# normally CreateSeuratObject detects that the data is lognormalised and adds it to the data slot
# but make sure
seurat_obj@assays$RNA@data <- seurat_obj@assays$RNA@counts
rm(spmat_datExpr)
######################################################################
############################## ANNOTATION ############################
######################################################################
Idents(seurat_obj) <- seurat_obj@meta.data[[colIdents]]
vec_idents <- Idents(seurat_obj) %>% as.character
sNames_0 <- vec_idents %>% unique %>% sort
######################################################################
######## DO SEURAT PROCESSING ON SUBSETTED EXPRESSION MATRICES #######
######################################################################
message("Subsetting the dataset")
subsets <- lapply(sNames_0, function(name) {
seurat_obj_sub <- subset(x= seurat_obj,idents=name)
# filter out genes not expressed in a sufficient number of cells
vec_featuresKeep <- rownames(seurat_obj_sub)[apply(X = GetAssayData(seurat_obj_sub),
MARGIN=1,
FUN = function(eachRow) sum(eachRow>0) >= minGeneCells)]
seurat_obj_sub <- subset(x=seurat_obj_sub, features=vec_featuresKeep)
return(seurat_obj_sub)
})
# Save stats for outputting at the end
n_cells_subsets = sapply(subsets, ncol)
vec_logicalCellClustOK <- if (dataType=="sc") n_cells_subsets > minCellClusterSize else !logical(length = length(subsets))
n_genes_subsets = sapply(subsets, nrow, simplify=T)
# Free up space
rm(seurat_obj)
if (!all(vec_logicalCellClustOK)) {
log_entry <- paste0(sNames_0[!vec_logicalCellClustOK], ": had <", minCellClusterSize," cells and was therefore dropped")
warning(log_entry)
cat(text = log_entry, file = pathLogCellClustersDropped, append=T, sep = "\n")
# Filter
}
sNames_1 <- sNames_0[vec_logicalCellClustOK]
subsets <- subsets[vec_logicalCellClustOK]
names(subsets) <- sNames_1
# Find variable features
if (dataType=="sc") {
message("Finding variable features")
fun <- function(seurat_obj, seuName) {
tryCatch({
FindVariableFeatures(object = seurat_obj,
selection.method = "vst",
do.plot=F,
nfeatures = if (featuresUse=="var.features") {
min(nFeatures, nrow(seurat_obj))
} else if (featuresUse %in% c('JackStrawPCLoading', 'JackStrawPCSignif')) {
nrow(seurat_obj)
} else 1000)
}, error = function(err) {
warning(paste0(seuName, ": FindVariableFeatures failed with selection.method = 'vst'. Trying selection.method = 'mean.var.plot' instead."))
FindVariableFeatures(object = seurat_obj,
selection.method = "mean.var.plot",
do.plot=F)
})
}
list_iterable = list("seurat_obj"=subsets, "seuName" = names(subsets))
outfile <- paste0(dirLog, prefixData, "_", prefixRun, "_FindVariableFeatures_log.txt")
subsets <- safeParallel(fun=fun,
list_iterable=list_iterable,
outfile=outfile)
} else if (dataType=="bulk") {
# filter out non-variable features
subsets <- lapply(subsets, function(seurat_obj_sub) {
vec_featuresKeep <- rownames(seurat_obj_sub)[WGCNA::goodGenes(datExpr = t(GetAssayData(seurat_obj_sub, slot="counts")))]
seurat_obj_sub <- subset(x=seurat_obj_sub, features=vec_featuresKeep)})
}
if (featuresUse %in% c('PCLoading', 'JackStrawPCLoading', 'JackStrawPCSignif')) {
# Scale data
message("Scaling data subsets")
# Scale data
fun<- function(seurat_obj, name) {
tryCatch({
ScaleData(object = seurat_obj,
# choice of features to scale constrains the genes for which we can get PCA loadings downstream
features = if (featuresUse=="var.features") VariableFeatures(object=seurat_obj) else rownames(seurat_obj), #
do.scale=T,
do.center=do.center,
block.size=15000,
min.cells.to.block=5000)},
error = function(err) {
stop(paste0(name,": ScaleData failed with the error: ", err))
})
}
list_iterable = list(seurat_obj = subsets, name = names(subsets))
outfile <- paste0(dirLog, prefixData, "_", prefixRun, "_ScaleData_log.txt")
subsets <- mapply(FUN = fun,seurat_obj=subsets, name=names(subsets))
message("Performing Principal Component Analysis")
start_time <- Sys.time()
if (dataType =="sc") {
fun = function(seurat_obj, name) {
seurat_tmp <- tryCatch({
out <- RunPCA(object = seurat_obj,
features = if (featuresUse %in% c('JackStrawPCLoading', 'JackStrawPCSignif') | length(VariableFeatures(seurat_obj)==0)) {
rownames(seurat_obj) } else {VariableFeatures(seurat_obj)},
npcs = if (length(VariableFeatures(seurat_obj))>0) {
min(nPC, min(length(VariableFeatures(seurat_obj))%/% 2, ncol(seurat_obj) %/% 2))
} else {
min(nPC, ncol(seurat_obj) %/% 2)
},
weight.by.var = T, # weighs cell embeddings
do.print = F,
seed.use = randomSeed,
maxit = maxit, # set to 500 as default
fastpath = fastpath,
verbose=T)
},
error = function(err) {
message(paste0(name, ": RunPCA's IRLBA algorithm failed with the error: ", err))
message("Trying RunPCA with var.features, fewer components, double max iterations and fastpath == F")
tryCatch({
out <- RunPCA(object = seurat_obj,
features = if (featuresUse %in% c('JackStrawPCLoading', 'JackStrawPCSignif') | length(VariableFeatures(seurat_obj)==0)) {
rownames(seurat_obj) } else { VariableFeatures(seurat_obj)},
npcs = if (length(VariableFeatures(seurat_obj))>0) {
min(nPC, min(length(VariableFeatures(seurat_obj))%/% 3, ncol(seurat_obj) %/% 3))} else {
min(nPC,ncol(seurat_obj) %/% 3)
},
weight.by.var = T,
seed.use = randomSeed,
maxit = maxit*2, # set to 500 as default
fastpath = F,
verbose=T)
}, error = function(err1) {
message(paste0(name, ": RunPCA's IRLBA algorithm failed again with error: ", err1))
message("Returning the original Seurat object with empty dr$pca slot")
return(seurat_obj)
})
})
return(seurat_tmp)
}
} else if (dataType=="bulk") {
fun = function(seurat_obj, name) {
seurat_tmp <- tryCatch({
seurat_obj@reductions$pca <- svd(x=GetAssayData(seurat_obj, slot = "scale.data"),
nu = min(nPC, ncol(seurat_obj) %/% 2),
nv = min(nPC, ncol(seurat_obj) %/% 2))
return(seurat_obj)
},
error = function(err) {
message(paste0(name, ": svd algorithm failed with the error: ", err))
message("Trying svd with fewer components")
tryCatch({
seurat_obj@reductions$pca <- svd(x=GetAssayData(seurat_obj, slot = "scale.data"),
nu = min(nPC, ncol(seurat_obj) %/% 3),
nv = min(nPC, ncol(seurat_obj) %/% 3))
return(seurat_obj)
}, error = function(err1) {
message(paste0(name, ": svd failed with error: ", err1))
message("Returning the original Seurat object with empty dr$pca slot")
return(seurat_obj)
})
})
return(seurat_tmp)
}
}
list_iterable <- list("seurat_obj" = subsets, "name" = names(subsets))
outfile <- paste0(dirLog, prefixData, "_", prefixRun, "_PCA_log.txt")
subsets <- safeParallel(fun=fun,
list_iterable=list_iterable,
outfile=outfile)
end_time <- Sys.time()
message(sprintf("PCA done, time elapsed: %s seconds", round(end_time - start_time,2)))
}
if (featuresUse=='PCLoading') {
# get cell * gene expression matrix with highest PC loading genes
if (dataType=="sc") {
list_datExpr <- lapply(subsets, function(seurat_obj) {
seurat_obj <- ProjectDim(object=seurat_obj,
reduction = "pca",
verbose=F,
overwrite=F)
loadingsAbs <- seurat_obj@reductions$pca@feature.loadings.projected %>% abs
apply(loadingsAbs, MARGIN=1, FUN=max) %>% sort(., decreasing=T) %>%
'['(1:(min(nFeatures, nrow(loadingsAbs)))) %>% names -> namesFeaturesUse
GetAssayData(object=seurat_obj,slot = "data")[namesFeaturesUse,] %>% t
})
} else if (dataType=="bulk") {
list_datExpr <- lapply(subsets, function(seurat_obj){
loadingsAbs <- seurat_obj@reductions$pca$u %>% abs # this returns a gene * singular vector matrix
rownames(loadingsAbs) <- rownames(seurat_obj)
apply(loadingsAbs, MARGIN=1, FUN=max) %>% sort(., decreasing=T) %>%
'['(1:(min(nFeatures, nrow(loadingsAbs)))) %>% names -> namesFeaturesUse
GetAssayData(object=seurat_obj,slot = "data")[namesFeaturesUse,] %>% t
})
}
} else if (featuresUse %in% c('JackStrawPCLoading', 'JackStrawPCSignif')) {
# Select significant PCs using empirical p-value based on JackStraw resampling
# Source: https://rdrr.io/cran/Seurat/src/R/plotting.R
# score the PCs using JackStraw resampling to get an empirical null distribution to get p-values for the PCs
# based on the p-values of gene loadings. Use these to select genes
message(sprintf("Performing JackStraw with %s replications to select genes that load on significant PCs", nRepJackStraw))
fun = function(seurat_obj, name) {
wrapJackStraw(seurat_obj_sub = seurat_obj,
nRepJackStraw = nRepJackStraw,
pvalThreshold = pvalThreshold,
featuresUse=featuresUse,
nFeatures = nFeatures,
nPC = nPC)
}
list_iterable = list(seurat_obj = subsets, name = names(subsets))
outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_JackStraw.txt")
list_datExpr<- safeParallel(fun=fun, list_iterable=list_iterable, outfile=outfile)
} else if (featuresUse == "var.features") {
list_datExpr <- lapply(subsets,
function(seurat_obj) GetAssayData(seurat_obj)[rownames(seurat_obj) %in% VariableFeatures(seurat_obj),] %>% t)
}
n_genes_subsets_used <- sapply(sNames_0, function(sName) {
if (sName %in% sNames_1) ncol(list_datExpr[[sName]]) else 0
})
# Clear up
rm(subsets)
invisible(gc())
######################################################################
########################### CHECKPOINT ###############################
######################################################################
# Save or load session image
resume = "checkpoint_1"
if (autosave) save.image(file=sprintf("%s%s_%s_checkpoint_1_image.RData.gz", dirTmp, prefixData, prefixRun), compress = "gzip")
}
if (resume == "checkpoint_1") {
######################################################################
###################### (UN) LOAD PACKAGES ############################
######################################################################
suppressPackageStartupMessages(library("dplyr"))
suppressPackageStartupMessages(library("Biobase"))
suppressPackageStartupMessages(library("Matrix"))
suppressPackageStartupMessages(library("parallel"))
suppressPackageStartupMessages(library("reshape"))
suppressPackageStartupMessages(library("reshape2"))
suppressPackageStartupMessages(library("WGCNA"))
disableWGCNAThreads()
######################################################################
####### PICK SOFT THRESHOLD POWER FOR ADJACENCY MATRIX ###############
######################################################################
message("Computing soft threshold powers to maximise the fit of a scale free topology to the adjacency matrix")
softPower <- 8 # Set a default value as fall back
outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_compute_softPowers.txt")
list_iterable = list("datExpr" = list_datExpr, "subsetName"=sNames_1)
fun = function(datExpr, subsetName) {
powers = c(1:30)
sft = pickSoftThreshold(data=datExpr,
powerVector = powers,
blockSize = min(maxBlockSize , ncol(datExpr)), #try to prevent crashing
corFnc = corFnc,
corOptions = corOptions,
networkType = networkType,
verbose = 1)
pdf(sprintf("%s%s_%s_%s_pickSoftThresholdSFTFit.pdf", dirPlots, prefixData, prefixRun, subsetName),width=10,height=5)
cex1 = 0.9;
# Scale-free topology fit index as a function of the soft-thresholding power
plot(sft$fitIndices[,1],
-sign(sft$fitIndices[,3])*sft$fitIndices[,2],
xlab="Soft Threshold (power)",
ylab="Scale Free Topology Model Fit,signed R^2",
type="n",
main = paste("Scale independence"));
text(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2],
labels=powers,cex=cex1,col="red");
# this line corresponds to using an R^2 cut-off of 0.9
abline(h=0.90,col="red")
dev.off()
# Mean connectivity as a function of the soft-thresholding power
pdf(sprintf("%s%s_%s_%s_pickSoftThresholdMeanCon.pdf", dirPlots, prefixData, prefixRun, subsetName),width=10,height=5)
plot(sft$fitIndices[,1], sft$fitIndices[,5],
xlab="Soft Threshold (power)",
ylab="Mean Connectivity",
type="n",
main = paste("Mean connectivity"))
text(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col="red")
dev.off()
# Select softPower: of lower .95 percentile connectivity, if several softPowers achieve 0.9 R.sq,
# take smallest softPower; else take best fitting one
fitIndices <- as.data.frame(sft$fitIndices)
fitIndices %>% dplyr::filter(median.k. <= quantile(median.k.,0.95, na.rm=T)) -> fitIndices_filter
if (sum(fitIndices_filter$SFT.R.sq >= 0.93) > 1) {
fitIndices_filter_2 <- fitIndices_filter[fitIndices_filter$SFT.R.sq>=0.93,]
fitIndices_filter_2[which.min(fitIndices_filter_2$Power), c(1,2,6)] -> df_sft
} else {
(fitIndices_filter %>% dplyr::arrange(desc(SFT.R.sq)))[1,c(1,2,6)] -> df_sft
}
return(df_sft)
}
list_sft = safeParallel(fun=fun,
list_iterable=list_iterable,
outfile=outfile)
names(list_sft) <- sNames_1
# TOM files will be saved here by consensusTOM
setwd(dirTmp)
if (nRepTOM > 0) {
######################################################################
############### RESAMPLE THE DATA FOR ROBUSTNESS #####################
######################################################################
message(sprintf("Resampling the expression data and computing the consensus Topological Overlap Matrix with fraction %s with replace = %s and %s replicates", fraction, replace, nRepTOM))
#message(sprintf("Computing the consensus Topological Overlap Matrix with %s permutations", nRepTOM))
fun <- function(datExpr,name) {
#tryCatch({
multiExpr <- bootstrap(datExpr=datExpr,
nPermutations = nRepTOM,
replace = replace,
fraction = fraction,
randomSeed = randomSeed)
consensusTOM(multiExpr = multiExpr,
checkMissingData = checkMissingData,
maxBlockSize = maxBlockSize,
blockSizePenaltyPower = blockSizePenaltyPower,
randomSeed = randomSeed,
corType = corType,
maxPOutliers = maxPOutliers,
quickCor = quickCor,
pearsonFallback = pearsonFallback,
cosineCorrelation = cosineCorrelation,
replaceMissingAdjacencies = replaceMissingAdjacencies,
power = list_sft[[name]][["Power"]],
networkType = networkType,
TOMDenom = TOMDenom,
saveIndividualTOMs = saveIndividualTOMs,
individualTOMFileNames = paste0(prefixData, "_", prefixRun, "_", name, "_individualTOM-Set%s-Block%b.RData"),
networkCalibration = networkCalibration,
sampleForCalibration = sampleForCalibration,
sampleForCalibrationFactor = sampleForCalibrationFactor,
getNetworkCalibrationSamples = getNetworkCalibrationSamples,
consensusQuantile = consensusQuantile,
useMean = useMean,
saveConsensusTOMs = saveConsensusTOMs,
consensusTOMFilePattern = paste0(prefixData,"_", prefixRun, "_", name,"_consensusTOM-block.%b.RData"),
returnTOMs = F,
useDiskCache = T,
cacheDir = dirTmp,
cacheBase = ".blockConsModsCache",
verbose = verbose,
indent = indent)
}
list_iterable <- list("datExpr"=list_datExpr, "name"=sNames_1)
outfile = outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_consensusTOM.txt")
additional_Gb = max(as.numeric(sapply(list_iterable[[1]], FUN = function(datExpr) {object.size(datExpr)*nRepTOM}, simplify = T)))/1024^3
obj_size_Gb <- as.numeric(sum(sapply(ls(envir = .GlobalEnv), function(x) object.size(x=eval(parse(text=x)))))) / 1024^3
n_cores <- min(max(sapply(list_iterable, length)), min(detectCores()%/%3, RAMGbMax %/% (obj_size_Gb + additional_Gb))-1)
list_consensus <- safeParallel(fun=fun,
list_iterable=list_iterable,
outfile=outfile
)
} else if (nRepTOM==0) {
message("Computing the Topological Overlap Matrix")
######################################################################
##### COMPUTE THE ADJACENCY MATRIX AND TOM WITHOUT RESAMPLING ########
######################################################################
outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_TOM_for_par.txt")
fun <- function(datExpr,name) {
adjacency = adjacency(datExpr=datExpr,
type=type,
power = list_sft[[name]]$Power,
corFnc = corFnc,
corOptions = corOptions)
consTomDS = TOMsimilarity(adjMat=adjacency,
TOMType=TOMType,
TOMDenom=TOMDenom,
verbose=verbose,
indent = indent)
colnames(consTomDS) <- rownames(consTomDS) <- colnames(datExpr)
save(consTomDS, file=sprintf("%s%s_%s_%s_consensusTOM-block.1.RData", dirTmp, prefixData, prefixRun, name)) # Save TOM the way consensusTOM would have done
}
list_iterable = list("datExpr"=list_datExpr, "name"=sNames_1)
invisible(safeParallel(fun=fun,
list_iterable=list_iterable,
outfile=outfile
))
list_consensus <- lapply(list_datExpr, function(datExpr)list("goodSamplesAndGenes"=list("goodGenes"=rep(TRUE,ncol(datExpr)))))
}
# Load TOMs into memory and convert to distance matrices
fun = function(name) {
load_obj(sprintf("%s%s_%s_%s_consensusTOM-block.1.RData", dirTmp, prefixData, prefixRun, name))
}
list_consTOM = lapply(X=sNames_1, FUN = fun)
# Filter datExpr to retain genes that were kept by goodSamplesGenesMS, called by consensusTOM
fun = function(datExpr, consensus, consTOM) {
if (!is.null(consTOM)) {
if (ncol(as.matrix(consTOM))==ncol(datExpr)) datExpr else datExpr[,consensus$goodSamplesAndGenes$goodGenes]
} else {
NULL
}
}
list_iterable=list(datExpr=list_datExpr, consensus=list_consensus, consTOM=list_consTOM)
outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_datExpr_gg.txt")
list_datExpr_gg <- safeParallel(fun=fun, list_iterable=list_iterable)
rm(list_datExpr)
# Convert proximity TOMs to distance matrices
list_iterable= list("X"=list_consTOM)
fun = function(consTOM) {
1-as.dist(consTOM)
}
list_dissTOM <- safeParallel(fun=fun, list_iterable=list_iterable)
rm(list_consTOM)
# Save list_dissTOM to harddisk
names(list_dissTOM) <- sNames_1
saveRDS(list_dissTOM, file=sprintf("%s%s_%s_list_dissTOM.rds.gz", dirTmp, prefixData, prefixRun), compress = "gzip")
######################################################################
######################### CLEAR UP TOMS IN MEMORY AND HD #############
######################################################################
rm(list_dissTOM)
for (subsetName in sNames_1) {
if (file.exists(sprintf("%s%s_%s_%s_consensusTOM-block.1.RData", dirTmp, prefixData, prefixRun, subsetName))) {
try(file.remove(sprintf("%s%s_%s_%s_consensusTOM-block.1.RData", dirTmp, prefixData, prefixRun, subsetName)))
}
# Delete individual TOMs from disk
indivTOM_paths <- dir(path=dirTmp, pattern=paste0(prefixData, "_", prefixRun, "_", subsetName, "_individualTOM"), full.names = T)
for (indivTOM in indivTOM_paths) {
try(file.remove(indivTOM))
}
}
######################################################################
############################ CHECKPOINT ##############################
######################################################################
resume="checkpoint_2"
if (autosave) save.image( file=sprintf("%s%s_%s_checkpoint_2_image.RData.gz", dirTmp, prefixData, prefixRun), compress = "gzip")
}
if (resume == "checkpoint_2") {
######################################################################
#################### (UN) LOAD PACKAGES #############################
######################################################################
# Free up DLLs
suppressPackageStartupMessages(library("dplyr"))
suppressPackageStartupMessages(library("Biobase"))
suppressPackageStartupMessages(library("Matrix"))
suppressPackageStartupMessages(library("parallel"))
suppressPackageStartupMessages(library("reshape"))
suppressPackageStartupMessages(library("reshape2"))
suppressPackageStartupMessages(library("WGCNA"))
######################################################################
##################### LOAD AND FILTER DISSTOMS #######################
######################################################################
# TODO: Could filter earlier
list_dissTOM_path <- dir(path = dirTmp, pattern = paste0(prefixData, "_", prefixRun, "_list_dissTOM"), full.names = T)
list_dissTOM <- load_obj(list_dissTOM_path)
# Remove NULL
vec_logicalCellClustOK <- !sapply(list_dissTOM, is.null)
if (!all(vec_logicalCellClustOK)) {
log_entry <-paste0(sNames_1[!vec_logicalCellClustOK], ": Topological Overlap Matrix step failed, dropped from analysis")
warning(log_entry)
cat(log_entry, file = pathLogCellClustersDropped, append=T, sep = "\n")
}
# Edit objects
list_dissTOM <- list_dissTOM[vec_logicalCellClustOK]
list_datExpr_gg <- list_datExpr_gg[vec_logicalCellClustOK]
sNames_2 <- sNames_1[vec_logicalCellClustOK]
######################################################################
####################### CLUSTER ON THE TOM ###########################
######################################################################
outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_parHclust.txt")
fun <- function(dissTOM) {hclust(d=dissTOM, method=hclustMethod)}
list_iterable = list("X"=list_dissTOM)
list_geneTree <- safeParallel(fun=fun,
list_iterable=list_iterable,
outfile = outfile
#hclustMethod=hclustMethod
)
names(list_geneTree) = sNames_2 # used for PlotDendro
######################################################################
######################### COMPUTE MODULES ############################
######################################################################
message("Computing modules on the Topological Overlap Matrix")
dims = sapply(list(minClusterSize, deepSplit, pamStage, moduleMergeCutHeight), length) # list of number of values per parameter
n_combs <- prod(dims) # Total number of combinations of parameter values
list_comb = vector("list", length = n_combs)
# Make a vector of different parameter combinations
k=1
for (size in 1:dims[1]) {
for (ds in 1:dims[2]) { # Gandal et al 2018 use c(50,100, 200)
for (pam in 1:dims[3]) {
for (dthresh in 1:dims[4]) {
list_comb[[k]] <- c(minClusterSize[size],deepSplit[ds], pamStage[pam], moduleMergeCutHeight[dthresh])
k = k+1
}
}
}
}
list_list_comb <- lapply(1:length(sNames_2), function(i) return(list_comb)) # just multiply..
attr(x=list_list_comb, which = "names") <- sNames_2 # for some reason, just setting names(list_list_comb) <- sNames_2 filled the list with NULLs...
outfile = paste0(dirLog, prefixData, "_", prefixRun, "_", "log_cutreeHybrid_for_vec.txt")
fun <- function(geneTree,dissTOM) {
lapply(list_comb, function(comb) {
tryCatch({
cutreeHybrid_for_vec(comb=comb,
geneTree=geneTree,
dissTOM = dissTOM,
maxPamDist = maxPamDist,
useMedoids = useMedoids)
}, error= function(err) {
message(paste0(comb), ": cutreeHybrid failed")
return(NULL)
})
}
)}
list_iterable = list("geneTree"=list_geneTree, "dissTOM"=list_dissTOM)
list_list_cutree <- safeParallel(fun=fun,
list_iterable=list_iterable,
outfile=outfile#,
#list_comb=list_comb,
#maxPamDist=maxPamDist,
#useMedoids=useMedoids
)
# free up memory
if (fuzzyModMembership=="kME") rm(list_dissTOM)
# Produce labels for plotting the modules found by different parameters
list_plot_label <- lapply(list_comb, function(comb) plotLabel_for_vec(comb=comb)) # list of labels for plot
# Make a copy of the labels for each subset
list_list_plot_label = list()
list_list_plot_label <- lapply(sNames_2, function(name) list_list_plot_label[[name]] = list_plot_label)
# Remove NULLs in nested lists where cutreeHybrid failed
list_vec_idx.combcutreeNULL <- lapply(list_list_cutree, function(list_cutree) {
sapply(list_cutree, is.null)
})
names(list_vec_idx.combcutreeNULL) = sNames_2
# filter
if (any(sapply(list_vec_idx.combcutreeNULL, function(idx) idx))) {
list_list_cutree <- mapply(function(list_cutree, vec_idx.combcutreeNULL) {
list_cutree[!vec_idx.combcutreeNULL]
}, list_cutree=list_list_cutree, vec_idx.combcutreeNULL = list_vec_idx.combcutreeNULL, SIMPLIFY=F)
list_list_comb <- mapply(function(list_comb, vec_idx.combcutreeNULL) {
list_comb[!vec_idx.combcutreeNULL]
}, list_comb=list_list_comb, vec_idx.combcutreeNULL = list_vec_idx.combcutreeNULL, SIMPLIFY=F)
list_list_plot_label <- mapply(function(list_plot_label, vec_idx.combcutreeNULL) {
list_plot_label[!vec_idx.combcutreeNULL]
}, list_plot_label = list_list_plot_label, vec_idx.combcutreeNULL = list_vec_idx.combcutreeNULL, SIMPLIFY=F)
}
names(list_list_cutree) <- names(list_list_comb) <- names(list_list_plot_label) <- sNames_2
# Filter at the cell cluster level
vec_logicalCellClustOK <- sapply(list_list_cutree, function(x) length(x)>0, simplify=T) %>% unlist
if (!all(vec_logicalCellClustOK)) {
log_entry <-paste0(sNames_2[!vec_logicalCellClustOK], " : cutreeHybrid failed, removed from analysis")
warning(log_entry)
cat(log_entry, file = pathLogCellClustersDropped, append=T, sep = "\n")
}
list_list_cutree <- list_list_cutree[vec_logicalCellClustOK]# Filter(f=length, x= list_list_cutree)
list_list_comb <-list_list_comb[vec_logicalCellClustOK] #Filter(f=length, x=list_list_comb)
list_list_plot_label <-list_list_plot_label[vec_logicalCellClustOK]# Filter(f=length, x=list_list_plot_label)
list_datExpr_gg <- list_datExpr_gg[vec_logicalCellClustOK]#list_datExpr_gg[names(list_datExpr_gg) %in% sNames_3]
sNames_3 <- sNames_2[vec_logicalCellClustOK]# names(list_list_cutree)
######################################################################
######################### MERGE CLOSE MODULES ########################
######################################################################
message(paste0("Merging close modules"))
if (fuzzyModMembership=="kME") {
fun = function(list_comb,list_cutree, datExpr, cellType) {
mapply(function(comb, cutree) {
colors <- rep("grey", times=ncol(datExpr))
MEs <- NULL
out <- list("colors"= colors, "MEs" = MEs)
if (length(unique(cutree$labels))>1) {
if (length(unique(cutree$labels))>2) {
merged <- try({mergeCloseModules(exprData=as.matrix(datExpr),
colors = cutree$labels,
impute =T,
corFnc = corFnc,
corOptions = corOptions,
cutHeight = comb[4],
iterate = T,
getNewMEs = F,
getNewUnassdME = F)