-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBatchImage_Processing.qmd
8911 lines (6545 loc) · 319 KB
/
BatchImage_Processing.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Dissecting glial scar formation by spatial point pattern and topological data analysis"
subtitle: "Supplementary data analysis notebook"
format:
html:
code-fold: true
embed-resources: true
toc: true
toc-location: left
theme: spacelab
knitr:
opts_chunk:
warning: false
message: false
editor: source
csl: nature-communications.csl
bibliography: references.bib
---
This notebook contains the analysis pipeline employed for the article "Dissecting glial scar formation by spatial point pattern and topological data analysis" published in XXX. This notebook allows the replication of results and the implementation of point pattern analysis (PPA) in multiple context. If the analysis approach is useful for your own experimental purposes, please cite us:
(L)
# I. Install and load required packages
Install and load the required libraries. Please uncomment (erase #) in the 'install.packages' line if installation is required.
## Install required Packages
```{r}
#| label: Install_Packages
#| include: true
#| warning: false
#| message: false
# To install packcages uncomment the following line
#install.packages(c("ggplot2","dpylr", "ggridges", "raincloudplots", "cowplot", "data.table", "ggrepel", "sjPlot", "bayesplot", "reshape2", "purrr", "tidyr", "brms", "emmeans", "modelr", "plyr", "pacthwork", "spatstat", "ggdist", "ggpubr", "bayesplot", "RandomFieldsUtils", "RandomFields", "gt", "gtsummary","bayestestR"))
#library(devtools)
#install_github ("cran/RandomFields")
```
## Load required packages
Load the libraries required for script execution every time a new R-session is started. Load also `R_rainclouds` and `summarySE.R` functions [@allen2021] available on Github (make sure are in the workng directory).
```{r}
#| label: Load_Packages
#| include: true
#| warning: false
#| message: false
library(ggplot2)
library(ggridges)
library(dplyr)
library(sjPlot)
library(ggrepel)
library(reshape2)
library(purrr)
library(tidyr)
library(gt)
library(gtsummary)
library(tibble)
library(brms)
library(emmeans)
library(modelr)
library(bayestestR)
library(tidybayes)
library(plyr)
library(patchwork)
library(spatstat)
library(data.table)
library(cowplot)
library(geosphere)
library(ggdist)
library(readr)
library(ggpubr)
library(raster)
library(bayesplot)
library(RandomFieldsUtils)
library(RandomFields)
# The following functions are available on the github site. Please change the root directory if required
source("R_Functions/R_rainclouds.R")
source("R_Functions/summarySE.R")
```
## Functions
### Plotting
```{r}
Plot_theme <- theme_classic() +
theme(
plot.title = element_text(size=18, hjust = 0.5, face="bold"),
plot.subtitle = element_text(size = 12, color = "black"),
plot.caption = element_text(size = 12, color = "black"),
axis.line = element_line(colour = "black", size = 1.5, linetype = "solid"),
axis.ticks.length=unit(7,"pt"),
axis.title.x = element_text(colour = "black", size = 16),
axis.text.x = element_text(colour = "black", size = 16, angle = 0, hjust = 0.5),
axis.ticks.x = element_line(colour = "black", size = 1),
axis.title.y = element_text(colour = "black", size = 16),
axis.text.y = element_text(colour = "black", size = 16),
axis.ticks.y = element_line(colour = "black", size = 1),
legend.position="right",
legend.direction="vertical",
legend.title = element_text(colour="black", face="bold", size=12),
legend.text = element_text(colour="black", size=10),
plot.margin = margin(t = 10, # Top margin
r = 2, # Right margin
b = 10, # Bottom margin
l = 10) # Left margin
)
```
# 1. Process data and generate point patterns
## 1.1 Process annotations files
We performed automated cell detection using QuPath [@bankhead2017a]. The software generates `_annotations.tsv` files containing the summary of detected cells per project (brain). These files are located in folders inside the `QupathProjects_5x` folder available in Zenodo (XXX). Download it and place it it the working directory.
Here we merge all the `_annotations.tsv`files to create a summary .csv file for all brains. Different scripts are generated for GFAP and IBA1/NeuN detection, as the latter contain additional cell classifiers from QuPath.
### 1.1.1 Annotations files for GFAP+ cells
```{r}
#| label: 5x_Anotations_GFAP
#| include: true
#| warning: false
#| message: false
append_annotations <- function(base_path, brain_name, results_path) {
Gfap_csv_path <- paste0(results_path, "/5x_Gfap_AnnotationsSummary.csv")
Annotations_Path <- paste0(base_path, "/", brain_name, "/Gfap/")
process_annotation(results_path = Gfap_csv_path, Annotations_Path)
}
process_annotation <- function(results_path, path) {
print (path)
Annotations <- list.files(path = path, pattern = "annotations.tsv", full.names = TRUE) %>%
lapply(read_tsv) %>%
bind_rows
print(Annotations)
Annotations <- as.data.frame(Annotations)
names(Annotations) <- NULL
write.table(Annotations, results_path, append = TRUE, sep=",")
}
basePath <- "QupathProjects_5x"
resultsPath <- "DataTables"
Gfap_csv_path <- paste0(resultsPath, "/5x_Gfap_AnnotationsSummary.csv")
Annotations_Header <- c("Image", "Name", "Class", "Parent", "ROI", "Centroid X ?m", "Centroid Y ?m", "ID", "Parent ID", "Side", "Num Detections", "Area ?m^2", "Perimeter ?m")
df_header <- data.frame(matrix(ncol = 13, nrow = 0))
names(df_header) <- Annotations_Header
write.csv(df_header, Gfap_csv_path)
brains <- list.dirs(basePath, full.names = FALSE, recursive = FALSE)
for (brain in brains){
append_annotations(basePath, brain, resultsPath)
}
```
### 1.1.1 Annotations files for IBA1+ and NeuN+ cells
We perform the same procedure for IBA1 and NeuN
```{r}
#| label: 5x_Anotations_Iba1/NeuN
#| include: true
#| warning: false
#| message: false
append_annotations <- function(base_path, brain_name, results_path) {
Iba1_csv_path <- paste0(results_path, "/5x_Iba1_AnnotationsSummary.csv")
Annotations_Path <- paste0(base_path, "/", brain_name, "/Iba1/")
process_annotation(results_path = Iba1_csv_path, Annotations_Path)
NeuN_csv_path <- paste0(results_path, "/5x_NeuN_AnnotationsSummary.csv")
Annotations_Path <- paste0(base_path, "/", brain_name, "/NeuN/")
process_annotation(results_path = NeuN_csv_path, Annotations_Path)
}
process_annotation <- function(results_path, path) {
print (path)
Annotations <- list.files(path = path, pattern = "annotations.tsv", full.names = TRUE) %>%
lapply(read_tsv) %>%
bind_rows
print(Annotations)
Annotations <- as.data.frame(Annotations)
names(Annotations) <- NULL
write.table(Annotations, results_path, append = TRUE, sep=",")
}
basePath <- "QupathProjects_5x"
resultsPath <- "DataTables"
Iba1_csv_path <- paste0(resultsPath, "/5x_Iba1_AnnotationsSummary.csv")
NeuN_csv_path <- paste0(resultsPath, "/5x_NeuN_AnnotationsSummary.csv")
Annotations_Header <- c("Image", "Name", "Class", "Parent", "ROI", "Centroid X ?m", "Centroid Y ?m", "ID", "Parent ID", "Side", "Num Detections", "Num Negatie", "Num Positive", "Positive %", "Num Positive per mm^2", "Area ?m^2", "Perimeter ?m")
df_header <- data.frame(matrix(ncol = 17, nrow = 0))
names(df_header) <- Annotations_Header
write.csv(df_header, Iba1_csv_path)
write.csv(df_header, NeuN_csv_path)
brains <- list.dirs(basePath, full.names = FALSE, recursive = FALSE)
for (brain in brains){
append_annotations(basePath, brain, resultsPath)
}
```
After executing the previous chunks, three files are located in the `DataTables` folder corresponding to each marker.
## 1.2 Process cell detection files
QuPath also generates `_detections.tsv` files containing the coordinates of individual cells per brain. In the following chunk, we manipulate the coordinates, clean and subset the data to obtain .csv summaries (per brain) containing relevant information, including cell coordinates. The results are stored in several files in the `ResultsTables/5x_Coordinates` folder.
```{r}
#| label: 5x_Detections
#| include: true
#| warning: false
#| message: false
process_initial_data <- function(Cells_Path, pattern, coordinates_columns, filename, brain_name) {
Cells_Raw <- list.files(path=Cells_Path, pattern = pattern, full.names=TRUE) %>% # Create object with all .tsv files in directory
lapply(read_tsv) %>% # Store all files in list
bind_rows # Combine data sets into one data set
# Convert to data frame
Cells <- as.data.frame(Cells_Raw)
# Transform coordinates from mm to microns for adecuate plotting in BrainRender
Cells$Z <- (Cells[,c(coordinates_columns[[1]])]*1000)
Cells$X <- (Cells[,c(coordinates_columns[[2]])]*1000)
Cells$Y <- (Cells[,c(coordinates_columns[[3]])]*1000)
# Subset the date set to keep only relevant columns
Cells <- subset(Cells, select = c(Image, Name, Parent, Z, X, Y))
Cells <- Cells[!(Cells$Name=="Negative" | Cells$Name=="Necrosis"),]
Cells <- Cells %>% sample_frac(.1)
# Extract metadata information from image name
Cells <- cbind(Cells, do.call(rbind , strsplit(Cells$Image , "[_\\.]"))[,3:5])
colnames(Cells) <- c( colnames(Cells[1:3]), paste0("New" , 1:3))
Cells <- cbind(Cells[c(-2,-3)] , Cells[c(2,3)])
# Rename columns
colnames(Cells) <- c("Image", "Z", "X", "Y", "MouseID", "DPI", "Section", "ObjectID", "Region")
Cells <- subset(Cells, select = c(MouseID, DPI, Region, Section, ObjectID, Z, X, Y))
# Write a .csv file
write.csv(Cells, filename)
}
process_brain <- function(basePath, resultsPath, path) {
set.seed(88071)
# Load cells data set
Iba1_Path <- paste0(basePath, "/", path, "/Iba1")
Iba1_Filename <- paste0(resultsPath, "/", path, "_Iba1_Coordinates.csv")
Iba1 <- process_initial_data(Iba1_Path, "detections.tsv", coordinates_columns = c(46, 47, 48), filename = Iba1_Filename, brain_name = path)
Gfap_Path <- paste0(basePath, "/", path, "/Gfap")
Gfap_Filename <- paste0(resultsPath, "/", path, "_Gfap_Coordinates.csv")
process_initial_data(Gfap_Path, "detections.tsv", c(46, 47, 48), Gfap_Filename, path)
Neun_Path <- paste0(basePath, "/", path, "/NeuN")
Neun_Filename <- paste0(resultsPath, "/", path, "_NeuN_Coordinates.csv")
process_initial_data(Neun_Path, "detections.tsv", c(46, 47, 48), Neun_Filename, path)
}
basePath <- "QupathProjects_5x"
resultsPath <- "DataTables/5x_Coordinates"
brains <- list.dirs(basePath, full.names = FALSE, recursive = FALSE)
for (brain in brains){
process_brain(basePath, resultsPath, brain)
}
```
## 1.3 Generate hyperframes and additional data tables
Now, we retrieve the files located in the `ResultsTables/5x_Coordinates` folder to generate point patterns, density kernels and tessellations, which are stored in a hyperframe. We also generate files containing intensity summaries and cell locations in tessellated images. This features will be explained later in the work flow.
```{r}
#| label: 5x_Hyperframe
#| include: true
#| warning: false
#| message: false
coordinatesPath <- "DataTables/5x_Coordinates"
densityTablesPath <- "DataTables"
CellsIntensity_5x_CSV_Path <- paste0(densityTablesPath, "/5x_CellsIntensity.csv")
CellsIntensity_5x_Header <- c("Brain", "Neurons_Intensity", "Astrocytes_Intensity", "Microglia_Intensity")
Tesselation_CSV_Path <- paste0(densityTablesPath, "/5x_CellsCovariance.csv")
Tesselation_Test_Header <- c("Brain", "AN1", "AN2", "MN1", "MN2", "AM1", "AM2")
# Results to generate
Result_Hyperframe <- NULL
# Functions
add_to_hyperframe <- function (...) {
if (is.null(Result_Hyperframe)){
Result_Hyperframe <<- hyperframe(...)
} else {
Result_Hyperframe <<- rbind(Result_Hyperframe, hyperframe(...))
}
}
create_empty_table <- function (path, header) {
df_header <- data.frame(matrix(ncol = length(header), nrow = 0))
names(df_header) <- header
write.csv(df_header, path)
}
create_empty_table(CellsIntensity_5x_CSV_Path, CellsIntensity_5x_Header)
create_empty_table(Tesselation_CSV_Path, Tesselation_Test_Header)
# Manipulate coordinates for correct plotting in R
coordinates_manipulation <- function (Raw_Table) {
Cell_Coor_X <- Raw_Table$Y
Cell_Coor_Y <- Raw_Table$X
## Bind the vectors, rotate and bind to original table
Coords <- cbind(Cell_Coor_X, Cell_Coor_Y)
Coords <- secr::rotate(Coords, 180)
Coords <- as.data.frame(Coords)
return(cbind(Raw_Table, Coords))
}
# Cretate a point pattern (PPP) object
create_point_pattern <- function(Subset) {
# We define the limits of the window according to Neuron coordinates
xlim <- range(Subset$Cell_Coor_X)
ylim <- range(Subset$Cell_Coor_Y)
# Create point pattern for neurons
Cells_PPP <- with(Subset, ppp(x = Subset$Cell_Coor_X, y = Subset$Cell_Coor_Y, xrange = xlim, yrange = ylim))
unitname(Cells_PPP) <- list("mm", "mm", 1.3/1000)
Cells_PPP <- spatstat.geom::rescale (Cells_PPP)
## We rescale the unit to obtain measurements in mm2
return(Cells_PPP)
}
define_convex_hull <- function(Neurons_PPP, Cells_PPP) {
chull <- convexhull(Neurons_PPP)
Window(Cells_PPP) <- chull
return(Cells_PPP)
}
tesselation <- function(Cells_Density) {
## We define the quantiles for Neurons
Cells_Quantiles <- c(0, 20, 150)
## We define the cutting spots according to quantiles
Cells_Cut <- cut(Cells_Density, breaks = Cells_Quantiles, labels = c ("Low", "High"))
## We generate the tesselation image
return(tess(image = Cells_Cut))
}
tesselation_data <- function(Cells_PPP, Cells_Tess) {
Result <- quadratcount(Cells_PPP, tess = Cells_Tess )
return(Result)
}
Neurons_Astrocytes_Function_Vector <- c()
Microglia_Neurons_Function_Vector <- c()
Astrocytes_Microglia_Function_Vector <- c()
process_file <- function (basePath, path) {
Neurons_Raw <- read.csv(file = paste0(basePath, '/', path, '_NeuN_Coordinates.csv'), header = TRUE)
Astrocytes_Raw <- read.csv(file = paste0(basePath, '/', path, '_Gfap_Coordinates.csv'), header = TRUE)
Microglia_Raw <- read.csv(file = paste0(basePath, '/', path, '_Iba1_Coordinates.csv'), header = TRUE)
Neurons <- coordinates_manipulation(Neurons_Raw)
Astrocytes <- coordinates_manipulation(Astrocytes_Raw)
Microglia <- coordinates_manipulation(Microglia_Raw)
# Subset neurons
Neurons_Subset <- Neurons[(Neurons$Section=="Scene3"),]
Neurons_Subset <- Neurons_Subset[(Neurons_Subset$Y < 5000),]
# We subset astrocytes
Astrocytes_Subset <- Astrocytes[(Astrocytes$Section=="Scene3"),]
Astrocytes_Subset <- Astrocytes_Subset[(Astrocytes_Subset$Y < 5000),]
# We subset microglia
Microglia_Subset <- Microglia[(Microglia$Section=="Scene3"),]
Microglia_Subset <- Microglia_Subset [(Microglia_Subset$Y < 5000),]
Neurons_PPP <- create_point_pattern(Neurons_Subset)
Astrocytes_PPP <- create_point_pattern(Astrocytes_Subset)
Microglia_PPP <- create_point_pattern(Microglia_Subset)
Neurons_PPP <- define_convex_hull(Neurons_PPP, Neurons_PPP)
Astrocytes_PPP <- define_convex_hull(Neurons_PPP, Astrocytes_PPP)
Microglia_PPP <- define_convex_hull(Neurons_PPP, Microglia_PPP)
Neurons_Intensity <- summary(Neurons_PPP)$intensity
Astrocytes_Intensity <- summary(Astrocytes_PPP)$intensity
Microglia_Intensity <- summary(Microglia_PPP)$intensity
Intensity_Row <- t(c(path, Neurons_Intensity, Astrocytes_Intensity, Microglia_Intensity))
write.table(Intensity_Row, CellsIntensity_5x_CSV_Path, append = TRUE, sep=",", col.names = FALSE)
Microglia_Density <- density(Microglia_PPP, sigma =0.2, positive=TRUE, equal.ribbon = TRUE, col = topo.colors, main = "")
Astrocytes_Density <- density(Astrocytes_PPP, sigma =0.2, positive=TRUE, equal.ribbon = TRUE, col = topo.colors, main = "")
Neurons_Density <- density(Neurons_PPP, sigma =0.3, positive=TRUE, equal.ribbon = TRUE, col = topo.colors, main = "")
Neurons_Tess <- tesselation(Neurons_Density)
Astrocytes_Tess <- tesselation(Astrocytes_Density)
Microglia_Tess <- tesselation(Microglia_Density)
Astrocytes_in_Neurons <-tesselation_data(Astrocytes_PPP, Neurons_Tess)
Microglia_in_Neurons <- tesselation_data(Microglia_PPP, Neurons_Tess)
Astrocytes_in_Microglia <- tesselation_data(Astrocytes_PPP, Microglia_Tess)
Tesselation_Row <- t(c(path, Astrocytes_in_Neurons, Microglia_in_Neurons, Astrocytes_in_Microglia))
write.table(Tesselation_Row, Tesselation_CSV_Path, append = TRUE, sep=",", col.names = FALSE)
Astrocytes_Neurons_Correlation <- ppm(Astrocytes_PPP ~ Neurons_Density)
Microglia_Neurons_Correlation <- ppm(Microglia_PPP ~ Neurons_Density)
Astrocytes_Microglia_Correlation <- ppm(Astrocytes_PPP ~ Microglia_Density)
fragments <- strsplit(path, "_")[[1]]
len <- length(fragments)
mouse <- fragments[3]
dpi <- fragments[4]
add_to_hyperframe(Neurons = Neurons_PPP, Astrocytes = Astrocytes_PPP, Microglia = Microglia_PPP, Neurons_Dens = Neurons_Density, Astrocytes_Dens = Astrocytes_Density, Microglia_Dens = Microglia_Density, Neurons_Tess = Neurons_Tess, Microglia_Tess = Microglia_Tess, ID = mouse, DPI=dpi, stringsAsFactors=TRUE)
}
csv_files <- list.files(coordinatesPath, full.names = FALSE, recursive = FALSE)
brains <- c()
for (csv in csv_files) {
fragments <- strsplit(csv, "_")[[1]]
len <- length(fragments)
brain_name <- paste(fragments[1:(len-2)], collapse="_")
brains <- append(brains, brain_name)
}
brains <- unique(brains)
for (brain in brains) {
process_file(coordinatesPath, brain)
}
saveRDS(Result_Hyperframe, "Hyperframes/5x_PointPatterns.rds")
```
The preceding generates an hyperframe called ``` 5x_``PointPatterns``.rds ``` stored in the hyperframes folder, and two files, 5x\_`CellsCovariance.csv` and 5x\_`CellsIntensity.csv` stored in the `DataTables` folder. With these files we are ready to start data analysis.
# 2. Analysis of cell intensity
We used the `spatstat` R-package [@baddeley2005; @baddeley2015; @spatstat] to convert the xy coordinates of detected cells into point patterns (ppp), using the code in [1.3 Generate hyperframes and additional data tables]. The point patterns were scaled in mm (1.3 mm/1000 px) and stored in the hyperframe. Additionally, we generated .csv files containing the estimated intensity (summary(Cells_PPP)\$intensity) in image #3 of each brain (see supplementary table 1 in the research article).
In the following sections, we handle the 5x\_`CellsIntensity.csv` data frame to perform scientific inference on the spatial intensity of NeuN, GFAP, and IBA1-expressing cells.
## 2.1 Load and prepare the dataset
Here, we load and handle the spatial intensity measurements to produce a tidy data frame.
```{r}
#| label: 5x_Handling_Cellintensity
#| include: true
#| warning: false
#| message: false
# Load raw data table
CellsIntensity_5x_Raw <- read.csv(file = 'DataTables/5x_CellsIntensity.csv',
header = TRUE)
# We subset the relevant columns
CellsIntensity_5x <- subset(CellsIntensity_5x_Raw, select = -c(X))
# Extract metadata from the image name and rename columns
CellsIntensity_5x <- cbind(CellsIntensity_5x, do.call(rbind , strsplit(CellsIntensity_5x$Brain, "[_\\.]"))[,3:4])
colnames(CellsIntensity_5x) <- c("Brain", "Neurons_Intensity", "Astrocytes_Intensity", "Microglia_Intensity", "MouseID", "DPI")
# We subset the relevant columns
CellsIntensity_5x <- subset(CellsIntensity_5x, select = c(MouseID, DPI, Neurons_Intensity, Astrocytes_Intensity, Microglia_Intensity))
# We convert DPI to a numeric variable (Perform this step if required by the model)
#CellsIntensity_5x$DPI[CellsIntensity_5x$DPI == '0D'] <- '0'
#CellsIntensity_5x$DPI[CellsIntensity_5x$DPI == '5D'] <- '5'
#CellsIntensity_5x$DPI[CellsIntensity_5x$DPI == '15D'] <- '15'
#CellsIntensity_5x$DPI[CellsIntensity_5x$DPI == '30D'] <- '30'
#CellsIntensity_5x$DPI <- as.numeric(CellsIntensity_5x$DPI)
# We set explicitly the factor level for DPI
CellsIntensity_5x$DPI <- factor(CellsIntensity_5x$DPI, levels = c("0D", "5D", "15D", "30D"))
# We plot the head of the data table to verify the transformation
gt(CellsIntensity_5x)
write.csv(CellsIntensity_5x, "DataTables/5x_CellsIntensity_Post.csv")
```
The data frame contain five columns: MouseId (animal unique identifier), DPI (days post-ischemia), Neurons_intensity (neuronal spatial intensity based on NeuN expression), Astrocytes_intensity (astrocytes spatial intensity based on GFAP expression), and Microglia_intensity (microglia spatial intensity based on IBA1 expression). As we refer in the research article, we are aware that GFAP and IBA1 are expressed by other cell types in the nervous system. However, this fact does not limit our approach. This usable table is also stored as `5x_CellsIntensity_Post.csv`in the DataTables folder.
## 2.2 Exploratory data visualization
We use `geom_density_ridges` [@ggridges] to visualize the data sets. The same graphical parameters are applied to all cell types. Graphs are stored in the `Plots` folder.
### 2.2.1 Visualization for NeuN
```{r}
#| label: 5x_Visualization_NeuN
#| include: true
#| warning: false
#| message: false
#| results: false
#| cache: true
set.seed(8807)
NeuN_Intensity_Ridges <- ggplot(CellsIntensity_5x,
aes(x = Neurons_Intensity,
y = DPI,
group = DPI)) + geom_density_ridges(
quantile_lines = TRUE,
rel_min_height = 0.01,
alpha = 0.8,
scale = 2,
jittered_points = TRUE,
point_alpha = 1,
point_size = 3) +
labs(title = "Raw intensity") +
scale_x_continuous(name="\n Neuronal intensity (NeuN) ",
limits=c(0, 70),
breaks=seq(0,100,10)) +
scale_y_discrete(name= " DPI \n",
labels = c("Control", "5D", "15D", "30D")) +
theme_classic() +
theme(
plot.title = element_text(size=18, hjust = 0.5, face="bold"),
plot.subtitle = element_text(size = 10, color = "black"),
axis.line = element_line(colour = "black", size = 1.5, linetype = "solid"),
axis.ticks.length=unit(7,"pt"),
axis.title.x = element_text(colour = "black", size = 16),
axis.text.x = element_text(colour = "black", size = 16, angle = 0, hjust = 0.5),
axis.ticks.x = element_line(colour = "black", size = 1),
axis.title.y = element_text(colour = "black", size = 16),
axis.text.y = element_text(colour = "black", size = 16),
axis.ticks.y = element_line(colour = "black", size = 1),
legend.position="right",
legend.direction="vertical",
legend.title = element_text(colour="black", face="bold", size=12),
legend.text = element_text(colour="black", size=10),
plot.margin = margin(t = 10, # Top margin
r = 10, # Right margin
b = 10, # Bottom margin
l = 10) # Left margin
)
ggsave(plot = NeuN_Intensity_Ridges, "Plots/NeuN_Intensity_Ridges.png",
width = 13,
height = 10,
units = "cm")
```
### 2.2.2 Visualization for GFAP
```{r}
#| label: 5x_Visualization_Gfap
#| include: true
#| warning: false
#| message: false
#| results: false
#| cache: true
set.seed(8807)
Gfap_Intensity_Ridges <- ggplot(CellsIntensity_5x,
aes(x = Astrocytes_Intensity,
y = DPI,
group = DPI)) + geom_density_ridges(
quantile_lines = TRUE,
rel_min_height = 0.01,
alpha = 0.8,
scale = 2,
jittered_points = TRUE,
point_alpha = 1,
point_size = 3) +
labs(title = "Raw intensity") +
scale_x_continuous(name="\n Astrocyte intensity (GFAP) ",
limits=c(0, 50),
breaks=seq(0,100,10)) +
scale_y_discrete(name= " DPI \n",
labels = c("Control", "5D", "15D", "30D")) +
theme_classic() +
theme(
plot.title = element_text(size=18, hjust = 0.5, face="bold"),
plot.subtitle = element_text(size = 10, color = "black"),
axis.line = element_line(colour = "black", size = 1.5, linetype = "solid"),
axis.ticks.length=unit(7,"pt"),
axis.title.x = element_text(colour = "black", size = 16),
axis.text.x = element_text(colour = "black", size = 16, angle = 0, hjust = 0.5),
axis.ticks.x = element_line(colour = "black", size = 1),
axis.title.y = element_text(colour = "black", size = 16),
axis.text.y = element_text(colour = "black", size = 16),
axis.ticks.y = element_line(colour = "black", size = 1),
legend.position="right",
legend.direction="vertical",
legend.title = element_text(colour="black", face="bold", size=12),
legend.text = element_text(colour="black", size=10),
plot.margin = margin(t = 10, # Top margin
r = 10, # Right margin
b = 10, # Bottom margin
l = 10) # Left margin
)
ggsave(plot = Gfap_Intensity_Ridges, "Plots/Gfap_Intensity_Ridges.png",
width = 13,
height = 10,
units = "cm")
```
### 2.2.3 Visualization for IBA1
```{r}
#| label: 5x_Visualization_Iba1
#| include: true
#| warning: false
#| message: false
#| results: false
#| cache: true
set.seed(8807)
Iba1_Intensity_Ridges <- ggplot(CellsIntensity_5x,
aes(x = Microglia_Intensity,
y = DPI,
group = DPI)) + geom_density_ridges(
quantile_lines = TRUE,
rel_min_height = 0.01,
alpha = 0.8,
scale = 2,
jittered_points = TRUE,
point_alpha = 1,
point_size = 3) +
labs(title = "Raw intensity") +
scale_x_continuous(name="\n Microglia intensity (IBA1) ",
limits=c(0, 60),
breaks=seq(0,100,10)) +
scale_y_discrete(name= " DPI \n",
labels = c("Control", "5D", "15D", "30D")) +
theme_classic() +
theme(
plot.title = element_text(size=18, hjust = 0.5, face="bold"),
plot.subtitle = element_text(size = 10, color = "black"),
axis.line = element_line(colour = "black", size = 1.5, linetype = "solid"),
axis.ticks.length=unit(7,"pt"),
axis.title.x = element_text(colour = "black", size = 16),
axis.text.x = element_text(colour = "black", size = 16, angle = 0, hjust = 0.5),
axis.ticks.x = element_line(colour = "black", size = 1),
axis.title.y = element_text(colour = "black", size = 16),
axis.text.y = element_text(colour = "black", size = 16),
axis.ticks.y = element_line(colour = "black", size = 1),
legend.position="right",
legend.direction="vertical",
legend.title = element_text(colour="black", face="bold", size=12),
legend.text = element_text(colour="black", size=10),
plot.margin = margin(t = 10, # Top margin
r = 10, # Right margin
b = 10, # Bottom margin
l = 10) # Left margin
)
ggsave(plot = Iba1_Intensity_Ridges, "Plots/Iba1_Intensity_Ridges.png",
width = 13,
height = 10,
units = "cm")
```
### 2.2.4 Plot the spatial intensity raw data
Here we plot the graphs for NeuN, GFAP and IBA1 generated in the previous chunks. These graphs are displayed in supplementary figure 2 of the research article.
```{r}
#| label: 5x_IntensityRidges
#| include: true
#| warning: false
#| message: false
#| column: screen-inset-shaded
#| layout-nrow: 1
#| fig-width: 20
#| fig-height: 5
ggarrange(NeuN_Intensity_Ridges, Gfap_Intensity_Ridges, Iba1_Intensity_Ridges + rremove("x.text"),
labels = c("A", "B", "C"),
ncol = 3, nrow = 1)
```
## 2.3 Bayesian modeling for cell spatial intensity
Here we employ the `brms` package [@bürkner2017; @bürkner2018; @brms]to perform statistical inference based on parameter estimation and uncertainty. Considering the initial data visualization, we fitted different models using student distributions (robust regression) to reduce the impact of extreme data. We also evaluated heteroskedasticity models to account for different variances in the data. In particular, we set DPI as a predictor and not a groping variable (multilevel model) given that that the control condition (sham animals) does not share information with stroked mice.
We set formulas and fit the models using 4 chains, 5000 iterations (2500 as a warm up) and seed 8807 (important for reproducibility purposes). Given that we have previous information regarding the expected decrease in spatial intensity, we used a weak informative prior to favor the random sampling. The models are saved as .rds objects and become available in the `BayesianModels/CellIntensity` folder. The model is loaded (not refitted) when the .rds file is available. To refit the model, erase the respective file in the output folder.
### 2.3.1 Modeling for neuronal intensity (NeuN)
Here we fir two bayesian models:
- **NeuNIntensity_5x_Mdl1:** We regress the neuronal intensity (Neurons_Intensity) on DPI, with out the calculation of an intercept (0 +).
$NeuN_{i} = \beta_{1} DPI_{i} + \epsilon_{i}$
This model uses the following user-defined prior:
$\beta \sim Student-t(df = 3, location = 15, scale = 5)$
All other priors are default by `brms`.
- **NeuNIntensity_5x_Mdl2:** We use the same regression that in `Mdl1`, including a term for heteroskedasticity (sigma) to account for non-constant variance. The model use the same user-defined priors for `Mdl1`and default priors by `brms`.
```{r}
#| label: 5x_Modeling_NeuNIntensity
#| include: true
#| warning: false
#| message: false
# Model 1 (DPI as a single predictor)
NeuNIntensity_5x_Mdl1 <- bf(Neurons_Intensity ~ 0 + DPI)
get_prior(NeuNIntensity_5x_Mdl1, data = CellsIntensity_5x)
NeuNIntensity_5x_Mdl1_Prior <- c(prior(student_t(3, 30, 20), class = b, lb= 0))
NeuNIntensity_5x_Fit1 <- brm(data = CellsIntensity_5x,
family = student,
formula = NeuNIntensity_5x_Mdl1,
prior = NeuNIntensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000,
seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/NeuNIntensity_5x_Fit1.rds",
file_refit = "never")
NeuNIntensity_5x_Fit1 <- add_criterion(NeuNIntensity_5x_Fit1, c("loo", "waic", "bayes_R2"))
# Model 2 (DPI as a predictor with heteroskedasticity)
NeuNIntensity_5x_Mdl2 <- bf(Neurons_Intensity ~ 0 + DPI,
sigma ~ 0 + DPI)
get_prior(NeuNIntensity_5x_Mdl2, data = CellsIntensity_5x)
NeuNIntensity_5x_Fit2 <- brm(data = CellsIntensity_5x,
family = student,
formula = NeuNIntensity_5x_Mdl2,
prior = NeuNIntensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000,
seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/NeuNIntensity_5x_Fit2.rds",
file_refit = "never")
NeuNIntensity_5x_Fit2 <- add_criterion(NeuNIntensity_5x_Fit2, c("loo", "waic", "bayes_R2"))
```
### 2.3.2 Modeling for Astrocyte intensity (GFAP)
We perform the same procedure for GFAP and later IBA1. We took into consideration using neuronal intensity as an additional predictor. However, this may induce model confounding given that the neuronal spatial intensity can be understood as a post-treatment effect of DPI.For this reason, we fit models with DPI as unique predictor as done for NeuN:
$Gfap_{i} = \beta_{1} DPI_{i} + \epsilon_{i}$
We set the following weak informative prior for `Mdl1` and `Mdl2` for facilitating exploration of the parameter space:
$\beta \sim Student-t(df = 3, location = 30, scale = 20)$
We fitted an additional model (`Mdl3`), having the neuronal intensity (Neurons_Intensity) as unique prediction to see their relation with GFAP following injury.The models uses default `brms` priors.
```{r}
#| label: 5x_Modeling_GfapIntensity
#| include: true
#| warning: false
#| message: false
# Model 1 (DPI as a predictor)
GfapIntensity_5x_Mdl1 <- bf(Astrocytes_Intensity ~ 0 + DPI)
get_prior(GfapIntensity_5x_Mdl1, data = CellsIntensity_5x)
GfapIntensity_5x_Mdl1_Prior <- c(prior( student_t(3, 30, 20), class = b, lb= 0))
GfapIntensity_5x_Fit1 <- brm(data = CellsIntensity_5x,
family = student,
formula = GfapIntensity_5x_Mdl1,
prior = GfapIntensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000, seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/GfapIntensity_5x_Fit1.rds",
file_refit = "never")
GfapIntensity_5x_Fit1 <- add_criterion(GfapIntensity_5x_Fit1, c("loo", "waic", "bayes_R2"))
# Model 2 (DPI as a predictor with heteroskedasticity)
GfapIntensity_5x_Mdl2 <- bf(Astrocytes_Intensity ~ 0 + DPI,
sigma ~ 0 + DPI)
get_prior(GfapIntensity_5x_Mdl2, data = CellsIntensity_5x)
GfapIntensity_5x_Fit2 <- brm(data = CellsIntensity_5x,
family = student,
formula = GfapIntensity_5x_Mdl2,
prior = GfapIntensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000, seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/GfapIntensity_5x_Fit2.rds",
file_refit = "never")
GfapIntensity_5x_Fit2 <- add_criterion(GfapIntensity_5x_Fit2, c("loo", "waic", "bayes_R2"))
# Model 3 (Neuronal intensity as a predictor)
GfapIntensity_5x_Mdl3 <- bf(Astrocytes_Intensity ~ 1 + Neurons_Intensity)
get_prior(GfapIntensity_5x_Mdl3, data = CellsIntensity_5x)
GfapIntensity_5x_Fit3 <- brm(data = CellsIntensity_5x,
family = student,
formula = GfapIntensity_5x_Mdl3,
#prior = GfapIntensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000, seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/GfapIntensity_5x_Fit3.rds",
file_refit = "never")
GfapIntensity_5x_Fit3 <- add_criterion(GfapIntensity_5x_Fit3, c("loo", "waic", "bayes_R2"))
```
### 2.3.3 Modeling for microglia intensity (IBA1)
We perform the same procedure for IBA1, as done for GFAP.
```{r}
#| label: 5x_Modeling_Iba1Intensity
#| include: true
#| warning: false
#| message: false
# Model 1 (DPI as a predictor)
Iba1Intensity_5x_Mdl1 <- bf(Microglia_Intensity ~ 0 + DPI)
get_prior(Iba1Intensity_5x_Mdl1, data = CellsIntensity_5x)
Iba1Intensity_5x_Mdl1_Prior <- c(prior( student_t(3, 30, 20), class = b, lb= 0))
Iba1Intensity_5x_Fit1 <- brm(data = CellsIntensity_5x,
family = student,
formula = Iba1Intensity_5x_Mdl1,
prior = Iba1Intensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000, seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/Iba1Intensity_5x_Fit1.rds",
file_refit = "never")
Iba1Intensity_5x_Fit1 <- add_criterion(Iba1Intensity_5x_Fit1, c("loo", "waic", "bayes_R2"))
# Model 2 (DPI as a predictor with heteroskedasticity)
Iba1Intensity_5x_Mdl2 <- bf(Microglia_Intensity ~ 0 + DPI,
sigma ~ 0 + DPI)
get_prior(Iba1Intensity_5x_Mdl2, data = CellsIntensity_5x)
Iba1Intensity_5x_Fit2 <- brm(data = CellsIntensity_5x,
family = student,
formula = Iba1Intensity_5x_Mdl2,
prior = Iba1Intensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000, seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/Iba1Intensity_5x_Fit2.rds",
file_refit = "never")
Iba1Intensity_5x_Fit2 <- add_criterion(Iba1Intensity_5x_Fit2, c("loo", "waic", "bayes_R2"))
# Model 3 (Neuronal intensity as a predictor)
Iba1Intensity_5x_Mdl3 <- bf(Microglia_Intensity ~ 1 + Neurons_Intensity)
get_prior(Iba1Intensity_5x_Mdl3, data = CellsIntensity_5x)
Iba1Intensity_5x_Fit3 <- brm(data = CellsIntensity_5x,
family = student,
formula = Iba1Intensity_5x_Mdl3,
#prior = Iba1Intensity_5x_Mdl1_Prior,
chains = 4, warmup = 2500, iter= 5000, seed = 8807,
control = list(adapt_delta = 0.99, max_treedepth = 15),
file = "BayesianModels/CellIntensity/Iba1Intensity_5x_Fit3.rds",
file_refit = "never")
Iba1Intensity_5x_Fit3 <- add_criterion(Iba1Intensity_5x_Fit3, c("loo", "waic", "bayes_R2"))
```
## 2.4 Analysis of fitted models
### 2.4.1 Analysis of neuronal intensity (NeuN) {#analysis-of-neuronal-intensity-neun}
#### 2.4.1.1 Posterior predictive checks for NeuN intensity
We generate graphs of posterior predictive checks for each of the fitted models
```{r}
#| label: 5x_PPchecks_NeuNIntensity
#| include: true
#| warning: false
#| message: false
#| results: false
set.seed(8807)
color_scheme_set("darkgray")
# Model 1
NeuNIntensity_5x_Mdl1_ppchecks <- brms::pp_check(NeuNIntensity_5x_Fit1, ndraws = 50) +
geom_density(lwd = 2) +
labs(title = "Model 1",
subtitle = "DPI as a predictor",
caption = "Model: Intensity ~ 0 + DPI") +
scale_x_continuous(name="\n Neuronal intensity (NeuN) ",