-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathsinglecell_gex_viper_analysis.R
2200 lines (2102 loc) · 119 KB
/
singlecell_gex_viper_analysis.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
#Stage annotations
#"pT3a"-- PatientA, Patient2, Patient3, Patient5(metastatic), Patient7
#"pT1b"-- PatientB, PatientC, Patient1, Patient4, Patient6, Patient8
#Grade annotations
#"1"-- Patient3, Patient4,
#"2"-- PatientB, PatientC, Patient1, Patient2, Patient6, Patient8
#"3"-- PatientA, Patient7
#"4"-- Patient5
#######
set.seed(1234)
library(reticulate)
library(SingleR)
library(Seurat)
library(cowplot)
library(dplyr)
library(iterClust)
library(cluster)
library(umap)
library(reshape)
library(pheatmap)
library(viper)
library("org.Hs.eg.db")
library(clustree)
library(factoextra)
library(leiden)
library(MAST)
library(Hmisc)
library(ggplot2)
library(scales)
library(flowCore)
library(ggcyto)
library(infercnv)
library(ggrepel)
library(plyr)
##bug-fixed version of CreateBigSingleRObject from singleR pipeline.
#in singleR version the internal function would default to fine.tune=T regardless of input parameter settings
CreateBigSingleRObjectv2=function (counts, annot = NULL, project.name, xy, clusters, N = 10000,
min.genes = 200, technology = "10X", species = "Human", citation = "",
ref.list = list(), normalize.gene.length = F, variable.genes = "de",
fine.tune = T, reduce.file.size = T, do.signatures = F, do.main.types = T,
temp.dir = getwd(), numCores = SingleR.numCores){
n = ncol(counts)
s = seq(1, n, by = N)
dir.create(paste0(temp.dir, "/singler.temp/"), showWarnings = FALSE)
for (i in s) {
print(i)
A = seq(i, min(i + N - 1, n))
singler = CreateSinglerObject(counts[, A], annot = annot[A],
project.name = project.name, min.genes = min.genes,
technology = technology, species = species, citation = citation,
do.signatures = do.signatures, clusters = NULL, numCores = numCores,fine.tune=fine.tune)
save(singler, file = paste0(temp.dir, "/singler.temp/", project.name, ".", i, ".RData"))
}
singler.objects.file <- list.files(paste0(temp.dir, "/singler.temp/"), pattern = "RData", full.names = T)
singler.objects = list()
for (i in 1:length(singler.objects.file)) {
load(singler.objects.file[[i]])
singler.objects[[i]] = singler}
singler = SingleR.Combine(singler.objects, order = colnames(counts), clusters = clusters, xy = xy)
singler
}
#takes a data matrix mat and clust as input, where each column of clust is a unique louvain clustering
#subsamples 1000 cells 100 times to compute silhouette score.
#outputs list of mean silhouette scores and standard deviations of silhouette scores for each clustering.
sil_subsample_v2=function(mat,clust){
out=as.data.frame(matrix(rep(NA,100*ncol(clust)),nrow=100))
for(x in 1:100){
i=sample(1:ncol(mat),min(1000,ncol(mat)))
d=as.dist(1 - cor(mat[,i], method = "pearson"))
for(j in 1:ncol(clust)){
if(length(table(clust[i,j]))==1){out[x,j]=0}
else{
sil=silhouette(as.numeric(clust[i,j]),d)
out[x,j]=mean(sil[, "sil_width"])}}
}
means=apply(out,2,mean)
sd=apply(out,2,sd)
return(list(means,sd))
}
#takes a data matrix mat and clust as input, where each column of clust is a unique louvain clustering
#subsamples 1000 cells 100 times to compute silhouette score. balanced subsampling to select proportional numbers of cells from each cluster
#outputs list of mean silhouette scores and standard deviations of silhouette scores for each clustering.
sil_subsample_v3=function(mat,clust){
out=as.data.frame(matrix(rep(NA,100*ncol(clust)),nrow=100))
for(x in 1:100){
for(j in 1:ncol(clust)){
i=c()
a=clust[,j]
for(lab in unique(a)){
i=c(i,sample((1:ncol(mat))[which(a==lab)],length(which(a==lab))/length(a)*min(1000,ncol(mat))))
}
d=as.dist(1 - cor(mat[,i], method = "pearson"))
if(length(table(clust[i,j]))==1){out[x,j]=0}
else{
sil=silhouette(as.numeric(clust[i,j]),d)
out[x,j]=mean(sil[, "sil_width"])}}
}
means=apply(out,2,median)
sd=apply(out,2,mad)
return(list(means,sd))
}
#Function to draw heatmap of genes in seurat object dat, with cluster labels clust
#seurat object must have labels "tissue" and "patient"
geneHeatmap=function(dat,clust,genes,genes_by_cluster=T,n_top_genes_per_cluster=5,viper=F,color_palette=NA,scaled=F){
identities <- levels(clust)
if(is.na(color_palette)){my_color_palette <- hue_pal()(length(identities))}
else{my_color_palette=color_palette}
features=genes
i=sample(1:ncol(dat),min(10000,ncol(dat)),replace = F)
if(viper==F){x=dat[["SCT"]]@data[features,i]}
if(viper==T){x=dat[["RNA"]]@data[features,i]}
#df <- data.frame(clust[i],dat$tissue[i],dat$patient[i])
df <- data.frame(clust[i],dat$tissue[i])
rownames(df)=colnames(x)
#colnames(df)=c("cluster","tissue","patient")
colnames(df)=c("cluster","tissue")
anno_colors <- list(cluster = my_color_palette,tissue=c("cornflowerblue","coral3"))
names(anno_colors$cluster) <- levels(df$cluster)
names(anno_colors$tissue)<-c("Normal","Tumor")
#o=order(df$cluster,df$tissue,df$patient)
o=order(df$cluster,df$tissue)
x=x[,o]
df=df[o,]
quantile_breaks <- function(xs, n = 10) {
breaks <- quantile(xs, probs = seq(0, 1, length.out = n))
breaks[!duplicated(breaks)]
}
#mat_breaks <- quantile_breaks(as.matrix(apply(x,1,function(x){(x-mean(x))/sd(x)})), n = 30)
if(scaled==F){t=as.matrix(apply(x,1,function(x){(x-mean(x))/sd(x)}))}
if(scaled==T){t=as.matrix(x)}
mat_breaks <- c(quantile_breaks(t[which(t<0)], n = 10),0,quantile_breaks(t[which(t>0)], n = 10))
mat_breaks=mat_breaks[2:(length(mat_breaks)-1)] #restrict range of data to quantiles 5%-95%, extreme values excluded
if(genes_by_cluster){
anno_colors$group=anno_colors$cluster
anno_row=data.frame(group=unlist(lapply(unique(df$cluster),function(x){rep(x,n_top_genes_per_cluster)})))
gene_names=rownames(x)
rownames(x)=1:nrow(x)
if(!scaled){pheatmap(x, cluster_rows=FALSE,show_rownames=T,cluster_cols=FALSE, annotation_row = anno_row,annotation_col=df,breaks=mat_breaks,color = colorRampPalette(colors = c('blue', 'white', 'red'))(length(mat_breaks)),fontsize_row = 10,show_colnames = F,annotation_colors = anno_colors,scale="row",gaps_row=(2:length(unique(clust))-1)*n_top_genes_per_cluster,annotation_names_row = F,labels_row=gene_names,row_annotation_legend=F)}
if(scaled){pheatmap(x, cluster_rows=FALSE,show_rownames=T,cluster_cols=FALSE, annotation_row = anno_row,annotation_col=df,breaks=mat_breaks,color = colorRampPalette(colors = c('blue', 'white', 'red'))(length(mat_breaks)),fontsize_row = 10,show_colnames = F,annotation_colors = anno_colors,gaps_row=(2:length(unique(clust))-1)*n_top_genes_per_cluster,annotation_names_row = F,labels_row=gene_names,row_annotation_legend=F)}
}
else{
if(!scaled){pheatmap(x, cluster_rows=FALSE,show_rownames=T,cluster_cols=FALSE, annotation_col=df,breaks=mat_breaks,color = colorRampPalette(colors = c('blue', 'white', 'red'))(length(mat_breaks)),fontsize_row = 8,show_colnames = F,annotation_colors = anno_colors,scale="row")}
if(scaled){pheatmap(x, cluster_rows=FALSE,show_rownames=T,cluster_cols=FALSE, annotation_col=df,breaks=mat_breaks,color = colorRampPalette(colors = c('blue', 'white', 'red'))(length(mat_breaks)),fontsize_row = 8,show_colnames = F,annotation_colors = anno_colors)}
}
}
#' Identifies MRs for given data using stouffer integration.
#'
#' @param dat.mat Matrix of protein activity (proteins X samples).
#' @param cluster Vector of cluster lables. If not included, integrates the entire matrix.
#' @param weights A named vector of sample weights. If included, stouffer integration is weighted.
#' @return Returns the stouffer integrated scores for each protien.
StoufferMRs <- function(dat.mat, cluster, weights) {
# generate dummy weights if missing
if (missing(weights)) {
weights <- as.numeric(rep(1, ncol(dat.mat))); names(weights) <- colnames(dat.mat)
}
# perform integration across full matrix if cluster was missing
if (missing(cluster)) {
sInt <- rowSums(t(t(dat.mat) * weights))
sInt <- rowSums(t(t(dat.mat) * weights)) / sqrt(sum(weights ** 2))
return(sInt)
}
# separate cluster specific matrices
k <- length(table(cluster))
mrs <- list()
for (i in 1:k) { # for each cluster
clust.cells <- names(cluster)[which(cluster == i)]
clust.mat <- dat.mat[, clust.cells]
clust.weights <- weights[clust.cells]
clust.mrs <- StoufferMRs(clust.mat, weights = clust.weights)
mrs[[paste('c', i, sep = '')]] <- sort(clust.mrs, decreasing = TRUE)
}
return(mrs)
}
#' Identifies MRs based on ANOVA analysis for a given clustering.
#'
#' @param dat.mat Matrix of protein activity (proteins X samples).
#' @param clustering Clustering vector
#' @return A named vector of p-values for each protein
AnovaMRs <- function(dat.mat, clustering) {
pVals <- c()
group.vec <- clustering[colnames(dat.mat)]
# perform an anova for each protein, storing pValues in a vector
for (i in 1:nrow(dat.mat)) {
aov.df <- data.frame('weights' = dat.mat[i,], 'group' = group.vec)
#print(aov.df)
aov.test <- aov(weights ~ group, aov.df)
pVal <- summary(aov.test)[[1]][1,5]
pVals <- c(pVals, pVal)
}
# name and return the vector
names(pVals) <- rownames(dat.mat)
return(pVals)
}
#' Performs a bootstrap t-test between two sample vectors x and y. Returns a log p-value.
#'
#' @param x Vector of test values.
#' @param y Vector of reference values.
#' @param bootstrap.num Number of bootstraps to use. Default of 100.
#' @return A signed log p-value.
LogBootstrapTTest <- function(x, y, bootstrap.num = 100) {
x.n <- length(x); y.n <- length(y)
log.pValue <- c()
## perform test for each bootstrap
for (i in 1:bootstrap.num) {
# create bootstraps
x.boot <- sample(1:x.n, size = x.n, replace = TRUE)
x.boot <- x[x.boot]
y.boot <- sample(1:y.n, size = y.n, replace = TRUE)
y.boot <- y[y.boot]
# perform t.test
test.res <- t.test(x = x.boot, y = y.boot, alternative = "two.sided")
# generate log p-value
log.p <- 2*pt(q = abs(test.res$statistic), df = floor(test.res$parameter), log.p = TRUE, lower.tail = FALSE)*(-sign(test.res$statistic))
log.pValue <- c(log.pValue, log.p)
}
# return mean log p-value
return(mean(log.pValue))
}
#' Performs a t-test between two sample vectors x and y. Returns a log p-value.
#' @param x Vector of test values.
#' @param y Vector of reference values.
#' @param bootstrap.num Number of bootstraps to use. Default of 100.
#' @return A signed log p-value.
LogTTest <- function(x, y) {
test.res <- t.test(x, y, alternative = 'two.sided')
log.p <- 2*pt(q = abs(test.res$statistic), df = floor(test.res$parameter), log.p = TRUE, lower.tail = FALSE)*(-sign(test.res$statistic))
return(log.p)
}
#' Identifies MRs based on a bootstraped Ttest between clusters.
#'
#' @param dat.mat Matrix of protein activity (proteins X samples).
#' @param clustering Vector of cluster labels.
#' @param bootstrap.num Number of bootstraps to use. Default of 10
#' @return Returns a list of lists; each list is a vector of sorted log p-values for each cluster.
BTTestMRs <- function(dat.mat, clustering, bootstrap.num = 100) {
# set initial variables
clustering <- clustering
k <- length(table(clustering))
mrs <- list()
# identify MRs for each cluster
for (i in 1:k) {
print(paste('Identifying MRs for cluster ', i, '...', sep = ''))
mrs.mat <- matrix(0L, nrow = nrow(dat.mat), ncol = bootstrap.num)
rownames(mrs.mat) <- rownames(dat.mat)
# split test and ref matrices
clust <- names(table(clustering))[i]
clust.vect <- which(clustering == clust)
test.mat <- dat.mat[, clust.vect]; ref.mat <- dat.mat[, -clust.vect]
t.n <- ncol(test.mat); r.n <- ncol(ref.mat)
# for each bootstrap
for (b in 1:bootstrap.num) {
test.boot <- test.mat[, sample(colnames(test.mat), size = t.n, replace = TRUE)]
ref.boot <- ref.mat[, sample(colnames(ref.mat), size = t.n, replace = TRUE)]
# for each gene
for (g in rownames(dat.mat)) {
mrs.mat[g, b] <- LogTTest(test.boot[g,], ref.boot[g,])
}
}
# sort and add to list
mList <- sort(rowMeans(mrs.mat), decreasing = TRUE)
mrs[[clust]] <- mList
}
# return
return(mrs)
}
#' Returns the master regulators for the given data.
#'
#' @param dat.mat Matrix of protein activity (proteins X samples).
#' @param method 'Stouffer' or 'ANOVA'
#' @param clustering Optional argument for a vector of cluster labels.
#' @param numMRs Number of MRs to return per cluster. Default of 50.
#' @param bottom Switch to return downregulated proteins in MR list. Default FALSE>
#' @param weights Optional argument for weights, which can be used in the Stouffer method.
#' @return Returns a list of master regulators, or a list of lists if a clustring is specified.
GetMRs <- function(dat.mat, clustering, method, numMRs = 50, bottom = FALSE, weights, ...) {
if (method == 'ANOVA') {
mr.vals <- AnovaMRs(dat.mat, clustering)
} else if (method == 'Stouffer') {
# generate dummy weights if not specified
if (missing(weights)) {
weights <- rep(1, ncol(dat.mat))
names(weights) <- colnames(dat.mat)
}
# recursive calls for each cluster
if (missing(clustering)) { # no clustering specified
mr.vals <- StoufferMRs(dat.mat, weights)
} else {
k <- length(table(clustering))
mrs <- list()
for (i in 1:k) {
# get cluster specific matrix and weights
clust.cells <- names(which(clustering == i))
clust.mat <- dat.mat[, clust.cells]
print(dim(clust.mat))
clust.weights <- weights[clust.cells]
# find mrs and add to list
clust.mrs <- GetMRs(clust.mat, method = method, weights = clust.weights, numMRs = numMRs, bottom = bottom)
print(head(clust.mrs))
mrs[[paste('c', i, sep = '')]] <- clust.mrs
}
return(mrs)
}
} else {
print('Invalid method: must be "Stouffer" or "ANOVA".')
}
# return appropriate portion of MR list
mr.vals <- sort(mr.vals, decreasing = TRUE)
if (bottom) {
return(c(mr.vals[1:numMRs], tail(mr.vals, numMRs)))
} else {
return(mr.vals[1:numMRs])
}
}
#' Identifies MRs on a cell-by-cell basis and returns a merged, unique list of all such MRs.
#'
#' @param dat.mat Matrix of protein activity (proteins X samples).
#' @param numMRs Default number of MRs to identify in each cell. Default of 25.
#' @return Returns a list of master regulators, the unique, merged set from all cells.
CBCMRs <- function(dat.mat, numMRs = 25) {
# identify MRs
cbc.mrs <- apply(dat.mat, 2, function(x) { names(sort(x, decreasing = TRUE))[1:numMRs] })
cbc.mrs <- unique(unlist(as.list(cbc.mrs)))
# return
return(cbc.mrs)
}
#' Unwraps a nested MR list: previous functions return cluster specific master regulators as a list of lists. This funciton will unwrap that object into one, unique list.
#'
#' @param MRs List of lists, with MR names as sub-list names and MR activity as sub-list entries.
#' @param top If specified, will subset the top X regulators from each set.
#' @return Returns a de-duplicated list of MRs.
MR_UnWrap <- function(MRs, top) {
if (missing(top)) {
return( unique(unlist(lapply(MRs, names), use.names = FALSE)) )
} else {
mr.unwrap <- lapply(MRs, function(x) {
names(sort(x, decreasing = TRUE))[ 1:min(top, length(x)) ]
})
return( unique(unlist(mr.unwrap, use.names = FALSE)) )
}
}
#' Performs a rank transformation on a given matrix.
#'
#' @param dat.mat Matrix of data, usually gene expression (genes X samples).
#' @return Rank transformed matrix.
RankTransform <- function(dat.mat) {
rank.mat <- apply(dat.mat, 2, rank)
median <- apply(rank.mat, 1, median)
mad <- apply(rank.mat, 1, mad)
rank.mat <- (rank.mat - median) / mad
return(rank.mat)
}
#' Make Cluster Metacells for ARACNe. Will take a clustering and produce saved meta cell matrices.
#'
#' @param dat.mat Matrix of raw gene expression (genes X samples).
#' @param dist.mat Distance matrix to be used for neighbor calculation. We recommend using a viper similarity matrix.
#' @param numNeighbors Number of neighbors to use for each meta cell. Default of 5.
#' @param clustering Vector of cluster labels.
#' @param subSize Size to subset the data too. Since 200 cells is adequate for ARACNe runs, this allows for speedup. Default of 200.
#' @param out.dir Directory for sub matrices to be saved in.
#' @param out.name Optional argument for preface of file names.
MakeCMfA <- function(dat.mat, numNeighbors = 10, clustering, subSize = 200, out.dir, out.name = '',sizeThresh=100) {
# generate cluster matrices
clust.mats <- ClusterMatrices(dat.mat, clustering,sizeThresh = sizeThresh)
clust.mats=clust.mats[which(!unlist(lapply(clust.mats,is.null)))]
# produce metaCell matrix and save for each cluster matrix
k <- length(clust.mats)
meta.mats <- list()
for (i in 1:k) {
mat <- clust.mats[[i]]
meta.mat <- MetaCells(mat, numNeighbors)
file.name <- paste(out.dir, out.name, '_clust-', i, '-metaCells_all', sep = '')
ARACNeTable(meta.mat, file.name, subset = FALSE)
meta.mats[[i]] <- meta.mat
if(subSize < ncol(meta.mat)){meta.mat=meta.mat[, sample(colnames(meta.mat), subSize)]}
meta.mat <- CPMTransform(meta.mat)
file.name <- paste(out.dir, out.name, '_clust-', i, '-metaCells', sep = '')
ARACNeTable(meta.mat, file.name, subset = FALSE)
}
return(meta.mats)
}
#' Generates a meta cell matrix for given data.
#'
#' @param dat.mat Raw gene expression matrix (genes X samples).
#' @param dist.mat Distance matrix to be used for neighbor inference.
#' @param numNeighbors Number of neighbors to use for each meta cell. Default of 10.
#' @param subSize If specified, number of metaCells to be subset from the final matrix. No subsetting occurs if not incldued.
#' @return A matrix of meta cells (genes X samples).
MetaCells <- function(dat.mat, numNeighbors = 10, subSize) {
# prune distance matrix if necessary
#dist.mat <- as.matrix(dist.mat)
#dist.mat <- dist.mat[colnames(dat.mat), colnames(dat.mat)]
#dist.mat <- as.dist(dist.mat)
dist.mat=as.dist(1 - cor(dat.mat, method = "pearson"))
# KNN function
KNN <- function(dist.mat, k){
dist.mat <- as.matrix(dist.mat)
n <- nrow(dist.mat)
neighbor.mat <- matrix(0L, nrow = n, ncol = k)
for (i in 1:n) {
neighbor.mat[i,] <- order(dist.mat[i,])[2:(k + 1)]
}
return(neighbor.mat)
}
knn.neighbors <- KNN(dist.mat, numNeighbors)
# create imputed matrix
imp.mat <- matrix(0, nrow = nrow(dat.mat), ncol = ncol(dat.mat))
rownames(imp.mat) <- rownames(dat.mat); colnames(imp.mat) <- colnames(dat.mat)
for (i in 1:ncol(dat.mat)) {
neighbor.mat <- dat.mat[,c(i, knn.neighbors[i,])]
imp.mat[,i] <- rowSums(neighbor.mat)
}
# subset if requested and return
if (missing(subSize)) {
return(imp.mat)
} else if (subSize > ncol(imp.mat)) {
return(imp.mat)
} else {
return(imp.mat[, sample(colnames(imp.mat), subSize) ])
}
}
#' Generates cluster-specific matrices for given data based on a clustering object.
#'
#' @param dat.mat Data matrix to be split (features X samples).
#' @param clust Clustering object.
#' @param savePath If specified, matrices will be saved. Otherwise, a list of matrices will be returned.
#' @param savePref Preface for file names, if saving.
#' @param sizeThresh Smallest size cluster for which a matrix will be created. Default 300.
#' @return If files are NOT saved, returnes a list of matrices, one for each cluster. Otherwise, returns nothing.
ClusterMatrices <- function(dat.mat, clust, savePath, savePref, sizeThresh = 100) {
## set savePath if it is specified
if(!missing(savePath)) {
if (!missing(savePref)) {
savePath <- paste(savePath, savePref, sep = '')
}
} else {
clust.mats <- list()
}
## generate matrices
clust.table <- table(clust)
for (i in 1:length(clust.table)) {
if (clust.table[i] > sizeThresh) {
clust.cells <- which(clust == names(clust.table)[i])
clust.mat <- dat.mat[, clust.cells]
clust.mat <- clust.mat[ rowSums(clust.mat) >= 1 ,]
if (missing(savePath)) {
clust.mats[[i]] <- clust.mat
} else {
saveRDS(clust.mat, file = paste(savePath, '_', names(clust.table)[i], '.rds', sep = ''))
}
}
}
## return if not saving
if (missing(savePath)) {
return(clust.mats)
}
}
#' Performs a CPM normalization on the given data.
#'
#' @param dat.mat Matrix of gene expression data (genes X samples).
#' @param l2 Optional log2 normalization switch. Default of False.
#' @return Returns CPM normalized matrix
CPMTransform <- function(dat.mat, l2 = FALSE) {
cpm.mat <- t(t(dat.mat) / (colSums(dat.mat) / 1e6))
if (l2) {
cpm.mat <- log2(cpm.mat + 1)
}
return(cpm.mat)
}
#' Saves a matrix in a format for input to ARACNe
#'
#' @param dat.mat Matrix of data (genes X samples).
#' @param out.file Output file where matrix will be saved.
#' @param subset Switch for subsetting the matrix to 500 samples. Default TRUE.
ARACNeTable <- function(dat.mat, out.file, subset = TRUE) {
dat.mat <- dat.mat[!duplicated(rownames(dat.mat)), ]
saveRDS(dat.mat, file = paste(out.file,".rds",sep=""))
if (subset) {
dat.mat <- dat.mat[, sample(colnames(dat.mat), min(ncol(dat.mat), 500)) ]
}
sample.names <- colnames(dat.mat)
gene.ids <- rownames(dat.mat)
m <- dat.mat
mm <- rbind( c("gene", sample.names), cbind(gene.ids, m))
write.table( x = mm , file = paste(out.file,".tsv",sep=""),
sep="\t", quote = F , row.names = F , col.names = F )
}
#' Processes ARACNe results into a regulon object compatible with VIPER.
#'
#' @param a.file ARACNe final network .tsv.
#' @param exp.mat Matrix of expression from which the network was generated (genes X samples).
#' @param out.dir Output directory for networks to be saved to.
#' @param out.name Optional argument for prefix of the file name.
RegProcess <- function(a.file, exp.mat, out.dir, out.name = '.') {
require(viper)
processed.reg <- aracne2regulon(afile = a.file, eset = exp.mat, format = '3col')
saveRDS(processed.reg, file = paste(out.dir, out.name, 'unPruned.rds', sep = ''))
pruned.reg <- pruneRegulon(processed.reg, 50, adaptive = FALSE, eliminate = TRUE)
saveRDS(pruned.reg, file = paste(out.dir, out.name, 'pruned.rds', sep = ''))
}
#batch1
#Patient A - pT3a, Grade III
#Patient B - pT1b, Grade II
#Patient C - pT1b, Grade II
###Sample IDs for RCC CyTEK.
#TvsAdjNormal: 1==Tumor, 2==AdjNormal
#PatientID= Patient number 1-10 as in excel
#patientdate MonthDayYear
#batch2
#1 ccRCC. pT1a, grade 2, negative margins CN1-4
#2 ccRCC. pT3a, grade 2, negative margins CN5-8
#3 ccRCC. pT3a, grade 1, negative margins CN9-12
#4 ccRCC. pT1a, grade 1, negative margins CN13-16
#6 ccRCC. pT3aN0M1, grade 4, positive margins CN21-24
#7 Oncocytoma CN26-28
#8 clear cell RCC, pT1a, grade 2, neg margins CN29-32
#9 clear cell RCC, pT2a, grade 3, neg margins CN33-36
#10 clear cell RCC, pT1a, grade 2, neg margins CN37-40
###
###LOAD AND ANNOTATE ALL DATA
###
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180426_DRAEK_NIVI_2_HUMAN_10X/CN004/outs/filtered_gene_bc_matrices/GRCh38")
pbmca1 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmca1$patient="PatientA"
pbmca1$tissue="Normal"
pbmca1$cd45="CD45+"
pbmca1$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180426_DRAEK_NIVI_2_HUMAN_10X/CN005/outs/filtered_gene_bc_matrices/GRCh38")
pbmca2 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmca2$patient="PatientA"
pbmca2$tissue="Tumor"
pbmca2$cd45="CD45+"
pbmca2$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180730_CHARLES_NIVI_3_HUMAN_10X/CN009/outs/filtered_gene_bc_matrices/GRCh38")
pbmcb1 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmcb1$patient="PatientB"
pbmcb1$tissue="Normal"
pbmcb1$cd45="CD45+"
pbmcb1$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180730_CHARLES_NIVI_3_HUMAN_10X/CN010/outs/filtered_gene_bc_matrices/GRCh38")
pbmcb2 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmcb2$patient="PatientB"
pbmcb2$tissue="Tumor"
pbmcb2$cd45="CD45+"
pbmcb2$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180730_CHARLES_NIVI_3_HUMAN_10X/CN011/outs/filtered_gene_bc_matrices/GRCh38")
pbmcb3 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmcb3$patient="PatientB"
pbmcb3$tissue="Tumor"
pbmcb3$cd45="CD45+"
pbmcb3$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180807_CHARLES_NIVI_3_HUMAN_10X/CN012/outs/filtered_gene_bc_matrices/GRCh38")
pbmcc1 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmcc1$patient="PatientC"
pbmcc1$tissue="Normal"
pbmcc1$cd45="CD45+"
pbmcc1$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180807_CHARLES_NIVI_3_HUMAN_10X/CN013/outs/filtered_gene_bc_matrices/GRCh38")
pbmcc2 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmcc2$patient="PatientC"
pbmcc2$tissue="Tumor"
pbmcc2$cd45="CD45+"
pbmcc2$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/180807_CHARLES_NIVI_3_HUMAN_10X/CN014/outs/filtered_gene_bc_matrices/GRCh38")
pbmcc3 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmcc3$patient="PatientC"
pbmcc3$tissue="Tumor"
pbmcc3$cd45="CD45+"
pbmcc3$batch="batch1"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN1/outs/filtered_feature_bc_matrix")
pbmc1 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc1$patient="Patient1"
pbmc1$tissue="Tumor"
pbmc1$cd45="CD45+"
pbmc1$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN2/outs/filtered_feature_bc_matrix")
pbmc2 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc2$patient="Patient1"
pbmc2$tissue="Tumor"
pbmc2$cd45="CD45-"
pbmc2$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN3/outs/filtered_feature_bc_matrix")
pbmc3 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc3$patient="Patient1"
pbmc3$tissue="Normal"
pbmc3$cd45="CD45+"
pbmc3$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN4/outs/filtered_feature_bc_matrix")
pbmc4 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc4$patient="Patient1"
pbmc4$tissue="Normal"
pbmc4$cd45="CD45-"
pbmc4$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN5/outs/filtered_feature_bc_matrix")
pbmc5 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc5$patient="Patient2"
pbmc5$tissue="Tumor"
pbmc5$cd45="CD45+"
pbmc5$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN6/outs/filtered_feature_bc_matrix")
pbmc6 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc6$patient="Patient2"
pbmc6$tissue="Tumor"
pbmc6$cd45="CD45-"
pbmc6$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN7/outs/filtered_feature_bc_matrix")
pbmc7 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc7$patient="Patient2"
pbmc7$tissue="Normal"
pbmc7$cd45="CD45+"
pbmc7$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190521_CHARLES_NIVI_9_HUMAN_10X/CN8/outs/filtered_feature_bc_matrix")
pbmc8 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc8$patient="Patient2"
pbmc8$tissue="Normal"
pbmc8$cd45="CD45-"
pbmc8$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN9/outs/filtered_feature_bc_matrix")
pbmc9 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc9$patient="Patient3"
pbmc9$tissue="Tumor"
pbmc9$cd45="CD45+"
pbmc9$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN10/outs/filtered_feature_bc_matrix")
pbmc10 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc10$patient="Patient3"
pbmc10$tissue="Tumor"
pbmc10$cd45="CD45-"
pbmc10$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN11/outs/filtered_feature_bc_matrix")
pbmc11 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc11$patient="Patient3"
pbmc11$tissue="Normal"
pbmc11$cd45="CD45+"
pbmc11$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN12/outs/filtered_feature_bc_matrix")
pbmc12 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc12$patient="Patient3"
pbmc12$tissue="Normal"
pbmc12$cd45="CD45-"
pbmc12$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190603_CHARLES_NIVI_9_HUMAN_10X/CN13/outs/filtered_feature_bc_matrix")
pbmc13 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc13$patient="Patient4"
pbmc13$tissue="Tumor"
pbmc13$cd45="CD45+"
pbmc13$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190603_CHARLES_NIVI_9_HUMAN_10X/CN14/outs/filtered_feature_bc_matrix")
pbmc14 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc14$patient="Patient4"
pbmc14$tissue="Tumor"
pbmc14$cd45="CD45-"
pbmc14$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190603_CHARLES_NIVI_9_HUMAN_10X/CN15/outs/filtered_feature_bc_matrix")
pbmc15 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc15$patient="Patient4"
pbmc15$tissue="Normal"
pbmc15$cd45="CD45+"
pbmc15$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190603_CHARLES_NIVI_9_HUMAN_10X/CN16/outs/filtered_feature_bc_matrix")
pbmc16 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc16$patient="Patient4"
pbmc16$tissue="Normal"
pbmc16$cd45="CD45-"
pbmc16$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN21b/outs/filtered_feature_bc_matrix")
pbmc_data=pbmc_data[,sample(colnames(pbmc_data),10000)]
pbmc21 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc21$patient="Patient5"
pbmc21$tissue="Tumor"
pbmc21$cd45="CD45+"
pbmc21$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN22b/outs/filtered_feature_bc_matrix")
pbmc_data=pbmc_data[,sample(colnames(pbmc_data),10000)]
pbmc22 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc22$patient="Patient5"
pbmc22$tissue="Tumor"
pbmc22$cd45="CD45-"
pbmc22$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN23/outs/filtered_feature_bc_matrix")
pbmc_data=pbmc_data[,sample(colnames(pbmc_data),10000)]
pbmc23 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc23$patient="Patient5"
pbmc23$tissue="Normal"
pbmc23$cd45="CD45+"
pbmc23$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190524_CHARLES_NIVI_10_HUMAN_10X/CN24/outs/filtered_feature_bc_matrix")
pbmc_data=pbmc_data[,sample(colnames(pbmc_data),10000)]
pbmc24 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc24$patient="Patient5"
pbmc24$tissue="Normal"
pbmc24$cd45="CD45-"
pbmc24$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN29/outs/filtered_feature_bc_matrix")
pbmc29 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc29$patient="Patient6"
pbmc29$tissue="Tumor"
pbmc29$cd45="CD45+"
pbmc29$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN30/outs/filtered_feature_bc_matrix")
pbmc30 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc30$patient="Patient6"
pbmc30$tissue="Tumor"
pbmc30$cd45="CD45-"
pbmc30$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN31/outs/filtered_feature_bc_matrix")
pbmc31 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc31$patient="Patient6"
pbmc31$tissue="Normal"
pbmc31$cd45="CD45+"
pbmc31$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN32/outs/filtered_feature_bc_matrix")
pbmc32 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc32$patient="Patient6"
pbmc32$tissue="Normal"
pbmc32$cd45="CD45-"
pbmc32$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN33/outs/filtered_feature_bc_matrix")
pbmc33 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc33$patient="Patient7"
pbmc33$tissue="Tumor"
pbmc33$cd45="CD45+"
pbmc33$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN34/outs/filtered_feature_bc_matrix")
pbmc34 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc34$patient="Patient7"
pbmc34$tissue="Tumor"
pbmc34$cd45="CD45-"
pbmc34$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN35/outs/filtered_feature_bc_matrix")
pbmc35 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc35$patient="Patient7"
pbmc35$tissue="Normal"
pbmc35$cd45="CD45+"
pbmc35$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190606_CHARLES_NIVI_8_HUMAN_10X/CN36/outs/filtered_feature_bc_matrix")
pbmc36 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc36$patient="Patient7"
pbmc36$tissue="Normal"
pbmc36$cd45="CD45-"
pbmc36$batch="batch2"
rm(pbmc_data)
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190825_VICTOR_VICTOR_1_HUMAN_10X/CN37/outs/filtered_feature_bc_matrix")
pbmc37 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc37$patient="Patient8"
pbmc37$tissue="Tumor"
pbmc37$cd45="CD45+"
pbmc37$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190825_VICTOR_VICTOR_1_HUMAN_10X/CN38/outs/filtered_feature_bc_matrix")
pbmc38 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc38$patient="Patient8"
pbmc38$tissue="Tumor"
pbmc38$cd45="CD45-"
pbmc38$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190825_VICTOR_VICTOR_1_HUMAN_10X/CN39/outs/filtered_feature_bc_matrix")
pbmc39 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc39$patient="Patient8"
pbmc39$tissue="Normal"
pbmc39$cd45="CD45+"
pbmc3$batch="batch2"
pbmc_data <- Read10X(data.dir = "singlecell_rawdata/190825_VICTOR_VICTOR_1_HUMAN_10X/CN40/outs/filtered_feature_bc_matrix")
pbmc40 <- CreateSeuratObject(counts = pbmc_data,min.features = 500,min.cells=50)
pbmc40$patient="Patient8"
pbmc40$tissue="Normal"
pbmc40$cd45="CD45-"
pbmc40$batch="batch2"
rm(pbmc_data)
##
##combine all samples and save in one file
##
pbmc.big=merge(pbmc1,y=c(pbmc2,pbmc3,pbmc4,pbmc5,pbmc6,pbmc7,pbmc8,pbmc9,pbmc10),project = "RCC_SC")
pbmc.big=merge(pbmc.big,y=c(pbmc11,pbmc12,pbmc13,pbmc14,pbmc15,pbmc16,pbmc21,pbmc22,pbmc23,pbmc24),project="RCC_SC")
pbmc.big=merge(pbmc.big,y=c(pbmc29,pbmc30,pbmc31,pbmc32,pbmc33,pbmc34,pbmc35,pbmc36,pbmc37,pbmc38,pbmc39,pbmc40),project="RCC_SC")
pbmc.big<- merge(pbmc.big, y = c(pbmca1,pbmca2,pbmcb1,pbmcb2,pbmcb3,pbmcc1,pbmcc2,pbmcc3), project = "RCC_SC")
rm(pbmca1,pbmca2,pbmcb1,pbmcb2,pbmcb3,pbmcc1,pbmcc2,pbmcc3)
rm(pbmc1,pbmc2,pbmc3,pbmc4,pbmc5,pbmc6,pbmc7,pbmc8,pbmc9,pbmc10,pbmc11,pbmc12,pbmc13,pbmc14,pbmc15,pbmc16,pbmc21,pbmc22,pbmc23,pbmc24,pbmc29,pbmc30,pbmc31,pbmc32,pbmc33,pbmc34,pbmc35,pbmc36,pbmc37,pbmc38,pbmc39,pbmc40)
big_list=SplitObject(pbmc.big, split.by = "cd45")
rm(pbmc.big)
pbmc.big=big_list[[1]]
pbmc.big <- PercentageFeatureSet(pbmc.big, pattern = "^MT-", col.name = "percent.mt")
VlnPlot(pbmc.big, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3,pt.size=0,group.by="tissue")
print(ncol(pbmc.big))
pbmc.big <- subset(pbmc.big, subset = percent.mt < 10 & nCount_RNA > 1500 & nCount_RNA < 15000)
VlnPlot(pbmc.big, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3,pt.size=0,group.by="tissue")
print(ncol(pbmc.big))
pbmc.big <- SCTransform(pbmc.big,return.only.var.genes = F,verbose = T,conserve.memory = T,ncells=10000)
pbmc.big <- RunPCA(pbmc.big, features = VariableFeatures(object = pbmc.big),npcs = 30)
ElbowPlot(pbmc.big)
pbmc.big <- RunUMAP(pbmc.big, dims = 1:30, verbose = FALSE,umap.method="umap-learn",metric="correlation")
pbmc.big.singler=CreateBigSingleRObjectv2(counts = pbmc.big[["SCT"]]@counts,annot=NULL,project.name="RCC1",N=10000,
min.genes=0,technology='10X',
species='Human',citation='',normalize.gene.length=F,
variable.genes='de',fine.tune=F,
reduce.file.size=T,do.signatures=F,
do.main.types=T,
temp.dir="RCC_singler/singler_rcc1",xy = [email protected],clusters = NULL)
pbmc.big$hpca_labels=pbmc.big.singler$singler[[1]][[1]][[2]]
pbmc.big$hpca_main_labels=pbmc.big.singler$singler[[1]][[4]][[2]]
pbmc.big$blueprint_labels=pbmc.big.singler$singler[[2]][[1]][[2]]
pbmc.big$blueprint_main_labels=pbmc.big.singler$singler[[2]][[4]][[2]]
pbmc.big$hpca_pvals=pbmc.big.singler$singler[[1]][[1]][[3]]
pbmc.big$hpca_main_pvals=pbmc.big.singler$singler[[1]][[4]][[3]]
pbmc.big$blueprint_pvals=pbmc.big.singler$singler[[2]][[1]][[3]]
pbmc.big$blueprint_main_pvals=pbmc.big.singler$singler[[2]][[4]][[3]]
rm(pbmc.big.singler)
big_list[[1]]=pbmc.big
rm(pbmc.big)
pbmc.big=big_list[[2]]
pbmc.big <- PercentageFeatureSet(pbmc.big, pattern = "^MT-", col.name = "percent.mt")
VlnPlot(pbmc.big, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3,pt.size=0,group.by="tissue")
print(ncol(pbmc.big))
pbmc.big <- subset(pbmc.big, subset = percent.mt < 10 & nCount_RNA > 1500 & nCount_RNA < 15000)
VlnPlot(pbmc.big, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3,pt.size=0,group.by="tissue")
print(ncol(pbmc.big))
pbmc.big <- SCTransform(pbmc.big,return.only.var.genes = F,verbose = T,conserve.memory = T,ncells=10000)
pbmc.big <- RunPCA(pbmc.big, features = VariableFeatures(object = pbmc.big),npcs = 30)
ElbowPlot(pbmc.big)
pbmc.big <- RunUMAP(pbmc.big, dims = 1:30, verbose = FALSE,umap.method="umap-learn",metric="correlation")
pbmc.big.singler=CreateBigSingleRObjectv2(counts = pbmc.big[["SCT"]]@counts,annot=NULL,project.name="RCC1",N=10000,
min.genes=0,technology='10X',
species='Human',citation='',normalize.gene.length=F,
variable.genes='de',fine.tune=F,
reduce.file.size=T,do.signatures=F,
do.main.types=T,
temp.dir="RCC_singler/singler_rcc1",xy = [email protected],clusters = NULL)
pbmc.big$hpca_labels=pbmc.big.singler$singler[[1]][[1]][[2]]
pbmc.big$hpca_main_labels=pbmc.big.singler$singler[[1]][[4]][[2]]
pbmc.big$blueprint_labels=pbmc.big.singler$singler[[2]][[1]][[2]]
pbmc.big$blueprint_main_labels=pbmc.big.singler$singler[[2]][[4]][[2]]
pbmc.big$hpca_pvals=pbmc.big.singler$singler[[1]][[1]][[3]]
pbmc.big$hpca_main_pvals=pbmc.big.singler$singler[[1]][[4]][[3]]
pbmc.big$blueprint_pvals=pbmc.big.singler$singler[[2]][[1]][[3]]
pbmc.big$blueprint_main_pvals=pbmc.big.singler$singler[[2]][[4]][[3]]
rm(pbmc.big.singler)
big_list[[2]]=pbmc.big
rm(pbmc.big)
saveRDS(big_list, file = "seurat_human_rcc_allpatients.rds")
rm(big_list)
#####
#####Do patient-level gene expression analysis for all patients
#####
big_list=readRDS("seurat_human_rcc_allpatients.rds")
seurat_list_cd45pos=SplitObject(big_list[[1]],split.by="patient")
seurat_list_cd45neg=SplitObject(big_list[[2]],split.by="patient")
rm(big_list)
for(iter in 1:length(seurat_list_cd45pos)){
print(iter)
s=seurat_list_cd45pos[[iter]]
patientnumber=unique(s$patient)
s <- PercentageFeatureSet(s, pattern = "^MT-", col.name = "percent.mt")
tiff(paste(patientnumber,"QCPlot_CD45pos.tiff",sep = "_"), width = 8, height = 6, units = 'in', res = 600)
plot(VlnPlot(s, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3,pt.size=0,group.by="tissue"))
dev.off()
s <- subset(s, subset = percent.mt < 10 & nCount_RNA > 1000 & nCount_RNA < 15000)
s <- SCTransform(s,return.only.var.genes = F,verbose = T,conserve.memory = T)
s <- RunPCA(s, features = VariableFeatures(object = s))
s <- RunUMAP(s, dims = 1:30, verbose = FALSE,umap.method="umap-learn",metric="correlation")
s <- FindNeighbors(s, dims = 1:30, verbose = FALSE)
s <- FindClusters(s, resolution=seq(0.01,1,by=0.01), verbose = FALSE,algorithm=1)
[email protected][,which(grepl("SCT_snn_res.",colnames([email protected])))]
mat=as.data.frame(t([email protected]))
out=sil_subsample_v3(mat,clust)
means=out[[1]]
sd=out[[2]]
x=seq(0.01,1,by=0.01)
tiff(paste(patientnumber,"louvain_resolution_CD45pos.tiff",sep = "_"), width = 6, height = 6, units = 'in', res = 600)
errbar(x,means,means+sd,means-sd,ylab="mean silhouette score",xlab="resolution parameter")
lines(x,means)
best=tail(x[which(means==max(means))],n=1)
legend("topright",paste("Best",best,sep = " = "))
dev.off()
[email protected][,which(colnames([email protected])==paste("SCT_snn_res.",best,sep=""))]
Idents(s) <- "seurat_clusters"
tiff(paste(patientnumber,"louvain_split_umap_CD45pos.tiff",sep = "_"), width = 8, height = 6, units = 'in', res = 600)
plot(DimPlot(s,reduction="umap",group.by="seurat_clusters",split.by="tissue"))
dev.off()
tiff(paste(patientnumber,"louvain_umap_CD45pos.tiff",sep = "_"), width = 6, height = 6, units = 'in', res = 600)
plot(DimPlot(s, reduction = "umap",label = TRUE) + NoLegend())
dev.off()
markers <- FindAllMarkers(s, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.5,test.use = "MAST")
top10 <- markers %>% group_by(cluster) %>% top_n(n = 5, wt = avg_logFC)
tiff(paste(patientnumber,"louvain_heatmap_CD45pos.tiff",sep = "_"), width = 8, height = 8, units = 'in', res = 600)
geneHeatmap(s,s$seurat_clusters,top10$gene)
dev.off()
l=s$blueprint_labels
l[which(s$blueprint_pvals>0.1)]=NA
l[which(l %in% names(which(table(l)<20)))]=NA
s$l=l
Idents(s) <- "l"
tiff(paste(patientnumber,"singler_umap_CD45pos.tiff",sep = "_"), width = 8, height = 6, units = 'in', res = 600)
plot(DimPlot(s, reduction = "umap",label=TRUE))
dev.off()
saveRDS(s, file = paste(patientnumber,"CD45pos.rds",sep="_"))
s_meta=MakeCMfA(dat.mat=as.matrix(s[["SCT"]]@counts),clustering=s$seurat_clusters,out.dir="metacell_aracne_inputs/",out.name=paste(patientnumber,"CD45pos",sep="_"))
meta=s_meta[[1]]
for(i in 2:length(s_meta)){
meta=merge(meta,s_meta[[i]],by=0,all=T)
rownames(meta)=meta[,1]
meta=meta[,2:ncol(meta)]
}
meta[is.na(meta)] <- 0
saveRDS(meta, file = paste(patientnumber,"CD45pos_metacells.rds",sep="_"))
}
for(iter in 1:length(seurat_list_cd45neg)){
print(iter)
s2=seurat_list_cd45neg[[iter]]
patientnumber=unique(s2$patient)
s2 <- PercentageFeatureSet(s2, pattern = "^MT-", col.name = "percent.mt")
tiff(paste(patientnumber,"QCPlot_CD45neg.tiff",sep = "_"), width = 8, height = 6, units = 'in', res = 600)
plot(VlnPlot(s2, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), ncol = 3,pt.size=0,group.by="tissue"))
dev.off()
s2 <- subset(s2, subset = percent.mt < 10 & nCount_RNA > 1000 & nCount_RNA < 15000)
s2 <- SCTransform(s2,return.only.var.genes = F,verbose = T,conserve.memory = T)
s2 <- RunPCA(s2, features = VariableFeatures(object = s2))
s2 <- RunUMAP(s2, dims = 1:30, verbose = FALSE,umap.method="umap-learn",metric="correlation")
s2 <- FindNeighbors(s2, dims = 1:30, verbose = FALSE)
s2 <- FindClusters(s2, resolution=seq(0.01,1,by=0.01), verbose = FALSE,algorithm=1)
[email protected][,which(grepl("SCT_snn_res.",colnames([email protected])))]
mat=as.data.frame(t([email protected]))
out=sil_subsample_v3(mat,clust)
means=out[[1]]
sd=out[[2]]
x=seq(0.01,1,by=0.01)
tiff(paste(patientnumber,"louvain_resolution_CD45neg.tiff",sep = "_"), width = 6, height = 6, units = 'in', res = 600)
errbar(x,means,means+sd,means-sd,ylab="mean silhouette score",xlab="resolution parameter")
lines(x,means)
best=tail(x[which(means==max(means))],n=1)
legend("topright",paste("Best",best,sep = " = "))
dev.off()
[email protected][,which(colnames([email protected])==paste("SCT_snn_res.",best,sep=""))]
Idents(s2) <- "seurat_clusters"
tiff(paste(patientnumber,"louvain_split_umap_CD45neg.tiff",sep = "_"), width = 8, height = 6, units = 'in', res = 600)
plot(DimPlot(s2,reduction="umap",group.by="seurat_clusters",split.by="tissue"))
dev.off()
tiff(paste(patientnumber,"louvain_umap_CD45neg.tiff",sep = "_"), width = 6, height = 6, units = 'in', res = 600)
plot(DimPlot(s2, reduction = "umap",label = TRUE) + NoLegend())
dev.off()
markers <- FindAllMarkers(s2, only.pos = TRUE, min.pct = 0.25, logfc.threshold = 0.5,test.use = "MAST")
top10 <- markers %>% group_by(cluster) %>% top_n(n = 5, wt = avg_logFC)
tiff(paste(patientnumber,"louvain_heatmap_CD45neg.tiff",sep = "_"), width = 8, height = 8, units = 'in', res = 600)
geneHeatmap(s2,s2$seurat_clusters,top10$gene)
dev.off()
l=s2$blueprint_labels
l[which(s2$blueprint_pvals>0.1)]=NA
l[which(l %in% names(which(table(l)<20)))]=NA
s2$l=l
Idents(s2) <- "l"
tiff(paste(patientnumber,"singler_umap_CD45neg.tiff",sep = "_"), width = 8, height = 6, units = 'in', res = 600)
plot(DimPlot(s2, reduction = "umap",label=TRUE))
dev.off()
saveRDS(s2, file = paste(patientnumber,"CD45neg.rds",sep="_"))