-
Notifications
You must be signed in to change notification settings - Fork 0
/
normalization.Rmd
1502 lines (1233 loc) · 54 KB
/
normalization.Rmd
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: "Normalization of the untargeted metabolomics data from CHRIS"
author: "Mar Garcia-Aloy, Johannes Rainer"
output:
BiocStyle::html_document:
toc: true
number_sections: false
toc_float: true
---
```{r include = FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
startpoint <- Sys.time()
```
In this document we are going to normalize the data from the CHRIS study.
# Preliminaries
We define the specific parameters for the current study, we load all
required libraries, and we set up the parallel processing.
## Parameters
```{r param, echo=TRUE}
polarity <- "NEG" # specify "POS" or "NEG"
myseed <- 589
da <- 0.01
# DEFINE PATHS:
IMAGE_PATH <- paste0("images/", polarity, "/normalization/")
dir.create(IMAGE_PATH, showWarnings = FALSE)
```
## Libraries
```{r libraries, echo=TRUE, warning=FALSE}
library(doParallel)
library(xcms)
library(Rdisop)
library(CompoundDb)
library(CompMetaboTools)
library(ggplot2)
library(RColorBrewer)
library(gridExtra)
library(reshape2)
library(beeswarm)
library(DESeq2)
library(pander)
library(readxl)
source("R/dobox.R")
## source("R/flag_model_inj_range.R")
## source("R/flag_model_cat_count.R")
## source("R/flag_model_mean_residual.R")
source("R/apply_colgroup.R")
source("R/mean_if.R")
source("R/plot_slope.R")
## source("R/flag_model_coef_count.R")
```
## Parallel processing
```{r parallel-cluster, eval=TRUE}
ncores <- Sys.getenv("SLURM_JOB_CPUS_PER_NODE", 3)
register(bpstart(MulticoreParam(ncores)))
```
# Load data
Below we load the data already processed with XCMS. Note that we have to
change/update the path to the original mzML files in case the
pre-processing was performed on a different computer (e.g. the cluster).
```{r data-load, echo=TRUE}
load(paste0("data/data_XCMS_filled_", polarity, ".RData"))
## Update the file path.
#if (length(validObject(xdata, test = TRUE)))
# dirname(xdata) <- sub("/data/massspec/mzML/", MZML_PATH,
# dirname(xdata), fixed = TRUE)
xdata$batch <- factor(xdata$batch)
batch_margin <- c()
for(i in 1:length(levels(xdata$batch))){
batch_margin <-
c(batch_margin, which(xdata$batch == levels(xdata$batch)[i])[
length(which(xdata$batch == levels(xdata$batch)[i]))])
}
```
Next we extract the raw as well as the filled-in feature abundances
with the `quantify` method. For features with multiple peaks the sum
is built to create a final abundance (parameter `method = "sum"`).
```{r data-extract, echo = FALSE, results = "hide"}
res <- quantify(xdata, method = "sum", filled = FALSE)
assays(res)$raw_filled <- featureValues(xdata, method = "sum",
filled = TRUE)
```
Below we load the Biocrates-based targeted metabolomics data.
The data is organized by having metabolites in the data’s rows,
samples in columns.
```{r biocrates, echo=TRUE}
injections <- read_xlsx("data/chris-files-annotated.xlsx")
injections <- injections[injections$sample_name %in%
gsub(".mzML", "", res$sampleNames), ]
injections <- injections[order(injections$timestamp), ]
library(biochristes7500)
data(biochristes7500)
all(injections$sample_name == gsub(".mzML", "", res$sampleNames)) # T
biocrates <- concentrations(biochristes7500, blessing = "none")
biocrates <- biocrates[, colnames(biocrates) %in% injections$id]
std_bioc <- read.csv("data/stds_biocrates.csv", stringsAsFactors = FALSE)
std_bioc <- std_bioc[std_bioc$abbreviation != "X", ]
biocrates <- biocrates[rownames(biocrates) %in% std_bioc$analyte_name, ]
```
## Colouring factors
Here we define colors to be used for the various experimental groups
throughout the experiment.
```{r colors, echo=TRUE}
xdata$class <- factor(xdata$class)
col_class <- brewer.pal(length(levels(xdata$class)), "Set1")
names(col_class) <- levels(xdata$class)
sample_colors <- col_class[xdata$class]
plot(1, 1, xaxt = 'n', yaxt = 'n', bty = 'n', ylab = '', xlab = '',
xlim = 0:1, ylim = 0:1)
legend("topleft", legend = names(col_class),
col = col_class, pch = 16, pt.cex = 2, cex = 2,
bty = 'n')
getPalette <- colorRampPalette(brewer.pal(9, "YlOrRd"))
col_batch <- getPalette(length(levels(xdata$batch)))
names(col_batch) <- levels(xdata$batch)
plot(1, 1, xaxt = 'n', yaxt = 'n', bty = 'n', ylab = '', xlab = '',
xlim = 0:1, ylim = 0:1)
legend("topleft", legend = names(col_batch),
col = col_batch, pch = 16, #pt.cex = 2, cex = 2,
bty = 'n', ncol = 5)
```
## Standards library
Next we determine which features match to the set of compounds for which
retention time and most likely ion have been determined.
To this end we get all features with their median retention time
within the expected retention time +/- 5 seconds and an m/z matching the
m/z of the expected ion (+/- 50 ppm). If more than one feature is found
for a standard, the one with the higher number of peaks is chosen,
if none if found the retention time window is extended to +/- 10 seconds.
All the detected features will be ploted in order to see which are good-quality features.
They will be used in the later steps for evaluating the performance of the normalization.
```{r features-for-standards}
is_info <- read.table(
"https://raw.githubusercontent.com/EuracBiomedicalResearch/lcms-standards/master/data/internal_standards.txt",
sep = "\t", header = TRUE, as.is = TRUE)
is_info$mix <- 0
is_info$"HMDB.code" <- NA
is_info <-
subset(is_info,
select = c("mix", "name", "abbreviation", "HMDB.code",
"formula", "POS", "NEG", "RT", "data_set", "sample",
"operator", "version", "quality_POS", "quality_NEG"))
std_info <- read.table(
"https://raw.githubusercontent.com/EuracBiomedicalResearch/lcms-standards/master/data/standards_dilution.txt",
sep = "\t", header = TRUE, as.is = TRUE)
std_info <- rbind(is_info, std_info)
rm(is_info)
std_info <- std_info[!is.na(std_info[, polarity]), ]
std_info <- std_info[!is.na(std_info$RT), ]
rownames(std_info) <- 1:nrow(std_info)
std_info$mzneut = NA
std_info$mz_ion = NA
for (i in seq(nrow(std_info))) {
if (grepl("C", std_info$formula[i])){
std_info$mzneut[i] <- getMolecule(
as.character(std_info$formula[i]))$exactmass
} else {
std_info$mzneut[i] = as.numeric(std_info$formula[i])
}
#' Calculate also the m/z
std_info$mz_ion[i] <- unlist(
mass2mz(std_info$mzneut[i],
adduct = as.character(
std_info[i, polarity])))
}
## Get for each standard a feature
std_info$feature_id <- NA_character_
for (i in seq(nrow(std_info))) {
ft <- featureDefinitions(xdata, mz = std_info$mz_ion[i],
rt = std_info$RT[i] + c(-5, 5),
ppm = 50, type = "any")
if (nrow(ft))
std_info$feature_id[i] <- rownames(ft[
order(ft$npeaks, decreasing = TRUE), ])[1]
else {
ft <- featureDefinitions(xdata, mz = std_info$mz_ion[i],
rt = std_info$RT[i] + c(-10, 10),
ppm = 50, type = "any")
if (nrow(ft))
std_info$feature_id[i] <- rownames(ft[
order(ft$npeaks, decreasing = TRUE), ])[1]
}
}
std_info$diff_rt <- std_info$RT -
featureDefinitions(xdata)[std_info$feature_id, "rtmed"]
std_info <- std_info[!is.na(std_info$feature_id), ]
#rownames(std_info) <- std_info$HMDB.code
#std_info$is_ok <- FALSE
#std_info$peak_note <- NA_character_
#write.table(std_info, file = paste0("data/std_info_", polarity, ".txt"),
# row.names = FALSE, sep = "\t")
```
```{r features-for-standards-plot, eval=FALSE}
dr <- paste0(IMAGE_PATH, "peak_shape/")
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in 1:nrow(std_info)) {
chrs <- featureChromatograms(xdata,
features = std_info$feature_id[i],
expandRt = 10, filled = TRUE)
pk_col <- col_class[chrs$class[chromPeaks(chrs)[, "sample"]]]
png(file = paste0(dr, std_info$feature_id[i], ".png"),
width = 12, height = 8, units = "cm", res = 300, pointsize = 4)
plot(chrs, peakPch = 16,
peakCol = paste0(pk_col, 80),
peakBg = paste0(pk_col, 10))
dev.off()
}
```
The table below lists the standards for which a feature was identified.
```{r standards-feature-table, echo = FALSE, results = "asis"}
T <- std_info[!is.na(std_info$feature_id), c("name", "quality_POS",
"feature_id", "diff_rt")]
rownames(T) <- NULL
pandoc.table(
T, style = "rmarkdown",
caption = paste0("Features for standards. Shown is the name, the",
" quality of the peak in the standards spike-in",
" experiment and the difference between the rt",
" in that and the present data set."))
```
For `r nrow(std_info)` standards a feature was detected/defined in the
present data set.
# Raw data
Before performing any data normalization we also evaluate the raw signal.
Following [@irizarryComparisonAffymetrixGeneChip2006] we distinguish
between *accuracy* and *precision* in evaluation of normalization
efficiency. High accuracy means that reported differences are highly similar to
the *real* differences in abundances, while high precision means that the
variation between replicated measurements is low. Low accuracy on the other hand
means that the measured data over- or underestimates the *real* differences or
abundances in the data and low precision that repeated measurements of the same
entity in the same sample yields different abundances.
To estimate the accuracy, we will use the targed measurements done with
Biocrates kit and to estimate the precision the repeated measurements of the
QC samples. The tools and visualization for these are linear models
for the former (measured against quantified concentrations) and coefficient of
variation (CV) and relative log-abundances (RLA) for the later. Precision
estimates will be performed separately for features of known compounds
(standards) and for all detected features in the data set.
Precision will be also evaluated using samples that were repeated in
2 different batches (POS: 20170615-20170728; NEG: 20170609-20170623)
First of all we calculate feature-wise RLA values considering the type of samples
(*blank*, *pool*, and *study_sample*) as grouping variable.
```{r raw-rla}
rla_raw <- rowRla(assay(res, "raw_filled"), group = res$class)
```
The plot below shows the distribution of RLA values per sample for the complete
data set.
```{r raw-rla-plot, fig.width = 16, fig.height = 6, fig.cap = "RLA of the raw data", echo = FALSE}
dobox(rla_raw, ylab = "RLA", main = "raw data",
col = col_class[res$class],
border = paste0(col_class[res$class], 40))
legend("bottomleft", col = col_class, legend = names(col_class),
h = TRUE, pch = 16)
```
Next we calculate CV values for each feature across QC samples.
```{r raw-rsd}
rsd_calculate <- function(x) {
## general
cvs <- data.frame(rowRsd(x[, res$class == "pool"]))
colnames(cvs) <- c("QC")
for (btch in levels(res$batch)) {
tmp <- data.frame(
rowRsd(x[, res$class == "pool" & res$batch == btch])
)
colnames(tmp) <- paste(c("QC"),
btch, sep = "_b")
cvs <- cbind(cvs, tmp)
}
cvs
}
cv_raw <- rsd_calculate(assay(res, "raw_filled"))
```
The table below lists the CV quantiles (across all features) for the QC samples.
```{r raw-rsd-table, results = "asis", echo = FALSE}
T <- quantile(cv_raw[, "QC"], na.rm = TRUE)
pandoc.table(round(T, 3), style = "rmarkdown",
caption = "Distribution of CV for QC samples (raw data).")
```
The percentage of features with a CV > 0.3 in QC samples is
`r round(sum(cv_raw$QC > 0.3, na.rm = TRUE) / length(cv_raw$QC)*100,1)`%.
The next table shows the CV quantiles for the features associated with
standards.
```{r raw-rsd-table-standards, results = "asis", echo = FALSE}
T <- quantile(cv_raw[std_info$feature_id, "QC"], na.rm = TRUE)
pandoc.table(round(T, 3), style = "rmarkdown",
caption = paste0("Distribution of CV for QC samples ",
"(raw data, features for standards)."))
```
The percentage of known features with a CV > 0.3 in QC samples is
`r round(sum(cv_raw[std_info$feature_id, "QC"] > 0.3, na.rm = TRUE) / length(cv_raw[std_info$feature_id, "QC"])*100,1)`%.
The table below lists the absolute differences quantiles
(across all features) for duplicated samples.
```{r raw-diff-table, results="asis"}
dplc <- injections[!is.na(injections$id),]
dplc <- dplc[dplc$id %in% dplc$id[duplicated(dplc$id)], ]
unique_id <- unique(dplc$id)
diff_calculate <- function(x){
set.seed(myseed)
dt <- imputeRowMinRand(
x, method = "from_to",
min_fraction = 1/2,
min_fraction_from = 1/1000
)
dt <- dt[, gsub(".mzML", "", colnames(dt)) %in% dplc$sample_name]
diff <- data.frame(matrix(ncol = length(unique_id), nrow = nrow(dt)))
colnames(diff) <- unique_id
rownames(diff) <- rownames(dt)
for(i in 1:length(unique_id)){
dt.tmp <- dt[, grep(unique_id[i], colnames(dt))]
dt.tmp <- log2(dt.tmp)
diff[,i] <- abs(dt.tmp[,1] - dt.tmp[,2])
}
diff$mean <- rowMeans(diff)
diff
}
diff_raw <- diff_calculate(assay(res, "raw_filled"))
T <- quantile(diff_raw[, "mean"], na.rm = TRUE)
pandoc.table(round(T, 3), style = "rmarkdown",
caption = paste0("Distribution of absolute mean differences for ",
"duplicated samples (raw data)."))
```
The next table shows the absolute differences quantiles for the features associated with
standards.
```{r raw-diff-table-standards, results = "asis", echo = FALSE}
T <- quantile(diff_raw[std_info$feature_id, "mean"], na.rm = TRUE)
pandoc.table(
round(T, 3), style = "rmarkdown",
caption = paste0("Distribution of absolute mean differences for ",
"duplicated samples (raw data, features for ",
"standards)."))
```
At last we compare quantified against measured concentrations for the
known compounds included in the Biocrates kit.
The table below lists the slope from the linear models for the regression of the
measured abundances on the quantified concentrations per metabolite (a
value of 1 represents a perfect linear correlation between abundance and
concentration) and the R squared from these model fits.
```{r raw-slopes-r-table, echo = FALSE, results = "asis"}
dt <- assay(res, "raw_filled")
acc_raw <- data.frame(matrix(nrow=0, ncol = 2))
colnames(acc_raw) <- c("raw_slope", "raw_R")
for(i in 1:nrow(std_bioc)){
if(std_bioc$abbreviation[i] %in% std_info$abbreviation){
acc_raw[nrow(acc_raw)+1,] <- NA
rownames(acc_raw)[nrow(acc_raw)] <- std_bioc$abbreviation[i]
a <- log2(dt[std_info$feature_id[
which(std_info$abbreviation == std_bioc$abbreviation[i])],])
names(a) <- injections$id
b <- log2(biocrates[std_bioc$analyte_name[i],])
common_names <- intersect(names(a), names(b))
a <- a[common_names]
b <- b[common_names]
lms <- lm(a~b)
acc_raw[nrow(acc_raw), 1] <- summary(lms)$coefficients[2] # slopes
acc_raw[nrow(acc_raw), 2] <- summary(lms)$adj.r.squared # correlation
}
}
pandoc.table(
round(acc_raw,3), style = "rmarkdown",
caption = paste0("Results from the regression analysis of ",
"measured abundances on quantified concentrations; ",
"raw data."))
```
# Normalization
## Between-sample normalization
Between-sample normalization aims to remove global abundance differences
between samples due to variations in sample collection, extraction,
processing and possibly amount.
### Sum of signals
We're going to normalize the abundances based on the total sum of the
signal. This is one of the simplest approaches.
```{r sum, echo=TRUE}
sms <- colSums(assay(res, "raw_filled"), na.rm = TRUE)
nf_sum <- sms / median(sms)
nf_sum[res$class == "blank"] <- 1
dt_sum <- sweep(assay(res, "raw_filled"), MARGIN = 2, nf_sum, `/`)
```
### Median of signals
This method is based on the normalization according to the median
abundance per sample. This is also one of the simplest approaches.
```{r median, echo=TRUE}
mdn <- colMedians(assay(res, "raw_filled"), na.rm = TRUE)
nf_mdn <- mdn / median(mdn)
nf_mdn[res$class == "blank"] <- 1
dt_mdn <- sweep(assay(res, "raw_filled"), MARGIN = 2, nf_mdn, `/`)
```
### Evaluation of normalization performance
Next we evaluate the performance of each normalization procedure based on the
coefficient of variation within QC samples.
```{r between-sample-rsd-boxplot, echo = FALSE, fig.path = IMAGE_PATH, fig.width = 10, fig.height = 8, fig.cap = "Coefficient of variation (distribution across all features) for the raw and normalized data."}
cv_sum <- rsd_calculate(dt_sum)
cv_mdn <- rsd_calculate(dt_mdn)
tmp <- data.frame(
raw = cv_raw$QC,
sum = cv_sum$QC,
mdn = cv_mdn$QC
)
par(mar = c(7, 4.3, 1, 1))
boxplot(tmp, las = 2, ylab = "CV", xlab = "")
grid(nx = NA, ny = NULL)
abline(h = 0.3, lty = 2)
```
Between-sample normalization slightly reduced the coefficient of variation in QC samples.
The table below summarizes this information.
```{r between-sample-rsd-table, echo = FALSE, results = "asis"}
T <- do.call(cbind, lapply(tmp, quantile, na.rm = TRUE))
T <- rbind(T, `% CV > 0.3` = vapply(tmp, function(z)
sum(z > 0.3, na.rm = TRUE) / length(z) * 100, numeric(1)))
pandoc.table(
T, style = "rmarkdown",
caption = paste0("Quantiles for the coefficient of variation for ",
"QC samples before and after ",
"between sample normalization (all features). ",
"Also the percentage of features with a CV > ",
"0.3 is shown."))
```
This evaluation was also performed separately for each batch
(see the images saved in the corresponding folder).
```{r between-sample-rsd-per-batch, echo = FALSE}
dr <- paste0(IMAGE_PATH, "between-sample-rsd-boxplot/")
dir.create(dr, showWarnings = FALSE)
dr <- paste0(dr, "all_feat/")
dir.create(dr, showWarnings = FALSE)
for (i in levels(res$batch)) {
tmp <- data.frame(
raw = cv_raw[, paste0("QC_b", i)],
sum = cv_sum[, paste0("QC_b", i)],
mdn = cv_mdn[, paste0("QC_b", i)]
)
png(filename = paste0(dr, "batch_", i, ".png"),
width = 10, height = 8, units = "cm", res = 300, pointsize = 4)
par(mar = c(7, 4.3, 1, 1))
boxplot(tmp, las = 2,
ylab = "CV", xlab = "", main = paste0("batch ", i))
grid(nx = NA, ny = NULL)
abline(h = 0.3, lty = 2)
dev.off()
}
```
Next we evaluate impact of the normalization on the CV for only features
associated with the (main ion) of the standards.
```{r between-sample-rsd-boxplot-std, echo = FALSE, fig.path = IMAGE_PATH, fig.width = 10, fig.height = 8, fig.cap = "Coefficient of variation (distribution across features for standards) for the raw and normalized data."}
tmp <- data.frame(
raw = cv_raw[std_info$feature_id, "QC"],
sum = cv_sum[std_info$feature_id, "QC"],
mdn = cv_mdn[std_info$feature_id, "QC"]
)
par(mar = c(7, 4.3, 1, 1))
boxplot(tmp, las = 2, ylab = "CV", xlab = "", main = "std features")
grid(nx = NA, ny = NULL)
abline(h = 0.3, lty = 2)
```
Between-sample normalization also reduced the coefficient of variation for QC samples
for features most likely detecting the main ion of a standard.
The table below summarizes this information.
```{r between-sample-rsd-table-std, echo = FALSE, results = "asis"}
T <- do.call(cbind, lapply(tmp, quantile, na.rm = TRUE))
T <- rbind(T, `% CV > 0.3` = vapply(tmp, function(z)
sum(z > 0.3, na.rm = TRUE) / length(z) * 100, numeric(1)))
pandoc.table(
T, style = "rmarkdown",
caption = paste0("Quantiles for the coefficient of variation for ",
"QC samples before and after ",
"between sample normalization (std features). ",
"Also the percentage of features with a CV > ",
"0.3 is shown."))
dr <- paste0(IMAGE_PATH, "between-sample-rsd-boxplot/std_feat/")
dir.create(dr, showWarnings = FALSE)
for (i in levels(res$batch)) {
tmp <- data.frame(
raw = cv_raw[std_info$feature_id, paste0("QC_b", i)],
sum = cv_sum[std_info$feature_id, paste0("QC_b", i)],
mdn = cv_mdn[std_info$feature_id, paste0("QC_b", i)]
)
png(filename = paste0(dr, "batch_", i, ".png"),
width = 10, height = 8, units = "cm", res = 300, pointsize = 4)
par(mar = c(7, 4.3, 1, 1))
boxplot(tmp, las = 2,
ylab = "CV", xlab = "", main = paste0("batch ", i))
grid(nx = NA, ny = NULL)
abline(h = 0.3, lty = 2)
dev.off()
}
```
We also evaluate the performance of each normalization procedure based on the
mean absolute differences in feature intensities within duplicated samples.
```{r between-sample-diff-boxplot, echo = FALSE, fig.path = IMAGE_PATH, fig.width = 10, fig.height = 8, fig.cap = "Coefficient of variation (distribution across all features) for the raw and normalized data."}
diff_sum <- diff_calculate(dt_sum)
diff_mdn <- diff_calculate(dt_mdn)
tmp <- data.frame(
raw = diff_raw$mean,
sum = diff_sum$mean,
mdn = diff_mdn$mean
)
par(mar = c(7, 4.3, 1, 1))
boxplot(tmp, las = 2, ylab = "mean(diff)", xlab = "")
grid(nx = NA, ny = NULL)
```
Between-sample normalization slightly reduced the mean absolute differences
in the feature intensiteis of duplicated samples.
The table below summarizes this information.
```{r between-sample-diff-table, echo = FALSE, results = "asis"}
T <- do.call(cbind, lapply(tmp, quantile, na.rm = TRUE))
pandoc.table(
round(T, 3), style = "rmarkdown",
caption = paste0("Quantiles for the mean of absolute differences for",
" duplicated samples before and after ",
"between sample normalization (all features). "))
```
Next we evaluate impact of the normalization on the mean of absolute
differences for only features associated with the (main ion) of the standards.
```{r between-sample-diff-boxplot-std, echo = FALSE, fig.path = IMAGE_PATH, fig.width = 10, fig.height = 8, fig.cap = "Coefficient of variation (distribution across features for standards) for the raw and normalized data."}
tmp <- data.frame(
raw = diff_raw[std_info$feature_id, "mean"],
sum = diff_sum[std_info$feature_id, "mean"],
mdn = diff_mdn[std_info$feature_id, "mean"]
)
par(mar = c(7, 4.3, 1, 1))
boxplot(tmp, las = 2, ylab = "mean(diff)", xlab = "", main = "std features")
grid(nx = NA, ny = NULL)
```
Between-sample normalization also reduced the mean of absolute differences
for duplicated samples for features most likely detecting the main ion of a standard.
The table below summarizes this information.
```{r between-sample-diff-table-std, echo = FALSE, results = "asis"}
T <- do.call(cbind, lapply(tmp, quantile, na.rm = TRUE))
pandoc.table(round(T, 3), style = "rmarkdown",
caption = paste0("Quantiles for the mean of absolute differences for ",
"duplicated samples before and after ",
"between sample normalization (std features)."))
```
Next we evaluate the impact of the between-sample normalization on the accuracy
(i.e. the slopes from the quantification values of the metabolites included in Biocrates kit).
```{r between-sample-accuracy-table, echo = FALSE, results = "asis"}
acc_sum <- data.frame(matrix(nrow=0, ncol = 2))
colnames(acc_sum) <- c("sum_slope", "sum_R")
for(i in 1:nrow(std_bioc)){
if(std_bioc$abbreviation[i] %in% std_info$abbreviation){
acc_sum[nrow(acc_sum)+1,] <- NA
rownames(acc_sum)[nrow(acc_sum)] <- std_bioc$abbreviation[i]
a <- log2(dt_sum[std_info$feature_id[
which(std_info$abbreviation == std_bioc$abbreviation[i])],])
names(a) <- injections$id
b <- log2(biocrates[std_bioc$analyte_name[i],])
common_names <- intersect(names(a), names(b))
a <- a[common_names]
b <- b[common_names]
lms <- lm(a~b)
acc_sum[nrow(acc_sum), 1] <- summary(lms)$coefficients[2] # slopes
acc_sum[nrow(acc_sum), 2] <- summary(lms)$adj.r.squared # correlation
}
}
acc_mdn <- data.frame(matrix(nrow=0, ncol = 2))
colnames(acc_mdn) <- c("mdn_slope", "mdn_R")
for(i in 1:nrow(std_bioc)){
if(std_bioc$abbreviation[i] %in% std_info$abbreviation){
acc_mdn[nrow(acc_mdn)+1,] <- NA
rownames(acc_mdn)[nrow(acc_mdn)] <- std_bioc$abbreviation[i]
a <- log2(dt_mdn[std_info$feature_id[
which(std_info$abbreviation == std_bioc$abbreviation[i])],])
names(a) <- injections$id
b <- log2(biocrates[std_bioc$analyte_name[i],])
common_names <- intersect(names(a), names(b))
a <- a[common_names]
b <- b[common_names]
lms <- lm(a~b)
acc_mdn[nrow(acc_mdn), 1] <- summary(lms)$coefficients[2] # slopes
acc_mdn[nrow(acc_mdn), 2] <- summary(lms)$adj.r.squared # correlation
}
}
acc_tb <- cbind(acc_raw, acc_sum, acc_mdn)
pandoc.table(
round(acc_tb,3), style = "rmarkdown", split.table = Inf,
caption = paste0("Results from the regression analysis of ",
"measured abundances on quantified concentrations for ",
"raw and normalized data."))
```
Between-sample normalization slighly improve accuracy for some compounds.
It seems that in this case the *sum* method it's a little bit better than the *median*.
### Summary
Between-sample normalization procedures slighly reduced the variability
(the coefficient of variation) between replicated measurements (QC samples).
Also a very low impact was observed on the slope representing the
regression/correlation of the measured intensity from the expected intensity for
quantified metabolites with the Biocrates kit.
Thus, between-sample normalization slighly improved the
precision by reducing the between replicate variances (i.e. removing technical
variances) with also small improvements in accuracy.
Considering both the precision and the accuracy, we use the median scaling as
the best performing between-sample normalization method.
```{r between-sample-summary}
assays(res)$norm_nofill <- sweep(assay(res, "raw"), MARGIN = 2, nf_mdn, `/`)
assays(res)$norm_filled <- sweep(assay(res, "raw_filled"), MARGIN = 2, nf_mdn, `/`)
```
## Within-batch
Next we perform a within-batch normalization to remove potential
injection order dependent signal drifts.
In order to define whether there is a similar injection order dependent
signal drift in each batch (i.e. the drift is independent of the batch)
we fit feature-wise linear models to the (log2 transformed) data of QC
samples within each batch and compare the slopes for each feature between
the batches (see the corresponding images in the folder *within-batch*).
```{r within-start}
injections <- injections[order(injections$timestamp), ]
all(injections$sample_name == gsub(".mzML", "", res$sampleNames)) # T
res$injection_idx <- NA
for(i in 1:length(levels(res$batch))){
res$injection_idx[res$batch == levels(res$batch)[i]] <-
seq_len(length(which(res$batch == levels(res$batch)[i])))
}
lm_btch <- list()
slps_btch <- list()
for(i in levels(factor(xdata$batch))) {
smps <- res$batch == i & res$class == "pool"
lm_btch[[i]] <- xcms:::rowFitModel(
y ~ inj_idx,
y = log2(assay(res, "norm_nofill")[, smps]),
method = "lmrob",
data = data.frame(inj_idx = res$injection_idx[smps]))
slps_btch[[i]] <- vapply(lm_btch[[i]], function(z)
ifelse(any(!is.na(z)), z$coefficients[2], NA_real_), numeric(1))
}
```
```{r within-batch-correlation-slopes-batch}
# , fig.height = 12, fig.width = 8, fig.path = IMAGE_PATH
plts_by2 <- combn(seq(length(levels(factor(res$batch)))), 2)
dr <- paste0(IMAGE_PATH, "within-batch/")
dir.create(dr, showWarnings = FALSE)
par(mfrow = c(4, 3),
mar = c(4, 4, 2, 1))
for(i in seq(ncol(plts_by2))){
if((length(slps_btch[[plts_by2[1,i]]]) !=
sum(is.na(slps_btch[[plts_by2[1,i]]]))) &
(length(slps_btch[[plts_by2[2,i]]]) !=
sum(is.na(slps_btch[[plts_by2[2,i]]])))){
png(filename = paste0(dr, "batch", plts_by2[1,i], "_batch",
plts_by2[2,i], ".png"),
width = 10, height = 8, units = "cm", res = 300, pointsize = 4)
plot(slps_btch[[plts_by2[1,i]]], slps_btch[[plts_by2[2,i]]],
pch = 16, col = "#00000040",
xlab = paste("batch ", plts_by2[1,i]),
ylab = paste("batch ", plts_by2[2,i]))
grid()
lmod <- lm(slps_btch[[plts_by2[2,i]]] ~ slps_btch[[plts_by2[1,i]]])
abline(lmod, lty = 2)
dev.off()
}
}
```
For most of batches there is only a very low correlation of the slopes
between them (e.g., in POS: B1 *vs* B23-B38-B57), suggesting that the injection
dependent signal drift is for the most part batch-dependent.
In other cases (e.g., in POS: B6-B42, B17-B30), there is an important
correlation of the slopes between them, suggesting that the signal drift
was common among them.
However, since in some cases it seems that the signal drift is
batch-dependent, we're going to apply this normalization method for each
batch separately.
Next we fit the linear models describing an (log scale) injection index
dependent signal drift to abundances separately for each batch. The
advantage of the separate analysis is that the analysis in one batch is
not dependent also on the number of valid measurements of the feature
also in the other batch. Below we fit linear models `y ~ inj_idx` to the
log2 transformed abundances (only of detected peaks) using robust
regression [@Koller:2017jsa]. Model fitting is skipped for features with
less than 6 valid signals (the total number of QC samples per batch is 10).
```{r within-batch-model-fit}
mdls <- withinBatchFit(res[,res$class == "pool"],
batch = res$batch[res$class == "pool"],
assay = "norm_nofill",
model = y ~ injection_idx, method = "lmrob",
minVals = 6)
```
We next remove fitted linear models for features for which valid measurements do
not span at least 3/4 of the injection index range.
```{r within-batch-flag-mdls}
## Defining the injection range on the full data set - assuming the
## same injection setup
inj_range <- diff(range(res$injection_idx))
mdls <- lapply(mdls, FUN = dropModels, FLAG_FUN = flag_model_inj_range,
min_range = inj_range * 3/4, column = "injection_idx")
```
```{r within-batch-model-fit-plot, echo = FALSE}
#fig.width = 10, fig.height = 15, fig.path = IMAGE_PATH,
# fig.cap = "Distribution of slopes from the models fitted to the data
# to estimate the injection-order-dependent signal drift."
## Calculate slopes for models per batch.
slps <- lapply(mdls, function(x) {
vapply(x, function(z) {
if (length(z) > 1)
coefficients(z)[2]
else NA_real_
}, numeric(1))
})
dr <- paste0(IMAGE_PATH, "slopes_batch_distribution/")
dir.create(dr, showWarnings = FALSE)
#par(mfrow = c(ceiling(sqrt(length(slps))), floor(sqrt(length(slps)))))
for (i in seq_along(slps)) {
if(sum(is.na(slps[[i]])) < length(slps[[i]])){
png(paste0(dr, "b_", names(slps)[i], ".png"),
width = 16, height = 7, res = 200, units = "cm", pointsize = 4)
hist(slps[[i]], breaks = 128, xlab = "slope",
main = paste("Batch", names(slps)[i]))
dev.off()
}
}
```
Most of the slopes, that represent the estimated injection order-dependent
signal drift, are close to 0 suggesting most features not being affected by this
bias (see the corresponding images in the folder *slopes_batch_distribution*).
Note that specifically the *injection index range filter* removed most of
the linear models with the largest estimated slopes/effects (mostly for the
first batch).
The table below lists the number of features for which the model was fitted and
the number of features for which model fitting was skipped or discarded.
```{r within-normalization-model-table, echo = FALSE, results = "asis"}
tab <- rbind(vapply(mdls, function(z) {
c(`total features` = length(z),
`excluded models` = sum(is.na(z)),
`valid models` = sum(!is.na(z)))
}, integer(3)))
colnames(tab) <- paste("Batch", colnames(tab))
cptn <- paste("Numbers of features (per batch) for which an injection index ",
"dependent model could be fitted.")
pandoc.table(t(tab), style = "rmarkdown", caption = cptn)
```
The number of features for which a model describing the injection dependent signal drift
was defined varies from 1/3 to half to 2/3 depending on the batch.
### Large injection order dependent drifts
Next we plot some examples for features with the largest injection
order-dependent signal drifts (see the plots saved in the fodler *largest_slopes*).
```{r within-batch-largest-slopes, echo = FALSE}
plot_feature_models <- function() {
for (ft in fts) {
mdl <- mdls_batch[[ft]]
smpls <- res$batch == name_batch
x <- res$injection_idx[smpls]
y <- log2(assay(res, "norm_filled")[ft, smpls])
y[is.na(y)] <- 0
pch <- ifelse(
is.na(assay(res, "norm_nofill")[ft, smpls]), yes = 1, no = 16)
png(paste0(dr2, ft, ".png"), width = 16, height = 7, res = 200,
units = "cm", pointsize = 4)
par(mfrow = c(1, 2))
plot_slope(x, y, mdl,
col = paste0(col_class[res$class[smpls]], "80"),
pch = pch, xaxt = "n", xlab = "",
main = paste("Batch", name_batch))
plot(1:ncol(res), log2(assay(res, "norm_nofill")[ft, ]),
col = paste0(col_class[res$class], "80"),
pch = 16, xaxt = "n", xlab = "", main = ft, ylab = "")
abline(v = batch_margin, col = "grey", lty = 2)
dev.off()
}
}
## plot the top x features with the largest absolute slopes per batch.
dr <- paste0(IMAGE_PATH, "largest_slopes/")
dir.create(dr, showWarnings = FALSE)
top_x <- 20
for (i in seq_along(slps)) {
slps_batch <- slps[[i]]
name_batch <- names(slps)[[i]]
mdls_batch <- mdls[[i]]
fts <- names(slps_batch)[order(abs(slps_batch),
decreasing = TRUE)][seq_len(top_x)]
dr2 <- paste0(dr, "batch_", name_batch, "/")
dir.create(dr2, showWarnings = FALSE)
plot_feature_models()
}
```
### Highest R squared of model fit.
Next we create plots for features with the highest R squared of the model fit
per batch (see the plots saved in the fodler *largest_R2*).
```{r within-batch-feature-models-highest-R-squared, echo = FALSE}
## Calculate slopes for models per batch.
adjrs <- lapply(mdls, function(x) {
vapply(x, function(z) {
if (length(z) > 1)
summary(z)$adj.r.squared
else NA_real_
}, numeric(1))
})
## plot the top x features
dr <- paste0(IMAGE_PATH, "largest_R2/")
dir.create(dr, showWarnings = FALSE)
top_x <- 20
for (i in seq_along(slps)) {
slps_batch <- slps[[i]]
name_batch <- names(slps)[[i]]
mdls_batch <- mdls[[i]]
adjrs_batch <- adjrs[[i]]
fts <- names(adjrs_batch)[order(abs(adjrs_batch),
decreasing = TRUE)][seq_len(top_x)]
dr2 <- paste0(dr, "batch_", name_batch, "/")
dir.create(dr2, showWarnings = FALSE)
plot_feature_models()
}
```
### Adjustment for the injection-order-dependent signal drift
Next we apply the within batch correction adjusting all feature abundances
based on the estimated models.
```{r within-batch-normalization-adjust, message = FALSE, echo=TRUE}
res <- withinBatchAdjust(res, models = mdls, batch = res$batch,
assay = "norm_filled",
shiftNegative = "replaceHalfMin")
## Also define the non-filled-in normalized data
tmp <- assay(res, "norm_filled")
tmp[is.na(assay(res, "raw"))] <- NA
assays(res)$norm_nofill <- tmp
```
### Evaluation of normalization performance
Like after between-sample normalization, we evaluate again the performance of
the normalization procedure based on the coefficient of variation and the slope
of the linear model fits through the quantified metabolites.
```{r within-batch-rsd-boxplot, echo = FALSE, fig.path = IMAGE_PATH, fig.width = 6, fig.height = 8, fig.cap = "Coefficient of variation (distribution across all features) for the raw and normalized data (after within-batch normalization)."}
cv_norm <- rsd_calculate(assay(res, "norm_filled"))
tmp <- data.frame(
raw = cv_raw$QC,
norm = cv_norm$QC