-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLung_lungLN_FACS_TotalTcell.r
2110 lines (1445 loc) · 71.9 KB
/
Lung_lungLN_FACS_TotalTcell.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
# the analysis script for Total T cells from lung and luLN
# author: Likai Tan
library(BiocManager)
library(devtools)
library(flowCore)
library(gtools)
library(flowWorkspace)
library(flowStats)
library(metR)
library(FlowSOM)
library(filesstrings)
library(reticulate)
# library(cytofkit2)
library(PeacoQC)
library(ConsensusClusterPlus)
# library(Rtsne)
library(umap)
library(matrixStats)
library(kableExtra)
library(tidyverse)
library(forcats)
library(reshape2)
library(pheatmap)
library(splitstackshape)
library(RColorBrewer)
library(Seurat)
# library('mlr')
source('/home/big/tanlikai/script/rscripts//funcs.r')
# readprocessed dataframe -------------------------------------------------
TotalT_corrected <- readRDS('totalTcell_processed_dataframe.rds')
# ##metadata tabl ---------------------------------------------------------
setwd('/home/big/tanlikai/Lung/FACSdata/')
# setwd('/home/big/tanlikai/Lung/PBMCs_Lung_panel_test/lung_LN/')
dir.create('figs')
fcsfiles <- list.files(pattern = c('cells.fcs') )
file_name <- list.files(pattern = c('cells.fcs') )
# meta data table
md <- data.frame(
#file
file_name = file_name,
#id
donor= str_extract(file_name,'p\\d\\d') ,
#group
# stimulation = str_extract(file_name,'stimulated|unstimulated') ,
tissue = str_extract(file_name,'LN|Lung') ) %>%
mutate(ID = paste0(donor, '_',tissue))
md
read.flow
###input trimmed FCS file
FCS_raw_totalT <- read.flowSet(
files = md$file_name,
transformation = FALSE,
truncate_max_range = FALSE)
for (i in file_name) {
print(i)
dim(FCS_raw_totalT@frames[[i]]) %>% print()
}
# add barcode to every cell
for (i in file_name) {
print(i)
FCS_raw_totalT@frames[[i]]
}
# setwd('..')
# colQuantiles(FCS_humangdT@frames[['export_DMHH190325 IELps_trialUnmixedSamplesKO_Live cells.fcs']]@exprs,
# probs = c(0.01, 0.2, 0.5, 0.75, 0.99))
FCS_raw_totalT@frames[["TotalT_LN1_p254_T4047_Live_T_cells.fcs"]]@parameters@data
##panels
panel <- FCS_raw_totalT@frames[[file_name[1]]]@parameters@data[, 1:2 ]
nrow(panel)
panel
# panel_fcs <- parameters(FCS_raw_totalT[[1]]) %>% Biobase::pData()
panel$desc <- gsub("-","",panel$desc)
Channel <- colnames(FCS_raw_totalT)
panel[7:32,] %>% kbl(row.names = F) %>% kable_styling(full_width = F, position="left")
# name desc
# FJComp-APC-A Vg9
# FJComp-APC-Fire 810-A CD3
# FJComp-APC-Vio 770-A Vd2
# FJComp-Alexa Fluor 700-A CD127
# FJComp-BUV395-A CD45RA
# FJComp-BUV496-A CD16
# FJComp-BUV563-A CD4
# FJComp-BUV661-A CD49a
# FJComp-BUV737-A KLRG1
# FJComp-BV421-A GATA3
# FJComp-BV480-A CD103
# FJComp-BV570-A CD45RO
# FJComp-BV650-A CD357
# FJComp-BV711-A CCR6
# FJComp-BV750-A CD26
# FJComp-BV785-A CD8
# FJComp-FITC-A Eomes
# FJComp-PE-A AREG
# FJComp-PE-Cy5-A TCRab
# FJComp-PE-Cy7-A CTLA4
# FJComp-PE-Dazzle594-A GMCSF
# FJComp-PE-Fire 700-A CD25
# FJComp-PerCP-Cy5.5-A GzmA
# FJComp-PerCP-Vio700-A TCRgd
# FJComp-VioGreen-A Vd1
# FJComp-Zombie NIR-A Live
# # Lineage markers
all_markers <- panel$desc[c(7:32)] %>% as.character()
lineage_markers <- setdiff(all_markers, c('Live','CD3', 'CD45RO', 'AREG', 'Gzma', 'GMCSF'))
lineage_markers_2 <-c('Vg9', 'Vd2', 'Vd1' ,'CD45RA', 'CD16', 'CD4', 'CD8', 'CD49a','KLRG1', 'GATA3',
'CD103', 'CD45RO', 'CD357', 'CD26', 'Eomes','TCRab', 'CTLA4', 'CD25', 'TCRgd')
# # Functional markers we don't use it here but should be useful for furture experiment design
functional_markers <-c('Vd1','Vd2','CD3',"TCRgd", 'TCRab', 'AREG', 'Gzma', 'GMCSF')
#abs the expr matrix
# for (i in file_name) {
# FCS_humangdT@frames[[i]]@exprs <- abs(FCS_humangdT@frames[[i]]@exprs)
# }
# ##biexpontential transform of data --------------------------------------
file_name[1]
##############check rawdata distribution
rawdata <- FCS_raw_totalT@frames[[file_name[1]]]@exprs[,7:32] %>% asinh()
rawdata
colnames(rawdata) <- all_markers
channales <- all_markers
raw <- list()
# raw[[11]]
colnm <- all_markers
for (i in 1:length(channales)) {
raw[[i]] <- ggplot(rawdata %>% as.data.frame(), aes_string(x = channales[i])) +
geom_density()+ggtitle(all_markers[i] )
}
plot_grid(plotlist = raw, ncol = 6)
figsave(plot_grid(plotlist = raw, ncol = 6), "rawsignals_Lung_totalT.pdf", w = 300, h = 300)
# save_plot("raw_Lung.pdf", plot_grid(plotlist = raw, ncol = 6), base_height = 20, base_width = 20)
# figsave(plot_grid(plotlist = raw, ncol = 6), 'rawsignals_lung.pdf', 300, 300)
# data transformation
fcs_totalT_transform_pre_qc <- fsApply(FCS_raw_totalT, function(x) {transform(x, estimateLogicle(x, c(Channel[7:32])))})
# save the transformed data
write.flowSet(fcs_totalT_transform_pre_qc, outdir = file.path(getwd(), "Transformed_FCS_files") , filename = paste0("",FCS_raw_totalT@phenoData@data$name))
fcs_totalT_transform_pre_qc <- read.flowSet(files = md$file_name, path=file.path(getwd(), "Transformed_FCS_files"), transformation = FALSE, truncate_max_range = FALSE)
# automatic QC, ------------------------------------------------
# Automated quality control ,
#
dir.create('PeacoQCresults')
for(i in 1:length(sampleNames(fcs_totalT_transform_pre_qc))){
ff <-fcs_totalT_transform_pre_qc[[i]]
channels=Channel[7:32]
peacoqc_res <- PeacoQC(ff, Channel[7:32], determine_good_cells = "all",
save_fcs = TRUE, plot=TRUE, output_directory = "PeacoQCresults")
}
fcs_totalT_transform <- read.flowSet(pattern = 'TotalT', path=file.path(getwd(), "PeacoQCresults","PeacoQC_results","fcs_files"), transformation = FALSE, truncate_max_range = F)
#
# QC result
sample_ids_raw <- rep(file_name, fsApply(fcs_totalT_transform_pre_qc, nrow))
sample_ids_trans <- rep(file_name, fsApply(fcs_totalT_transform , nrow))
cell_table_raw <- table(sample_ids_raw)
cell_table_trans <- table(sample_ids_trans)
qc_table <- data.frame(cell_table_raw,cell_table_trans)
qc_table$sample_ids_trans <- NULL
colnames(qc_table) <- c("Sample_ID","Pre-QC cell count","Post-QC cell count")
qc_table$Removed <- qc_table$`Pre-QC cell count`-qc_table$`Post-QC cell count`
qc_table$Removed_perc <- round(((qc_table$Removed/qc_table$`Pre-QC cell count`)*100), digits=2)
colnames(qc_table) <- c("Sample_ID","Pre-QC cell count","Post-QC cell count","Removed (n)","Removed (%)")
qc_table %>% kbl(row.names = T) %>% kable_styling(full_width = F, position="left")
fcs_totalT_transform <- fcs_totalT_transform[sampleNames(fcs_totalT_transform), colnames(fcs_totalT_transform)[7:32]]
# manually exponential transform, skip -----------------------------------
#the a value will decide how much the negative values will be put together
testraw <-FCS_raw_totalT@frames[[file_name[1]]]
file_name[[1]]
biexp <- biexponentialTransform('biexp_transform',w = 5,
a= 200000)
biexp2 <- biexponentialTransform('biexp_transform',w =5,
a= 100 , c = 300)
after.1<- c()
after.1 <- transform(testraw, transformList(panel[c(7:32), 1], biexp))
colnames(after.1) <- gsub("-| ", "_", colnames(after.1))
# check if transfroming is enough
channales <- colnames(after.1@exprs)[c(7:32)] %>% as.character()
bie_tr <- c()
for (i in 1:length(channales)) {
bie_tr[[i]] <- ggplot(after.1@exprs %>% as.data.frame(), aes_string(x = channales[i])) +
geom_density()+ggtitle(all_markers[i] )
}
plot_grid(plotlist = bie_tr, ncol = 6)
##do the formal transform
##biexp
FCS_humangdT <- FCS_raw
for (i in file_name) {
FCS_humangdT@frames[[i]] <- transform(FCS_raw@frames[[i]],
transformList(panel[c(7:32),1], biexp))
}
# for (i in file_name) {
# FCS_humangdT@frames[[i]] <- transform(FCS_humangdT@frames[[i]],
# transformList(panel[c(7:18),1], biexp))
# }
FCS_humangdT_biexp <- fsApply(FCS_humangdT, function(x){
colnames(x) <- colnames(FCS_humangdT)
expr <- Biobase::exprs(x)
# expr <- expr[,all_markers ]
exprs(x) <- expr
x
})
# data scale, skip ----------------------------------------------------------------------
expr <- fsApply(fcs_totalT_transform , Biobase::exprs)
colnames(expr)
# colQuantiles(fcs_raw@frames$CD3neg.fcs@exprs[, 21], probs = c(0.01, 0.25, 0.5, 0.75, 0.99))
## Extract expression
# expr <- fsApply(FCS_humangdT_biexp, Biobase::exprs)
expr <- expr%>% `colnames<-`(all_markers)
dim(expr)
colnames(expr)
###data normalization
# testdf <- data.frame(HA = c(1:100), GD = c(2:101), C = (-1:98), D = (20:119)) %>% as.matrix()
# colQuantiles(testdf, probs = c(0.01, 0.50))
#determin the datarange of each marker
rng <- colQuantiles(expr, probs = c(0.01, 0.99))
##normalize the expression matrix by :
#expression value - minimal expression value across all cells / data range
expr01 <- t((t(expr) - rng[, 1]) / (rng[, 2] - rng[, 1]))
expr01[expr01 < 0] <- 0
expr01[expr01 > 1] <- 1
dim(expr01)
##scale
### Generate sample IDs corresponding to each cell in the `expr` matrix
sample_ids <- rep(md$file_name, fsApply(fcs_totalT_transform , nrow))
# donor <- rep(md$donor, fsApply(FCS_humangdT, nrow))
# stimulation <- rep(md$stimulation, fsApply(FCS_humangdT, nrow))
tissue <- rep(md$tissue, fsApply(fcs_totalT_transform , nrow))
donor <- rep(md$donor, fsApply(fcs_totalT_transform , nrow))
ID <- rep(md$ID, fsApply(fcs_totalT_transform , nrow))
## Diagnostic plots
ggdf <- data.frame(sample_id = sample_ids, tissue, donor, ID, expr)
ggdf %>% head
##transfor the ggdf to long table
ggdf <- melt(ggdf, id.var = c('sample_id','tissue',
'donor', 'ID'
),
value.name = "expression", variable.name = "antigen")
ggdf %>% head
# mm <- match(ggdf$sample_id, md$sample_id)
# ggdf$condition <- md$condition[mm]
dim(ggdf)
##downsample
sampFreq<-function(cdf,col,ns) {
x<-as.factor(cdf[,col])
freq_x<-table(x)
prob_x<-freq_x/sum(freq_x)
df_prob = prob_x[as.factor(cdf[,col])]
nr=nrow(cdf)
sLevels = levels(as.factor(cdf[,col]))
nLevels = length(sLevels)
rat = ns/nr
rdata = NULL
for (is in seq(1,nLevels)) {
ldata <- cdf[cdf[,col]==sLevels[is],]
ndata <- nrow(ldata)
nsdata = max(ndata*rat,1)
srows <- sample(seq(1,ndata),nsdata,replace=rat>1)
sdata <- ldata[srows,]
rdata <- rbind(rdata,sdata)
}
return(rdata)
}
#downsample cell number to ~300,000
ggdf_ds <- sampFreq(ggdf, col = 1, ns = 20000)
head(ggdf_ds)
nrow(ggdf_ds)
table(ggdf_ds$sample_id)
ggdf_ds
histog_allmarkers <-ggplot(ggdf_ds, aes(x = expression, color = ID,
group = ID)) +
geom_density() +
facet_wrap(~ antigen, nrow = 4, scales = "free") +
# theme_classic() + scale_color_manual(labels = c('Neonate', 'Adult'), values = c('blue', 'red'))+
theme(axis.text.x = element_text(angle = 90, hjust = 1), text = element_text(size = 8),
strip.text = element_text(size = 7), axis.text = element_text(size = 5)) +
guides(color = guide_legend(ncol = 1))
histog_allmarkers %T>% figsave('hist_permeabilization_without_batch_correction_lung_totalT_foursample.pdf', 300, 300)
# boxplot <-ggplot(ggdf, aes(y = expression, color = sample_id,
# x = antigen))+ geom_boxplot()
# boxplot
# Get the median marker expression per sample
# expr_median_sample_tbl <- data.frame(sample_id = sample_ids, expr) %>%
# group_by(sample_id) %>%
# summarize_all(funs(median))
# #transform to long-table
# expr_median_sample <- t(expr_median_sample_tbl[, -1])
# colnames(expr_median_sample) <- expr_median_sample_tbl$sample_id
##multi-dimensional scaling (MDS) plotSuch plots show similarities between samples measured in an unsupervised way and give a sense of how much differential expression can be detected before conducting any formal tests.
# expr_median_sample <- as.data.frame(expr_median_sample)
# expr_median_sample$Condition <- 0
#
# mds <- plotMDS(expr_median_sample, plot = FALSE)
# ggdf <- data.frame(MDS1 = mds$x, MDS2 = mds$y,
# sample_id = colnames(expr_median_sample))
# mm <- match(ggdf$sample_id, md$sample_id)
# ggplot(ggdf, aes(x = MDS1, y = MDS2)) +
# geom_point(size = 2, alpha = 0.8) +
# geom_label_repel(aes(label = sample_id)) +
# theme_bw()
# Batch effection correction ----------------------------------------------
library(cyCombine)
write.csv(md %>% mutate(file_name = str_replace(file_name, 'cells', 'cells_QC')), 'PeacoQCresults/PeacoQC_results/fcs_files/metadata_TotalT_lung_LN.csv')
md
uncorrected <- prepare_data(data_dir = '/home/big/tanlikai/Lung/FACSdata/PeacoQCresults/PeacoQC_results/fcs_files/',
markers = all_markers,
transform = FALSE,
pattern = "fcs",
metadata = 'PeacoQCresults/PeacoQC_results/fcs_files/metadata_TotalT_lung_LN.csv', # Can also be .csv file or data.frame object
filename_col = "file_name",
batch_ids = "donor",
condition = "tissue",
sample_ids = 'file_name',
down_sample =F,
# sample_size = 500000,
# seed = 473,
cofactor = 5)
head(uncorrected)
uncorrected$condition
# uncorrected$sample_id
dim(uncorrected)
uncorrected<- uncorrected[,!is.na(colnames(uncorrected))]
as.data.frame(uncorrected)
# colnames(dr_umap)
# uncorrected <- dr_umap[,c( 3:26,29:32)]
dir.create('figs/batch')
all_markers
uncorrected %>%
detect_batch_effect(markers = all_markers,
batch_col = 'batch',
out_dir = 'figs/batch',
seed = 434,
name = 'Tcells')
colnames(uncorrected)
map(all_markers, ~ ggplot(uncorrected, aes_string(x = ., color = 'batch',
group = 'batch')) +
geom_density() ) %>% PG(nrow = 5) %T>% figsave('batch/batch_uncorrected_histgram.pdf', 600, 400)
uncorrected$condition
corrected <- uncorrected %>%
batch_correct(markers = all_markers,
# out_dir = 'figs/batch',
xdim = 10, ydim = 10, covar = 'condition',
norm_method = "scale", # "rank" is recommended when combining data with heavy batch effects
rlen = 20, seed = 22)
head(corrected)
start_time_8 <- Sys.time()
labels <- corrected %>%
cyCombine::create_som(rlen = 20,
xdim = 10,
ydim = 10,
seed = 22,
markers = gsub('_', '', all_markers))
end_time_8 <- Sys.time()
# Add labels
corrected <- corrected %>%
dplyr::mutate(som = labels)
map(all_markers, ~ ggplot(corrected, aes_string(x = ., color = 'batch',
group = 'batch')) +
geom_density() ) %>% PG(nrow = 5) %T>% figsave('batch/batch_corrected_histgram.pdf', 600, 400)
# Set column for evaluation of EMD (per-cluster)
celltype_col <- "som"
colnames(corrected)
# Transfer labels to uncorrected data
uncorrected <- corrected %>%
dplyr::select(id, all_of(celltype_col)) %>%
dplyr::left_join(uncorrected, by = "id")
uncorrected$som <- corrected$som
uncorrected$id <- corrected$id
# Evaluation using EMD
emd_val <- uncorrected %>%
cyCombine::evaluate_emd(corrected,
binSize = 0.1,
markers = gsub('_', '', all_markers),
cell_col = celltype_col)
# Show plots
cowplot::plot_grid(emd_val$violin, emd_val$scatterplot)
plot_density(uncorrected, corrected, ncol = 6) %T>% figsave('batch/histogram_corrected_vs_uncorrected.pdf', 400, 400)
plot1 <- plot_dimred(uncorrected, name = 'Uncorrected', type = 'umap', markers = lineage_markers)
plot2 <- plot_dimred(corrected, name = 'Corrected 8x8', type = 'umap', markers = lineage_markers)
plot3 <- plot_dimred(corrected, name = 'corrected', type = 'umap', plot = 'som',
markers = lineage_markers_2)
(rasterise(plot3,dpi = 300) +facet_wrap(~Batch))
cowplot::plot_grid( rasterise(plot1,dpi = 300) , rasterise(plot2,dpi = 300)) %>%
figsave('batch/Uncorrected_vs_batchcorrected.pdf', 400, 200)
plot1$data
(rasterise(plot1,dpi = 300) +facet_wrap(~Batch)) %T>%
figsave('batch/Uncorrected_facet4.pdf', 400, 200)
(rasterise(plot2,dpi = 300) +facet_wrap(~Batch))%T>%
figsave('batch/corrected_facet4.pdf', 400, 200)
(rasterise(plot3,dpi = 300) +facet_wrap(~Batch))%T>%
figsave('batch/corrected_facet4_fewermarker.pdf', 400, 200)
colnames(uncorrected)
colnames(corrected)
plot3$data
head(corrected)
ncol(uncorrected)
head(uncorrected)[,3:27]
rng <- colQuantiles(as.matrix(corrected[3:28]), probs = c(0.005, 0.995))
##normalize the expression matrix by :
#expression value - minimal expression value across all cells / data range
expr01 <- t((t(as.matrix(corrected[3:28])) - rng[, 1]) / (rng[, 2] - rng[, 1]))
expr01[expr01 < 0] <- 0
expr01[expr01 > 1] <- 1
TotalT_corrected <- cbind(plot3$data[,1:2], corrected,
rename_with(uncorrected[,3:28] , ~paste0(., '_uncorrected')),
rename_with(as.data.frame(expr01) , ~paste0(., '_scaled'))
) %>%
mutate(sample = paste0(batch, '_','condition')) %>%
as.data.frame()
head(TotalT_corrected)
# TotalT_corrected$sample <- paste0(TotalT_corrected$batch, '_', TotalT_corrected$condition)
Feature_rast(TotalT_corrected, 'condition', d1 = 'UMAP1', d2 = 'UMAP2', facets = 'batch', do.label = F) %T>%
figsave('four_donor_tissue_UMAP.pdf', 200, 200)
Feature_rast(TotalT_corrected, 'sample', d1 = 'UMAP1', d2 = 'UMAP2', do.label = T) %T>%
figsave('allsamples.pdf', 200, 150)
Feature_rast(TotalT_corrected, all_markers, d1 = 'UMAP1', d2 = 'UMAP2', ncol = 4, sz = 0.1) %T>%
figsave('allmarkers.pdf', 300, 400)
Feature_rast(TotalT_corrected, paste0(all_markers, '_scaled'), d1 = 'UMAP1', d2 = 'UMAP2', ncol = 4, sz = 0.1) %T>%
figsave('allmarkers_scaled.pdf', 300, 400)
saveRDS(TotalT_corrected, 'totalTcell.rds')
# SOM clustering ----------------------------------------------------------
fsom <- ReadInput(fcs_totalT_transform , transform = FALSE, scale = F)
fsom
# fsom_ns <- ReadInput(FCS_humangdT_biexp)
# replace the data in fsom with batch corrected data.
fsom$data %>% colnames()
str(fsom)
typeof(fsom$data)
fsom$scale
dim(corrected)
colnames(corrected)
panel
abcolors <- fsom$data %>% colnames() %>% as.vector()
cdata <- TotalT_corrected[, all_markers] %>% `colnames<-`(abcolors) %>% as.matrix()
fsom$data <- cdata
# build up som
# color to use
lineage_colors <- panel %>% dplyr::filter(desc %in% lineage_markers_2) %>% pull(name) %>% as.vector()
set.seed(1234)
som <- BuildSOM(fsom, colsToUse = lineage_colors)
head(som)
# Metaclustering into 20 clusters with ConsensusClusterPlus
library(ConsensusClusterPlus)
nmc <- 30
codes <- som$map$codes
t(codes) %>% head
dir.create('som_corrected')
dir.create('som_corrected/consensus_plots')
plot_outdir <- "som_corrected/consensus_plots"
mc <- ConsensusClusterPlus(t(codes), maxK = nmc, reps = 1000,
pItem = 0.9, pFeature = 1, title = plot_outdir, plot = "pdf",
clusterAlg = "hc", innerLinkage = "average", finalLinkage = "average",
distance = "euclidean", seed = 1234)
head(mc)
code_clustering1 <- mc[[17]]$consensusClass
cell_clustering1 <- code_clustering1[som$map$mapping[,1]]
# SOM with out CD4CD8 -----------------------------------------------------
lineage_markers_3 <- c(setdiff(lineage_markers_2, c('CD4', 'CD8')), 'TCRab', 'TCRgd')
lineage_colors_w4w8 <- panel %>% dplyr::filter(desc %in% lineage_markers_3) %>% pull(name) %>% as.vector()
set.seed(1234)
som2 <- BuildSOM(fsom, colsToUse = lineage_colors_w4w8)
library(ConsensusClusterPlus)
nmc <- 30
codes <- som2$map$codes
t(codes) %>% head
dir.create('som_corrected_w4w8')
dir.create('som_corrected_w4w8/consensus_plots')
plot_outdir <- "som_corrected_w4w8/consensus_plots"
mc <- ConsensusClusterPlus(t(codes), maxK = nmc, reps = 1000,
pItem = 0.9, pFeature = 1, title = plot_outdir, plot = "pdf",
clusterAlg = "hc", innerLinkage = "average", finalLinkage = "average",
distance = "euclidean", seed = 1234)
head(mc)
code_clustering2 <- mc[[17]]$consensusClass
cell_clustering2 <- code_clustering2[som2$map$mapping[,1]]
# # plot_outdir <- "FCS/exp1125/consensus_plots"
# # codes_ns <- som_ns$map$codes
# #
# # mc <- ConsensusClusterPlus(t(codes_ns), maxK = nmc, reps = 1000,
# # pItem = 0.9, pFeature = 1, title = plot_outdir, plot = "pdf",
# # clusterAlg = "hc", innerLinkage = "average", finalLinkage = "average",
# # distance = "euclidean", seed = 1234)
# #
# #
# # ## Get cluster ids for each cell
# # # choose 10 clusters according to the plot above
# #
# #
# # code_clustering2 <- mc[[15]]$consensusClass
# # cell_clustering2 <- code_clustering2[som_ns$map$mapping[,1]]
#
#
# length(cell_clustering1)
# # !!skip ##clustering by hclust --------------------------------------------------
# #complete
# #scale expression
# nrow(codes)
#
#
# celldist <- dist(codes, method = 'euclidean')
# cell_hc <- hclust(celldist, method = 'complete')
#
# plot(cell_hc)
# abline(h = 3.5, col = "red")
# abline(h = 3.9, col = "red")
#
# h1 <- cutree(cell_hc, h = 3.5)
# h2 <- cutree(cell_hc, h = 3.9)
# h3 <- cutree(cell_hc, k = 15)
#
#
# som$map$mapping
#
# cell_hcluster <- h1[som$map$mapping[,1]]
# cell_hcluster_2 <- h2[som$map$mapping[,1]]
# cell_hcluster_3 <- h3[som$map$mapping[,1]]
#
# length(cell_hcluster)
# ###assign colors
# color_clusters <- set_sample(ggplotColours(30))
#
# #average or median
# cell_hca <- hclust(celldist, method = 'average')
# plot(cell_hca)
# abline(h = 2.8, col = "red")
#
# h4 <- cutree(cell_hca, k = 15)
# cell_hcluster_4 <- h4[som$map$mapping[,1]]
#
# marker heatmap ----------------------------------------------------------
###build the function for heatmap
plot_clustering_heatmap_wrapper <- function(expr, expr01,
#alternatively
cell_clustering, color_clusters, cluster_merging = NULL){
# Calculate the median expression
expr_median <- data.frame(expr, cell_clustering = cell_clustering) %>%
group_by(cell_clustering) %>%
summarize_all(funs(median))
expr01_median <- data.frame(expr01, cell_clustering = cell_clustering) %>%
group_by(cell_clustering) %>%
summarize_all(funs(median))
# Calculate cluster frequencies
clustering_table <- as.numeric(table(cell_clustering))
# This clustering is based on the markers that were used for the main clustering
d <- dist(expr_median[, colnames(expr)], method = "euclidean")
cluster_rows <- hclust(d, method = "average")
#the heating value of heat map
expr_heat <- as.matrix(expr01_median[, colnames(expr01)])
rownames(expr_heat) <- expr01_median$cell_clustering
#mark the percentage of each cluster
labels_row <- paste0(rownames(expr_heat), " (",
round(clustering_table / sum(clustering_table) * 100, 2), "%)")
labels_col <- colnames(expr_heat)
# Row annotation for the heatmap
# I think cluster names can be changed here
annotation_row <- data.frame(cluster = factor(expr01_median$cell_clustering))
rownames(annotation_row) <- rownames(expr_heat)
###if want to change color look here?
color_clusters <- color_clusters[1:nlevels(annotation_row$cluster)]
names(color_clusters) <- levels(annotation_row$cluster)
annotation_colors <- list(cluster = color_clusters)
annotation_legend <- FALSE
####here to give new cluster names & merge clusters
#here in comment is how-to
# test <- data.frame(old_cluster = c(1:10), new_cluster = c("A","A","A","B", "A","C","C","C","D", "E"))
# test$new_cluster <- factor(test$new_cluster)
# annotation_row$cluster_mergering <- test$new_cluster
# annotation_row
if(!is.null(cluster_merging)){
cluster_merging$new_cluster <- factor(cluster_merging$new_cluster)
annotation_row$cluster_merging <- cluster_merging$new_cluster
color_clusters <- color_clusters[1:nlevels(cluster_merging$new_cluster)]
names(color_clusters) <- levels(cluster_merging$new_cluster)
annotation_colors$cluster_merging <- color_clusters
annotation_legend <- TRUE
}
# Colors for the heatmap
color <- colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = "RdYlBu")))(100)
pheatmap::pheatmap(expr_heat, color = color,
cluster_cols = FALSE, cluster_rows = cluster_rows,
labels_col = labels_col, labels_row = labels_row,
display_numbers = TRUE, number_color = "black",
fontsize = 8, fontsize_number = 8,
annotation_row = annotation_row, annotation_colors = annotation_colors,
annotation_legend = annotation_legend)
}
heatmap_orig_hcluster <- plot_clustering_heatmap_wrapper(expr = corrected[,3:27],
expr01 = expr01[,1:25],
cell_clustering = cell_clustering1,
color_clusters = ggplotColours(20))%>% ggplotify::as.ggplot()
TotalT_corrected$som_cluster <- as.factor(cell_clustering1)
TotalT_corrected$som_cluster_w4w8 <- as.factor(cell_clustering2)
Feature_rast(TotalT_corrected, c('som_cluster','som_cluster_w4w8'),d1 = 'UMAP1', d2 = 'UMAP2', facets = 'batch', sz = 0.2)
Feature_rast(TotalT_corrected, c('som_cluster','som_cluster_w4w8'),d1 = 'cUMAP_1', d2 = 'cUMAP_2', facets = 'batch', sz = 0.2)
saveRDS(TotalT_corrected, 'totalTcell_processed_dataframe.rds')
#
# heatmap_orig_merge <- plot_clustering_heatmap_wrapper(expr = expr01,
# expr01 = expr01,
# cell_clustering = cell_clustering_merging,
# color_clusters =clm ) %>% ggplotify::as.ggplot()
#
#
#alternatively, with merging clusters
#set the dataframe for cluser merging
## Find and skip duplicates
dups <- which(!duplicated(corrected[, lineage_markers]))
dups
## Data subsampling: create indices by sample
inds <- split(1:length(sample_ids), sample_ids)
inds
## How many cells to downsample per-sample
set.seed(1234)
tsne_ncells <- pmin(table(sample_ids), 10000)
## Get subsampled indices
set.seed(8964)
tsne_inds <- lapply(names(inds), function(i){
s <- sample(inds[[i]], tsne_ncells[i], replace = FALSE)
intersect(s, dups)
})
tsne_inds <- unlist(tsne_inds)
tsne_expr <- expr[tsne_inds, all_markers]
tsne_expr %>% head
expr
library(umap)
## umap embedding of 150 items in 2 dimensions
## object components: layout, data, knn, config
# Umap_withoutCD4CD8 --------------------------------------------------------------------
library(reticulate)
#Run tSNE
#position info stored in the tsne_out$Y
set.seed(1234)
# tsne_out <- Rtsne(tsne_expr, check_duplicates = FALSE, pca = FALSE )
tsne_expr
all_markers
lineage_markers_3 <- c(setdiff(lineage_markers_2, c('CD4', 'CD8')), 'TCRab', 'TCRgd')
umap_out_woCD4CD8 <- uwot::umap(TotalT_corrected[,lineage_markers_3], scale = "Z", n_neighbors = 10, ret_model = T, min_dist = 0.1)
# uwot::save_uwot(umap_out3, paste0(dir_FACS,'umapmodel'))
plot(umap_out_woCD4CD8$embedding)
#introduce UMAP without CD4 CD8 into datafrom----------------------------------------------
# umap_out$layout %>% head
TotalT_corrected <- data.frame(cUMAP_1 = umap_out_woCD4CD8$embedding[,1] ,
cUMAP_2 = umap_out_woCD4CD8$embedding[,2] ,
TotalT_corrected)
TotalT_corrected %>% colnames()
Feature_rast(TotalT_corrected,c('CD4_scaled', 'CD8_scaled', 'KLRG1_scaled',"CD45RA_scaled","CD16_scaled",
'GzmA_scaled', 'CD103_scaled','som_cluster_withoutCD4CD8'),
d1 = 'cUMAP_1', d2 = 'cUMAP_2' )
T
# CD4 and CD8 gating ------------------------------------------------------
TotalT_corrected %>% colnames()
TotalT_corrected$condition
Feature_rast(TotalT_corrected, 'condition', d1 = 'CD4', d2= 'CD8', noaxis = F, axis.number = T,facets = 'batch')
celldist <- dist(TotalT_corrected[,c('CD4', 'CD8')], method = 'euclidean')
library(fastcluster)
hc <- fastcluster::hclust(celldist,method = 'complete')
plot(hc)
abline(h = 4.5, col = 'red')
h45 <- cutree(hc, h = 4.5)
h45
TotalT_corrected$CD4CD8_cluster <- as.factor(h45)
Feature_rast(TotalT_corrected, c( 'CD4CD8_cluster'), d1 = 'CD4', d2= 'CD8', noaxis = F, axis.number = T)
CD4CD8_colors <- panel %>% dplyr::filter(desc %in% c('CD4', 'CD8')) %>% pull(name) %>% as.vector()
set.seed(1234)
CD4CD8som <- BuildSOM(fsom, colsToUse = CD4CD8_colors)
head(som)
# Metaclustering into 20 clusters with ConsensusClusterPlus
library(ConsensusClusterPlus)
nmc <- 5
codes <- CD4CD8som$map$codes
t(codes) %>% head
dir.create('som_48')
dir.create('som_48/consensus_plots')
plot_outdir <- "som_48/consensus_plots"
mc <- ConsensusClusterPlus(t(codes), maxK = nmc, reps = 1000,
pItem = 0.9, pFeature = 1, title = plot_outdir, plot = "pdf",
clusterAlg = "hc", innerLinkage = "average", finalLinkage = "average",
distance = "euclidean", seed = 1234)
head(mc)
code_48 <- mc[[3]]$consensusClass
cell_48 <- code_48[CD4CD8som$map$mapping[,1]]
TotalT_corrected$CD4CD8_cluster <- as.factor(cell_48)
Feature_rast(TotalT_corrected, c( 'CD4CD8_cluster'), d1 = 'CD4', d2= 'CD8', noaxis = F, axis.number = T)
# plot(cell_hc)
# abline(h = 3.5, col = "red")
# abline(h = 3.9, col = "red")
#
# h1 <- cutree(cell_hc, h = 3.5)
# h2 <- cutree(cell_hc, h = 3.9)
# h3 <- cutree(cell_hc, k = 15)
#
#