This repository has been archived by the owner on Jun 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
.Rhistory
512 lines (512 loc) · 16.8 KB
/
.Rhistory
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
}
## Create annotation data.frame
x <- rbind(pval.sig, pval.fdr.sig)
# x <- data.frame("p_value" = pval,
# "p_value_FDR" = pval.fdr)
x <- t(x)
x <- as.data.frame(x)
# x <- as.matrix(x)
# feature.annots <- as.data.frame(x)
# rownames(feature.annots) <- plot.cols
# feature.annots
#str(feature.annots)
#str(my_sample_col)
str(x)
feature.annots <- x
p.val.annots
p.val.fdr.annots
annotation_colors <- c(p.val.annots, p.val.fdr.annots)
# annotation_colors <- list('p_value' = c('NS' = "Black", "Significant" = "Blue"),
# 'p_value_FDR' = c('NS' = "Black", "Significant" = "Red"))
##########################################################################################################
#### Differential heatmap
##########################################################################################################
setwd(OutputDirectory)
dir.create("Output - heatmaps with stats")
setwd("Output - heatmaps with stats")
sum.dat.z[[group.col]]
make.pheatmap(sum.dat.z,
sample.col = sample.col,
plot.cols = plot.cols,
annot.cols = annot.cols,
feature.annots = feature.annots,
annotation_colors = annotation_colors,
is.fold = TRUE,
fold.range = c(3, -3),
dendrograms = 'column',
row.sep = c(55,108),
#cutree_rows = 2,
cutree_cols = 8,
plot.title = "All features - z-score (static rows)",
file.name = "All features - z-score (static rows).png")
make.pheatmap(sum.dat.z,
sample.col = sample.col,
plot.cols = plot.cols,
annot.cols = annot.cols,
feature.annots = feature.annots,
annotation_colors = annotation_colors,
is.fold = TRUE,
fold.range = c(3, -3),
cutree_rows = 2,
cutree_cols = 8,
plot.title = "All features - z-score",
file.name = "All features - z-score.png")
##########################################################################################################
#### Volcano plots
##########################################################################################################
setwd(OutputDirectory)
dir.create("Output - volcano plots")
setwd("Output - volcano plots")
### Setup
comps <- list()
for(i in c(1:length(comparisons))){
temp <- comparisons[[i]]
strg <- paste0(temp[[1]], " to ", temp[[2]])
comps[[i]] <- strg
}
comps
### Uncorrected volcanos
setwd(OutputDirectory)
dir.create("Output - volcano plots")
setwd("Output - volcano plots")
dir.create("Uncorrected p-values")
setwd("Uncorrected p-values")
for(i in comps){
temp <- sum.dat.stats.raw[sum.dat.stats.raw[["Comparison"]] == i,]
p.dat <- temp[temp[["Type"]] == "p-value",]
p.dat <- p.dat[,names(p.dat)[c(3:length(names(p.dat)))], with = FALSE]
fc.dat <- temp[temp[["Type"]] == "FClog2",]
fc.dat <- fc.dat[,names(fc.dat)[c(3:length(names(fc.dat)))], with = FALSE]
nms <- names(fc.dat)
make.volcano.plot(dat.p = p.dat,
dat.fc = fc.dat,
vars = nms,
title = i,
xlim = c(-3.5, 3.5))
}
### Corrected
setwd(OutputDirectory)
dir.create("Output - volcano plots")
setwd("Output - volcano plots")
dir.create("Corrected p-values")
setwd("Corrected p-values")
for(i in comps){
temp <- sum.dat.stats.FDR[sum.dat.stats.FDR[["Comparison"]] == i,]
p.dat <- temp[temp[["Type"]] == "p-value_fdr",]
p.dat <- p.dat[,names(p.dat)[c(3:length(names(p.dat)))], with = FALSE]
fc.dat <- temp[temp[["Type"]] == "FClog2",]
fc.dat <- fc.dat[,names(fc.dat)[c(3:length(names(fc.dat)))], with = FALSE]
nms <- names(fc.dat)
make.volcano.plot(dat.p = p.dat,
dat.fc = fc.dat,
vars = nms,
title = i,
xlim = c(-3.5, 3.5))
}
##########################################################################################################
#### Output
##########################################################################################################
setwd(OutputDirectory)
dir.create("Output - data or stats")
setwd("Output - data for stats")
fwrite(sum.dat, "sum.dat.csv")
fwrite(as.data.table(plot.cols), "plot.cols.csv", col.names = FALSE)
View(merged.dat.zscr)
dat <- Spectre::demo.clustered
dat$FlowSOM_cluster <- NULL
dat$FlowSOM_metacluster <- NULL
as.matrix(names(dat))
use.cols <- names(dat)[c(11:19)]
sample.col <- "Sample"
batch.col <- "Batch"
xdim = 5
ydim = 5
nClus = 1
nCells = NULL
scale = FALSE
seed = 1
### Single cluster preferences
if(nClus == 1){
nClus <- 5
one.clust <- TRUE
} else {
one.clust <- FALSE
}
### Create 'temp' folder
starting.dir <- getwd()
setwd(starting.dir)
dir.create("tmp-cytonorm-fsom")
setwd("tmp-cytonorm-fsom")
### Write files
message("Step 1/4 - Splitting files for use with original FlowSOM function")
dat.list <- unique(dat[[sample.col]])
dat.list
# dat.list <- dat.list[order(dat.list)]
# dat.list
for(i in c(1:length(dat.list))){
# i <- 1
a <- dat.list[[i]]
temp <- dat[dat[[sample.col]] == a,]
write.files(temp,
file.prefix = a,
write.csv = FALSE,
write.fcs = TRUE)
}
files <- list.files(getwd(), ".fcs")
files
## Get batch for each file
batches <- vector()
for(a in files){
#a <- "export_TA203-2.fcs"
a <- gsub(".fcs", "", a)
temp <- dat[dat[[sample.col]] == a,]
res <- temp[[batch.col]][1]
## Should add a test to check for multiple batch entries per sample
batches <- cbind(batches, res)
}
batches <- as.vector(batches)
batches
### Run FlowSOM on ref data (--> save as ref.ff, also save as ref.dat)
message("Step 2/4 - Running FlowSOM")
fsom <- prepareFlowSOM(files,
colsToUse = use.cols,
nCells = nCells, #########################
FlowSOM.params = list(xdim = xdim,
ydim = ydim,
nClus = nClus,
scale = scale),
seed = seed)
if(nrow(fsom$FlowSOM$data) != nrow(dat)){
stop("Error - the numer of rows (cells) is different in the starting dataset and the FlowSOM prepared dataset")
}
#nrow(fsom$FlowSOM$data)
#nrow(dat)
setwd(starting.dir)
### Data, clusters, and metaclusters
# fsom$FlowSOM$data # data
# fsom$FlowSOM$map$mapping[,1] # 1* clusters
# unique(fsom$FlowSOM$map$mapping[,1]) # unique 1* clusters
# fsom$metaclustering # metaclusters
### Mapping
# fsom$metaclustering[fsom$FlowSOM$map$mapping[,1]]
### Merge outputs into Spectre format
message("Step 3/4 - Preparing FlowSOM object and results data.table")
if(one.clust == TRUE){
length(fsom$metaclustering)
fsom$metaclustering <- rep(1, length(fsom$metaclustering))
}
A <- fsom$FlowSOM$data
B <- fsom$FlowSOM$map$mapping[,1]
C <- fsom$metaclustering[fsom$FlowSOM$map$mapping[,1]]
if(nrow(A) != length(B)){
stop("Error - the numer of rows (cells) is different in the data, clusters, and/or metaclusters")
}
if(nrow(A) != length(C)){
stop("Error - the numer of rows (cells) is different in the data, clusters, and/or metaclusters")
}
if(length(B) != length(C)){
stop("Error - the numer of rows (cells) is different in the data, clusters, and/or metaclusters")
}
# nrow(A)
# length(B)
# length(C)
### Merge
fsom.dt <- as.data.table(A)
fsom.dt <- cbind(A, prep.fsom.cluster = B, prep.fsom.metacluster = C)
fsom.dt <- as.data.table(fsom.dt)
# str(fsom.dt)
### Results
setwd(starting.dir)
unlink("tmp-cytonorm-fsom", recursive = TRUE)
files <- gsub(".fcs", "", files)
fsom$files <- files
fsom$filenums <- unique(fsom.dt$File)
fsom$batches <- batches
fsom$features <- use.cols
res <- named.list(fsom, fsom.dt)
message("Step 4/4 - FlowSOM complete")
require(Spectre)
require(data.table)
require(CytoNorm)
require(flowCore)
require(Biobase)
if(nClus == 1){
nClus <- 5
one.clust <- TRUE
} else {
one.clust <- FALSE
}
### Create 'temp' folder
starting.dir <- getwd()
setwd(starting.dir)
dir.create("tmp-cytonorm-fsom")
setwd("tmp-cytonorm-fsom")
### Write files
message("Step 1/4 - Splitting files for use with original FlowSOM function")
dat.list <- unique(dat[[sample.col]])
dat.list
# dat.list <- dat.list[order(dat.list)]
# dat.list
for(i in c(1:length(dat.list))){
# i <- 1
a <- dat.list[[i]]
temp <- dat[dat[[sample.col]] == a,]
write.files(temp,
file.prefix = a,
write.csv = FALSE,
write.fcs = TRUE)
}
files <- list.files(getwd(), ".fcs")
files
## Get batch for each file
batches <- vector()
for(a in files){
#a <- "export_TA203-2.fcs"
a <- gsub(".fcs", "", a)
temp <- dat[dat[[sample.col]] == a,]
res <- temp[[batch.col]][1]
## Should add a test to check for multiple batch entries per sample
batches <- cbind(batches, res)
}
batches <- as.vector(batches)
batches
### Run FlowSOM on ref data (--> save as ref.ff, also save as ref.dat)
message("Step 2/4 - Running FlowSOM")
fsom <- prepareFlowSOM(files,
colsToUse = use.cols,
nCells = nCells, #########################
FlowSOM.params = list(xdim = xdim,
ydim = ydim,
nClus = nClus,
scale = scale),
seed = seed)
if(nrow(fsom$FlowSOM$data) != nrow(dat)){
stop("Error - the numer of rows (cells) is different in the starting dataset and the FlowSOM prepared dataset")
}
#nrow(fsom$FlowSOM$data)
#nrow(dat)
setwd(starting.dir)
### Data, clusters, and metaclusters
# fsom$FlowSOM$data # data
# fsom$FlowSOM$map$mapping[,1] # 1* clusters
# unique(fsom$FlowSOM$map$mapping[,1]) # unique 1* clusters
# fsom$metaclustering # metaclusters
### Mapping
# fsom$metaclustering[fsom$FlowSOM$map$mapping[,1]]
### Merge outputs into Spectre format
message("Step 3/4 - Preparing FlowSOM object and results data.table")
if(one.clust == TRUE){
length(fsom$metaclustering)
fsom$metaclustering <- rep(1, length(fsom$metaclustering))
}
A <- fsom$FlowSOM$data
B <- fsom$FlowSOM$map$mapping[,1]
C <- fsom$metaclustering[fsom$FlowSOM$map$mapping[,1]]
if(nrow(A) != length(B)){
stop("Error - the numer of rows (cells) is different in the data, clusters, and/or metaclusters")
}
if(nrow(A) != length(C)){
stop("Error - the numer of rows (cells) is different in the data, clusters, and/or metaclusters")
}
if(length(B) != length(C)){
stop("Error - the numer of rows (cells) is different in the data, clusters, and/or metaclusters")
}
# nrow(A)
# length(B)
# length(C)
### Merge
fsom.dt <- as.data.table(A)
fsom.dt <- cbind(A, prep.fsom.cluster = B, prep.fsom.metacluster = C)
fsom.dt <- as.data.table(fsom.dt)
# str(fsom.dt)
### Results
setwd(starting.dir)
unlink("tmp-cytonorm-fsom", recursive = TRUE)
files <- gsub(".fcs", "", files)
fsom$files <- files
fsom$filenums <- unique(fsom.dt$File)
fsom$batches <- batches
fsom$features <- use.cols
res <- named.list(fsom, fsom.dt)
message("Step 4/4 - FlowSOM complete")
res
### Load packages
library(Spectre)
library(SpectreMAP)
package.check()
package.load()
library('tiff') # for reading tiffs
library('raster') # managing images as rasters
library('rgeos') # spatial functions
library('tidyr') # to use the 'gather' function
library('sp') # spatial functions (in particular, for fast creation of polygons)
library('sf') # spatial functions (in particular, for fast creation of polygons)
library('stars') # spatial functions (in particular, for fast creation of polygons)
library('velox') # fast creation of 'single cell' data
### Set PrimaryDirectory
dirname(rstudioapi::getActiveDocumentContext()$path) # Finds the directory where this script is located
setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) # Sets the working directory to where the script is located
getwd()
PrimaryDirectory <- getwd()
PrimaryDirectory
### Create output directory
setwd(PrimaryDirectory)
dir.create("Output - SpectreMAP demo")
setwd("Output - SpectreMAP demo")
OutputDirectory <- getwd()
###################################################################################
### Read in TIFF channel images
###################################################################################
### Read TIFF files into spatial.dat object
setwd(PrimaryDirectory)
setwd("ROIs/")
rois <- list.dirs(getwd(), full.names = FALSE, recursive = FALSE)
as.matrix(rois)
spatial.dat <- SpectreMAP::read.spatial.files(roi.loc = getwd(), rois = rois)
### Check the spatial data object
as.matrix(names(spatial.dat)) # ROI names
str(spatial.dat, 3) # shows the structure
as.matrix(names(spatial.dat[[1]]$RASTERS)) # TIFF names of first ROI
###################################################################################
### Read in masks
###################################################################################
### Setup to read masks
setwd(PrimaryDirectory)
setwd("Masks")
list.files()
mask.ext <- "_ilastik_s2_Probabilities_mask.tiff"
masks <- list.files(pattern = mask.ext)
masks
### Read in masks and add to spatial.dat
spatial.dat <- do.add.masks(spatial.dat = spatial.dat,
mask.loc = getwd(),
masks = masks,
mask.ext = mask.ext,
mask.label = "cell_mask")
### Review
str(spatial.dat, 3) # shows the structure
###################################################################################
### Create mask outlines/polygons and calculate cellular data
###################################################################################
### Review mask names
names(spatial.dat[[1]]$MASKS)
### Calculate polygons and outlines for each mask object
spatial.dat <- do.create.outlines(spatial.dat = spatial.dat,
mask.name = "cell_mask")
str(spatial.dat, 3)
str(spatial.dat[[1]]$MASKS$cell_mask, 1)
###################################################################################
### Extract 'cellular' data using masks
###################################################################################
### Calculate cellular data
spatial.dat <- do.extract(dat = spatial.dat, mask = "cell_mask", name = "CellData", fun = "mean")
spatial.dat
str(spatial.dat, 3)
spatial.dat[[1]]$DATA
str(spatial.dat, 3)
setwd(OutputDirectory)
dir.create("Spatial plots")
setwd("Spatial plots")
as.matrix(names(spatial.dat))
as.matrix(names(spatial.dat[[1]]$RASTERS))
make.spatial.plot(spatial.dat = spatial.dat,
image.roi = '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',
image.channel = "CD20_Dy161")
make.spatial.plot(spatial.dat = spatial.dat,
image.roi = '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',
image.channel = "CD20_Dy161",
mask.outlines = "cell_mask")
make.spatial.plot(spatial.dat = spatial.dat,
image.roi = '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',
image.channel = "CD20_Dy161",
mask.outlines = "cell_mask",
cell.dat = "CellData",
cell.col = "CD20_Dy161")
setwd(OutputDirectory)
dir.create("Cellular plots")
setwd("Cellular plots")
cell.dat <- do.pull.data(spatial.dat = spatial.dat,
target.dat = "CellData")
cell.dat
as.matrix(names(cell.dat))
cellular.cols <- names(cell.dat)[c(17:29)]
as.matrix(names(cell.dat))
clustering.cols <- names(cell.dat)[c(18:24,29)]
cell.dat <- do.asinh(cell.dat, cellular.cols, cofactor = 1)
cellular.cols <- paste0(cellular.cols, "_asinh")
clustering.cols <- paste0(clustering.cols, "_asinh")
cell.dat <- run.flowsom(cell.dat, clustering.cols, meta.k = 10)
cell.dat <- run.umap(cell.dat, clustering.cols)
make.colour.plot(cell.dat, "UMAP_X", "UMAP_Y", col.axis = "FlowSOM_metacluster", col.type = 'factor', add.label = TRUE)
make.multi.plot(cell.dat, "UMAP_X", "UMAP_Y", cellular.cols)
make.spatial.plot(spatial.dat = spatial.dat,
image.roi = '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',
image.channel = "CD20_Dy161",
mask.outlines = "cell_mask",
cell.dat = cell.dat[cell.dat[["ROI"]] == '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',],
cell.col = "CD20_Dy161")
make.spatial.plot(spatial.dat = spatial.dat,
image.roi = '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',
image.channel = "CD20_Dy161",
mask.outlines = "cell_mask",
cell.dat = cell.dat[cell.dat[["ROI"]] == '20171228_spleen315_500x500_editedforFAS_s1_p9_r2_a2_ac',],
cell.col = "FlowSOM_metacluster",
cell.col.type = 'factor')
exp <- do.aggregate(dat = cell.dat, use.cols = cellular.cols, by = 'FlowSOM_metacluster', func = 'mean')
make.pheatmap(dat = exp, sample.col = 'FlowSOM_metacluster', plot.cols = cellular.cols)
setwd(OutputDirectory)
dir.create("Data")
setwd("Data")
all.neg <- function(test) -1*abs(test)
y_invert <- cell.dat[['y']]
y_invert <- all.neg(y_invert)
cell.dat[['y_invert']] <- y_invert
cell.dat
write.files(cell.dat, "Sp_AllData", write.csv = TRUE, write.fcs = TRUE)
write.files(cell.dat, "Sp", divide.by = "ROI", write.csv = TRUE, write.fcs = TRUE)
saveRDS(spatial.dat, 'spatial.data.rds')
library(Spectre)
Spectre::demo.clustered
cell.dat <- Spectre::demo.clustered
cell.dat
sub <- cell.dat[1,]
sub
cell.dat[,c(1,3,5)]
cell.dat[,c(1:10,5)]
as.mattrix(names(cell.dat))
as.matrix(names(cell.dat))
## Select columns names 11 to 19
cols <- names(cell.dat)[c(11:19)]
cols
## OPTION 1 - Select columns using '..'
sub <- cell.dat[,..cols]
sub
## OPTION 2 - Select columns using 'with = FALSE'
sub <- cell.dat[,cols, with = FALSE]
sub
sub <- cell.dat[cell.dat[["Ly6C_asinh"]] > 2,]
sub
sub <- cell.dat[cell.dat[["Ly6C_asinh"]] > 2,]
sub
sub <- cell.dat[cell.dat[["FlowSOM_metacluster"]] == 5,]
sub
cell.dat
cell.dat[["FlowSOM_metacluster"]] == 5
sub <- cell.dat[cell.dat[["Ly6C_asinh"]] > 2 |
cell.dat[["Population"]] == 'Infil Macrophages'
,]
sub
ibrary(devtools)
library(roxygen2)
setwd("/Users/thomasa/Google Drive File Stream/My Drive/_Sydney Cytometry/Libraries (synced)/GitHub/Public github/SpectreMAP/")
document()
library(devtools)
library(roxygen2)
setwd("/Users/thomasa/Google Drive File Stream/My Drive/_Sydney Cytometry/Libraries (synced)/GitHub/Public github/SpectreMAP/")
document()
## Install devtools (if not already installed)
if(!require('devtools')) {install.packages('devtools')}
### Install Spectre and SpectreMAP
library('devtools')
#install_github("sydneycytometry/spectre")
install_github("tomashhurst/SpectreMAP")