/
QuantileNorm.R
506 lines (466 loc) · 20.1 KB
/
QuantileNorm.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
#' getQuantiles
#'
#' @param files Full paths of to the fcs files of the samples
#' @param channels Names of the channels to compute the quantiles for
#' @param transformList Transformation list to pass to the flowCore
#' \code{transform} function
#' @param nQ Number of quantiles to compute Default = 101, which
#' results in quantiles for every percent of the data.
#' Ignored if quantileValues is given.
#' @param minCells Minimum number of cells required to compute trust-worthy
#' quantiles. Otherwise NA is returned. Default = 50.
#' @param quantileValues Vector of length with values between 0 and 1, giving
#' the percentages at which the quantiles should be
#' computed. If NULL (default), the quantiles will be
#' evenly distributed, including 0 and 1.
#' @param labels A label for every file, indicating to which group it
#' belongs. If multiple files have the same label, they
#' get aggregated. If NULL, all files are handled separately.
#' @param selection List with indexation vector for every file.
#' @param verbose If TRUE, extra output is printed. Default = FALSE
#' @param plot If TRUE, plots are generated showing all quantiles.
#' Default = FALSE.
#'
#' @examples
#' dir <- system.file("extdata", package = "CytoNorm")
#' files <- list.files(dir, pattern = "fcs$")
#'
#' ff <- flowCore::read.FCS(file.path(dir, files[1]))
#' channels <- grep("Di$", flowCore::colnames(ff), value = TRUE)
#' transformList <- flowCore::transformList(channels,
#' cytofTransform)
#'
#' quantiles <- getQuantiles(files = file.path(dir, files),
#' channels = channels,
#' transformList = transformList)
#'
#' pheatmap::pheatmap(quantiles[[1]],
#' cluster_rows = FALSE,
#' cluster_cols = FALSE,
#' labels_col =
#' paste0(FlowSOM::get_markers(ff, colnames(quantiles[[1]])),
#' " (", colnames(quantiles[[1]]), ")"),
#' main = files[1])
#'
#' @export
getQuantiles <- function(files,
channels,
nQ = 101,
minCells = 50,
quantileValues = NULL,
transformList = NULL,
labels = NULL,
selection = NULL,
verbose = FALSE,
plot = FALSE){
if (is.null(labels)) labels <- files
# Compute quantiles for each label
if (verbose) message("Computing Quantiles")
quantiles <- list()
if (is.null(quantileValues)) {
quantileValues <- c(0, (1:(nQ-1))/(nQ-1))
} else {
nQ <- length(quantileValues)
}
for(label in unique(labels)){
ids <- which(labels == label & file.exists(files))
if(verbose) message(" ", label, " (FileID ", paste(ids, collapse = "," ), ")")
# Read the file(s) and transform if necessary
if (length(ids) > 1) {
ff <- FlowSOM::AggregateFlowFrames(files[ids], 1e12, keepOrder = TRUE)
} else if(length(ids) == 1) {
o <- capture.output(ff <- flowCore::read.FCS(files[ids]))
if (verbose) message(o)
} else {
ff <- NULL
}
if (!is.null(ff) && !is.null(transformList)) {
ff <- flowCore::transform(ff, transformList)
}
if (!is.null(ff) & !is.null(selection)){
ff <- ff[selection[[file]], ]
}
# Compute quantiles for all channels to normalize
if (!is.null(ff) && flowCore::nrow(ff) > minCells) {
quantiles[[label]] <- apply(flowCore::exprs(ff)[, channels],
2,
function(x){
stats::quantile(x,
quantileValues)
})
if(plot){
textPlot(label)
for(channel in channels){
dens <- stats::density(flowCore::exprs(ff)[, channel],
bw = 0.1)
graphics::plot(dens,
bty = "n", xaxt = "n", yaxt = "n",
xlab = "", ylab = "", main = "",
xlim = c(0,
max(flowCore::exprs(ff)[, channel],
8)))
graphics::abline(v = quantiles[[label]][, channel],
col = "grey")
graphics::lines(dens, lwd = 2)
}
}
} else {
if(is.null(ff)){
message(" Could not find ", paste(files[ids], collapse = ", "))
} else {
message(" Less then ", minCells, " cells in ", label,
" (", flowCore::nrow(ff), "). No quantiles computed.")
}
quantiles[[label]] <- matrix(NA,
nrow = nQ,
ncol = length(channels),
dimnames =
list(as.character(quantileValues),
channels))
if(plot){
textPlot(label)
for(channel in channels){
textPlot("NA")
}
}
}
}
return(quantiles)
}
#' QuantileNorm.train
#'
#' Learn the batch effects from control samples.
#' This function computes quantiles to describe the distribution of the data,
#' and infers spline functions to equalize these distributions over the files.
#' Typically, you will use the function \code{\link{QuantileNorm.normalize}}
#' after this function to reverse the batch effects on other files.
#'
#' @param files Full paths of to the fcs files of the control samples
#' @param labels A label for every file, indicating to which batch it
#' belongs, e.g. the plate ID.
#' @param channels Names of the channels to normalize
#' @param transformList Transformation list to pass to the flowCore
#' \code{transform} function
#' @param nQ Number of quantiles to use. Default = 101, which results in
#' quantiles for every percent of the data.
#' @param quantileValues If specified, it should be a vector of length nQ with
#' values between 0 and 1, giving the percentages at
#' which the quantiles should be computed. If NULL
#' (default), the quantiles will be evenly distributed,
#' including 0 and 1.
#' @param limit These values will be modelled to map onto themselves by the
#' spline
#' @param goal Goal distribution. Default "mean", can also be nQ numeric
#' values or one of the batch labels.
#' @param plot If TRUE, a plot is generated (using the \code{layout}
#' function) showing all quantiles. Default = FALSE.
#' @param plotTitle Title to use in the plot. Default = "Quantiles".
#' @param verbose If TRUE, progress updates are printed. Default = FALSE.
#'
#' @return A list containing all the splines and quantile information. This can
#' be used as input for the \code{\link{QuantileNorm.normalize}} function.
#' @seealso \code{\link{CytoNorm.train}}, \code{\link{QuantileNorm.normalize}}
#'
#' @examples
#'
#' dir <- system.file("extdata", package = "CytoNorm")
#' files <- list.files(dir, pattern = "fcs$")
#' data <- data.frame(File = files,
#' Path = file.path(dir, files),
#' Type = stringr::str_match(files, "_([12]).fcs")[,2],
#' Batch = stringr::str_match(files, "PTLG[0-9]*")[,1],
#' stringsAsFactors = FALSE)
#' data$Type <- c("1" = "Train", "2" = "Validation")[data$Type]
#' train_data <- dplyr::filter(data, Type == "Train")
#'
#' ff <- flowCore::read.FCS(data$Path[1])
#' channels <- grep("Di$", flowCore::colnames(ff), value = TRUE)
#' transformList <- flowCore::transformList(channels,
#' cytofTransform)
#'
#' png("nQ101.png",
#' width = length(channels) * 300,
#' height = (nrow(train_data) * 2 + 1) * 300)
#' model_nQ_101 <- QuantileNorm.train(
#' files = train_data$Path,
#' labels = train_data$Batch,
#' channels = channels,
#' transformList = transformList,
#' nQ = 101,
#' plot = TRUE)
#' dev.off()
#'
#' png("nQ101_limited.png",
#' width = length(channels) * 300,
#' height = (nrow(train_data) * 2 + 1) * 300)
#' model_nQ_101 <- QuantileNorm.train(
#' files = train_data$Path,
#' labels = train_data$Batch,
#' channels = channels,
#' transformList = transformList,
#' nQ = 101,
#' limit = c(0,8),
#' plot = TRUE)
#' dev.off()
#'
#' png("nQ_2.png",
#' width = length(channels) * 300,
#' height = (nrow(train_data) * 2 + 1) * 300)
#' model_nQ_2 <- QuantileNorm.train(
#' files = train_data$Path,
#' labels = train_data$Batch,
#' channels = channels,
#' transformList = transformList,
#' nQ = 2,
#' quantileValues = c(0.001, 0.999),
#' plot = TRUE)
#' dev.off()
#'
#' model_goal_mean <- QuantileNorm.train(
#' files = train_data$Path,
#' labels = train_data$Batch,
#' channels = channels,
#' transformList = transformList)
#'
#' model_goal_batch1 <- QuantileNorm.train(
#' files = train_data$Path,
#' labels = train_data$Batch,
#' channels = channels,
#' transformList = transformList,
#' goal = "PTLG021")
#'
#' model_goal_fixed <- QuantileNorm.train(
#' files = train_data$Path,
#' labels = train_data$Batch,
#' channels = channels,
#' transformList = transformList,
#' nQ = 21,
#' goal = seq(0, 1, by = 0.05))
#'
#' @export
QuantileNorm.train <- function(files,
labels,
channels,
transformList,
nQ = 101,
limit = NULL,
quantileValues = NULL,
goal = "mean",
verbose = FALSE,
plot = FALSE,
plotTitle = "Quantiles"){
if(length(labels) != length(files)){
stop("Input parameters 'labels' and 'files'",
" should have the same length")
}
labels <- as.character(labels)
if(plot){
xdim = 1 + length(channels)
ydim = 2 + 2*length(unique(labels))
graphics::layout(matrix(1:(xdim*ydim), ncol = xdim, byrow = TRUE))
graphics::par(mar=c(1, 1, 0, 0))
textPlot(plotTitle)
ff_tmp <- flowCore::read.FCS(files[file.exists(files)][1])
for(channel in channels){
marker <- flowCore::getChannelMarker(ff_tmp, channel)[,2]
if(is.na(marker)){
textPlot(channel)
} else {
textPlot(paste0(marker, " (", channel, ")"))
}
}
}
quantiles <- getQuantiles(files = files,
labels = labels,
channels = channels,
transformList = transformList,
nQ = nQ,
quantileValues = quantileValues,
verbose = verbose,
plot = plot)
# Get the goal distributions
if(is.character(goal) && goal == "mean"){
refQuantiles <- matrix(apply(matrix(unlist(quantiles),
ncol = length(unique(labels))),
1, mean, na.rm = TRUE),
nrow = nQ,
dimnames = list(c(0,(1:(nQ-1))/(nQ-1)),
channels))
} else if (is.numeric(goal)) {
if(length(goal) == nQ){
refQuantiles <- matrix(goal,
nrow = nQ,
ncol = length(channels),
dimnames = list(quantileValues,
channels))
} else if ((nrow(goal) == nQ) & (ncol(goal) == length(channels))){
refQuantiles <- goal
} else {
stop("Goal should be 'mean', a batch label",
"a numeric vector of length nQ, or a matrix with nQ rows
and length(channels) columns.")
}
} else if (goal %in% unique(labels)) {
refQuantiles <- quantiles[[goal]]
} else {
stop("Goal should be 'mean', a batch label",
"a numeric vector of length nQ, or a matrix with nQ rows
and length(channels) columns.")
}
if(plot){
textPlot("Goal distribution")
for(channel in channels){
graphics::plot(0, type = "n", xlim = c(0, 8),
bty = "n", xaxt = "n", yaxt = "n",
xlab = "", ylab = "", main = "")
graphics::abline(v = refQuantiles[,channel])
}
}
# Compute splines for each label
splines <- list()
if(verbose) message("Computing Splines")
for(label in unique(labels)){
if(verbose) message(" ",label)
if(plot){ textPlot(label) }
splines[[label]] <- list()
if(!is.null(quantiles[[label]]) & !any(is.na(quantiles[[label]])) & !any(is.na(refQuantiles))){
for(channel in channels){
refQ <- refQuantiles[, channel]
labelQ <- quantiles[[label]][, channel]
if(!is.null(limit)){
refQ <- c(refQ, limit)
labelQ <- c(labelQ, limit)
}
if(length(unique(labelQ)) > 1){
suppressWarnings(spl <- stats::splinefun(labelQ,
refQ,
method="monoH.FC"))
} else {
spl <- identityFunction
warning("Not enough unique quantiles for ", label, " in ",
channel, ". The identity function will be used.")
}
splines[[label]][[channel]] <- spl
if(plot){
graphics::plot(labelQ, refQ, xlim = c(0, 8), ylim = c(0, 8),
pch = 19, bty = "n", xaxt = "n", yaxt = "n",
xlab = "", ylab = "", main = "")
graphics::lines(c(-0.5, 8), c(-0.5, 8), col="#999999")
x <- seq(-0.5, 8, 0.1)
graphics::lines(x,
splines[[label]][[channel]](x),
col = "#b30000")
}
}
} else {
warning("Not enough cells for ", label,
"\nThe identity function will be used.")
for(channel in channels){
splines[[label]][[channel]] <- identityFunction
if(plot){
graphics::plot(c(0,8), c(0,8), col = "#999999", type = "l",
xlim = c(0,8), ylim = c(0,8),
pch = 19, bty = "n", xaxt = "n", yaxt = "n",
xlab = "", ylab = "", main = "")
}
}
}
}
named.list(channels, splines, quantiles, quantileValues, refQuantiles)
}
#' QuantileNorm.normalize
#'
#' Normalize data, given the batch effects learned from control samples per
#' cell type/cluster (output from \code{\link{QuantileNorm.train}}). New fcs
#' files are written to the given output directory.
#'
#' @param model Model of the batch effercts, as computed by
#' \code{\link{QuantileNorm.train}}
#' @param files Full paths of to the fcs files of the samples to normalize
#' @param labels A label for every file, indicating to which batch it
#' belongs, e.g. the plate ID.
#' @param transformList Transformation list to pass to the flowCore
#' \code{transform} function
#' @param transformList.reverse Transformation list with the reverse functions,
#' so the normalized files can be saved in the untransformed
#' space
#' @param outputDir Directory to put the temporary files in. Default = "."
#' @param prefix Prefix to put in front of the normalized file names.
#' Default = "Norm_"
#' @param removeOriginal Should the original fcs be removed? Default = FALSE.
#' @param verbose If TRUE, progress updates are printed. Default = FALSE.
#'
#' @return Nothing is returned, but the new FCS files are written to the output
#' directory
#' @seealso \code{\link{QuantileNorm.train}}
#'
#' @examples
#'
#' @export
QuantileNorm.normalize <- function(model,
files,
labels,
transformList,
transformList.reverse,
outputDir = ".",
prefix = "Norm_",
removeOriginal = FALSE,
verbose = FALSE){
if(is.null(model$channels) |
is.null(model$splines) |
is.null(model$quantiles)){
stop("The 'model' parameter should be the result of using the ",
"QuantileNorm.train function.")
}
if(length(labels) != length(files)){
stop("Input parameters 'labels' and 'files' ",
"should have the same length")
}
# Create temporary directory
if (!dir.exists(outputDir)) dir.create(outputDir)
labels <- labels
channels <- model$channels
# Normalize each file based on label
for(i in seq_along(files)){
file <- files[i]
if(file.exists(file)){
label <- as.character(labels[i])
if(verbose) message(" ",file," (",label,")")
if(label %in% names(model$splines)){
# Read the file
ff <- flowCore::read.FCS(file)
# Transform if necessary
if(!is.null(transformList)){
#description_original <- ff@description
#parameters_original <- ff@parameters
ff <- flowCore::transform(ff, transformList)
}
# Overwrite the values with the normalized values
if (verbose) message("Normalizing ",label)
for (channel in channels) {
flowCore::exprs(ff)[, channel] <-
model$splines[[label]][[channel]](
flowCore::exprs(ff[, channel]))
}
if (!is.null(transformList.reverse)) {
ff <- flowCore::transform(ff, transformList.reverse)
} else if (!is.null(transformList)) {
warning("Please provide a reverse transformation list if
you want the files to be saved in the original
untransformed space.")
}
suppressWarnings(flowCore::write.FCS(ff,
filename = file.path(outputDir,
paste0(prefix,
gsub(".*/","",file)))))
if (removeOriginal) {
file.remove(file)
}
} else {
warning("The model was not trained for ", label, ".")
}
} else {
warning(file, " does not exist, skipped.")
}
}
}