-
Notifications
You must be signed in to change notification settings - Fork 0
/
A01 HUMANIZED Flow.R
1005 lines (824 loc) · 40.7 KB
/
A01 HUMANIZED Flow.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
library(flowCore)
library(flowWorkspace)
library(ggcyto)
library(flowAI)
library(gridExtra)
library(tidyverse)
library(flowStats)
library(CytoML)
library(Rtsne)
library(FlowSOM)
library(ggplot2)
library(ggpubr)
########### 1. Generate Counts From Manual Gating ###########
###########
#plot_dir <- "C:/Users/edmondsonef/Desktop/Humanized/Flow/Figures/Manual Gating Plots/"
data_dir <- "C:/Users/edmondsonef/Desktop/Humanized/Flow/"
#study_dir <- "1-05Jan2022/"
#study_dir <- "2-02Feb2022/"
#study_dir <- "3-15Feb2022 - NSG/"
#study_dir <- "4-28Feb2022/"
#study_dir <- "5-02Mar2022/"
#study_dir <- "6-10Mar2022/"
study_dir <- "7-24Mar2022/"
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15679 06Jan2022 Simone.wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15701 02Feb2022 Simone.wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15708 15Feb2022 Simone.wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15716 28Feb2022 Simone.wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15719 02Mar2022 Simone.wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15726 10Mar2022 Simone.wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15738 23Mar2022 LASP.wsp"))
ws <- open_flowjo_xml(paste0(data_dir,study_dir,".wsp"))
ws <- open_flowjo_xml(paste0(data_dir,study_dir,".wsp"))
ws <- open_flowjo_xml(paste0(data_dir,study_dir,".wsp"))
ws <- open_flowjo_xml(paste0(data_dir,study_dir,".wsp"))
#ws <- open_flowjo_xml(paste0(data_dir,study_dir,"15738 24Mar2022 LASP 2nd day.wsp"))
ws
fj_ws_get_samples(ws, group_id = c(5))
gs <- flowjo_to_gatingset(ws, name = 5, path=paste0(data_dir,study_dir))
gs_get_pop_paths(gs)
recompute(gs)
#####
#####http://bioconductor.org/help/course-materials/2017/BioC2017/Day2/Workshops/CyTOF/doc/cytofWorkflow_BioC2017workshop.html
gs_get_pop_paths(gs)[c(6,10,13,17,18,22,25,26,27,30)]
counts_table <- gs_pop_get_count_fast(gs, format = "long", subpopulations = gs_get_pop_paths(gs)[c(6,10,13,17,18,22,25,26,27,30)])
counts_table
counts_table <- counts_table %>% pivot_wider(id_cols = name,
names_from = Population,
values_from = c("Count", "ParentCount"))
write.csv(counts_table, "C:/Users/edmondsonef/Desktop/HumanizedPROP.csv")
counts_table <- read.csv("C:/Users/edmondsonef/Desktop/HumanizedPROP.csv")
library(dplyr)
counts_table_t <- counts_table[-1] %>% t() %>% as.data.frame() %>% setNames(counts_table[,1])
props_table <- t(t(counts_table_t) / colSums(counts_table_t[])) * 100
props_table_t <- props_table[] %>% t() %>% as.data.frame() %>% setNames(row.names(props_table))
counts <- as.data.frame.matrix(counts_table_t)
props <- as.data.frame.matrix(props_table)
write.csv(props, "C:/Users/edmondsonef/Desktop/props.csv")
props <- read.csv("C:/Users/edmondsonef/Desktop/props.csv", header = T, stringsAsFactors = F)
library(lme4)
library(multcomp)
props <- data.frame(props[,-1], row.names = props[,1])
ggdf <- reshape2::melt(data.frame(cluster = rownames(props), props),
id.vars = "cluster", value.name = "proportion", variable.name = "sample_id")
write.csv(ggdf, "C:/Users/edmondsonef/Desktop/ggdf.csv")
ggdf <- read.csv("C:/Users/edmondsonef/Desktop/ggdf.csv", header = T, stringsAsFactors = F)
color_clusters <- c("#DC050C", "#FB8072", "#1965B0", "#7BAFDE", "#882E72",
"#B17BA6", "#FF7F00", "#FDB462", "#E7298A", "#E78AC3",
"#33A02C", "#B2DF8A", "#55A1B1", "#8DD3C7", "#A6761D",
"#E6AB02", "#7570B3", "#BEAED4", "#666666", "#999999",
"#aa8282", "#d4b7b7", "#8600bf", "#ba5ce3", "#808000",
"#aeae5c", "#1e90ff", "#00bfff", "#56ff0d", "#ffff00")
plot <- ggplot(ggdf, aes(x = sample_id, y = proportion, fill = cluster)) +
geom_bar(stat = "identity") +
facet_wrap(~ tissue, scales = "free_x") +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
scale_fill_manual(values = color_clusters)
setwd("C:/Users/edmondsonef/Desktop/R-plots/")
tiff("6-10Mar_blood_marrow_spl.tiff", units="in", width=10, height=7, res=600)
plot
dev.off()
#########
######### STACKED BAR CHART
########
png(paste0(plot_dir,"7-1sp-24Mar2022-01_Gates.png"), width = 3000, height =1800,res = 165)
plot(gs)
dev.off()
png(paste0(plot_dir,"7-1sp-24Mar2022-02_scatter.png"), width = 3000, height =1800,res = 165)
autoplot(gs, "/scatter")
dev.off()
png(paste0(plot_dir,"7-1sp-24Mar2022-03_scatter-sing.png"), width = 3000, height =1800,res = 165)
autoplot(gs, "/scatter/sing")
dev.off()
png(paste0(plot_dir,"7-1sp-24Mar2022-04_hCD45.png"), width = 3000, height =2400,res = 165)
autoplot(gs, "hCD45+")
dev.off()
png(paste0(plot_dir,"7-1sp-24Mar2022-05_CD4intermediate.png"), width = 3000, height =2400,res = 165)
autoplot(gs, "CD4 intermediate ?")
dev.off()
png(paste0(plot_dir,"7-1BM-24Mar2022-05_huCD45+ CD33+.png"), width = 3000, height =2400,res = 165)
autoplot(gs, "huCD45+ CD33+")
dev.off()
png(paste0(plot_dir,"7-1BM-24Mar2022-05_CD3-CD4intermediate.png"), width = 3000, height =2400,res = 165)
autoplot(gs, "CD4 intermediate ?")
dev.off()
png(paste0(plot_dir,"7-1BM-24Mar2022-06_CD19.png"), width = 3000, height =2400,res = 165)
autoplot(gs, "Q1: CD3- , CD19 [APC-F750]+")
dev.off()
png(paste0(plot_dir,"7-1BM-24Mar2022-07_CD3.png"), width = 3000, height =2400,res = 165)
autoplot(gs, "Q3: CD3+ , CD19 [APC-F750]-")
dev.off()
########### 2. Preprocessing and QC ###########
########### ###########
# 2. Define the general and preprocessing variables
#study_dir <- "1-05Jan2022/"
#study_dir <- "2-02Feb2022/"
#study_dir <- "3-15Feb2022/"
#study_dir <- "4-28Feb2022/"
#study_dir <- "5-02Mar2022/"
#study_dir <- "6-10Mar2022/"
study_dir <- "7-24Mar2022/"
data_dir <- "C:/Users/edmondsonef/Desktop/Humanized/Flow/"
file_pattern <- "\\d.fcs"
reference_file <- read.FCS(paste0(data_dir,study_dir,'Samples 24Mar2022_Tube_020 Animal 112 BMC_047.fcs'), truncate_max_range = FALSE)
reference_marker <- "PE-A" # Scatter values will be scaled to have the same range
markers_of_interest <- c("BB515-A",
"BB700-P-A",
"APC-A",
"APC-Cy7-A",
"BV421-A",
"BV786-A",
"BUV395-A",
"BUV805-A",
"PE-A",
"PE-CF594-A",
"PE-Cy7-A")
live_gate <- flowCore::polygonGate(filterId = "Live",
.gate = matrix(data = c(60000, 100000, 150000,
250000, 250000, 60000,
60000, 1.6, 1.9, 2.5,
2.5, -0.3, -0.3, 1.6),
ncol = 2,
dimnames = list(c(),
c("FSC-A",
"APC-Cy7-A"))))
# 3. Define and create the directories
dir_prepr <- paste0(data_dir,study_dir,"1-Preprocessed/") #where the preprocessed data will be stored
dir_QC <- paste0(data_dir,study_dir,"2-QC/") #where the data QC results will be stored
dir_RDS <- paste0(data_dir,study_dir,"3-RDS/") #where the R objects will be stored
dir_results <- paste0(data_dir,study_dir,"4-Results/") #where the results will be stored
dir_raw <- paste0(data_dir,study_dir) #where the raw data is located
path_comp <- "C:/Users/edmondsonef/Desktop/0-Autospill/6-10Mar2022/autospill_compensation.csv" #where comp matrix is located
for (path in c(dir_prepr, dir_QC, dir_RDS, dir_results)){
dir.create(path)
}
# 4. Prepare some additional information for preprocessing the files
# given the variable choices of step 2.
files <- list.files(path = dir_raw, pattern = "Samples")
files
channels_of_interest <- GetChannels(object = reference_file,
markers = markers_of_interest,
exact = FALSE)
compensation_matrix <- read.csv(path_comp,
check.names = FALSE, row.names = 1)
colnames(compensation_matrix) <- sub(" :: .*", "",
colnames(compensation_matrix))
# Compute transformation list
ff_m <- PeacoQC::RemoveMargins(reference_file, channels_of_interest)
names(ff_m)
exprs(ff_m)
each_col(ff_m, median)
ff_c <- flowCore::compensate(ff_m, compensation_matrix)
translist <- estimateLogicle(ff_c, colnames(compensation_matrix))
ff_t <- flowCore::transform(ff_c, translist)
q5_goal <- quantile(exprs(ff_t)[,reference_marker], 0.05)
q95_goal <- quantile(exprs(ff_t)[,reference_marker], 0.95)
q5_SSCA <- quantile(exprs(ff_t)[,"SSC-A"], 0.05)
q95_SSCA <- quantile(exprs(ff_t)[,"SSC-A"], 0.95)
SSCA_a <- (q95_goal - q5_goal) / (q95_SSCA - q5_SSCA)
SSCA_b <- q5_goal - q5_SSCA * (q95_goal - q5_goal) / (q95_SSCA - q5_SSCA)
translist <- c(translist,
transformList("SSC-A", flowCore::linearTransform(a = SSCA_a,
b = SSCA_b)))
translist
# 5. Read the first fcs file into a flowframe
ff <- read.FCS(paste0(dir_raw, files[7]), truncate_max_range = FALSE)
# 6. Remove margin events
ff_m <- PeacoQC::RemoveMargins(ff, channels_of_interest)
# 7. Compensate
ff_c <- flowCore::compensate(ff_m, compensation_matrix)
# 8. Transform, logicle for marker channels, linear for scatter channel
ff_t <- flowCore::transform(ff_c, translist)
# 9. Remove doublets and filter live cells
ff_s <- PeacoQC::RemoveDoublets(ff_t)
selected_live <- flowCore::filter(ff_s, live_gate)
ff_l <- ff_s[selected_live@subSet, ]
# 10. QC with PeacoQC
PQC <- PeacoQC::PeacoQC(ff = ff_s,
channels = channels_of_interest,
plot = TRUE, save_fcs = FALSE,
output_directory = dir_QC)
# 11. Save the preprocessed data
write.FCS(PQC$FinalFF,
file = paste0(dir_prepr, files[1]))
# 12. Visualize the preprocessing
filter_plot <- function(ff_pre, ff_post, title, channel_x, channel_y){
df <- data.frame(x = exprs(ff_pre)[,channel_x],
y = exprs(ff_pre)[,channel_y])
i <- sample(nrow(df), 10000)
if (!"Original_ID" %in% colnames(exprs(ff_pre))) {
ff_pre@exprs <- cbind(ff_pre@exprs,
Original_ID = seq_len(nrow(ff_pre@exprs)))
}
p <- ggplot(df[i,], aes(x = x, y = y)) +
geom_point(size = 0.5,
color = ifelse(exprs(ff_pre)[i,"Original_ID"] %in%
exprs(ff_post)[,"Original_ID"], 'blue', 'red')) +
xlab(GetMarkers(ff_pre, channel_x)) +
ylab(GetMarkers(ff_pre, channel_y)) +
theme_minimal() + theme(legend.position = "none") +
ggtitle(title)
return(p)
}
to_plot <- list(list(ff_pre = ff,
ff_post = ff_m,
title = "Removed margin events",
channel_x = "BUV395-A",
channel_y = "BUV805-A"),
list(ff_pre = ff_t,
ff_post = ff_s,
title = "Removed doublets",
channel_x = "FSC-A",
channel_y = "FSC-H"),
list(ff_pre = ff_s,
ff_post = ff_l,
title = "Removed debris and dead cells",
channel_x = "FSC-A",
channel_y = "BUV395-A"),
list(ff_pre = ff_l,
ff_post = PQC$FinalFF,
title = "Removed low quality events",
channel_x = "Time",
channel_y = "BUV395-A"))
plot_list <- list()
for (plot in to_plot) {
plot_list[[length(plot_list) + 1]] <- filter_plot(ff_pre = plot$ff_pre,
ff_post = plot$ff_post,
title = plot$title,
channel_x = plot$channel_x,
channel_y = plot$channel_y)
}
png(paste0(dir_QC, sub("fcs", "png", files[1])), width = 1920)
print(ggpubr::ggarrange(plotlist = plot_list, nrow = 1))
dev.off()
# 13. Run the preprocessing pipeline for all the files
for (file in files){
ff <- read.FCS(paste0(dir_raw, file), truncate_max_range = FALSE)
ff_m <- PeacoQC::RemoveMargins(ff, channels_of_interest)
ff_c <- flowCore::compensate(ff_m, compensation_matrix)
ff_t <- flowCore::transform(ff_c, translist)
ff_s <- PeacoQC::RemoveDoublets(ff_t)
selected_live <- flowCore::filter(ff_s, live_gate)
ff_l <- ff_s[selected_live@subSet, ]
PQC <- PeacoQC::PeacoQC(ff = ff_l,
channels = channels_of_interest,
plot = TRUE, save_fcs = FALSE,
output_directory = dir_QC)
write.FCS(PQC$FinalFF,
file = paste0(dir_prepr, file))
# to_plot <- list(list(ff_pre = ff,
# ff_post = ff_m,
# title = "Removed margin events",
# channel_x = "BUV395-A",
### channel_y = "BUV805-A"),
# list(ff_pre = ff_t,
### ff_post = ff_s,
# title = "Removed doublets",
# channel_x = "FSC-A",
# channel_y = "FSC-H"),
# list(ff_pre = ff_s,
# ff_post = ff_l,
# title = "Removed debris and dead cells",
# channel_x = "FSC-A",
# channel_y = "BUV395-A"),
# list(ff_pre = ff_l,
### ff_post = PQC$FinalFF,
# title = "Removed low quality events",
# channel_x = "Time",
# channel_y = "BUV395-A"))
# plot_list <- list()
# for (plot in to_plot) {
# plot_list[[length(plot_list) + 1]] <- filter_plot(ff_pre = plot$ff_pre,
# ff_post = plot$ff_post,
# title = plot$title,
# channel_x = plot$channel_x,
# channel_y = plot$channel_y)
# }
png(paste0(dir_QC, sub("fcs", "png", file)), width = 1920)
print(ggpubr::ggarrange(plotlist = plot_list, nrow = 1))
dev.off()
}
########### 3. Additional QC ###########
########### ###########
# 14. Perform quality control between all files
# 14.(A) Plot the signal per channel and per file
# 14.(A)(i) Define the variables
#file_names <- sub(".*15_(.*).fcs", "\\1", files)
write.csv(files, paste0(dir_raw,"names.csv"))
library(readxl)
data <- read_excel("C:/Users/edmondsonef/Desktop/Humanized/Flow/Group.Names.xlsx",
sheet = "7-24Mar")
file_groups <- data$Group
file_groups
# 14.(A)(ii) Make the overview plot
PlotFileScatters(input = paste0(dir_prepr, files),
channels = channels_of_interest,
#names = file_groups,
legend = T,
groups = file_groups, nrow = 4,
plotFile = paste0(dir_QC, "file_scatters.png"))
# 14.(B) Perform principal commponent analysis (PCA)
# 14.(B)(i) Retrieve the median marker expression values per file
medians <- matrix(data = NA,
nrow = length(files), ncol = length(channels_of_interest),
dimnames = list(files, channels_of_interest))
for (file in files){
ff <- read.FCS(paste0(dir_prepr, file))
medians[file,] <- apply(exprs(ff)[,channels_of_interest], 2, median)
}
# 14.(B)(ii) Calculate the PCs
pc <- prcomp(medians, scale. = TRUE)
# 14.(B)(iii) Visualize the PCs
ggplot(data.frame(pc$x[,1:2], file_groups)) +
geom_point(aes(x= PC1, y = PC2, col = file_groups)) +
theme_minimal()
ggsave(paste0(dir_QC, "file_PCA.png"), width = 10)
########### 4. Create Aggegregate Files ###########
########### ###########
data_dir <- "C:/Users/edmondsonef/Desktop/Humanized/Flow/"
#study_dir <- "1-05Jan2022/"
#study_dir <- "2-02Feb2022/"
#study_dir <- "3-15Feb2022/"
#study_dir <- "4-28Feb2022/"
#study_dir <- "5-02Mar2022/"
#study_dir <- "6-10Mar2022/"
study_dir <- "7-24Mar2022/"
dir_prepr <- paste0(data_dir,study_dir,"1-Preprocessed/") #where the preprocessed data will be stored
dir_QC <- paste0(data_dir,study_dir,"2-QC/") #where the data QC results will be stored
dir_RDS <- paste0(data_dir,study_dir,"3-RDS/") #where the R objects will be stored
dir_results <- paste0(data_dir,study_dir,"4-Results/") #where the results will be stored
dir_raw <- paste0(data_dir,study_dir) #where the raw data is located
#dir_group <- paste0(dir_raw,"/1-Preprocessed/NSG/")
#dir_group <- paste0(dir_raw,"/1-Preprocessed/NSG-IL15/")
dir_group <- paste0(dir_raw,"/1-Preprocessed/BM/")
#dir_group <- paste0(dir_raw,"/1-Preprocessed/")
# 15. Choose the number of cells to include in the aggregate file
n <- 700000
# 16. Make an aggregate file
set.seed(2020)
files <- list.files(path = dir_group, pattern = "Samples")
files
paste0(dir_group, files)
agg <- AggregateFlowFrames(paste0(dir_group, files),
cTotal = n,
writeOutput = TRUE,
outputFile = paste0(dir_group, "aggregate.fcs"))
########### 5. Train FlowSOM model ###########
########### ###########
#agg <- read.FCS(paste0(dir_group,'aggregate.fcs'), truncate_max_range = FALSE)
#Level 1 - create model to separate human cells from mouse
#SOM_x <- 10
#SOM_y <- 10
n_meta <- 10
seed <- 2020
scaling <- FALSE
#scaling <- TRUE
###All...###
###All...###
###All...###
fsom <- FlowSOM(input = agg,
scale = F,
transform = T,
toTransform = c(7:17),
colsToUse = c(7:17),
seed = seed,
nClus = n_meta)
PlotStars(fsom = fsom,
backgroundValues = fsom$metaclustering)
tsne <- Rtsne::Rtsne(fsom$map$codes, perplexity = 6)
PlotStars(fsom = fsom, view = tsne$Y,
backgroundValues = fsom$metaclustering)
FlowSOMmary(fsom = fsom,
plotFile = paste0(dir_group, "ALL_fsom.trans_summary.pdf"))
saveRDS(fsom, paste(dir_RDS, "fsom.rds"))
fsom$prettyColnames
QueryStarPlot(fsom, query="BUV805-A")
ManualVector()
QueryMultiple(fsom = fsom_level1, cellTypes = )
###All...###
###All...###
###All...###
###All...###
fsom_level1 <- FlowSOM(input = agg,
scale = F,
transform = T,
toTransform = c(7:17),
colsToUse = c("BUV395-A","BUV805-A"),
seed = seed,
nClus = 8)
PlotLabels(fsom_level1, labels = fsom_level1$metaclustering)
p <- PlotMarker(fsom_level1, "BUV805-A")
print(p, newpage = T)
p <- PlotMarker(fsom_level1, "BUV395-A")
print(p, newpage = T)
Plot2DScatters(fsom = fsom_level1,
channelpairs = list(c("BUV805-A", "BUV395-A")),
metaclusters = 1:8,
plotFile = paste0(dir_group, "mCD45-hCD45_level1.png"))
FlowSOMmary(fsom = fsom_level1,
plotFile = paste0(dir_group, "L1_fsom_summary.pdf"))
saveRDS(fsom_level1, paste(dir_RDS, "fsom_level1.rds"))
#MC 1 and 5 are the huCD45+
#MC 2, 3, and 4 are the mCD45+
# Subset the original fcs file
fsom_tmp <- NewData(fsom_level1, agg)
clustering <- GetMetaclusters(fsom_tmp)
agg_tmp_hCD45 <- agg[clustering %in% c(1,2,4,5),]
#agg_tmp_mCD45 <- agg[clustering %in% c(),]
#HUMAN: Create hCD45 subset
fsom_level2_hCD45 <- FlowSOM(input = agg_tmp_hCD45,
scale = F,
colsToUse = c(4,7:17),
#colsToUse = c(7:12,15:17),
seed = 2020)
p <- PlotMarker(fsom_level2_hCD45, "BUV805-A")
print(p, newpage = T)
p <- PlotMarker(fsom_level2_hCD45, "BUV395-A")
print(p, newpage = T)
PlotStars(fsom = fsom_level2_hCD45,
backgroundValues = fsom_level2_hCD45$metaclustering)
FlowSOMmary(fsom = fsom_level2_hCD45,
plotFile = paste0(dir_group, "L2_hCD45_fsom_summary.pdf"))
saveRDS(fsom_level2_hCD45, paste(dir_RDS, "fsom_level2_hCD45.rds"))
#MOUSE: Create mCD45 subset
fsom_level2_mCD45 <- FlowSOM(input = agg_tmp_mCD45,
scale = F,
colsToUse = c(7:17),
seed = 2020)
saveRDS(fsom_level2_mCD45, paste(dir_RDS, "fsom_level2_mCD45.rds"))
FlowSOMmary(fsom = fsom_level2_mCD45,
plotFile = paste0(dir_group, "L2_mCD45_fsom_summary.pdf"))
########### 6. Test Quality ###########
########### ###########
fsom <- fsom_level2_hCD45
agg <- agg_tmp_hCD45
# 20. Check the FlowSOM quality
# 20.(A) Make 2D scatter plots
# 20.(A)(i) Specify the parameters
fsom$prettyColnames
channel_pairs = list(c("FSC-A", "SSC-A"),
c("BB700-P-A", "BB515-A"),
c("BV421-A", "APC-Cy7-A"),
c("APC-A", "BV786-A"),
c("PE-CF594-A", "BV786-A"),
c("BV786-A", "PE-A"),
c("BUV805-A", "BUV395-A"))
metaclusters_of_interest <- seq_len(n_meta)
clusters_of_interest <- NULL
# 20.(A)(ii) Make the 2D scatter plots
Plot2DScatters(fsom = fsom,
channelpairs = channel_pairs,
metaclusters = metaclusters_of_interest,
clusters = clusters_of_interest,
plotFile = paste0(dir_group, "fsom_2D_scatters.png"))
########### 7. Test with Manual Gating ###########
###########
fsom <- fsom_level2_hCD45
agg <- agg_tmp_hCD45
fsom$prettyColnames
#wspFile = "C:/Users/edmondsonef/Desktop/Humanized/Flow/5-02Mar2022/15719 02Mar2022 Simone.wsp"
#wspFile = "C:/Users/edmondsonef/Desktop/Humanized/Flow/2-02Feb2022/15701 02Feb2022 Simone.wsp"
wspFile = "C:/Users/edmondsonef/Desktop/Humanized/Flow/6-10Mar2022/15726 10Mar2022 Simone.wsp"
wspFile = "C:/Users/edmondsonef/Desktop/Humanized/Flow/7-24Mar2022/15738 24Mar2022 LASP 2nd day.wsp"
ws <- open_flowjo_xml(wspFile)
ws
fj_ws_get_samples(ws, group_id = 7)
files <- list.files(path = dir_group, pattern = "Samples")
files
# 20.(B) Check the consistency with manual labeling
# 20.(B)(i) Extract the gating information from the wsp file
gating <- GetFlowJoLabels(files = files, cellTypes = "hCD45+",
wspFile = wspFile, group =7,
path = dir_raw, additional.sampleID = TRUE)
####*EFE TIP: PHYSICALLY REMOVE CONTROLS, etc####
# 20.(B)(ii) Get an overview of the gatenames and define the cell types of interest
print(levels(gating[[1]][["manual"]]))
cell_types_of_interest <- c(#"Unlabeled",
#"hCD45+",
"Q6: CD3+ , CD4 [PCP55]+",
"Q7: CD3+ , CD4 [PCP55]-",
"Q8: CD3- , CD4 [PCP55]-",
"Q9: CD3- , CD8 [FITC]+",
"Q10: CD3+ , CD8 [FITC]+",
"Q11: CD3+ , CD8 [FITC]-",
"Q12: CD3- , CD8 [FITC]-",
"Q13: CD3- , CD19 [AFire750]+",
"Q14: CD3+ , CD19 [AFire750]+",
"Q15: CD3+ , CD19 [AFire750]-",
"Q16: CD3- , CD19 [AFire750]-",
"Q17: CD3- , CD56+",
"Q18: CD3+ , CD56+",
"Q19: CD3+ , CD56-",
"Q20: CD3- , CD56-",
"Q29: CD66b [PEDazz]- , CD11b [AF647]+",
"Q30: CD66b [PEDazz]+ , CD11b [AF647]+",
"Q31: CD66b [PEDazz]+ , CD11b [AF647]-",
"Q32: CD66b [PEDazz]- , CD11b [AF647]-",
"Q33: CD33- , CD11b [AF647]+",
"Q34: CD33+ , CD11b [AF647]+",
"Q35: CD33+ , CD11b [AF647]-",
"Q36: CD33- , CD11b [AF647]-",
"Q37: CD25- , CD3+",
"Q38: CD25+ , CD3+",
"Q39: CD25+ , CD3-",
"Q40: CD25- , CD3-")
cell_types_of_interest <- c("hCD45+", "Q6: CD3+ , CD4 [PCP55]+",
"Q10: CD3+ , CD8 [FITC]+",
"Q13: CD3- , CD19 [AFire750]+",
"Q30: CD66b [PEDazz]+ , CD11b [AF647]+",
"Q34: CD33+ , CD11b [AF647]+")
cell_types_of_interest <- c("Q15: CD3+ , CD19 [AFire750]-",
"Q31: CD66b [PEDazz]+ , CD11b [AF647]-",
"Q10: CD3+ , CD8 [FITC]+",
"Q17: CD3- , CD56+",
"Q34: CD33+ , CD11b [AF647]+","Q6: CD3+ , CD4 [PCP55]+",
"Q13: CD3- , CD19 [AFire750]+",
"Q29: CD66b [PEDazz]- , CD11b [AF647]+")
# 20.(B)(iii) Compile the labels of the aggregate file
aggregate_labels <- c()
for (file in unique(exprs(agg)[, "File"])) {
aggregate_labels <- c(aggregate_labels,
as.character(ManualVector(gating[[file]][["matrix"]],
cell_types_of_interest)
[exprs(agg)[, "Original_ID"]
[exprs(agg)[, "File"] == file]]))
}
# 20.(B)(iv) Show the manual labeling on the FlowSOM tree
PlotPies(fsom = fsom,
cellTypes = factor(aggregate_labels, levels = c("Unlabeled",
cell_types_of_interest)))
ggsave(paste0(dir_group, "Human_fsom_Labeled.pdf"))
# 19.(B)(v) Calculate the purity of the FlowSOM clustering
Purity(realClusters = aggregate_labels,
predictedClusters = GetClusters(fsom))
# 20.(C) Inspect the file contribution per cluster
# 20.(C)(i) Specify a color vector (optional)
file_colors <- c("#990000", "#cc0000", "#ff0000", #Different shades within the groups
"#1d1d77", "#2b3b92", "#3859ac", "#4677c7")
file_colors <- c("#990000", "#4677c7")
# 20.(C)(ii) Show the file contribution
p <- PlotPies(fsom = fsom,
cellTypes = factor(files[fsom$data[,"File"]]),
#cellTypes = cell_types_of_interest,
colorPalette = file_colors)
AddStarsPies(p = p, # Legend to show how it should be
arcs = data.frame(
x0 = rep(0, length(files)),
y0 = rep(0, length(files)),
start = seq(0, 2 * pi, length.out = 8)[-8],
end = seq(0, 2 * pi, length.out = 8)[-1],
value = rep(1, length(files)),
Markers = files),
colorPalette = file_colors)
ggsave(paste0(dir_group, "fsom_filecontribution.pdf"))
PlotManualBars(fsom, list_insteadof_plots = T,
manualVector = factor(aggregate_labels, levels = c(cell_types_of_interest)))
ggsave(paste0(dir_group, "fsom_filecontribution.pdf"))
########## 8. Discovery and downstream analysis ###########
##########
fsom <- readRDS("C:/Users/edmondsonef/Desktop/Humanized/Flow/6-10Mar2022/3-RDS/ fsom_level2_hCD45.rds")
fsom <- readRDS("C:/Users/edmondsonef/Desktop/Humanized/Flow/7-24Mar2022/3-RDS/ fsom_level2_hCD45.rds")
# 21. Explore the FlowSOM result
# 21.(B) Look for nodes with a specific pattern
# 21.(B)(i) Specify the query
query <- list("B cells" = c("CD19 [APC-F750]" = "high", "CD3" = "low"),
#"Activated T cells" = c("CD3" = "high", "CD25"="high"),
"CD11b-hi/CD66b-hi" = c("CD66b [PE-Dazz]" = "high","CD11b [AF647]" = "high"),
"CD11b-hi/CD66-lo" = c("CD11b [AF647]" = "high","CD66b [PE-Dazz]" ="low"),
"CD33-hi/CD11b-hi/" = c("CD33"="high", "CD11b [AF647]"="high"),
"CD33-hi/CD11b-hi" = c("CD33"="high", "CD11b [AF647]"="high"),
"CD33-hi/CD11b-hi" = c("CD33"="high", "CD11b [AF647]"="high"),
"CD33-hi/CD11b-lo" = c("CD33"="high", "CD11b [AF647]"="low"),
#"B cells Activated" = c("CD19 [APC-F750]" = "high", "CD25"="high"),
#"Mouse CD45+" = c("mCD45" = "high"),
#"Human CD45+" = c("huCD45" = "high"),
"NK Cell" = c("CD56" = "high", "CD3" = "low"),
"NK T Cell" = c("CD56" = "high", "CD3" = "high"),
#"CD4 T Cell Activated" = c("CD4 [PerCPCy55]" = "high", "CD3"="high", "CD25"="high"),
"CD4 T Cell" = c("CD4 [PerCPCy55]" = "high", "CD3"="high"),
"CD8 T Cell" = c("CD8 [FITC]" = "high", "CD3"="high"))#,
#"CD8 T Cell Activated" = c("CD8 [FITC]" = "high", "CD3"="high", "CD25"="high"))#,
#"T cells" = c("CD3" = "high"))
# 21.(B)(ii) Retrieve the cluster labels based on the query
labels <- QueryMultiple(fsom = fsom,
cellTypes = query,
plotFile = paste0(dir_group, "fsom_QueryStarPlot.pdf"))
# 21.(B)(iii) Show the retrieved labels on the FlowSOM tree
#library(RColorBrewer)
#display.brewer.all()
PlotVariable(fsom = fsom,
colorPalette = brewer.pal(n = 10, name = "Paired"),
variable = labels)
ggsave(paste0(dir_results, "fsom_query.pdf"))
########## 9. Compare Groups ###########
##########
data_dir <- "C:/Users/edmondsonef/Desktop/Humanized/Flow/"
#study_dir <- "1-05Jan2022/"
#study_dir <- "2-02Feb2022/"
#study_dir <- "3-15Feb2022/"
#study_dir <- "4-28Feb2022/"
#study_dir <- "5-02Mar2022/"
#study_dir <- "6-10Mar2022/"
study_dir <- "7-24Mar2022/"
dir_prepr <- paste0(data_dir,study_dir,"1-Preprocessed/") #where the preprocessed data will be stored
dir_QC <- paste0(data_dir,study_dir,"2-QC/") #where the data QC results will be stored
dir_RDS <- paste0(data_dir,study_dir,"3-RDS/") #where the R objects will be stored
dir_results <- paste0(data_dir,study_dir,"4-Results/") #where the results will be stored
dir_raw <- paste0(data_dir,study_dir) #where the raw data is located
#dir_group <- paste0(dir_raw,"/1-Preprocessed/NSG/")
#dir_group <- paste0(dir_raw,"/1-Preprocessed/NSG-IL15/")
dir_group <- paste0(dir_raw,"/1-Preprocessed/BM/")
#dir_group <- paste0(dir_raw,"/1-Preprocessed/")
files <- list.files(path = dir_group, pattern = "Samples")
files
fsom <- readRDS("C:/Users/edmondsonef/Desktop/Humanized/Flow/6-10Mar2022/3-RDS/ fsom_level2_hCD45.rds")
fsom <- readRDS("C:/Users/edmondsonef/Desktop/Humanized/Flow/7-24Mar2022/3-RDS/ fsom_level2_hCD45.rds")
# 22. Get features per fcs file
# Specify the variables of interest
types <- c("counts", "percentages", "MFIs")
MFIs <- c("CD3", "CD19 [APC-F750]", "huCD45",
"CD8 [FITC]","CD56","CD25","CD33",
"CD66b [PE-Dazz]","CD11b [AF647]","CD4 [PerCPCy55]")
MFIs <- c("CD56")
# Get the features
features <- GetFeatures(fsom = fsom,
files = paste0(dir_group, files),
filenames = files,
type = types,
MFI = MFIs)
file_names = paste0(dir_group, files)
fsom <- fsom_level2_hCD45
# 23. Define the groups and feature you would want to compare.
feature <- "MFIs"
stat <- "fold changes"
grouplist = list("NSG-IL15" = files[1:4], "NSG" = files[5:8])
# 24. Compare the 2 groups of interest
stats <- GroupStats(features$cluster_MFIs,
#groups = grouplist)
groups = list("NSG-IL15" = files[1:4], "NSG" = files[5:8]))
# 25. Show the findings of step 24 on the trees
# Define the plotting variables
stat_levels <- c(paste0(names(grouplist)[2], " underrepresented compared to ",
names(grouplist)[1]),
paste0(names(grouplist)[1], " underrepresented compared to ",
names(grouplist)[2]),
"--")
colors <- c("blue", "red", "white")
# Show statistical findings on FlowSOM trees
cluster_stat <- stats[stat,]
cluster_stat <- factor(ifelse(cluster_stat < -2.5, stat_levels[1],
ifelse(cluster_stat > 2.5, stat_levels[2],
stat_levels[3])),
levels = stat_levels)
cluster_stat[is.na(cluster_stat)] <- stat_levels[3]
gr_1 <- PlotStars(fsom = fsom, title = names(grouplist)[1],
nodeSizes = stats[paste0("medians ", names(grouplist)[1]),],
backgroundValues = cluster_stat,
backgroundColors = colors,
list_insteadof_ggarrange = TRUE)
gr_2 <- PlotStars(fsom = fsom, title = names(grouplist)[2],
nodeSizes = stats[paste0("medians ", names(grouplist)[2]),],
backgroundValues = cluster_stat,
backgroundColors = colors,
list_insteadof_ggarrange = TRUE)
ggpubr::ggarrange(plotlist = list(gr_1$tree, gr_2$tree, gr_2$starLegend,
gr_2$backgroundLegend),
heights = c(3,1))
ggsave(paste0(dir_results, "NSG_vs_IL15_fsom_groups.pdf"), width = 10, height = 7.5)
p <- PlotVariable(fsom, title = "Fold change group 1 vs. group 2",
variable = C_stats["fold changes", ])
print(p, newpage = FALSE)
########## 10. Map new data onto FlowSOM object ###########
##########
# 26. Map new data on the FlowSOM object
for (file in files){
ff_prepr <- read.FCS(paste0(dir_prepr, file))
ff_raw <- read.FCS(paste0(dir_raw, file))
fsom_tmp <- NewData(fsom = fsom,
input = ff_prepr)
clustering <- GetClusters(fsom_tmp)
clustering_raw <- matrix(data = rep(0, nrow(exprs(ff_raw))),
ncol = 1, dimnames = list(c(), "FlowSOM"))
clustering_raw[exprs(ff_prepr)[,"Original_ID"]] <- clustering
ff_tmp <- flowCore::fr_append_cols(ff_raw, clustering_raw)
write.FCS(ff_tmp, paste0(dir_prepr, "FlowSOM_", file))
}
########## 11. Additional ###########
########## Applying FlowSOM to files or groups separately and then meta-cluster on all ####
# Compute separate FlowSOM objects
fsom_KO <- FlowSOM(input = paste0(dir_prepr, files[1:3]),
scale = FALSE, colsToUse = channels_of_interest,
seed = 2020)
fsom_WT <- FlowSOM(input = paste0(dir_prepr, files[4:7]),
scale = FALSE, colsToUse = channels_of_interest,
seed = 2020)
# Extract the cluster median fluorescence intensity values (MFIs)
MFI_KO <- GetClusterMFIs(fsom = fsom_KO, prettyColnames = TRUE, colsUsed = TRUE)
rownames(MFI_KO) <- paste0("KO", rownames(MFI_KO))
MFI_WT <- GetClusterMFIs(fsom = fsom_WT, prettyColnames = TRUE, colsUsed = TRUE)
rownames(MFI_WT) <- paste0("WT", rownames(MFI_WT))
# Obtain the meta-clusters by hierarchical clustering
all_clusters <- rbind(MFI_KO, MFI_WT)
hclust <- hclust(dist(all_clusters))
metaclustering <- cutree(hclust, 15) #MC 14 corresponds to the NK cells
# Generate one clustering heatmap from all clusters
ann <- data.frame(cohort = rep(c("KO", "WT"), each = 100),
row.names = rownames(all_clusters))
p <- pheatmap::pheatmap(t(all_clusters), cluster_rows = F, cutree_cols = 15,
cellwidth = 5, fontsize_col = 3, annotation_col = ann,
cluster_cols = hclust)
ggsave(p, filename = paste0(dir_results, "Higher_level_clustering.pdf"), width = 17)
# Generate the meta-cluster percentages boxplots
fsom_KO$metaclustering <- factor(unname(metaclustering[1:100]), levels = 1:15)
fsom_WT$metaclustering <- factor(unname(metaclustering[101:200]), levels = 1:15)
perc_KO <- GetFeatures(fsom = fsom_KO,
files = paste0(dir_prepr, files[1:3]),
level = "metaclusters", type = "percentages",
filenames = files[1:3])
perc_WT <- GetFeatures(fsom = fsom_WT,
files = paste0(dir_prepr, files[4:7]),
level = "metaclusters", type = "percentages",
filenames = files[4:7])
df <- data.frame(rbind(perc_KO[[1]], perc_WT[[1]])*100,
cohort = rep(c("KO", "WT"), c(3, 4)), check.names = FALSE)
df_g <- tidyr::gather(df, "MC", "percentage", -cohort)
ggplot(df_g, aes(x = cohort, y = percentage)) +
geom_boxplot() +
facet_wrap(~MC, scales = "free") +
theme_minimal()
ggsave(filename = "Results/FlowSOM_boxplot.pdf", width = 10, height = 10)
########## 12. Subset and hierarchical approach ###########
wspFile = "C:/Users/edmondsonef/Desktop/Humanized/Flow/5-02Mar2022/15719 02Mar2022 Simone.wsp"
ws <- open_flowjo_xml("C:/Users/edmondsonef/Desktop/Humanized/Flow/5-02Mar2022/15719 02Mar2022 Simone.wsp")
ws
head(fj_ws_get_samples(ws, group_id = 5))
files <- list.files(path = dir_raw, pattern = "Samples")
files
# 20.(B) Check the consistency with manual labeling
# 20.(B)(i) Extract the gating information from the wsp file
gating <- GetFlowJoLabels(files = files,
wspFile = wspFile, group =5,
path = dir_raw)
# 20.(B)(ii) Get an overview of the gatenames and define the cell types of interest
print(levels(gating[[1]][["manual"]]))
cell_types_of_interest <- c("hCD45+","Q6: CD3+ , CD4 [PCP55]+",
"Q10: CD3+ , CD8 [FITC]+",
"Q13: CD3- , CD19 [AFire750]+",
"Q17: CD3- , CD56+",
"Q18: CD3+ , CD56+",
"Q29: CD66b [PEDazz]- , CD11b [AF647]+",
"Q30: CD66b [PEDazz]+ , CD11b [AF647]+",
"Q31: CD66b [PEDazz]+ , CD11b [AF647]-",
"Q33: CD33- , CD11b [AF647]+",
"Q38: CD25+ , CD3+",
"Q35: CD33+ , CD11b [AF647]-",
"Q39: CD25+ , CD3-")
# 20.(B)(iii) Compile the labels of the aggregate file
aggregate_labels <- c()
for (file in unique(exprs(agg)[, "File"])) {
aggregate_labels <- c(aggregate_labels,
as.character(ManualVector(gating[[file]][["matrix"]],
cell_types_of_interest)
[exprs(agg)[, "Original_ID"]
[exprs(agg)[, "File"] == file]]))
}
# Read in preprocessed fcs file, lymphocyte panel
ff <- read.FCS(paste0(data_dir,study_dir3,'1-Preprocessed/NSG/Samples_Tube_015 Animal 142_027.fcs'), truncate_max_range = FALSE)
#manual_labels <- readRDS(paste0(dir_raw, "attachments/lympho_labels.rds"))
# Perform a first level clustering to isolate the lymphocytes
fsom_level1 <- FlowSOM(input = ff,
scale = FALSE, nClus = 3,
colsToUse = c(13:14),
seed = 2020)
fsom_level1$prettyColnames
PlotStars(fsom = fsom_level1,
backgroundValues = fsom_level1$metaclustering)
# Inspect the 2D scatter plots to identify the meta-clusters of interest
Plot2DScatters(fsom = fsom_level1,
channelpairs = list(c("BUV805-A", "BUV395-A")),
metaclusters = 1:2,
plotFile = paste0(data_dir, "hierarchy_level1.png"))
#MC 1, 4 and 5 are the lymphocytes (CD3+, CD161-)
# Subset the original fcs file
fsom_tmp <- NewData(fsom_level1, ff)
clustering <- GetMetaclusters(fsom_tmp)
ff_tmp <- ff[clustering %in% c(2),]
# Perform a second level clustering to characterize the lymphocytes
fsom_level2 <- FlowSOM(input = ff_tmp,
scale = FALSE,
colsToUse = c(7:17),
seed = 2020)
# Plot the lymphocytes FlowSOM tree
PlotStars(fsom = fsom_level2,
backgroundValues = fsom_level2$metaclustering)
# Show the manual labels on the FlowSOM trees
PlotPies(fsom = fsom_level1, cellTypes = manual_labels,
title = "First level clustering")
PlotPies(fsom = fsom_level2, cellTypes = factor(manual_labels[clustering %in% c(1, 4, 5)]),
backgroundValues = fsom_level2$metaclustering, title = "Second level clustering")
########## 13. PlotDimRed ###########
PlotDimRed(fsom, cTotal = 500,
colsToUse = fsom$map$colsUsed,
colorBy = "metaclusters",