-
Notifications
You must be signed in to change notification settings - Fork 0
/
CHRIS_preprocessing_pos.Rmd
1532 lines (1256 loc) · 50.5 KB
/
CHRIS_preprocessing_pos.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: "CHRIS preprocessing posititve mode"
author: "Marilyn De Graeve, Philippine Louail, Johannes Rainer"
affiliation: "Eurac Research, Bolzano, Italy"
date: "2024-02-28"
graphics: yes
output:
BiocStyle::html_document:
toc_float: true
code_folding: hide
bibliography: references.bib
editor_options:
markdown:
wrap: 72
---
**Modified**: `r file.info("CHRIS_preprocessing_pos.Rmd")$mtime`<br />
**Compiled**: `r date()`
```{r style, message = FALSE, echo = FALSE, warning = FALSE, results = "asis"}
knitr::knit_hooks$set(time_it = local({
now <- NULL
function(before, options) {
if (before) {
# record the current time before each chunk
now <<- Sys.time()
} else {
# calculate the time difference after a chunk
res <- difftime(Sys.time(), now, units = "secs")
# return a character string to show the time
paste("Time for this code chunk to run:", round(res,
2), "seconds")
}
}
}))
library("BiocStyle")
library("kableExtra")
library("knitr")
suppressMessages(library("rmarkdown"))
opts_chunk$set(message = FALSE, error = FALSE, warning = FALSE,
cache = FALSE, fig.width = 7, fig.height = 7, time_it = TRUE)
```
# Introduction
During this workflow, the preprocessing (PP) of the untargeted metabolomics data of the Cooperative Health Research in South Tirol (CHRIS) study is performed. For a description of the study, methods used for the collection, handling and aqcuisition of the liquid chromatography-mass spectrometry (LC-MS) samples, please see [@verri_hernandes_age_2022]. Samples are aquired in both positive and negative ionization mode, for which the PP of the positive (pos) mode will be performed in this Rmarkdown document.
# Packages
```{r packages, message=FALSE}
suppressMessages(library(magick))
suppressMessages(library(MetaboAnnotation))
library(MetaboCoreUtils)
library(MsBackendSql)
suppressMessages(library(MsExperiment))
library(MsQuality)
library(pander)
library(pheatmap)
library(RColorBrewer)
library(readxl)
library(RSQLite)
suppressMessages(library(Spectra))
suppressMessages(library(SummarizedExperiment))
suppressMessages(library(vioplot))
suppressMessages(library(xcms))
```
# Data import
Create a `MsExperiment` representing the data: we restrict the data set to data
measured in positive polarity and in addition exclude the additional (extended)
quality control samples available for some batches (i.e., the *pool dilution
series* samples).
```{r load_dataa}
#' Load the spectra data from the database
sps <- Spectra("data/NAFLD_untargeted.sqlite", drv = SQLite(),
source = MsBackendOfflineSql())
nafld <- MsExperiment(spectra = sps)
#' Subset for pos
nafld <- nafld[sampleData(nafld)$polarity == "POS"]
#' Restrict to Blank, Study and Pool samples
nafld <- nafld[sampleData(nafld)$sample_type %in% c("Blank", "Pool", "Study")]
```
```{r parallel_processing_setup}
#' Set up parallel processing using 10 cores
if (.Platform$OS.type == "unix") {
register(bpstart(MulticoreParam(10)))
} else {
register(bpstart(SnowParam(10)))
}
```
# Data organisation
The experimental data is now a `MsExperiment` object:
```{r}
nafld
```
```{r phenodata, echo=FALSE, results="asis"}
sampleData(nafld)[, c(5, 10, 11, 13)] |>
as.data.frame() |>
head() |>
pandoc.table(style = "rmarkdown",
caption = "Some samples from the data set.")
```
The number of samples for the various *sample types* are:
```{r, results = "asis"}
table(sampleData(nafld)$sample_type) |>
as.data.frame() |>
pandoc.table(style = "rmarkdown",
caption = "Numer of samples per sample type")
```
The available sample types are:
- *Blank*: blanks. TODO: need to figure out if it's pure water or
solvent/matrix.
- *Pool*: pool of serum samples from about 5,000 participants of the CHRIS
study.
- *Study*: serum samples from individual study participants.
```{r define_colors, include=FALSE}
#' Define colors for the groups.
#' Sample type
col_phenotype <- brewer.pal(8, "Accent")[c(1, 5, 8)]
names(col_phenotype) <- c("Study", "Pool", "Blank")
col_sample <- col_phenotype[sampleData(nafld)$sample_type]
#' Batches
col_batch_id <- brewer.pal(7, "Paired")[c(4, 3, 1, 5, 2, 6, 7)]
names(col_batch_id) <- c("BATCH0125", "BATCH0130", "BATCH0143",
"BATCH0159", "BATCH0165", "BATCH0169",
"BATCH0186")
col_batches <- col_batch_id[sampleData(nafld)$batch_id]
```
We therefore have an data set of `r length(nafld)` samples for a total
of `r length(spectra(nafld))` spectra.
The retention time range for the entire data set is: `r range(rtime(spectra(nafld)))`
Get some data overview to be sure everything is fine:
```{r some_healthy_stuff}
#' check number of spectra per file
fromFile(nafld) |>
table() |>
quantile()
```
No sample with below average number of spectra
# Visualisation
## BPC
```{r filter_rtime}
#' Filter for ret time
nafld <- filterRt(nafld, c(10, 250))
```
```{r bpc_raw_col_phenotype, include=FALSE}
#' Plot again
bpc_raw <- chromatogram(nafld, aggregationFun = "max", chunkSize = 10)
plot(bpc_raw, col = paste0(col_sample, 60), main = "BPC after rt filtering")
grid()
legend("topright", col = col_phenotype, legend = names(col_phenotype),
lty = 1)
```
Coloring the BPC by batch.
```{r bpc_raw_col_batch}
plot(bpc_raw, col = paste0(col_batches, 60), main = "BPC after rt filtering")
grid()
legend("topright", col = col_batch_id, legend = names(col_batch_id),
lty = 1)
```
Clear differences between batches can be observed.
## Internal standards
Here just generate EICs for all standard, see the EIC_IS folder for the images.
Code will be displayed for the first one as an example but not for the others.
### All
```{r EIC_extract_for_internal_standard, include=FALSE}
#' get the list
intern_standard <- read.delim("internal_standards.txt")
intern_standard <- intern_standard[!is.na(intern_standard$POS), ]
rownames(intern_standard) <- intern_standard$abbreviation
#'generate calcualte formula
intern_standard$mz <- mapply(intern_standard$formula,
intern_standard$POS,
FUN = mass2mz)
#' Fit for each standards
intern_standard$mzmin <- intern_standard$mz - 0.02
intern_standard$mzmax <- intern_standard$mz + 0.02
intern_standard$rtmin <- intern_standard$RT - 15
intern_standard$rtmax <- intern_standard$RT + 15
#' Extract the EICs
eics <- chromatogram(nafld,
mz = as.matrix(intern_standard[, c("mzmin", "mzmax")]),
rt = as.matrix(intern_standard[, c("rtmin", "rtmax")]),
chunkSize = 10)
dr <- "EIC_IS/full/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(intern_standard))) {
png(paste0(dr, "EIC_", intern_standard$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
plot(eics[i, ], main = intern_standard$name[i],
col = paste0(col_sample, 80))
grid()
legend("topright", col = col_phenotype,
legend = names(col_phenotype), lty = 1)
abline(v = intern_standard$RT[i], col = "red", lty = 3)
dev.off()
}
#' Add info on the EICs:
#' ... seems not to work properly.
```
### Batch all sample
All samples colored by different col_batches
```{r eic_is_all, include=FALSE}
dr <- "EIC_IS/batch/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(intern_standard))) {
png(paste0(dr, "EIC_", intern_standard$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
plot(eics[i, ], main = intern_standard$name[i],
col = paste0(col_batches, 80))
grid()
legend("topright", col = col_batch_id,
legend = names(col_batch_id), lty = 1)
abline(v = intern_standard$RT[i], col = "red", lty = 3)
dev.off()
}
```
### Only study samples
Only the study samples colored by batches
```{r eic_is_study, include=FALSE}
#' select for study samples
study_idx <- grep("Study", sampleData(nafld)$sample_type)
batches_study <- col_batch_id[sampleData(nafld)$batch_id][study_idx]
dr <- "EIC_IS/sample/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(intern_standard))) {
png(paste0(dr, "EIC_", intern_standard$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
plot(eics[i, study_idx], main = intern_standard$name[i],
col = paste0(batches_study, 80))
grid()
legend("topright",
col = col_batch_id,
legend = names(col_batch_id),
lty = 1)
abline(v = intern_standard$RT[i], col = "red", lty = 3)
dev.off()
}
```
### Only pool
The pool samples colored by batches.
```{r}
pool_index <- which(sampleData(nafld)$sample_type == "Pool")
batches_pool <- col_batch_id[sampleData(nafld)$batch_id][pool_index]
```
```{r eic_is_pool, include=FALSE}
dr <- "EIC_IS/Pool_batch/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(intern_standard))) {
png(paste0(dr, "EIC_", intern_standard$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
plot(eics[i, pool_index], main = intern_standard$name[i],
col = paste0(batches_pool, 80))
grid()
legend("topright",
col = col_batch_id,
legend = names(col_batch_id),
lty = 1)
abline(v = intern_standard$RT[i], col = "red", lty = 3)
dev.off()
}
#' get the list
standards_all <- read.delim("standards_dilution_nafld.txt")
standards_all <- standards_all[!is.na(standards_all$POS), ]
rownames(standards_all) <- standards_all$abbreviation
#'generate calcualte formula
standards_all$mass <- mapply(standards_all$formula,
FUN = calculateMass)
standards_all$mz <- mapply(standards_all$mass,
standards_all$POS,
FUN = mass2mz)
#' Fit for each standards
standards_all$mzmin <- standards_all$mz - 0.01
standards_all$mzmax <- standards_all$mz + 0.01
standards_all$rtmin <- standards_all$RT - 15
standards_all$rtmax <- standards_all$RT + 15
eics_s <- chromatogram(nafld[pool_index],
mz = as.matrix(standards_all[, c("mzmin", "mzmax")]),
rt = as.matrix(standards_all[, c("rtmin", "rtmax")]),
chunkSize = 10)
dr <- "EIC_standard/Pool_batch/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(standards_all))) {
png(paste0(dr, "EIC_", standards_all$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
plot(eics_s[i], main =standards_all$name[i], col = batches_pool)
grid()
legend("topright",
col = col_batch_id,
legend = names(col_batch_id),
lty = 1)
abline(v = standards_all$RT[i], col = "red", lty = 3)
dev.off()
}
```
## Evaluation of chromatographic data between samples and batches
We next aim to explore similarities and dissimilarities between the general
chromatographic data between samples and batches. We thus compare the total ion
signal between the various measurements (samples), binned by 2 seconds.
```{r heatmap, fig.height=8, fig.width=7}
#' Heatmap from total ion chromatogram
tic <- chromatogram(nafld, aggregationFun = "sum", chunkSize = 10) |>
bin(binSize = 2)
#' Correlation between the binned TICs.
ticmap <- do.call(cbind, lapply(tic, intensity)) |>
cor()
#' yes the code is weird but pheatmap has a weird problems
#' with rownames/colnames handling.
col_hm <- data.frame(sample_type = sampleData(nafld)[, "sample_type"])
rownames(col_hm) <- colnames(ticmap)
row_hm <- data.frame(batch = sampleData(nafld)[, "batch_id"])
rownames(row_hm) <- rownames(ticmap)
ann_color <- list(
sample_type = col_phenotype,
batch = col_batch_id
)
rownames(ticmap) <- rownames(row_hm)
colnames(ticmap) <- rownames(col_hm)
pheatmap(ticmap, annotation_row = row_hm, annotation_col = col_hm,
annotation_colors = ann_color, annotation_names_row = FALSE,
annotation_names_col = FALSE, show_rownames = FALSE,
show_colnames = FALSE, annotation_legend = TRUE)
```
As expected, samples group mostly by batch, with blank samples and samples with
presumably failed injections also separating from all other samples.
## Evaluation of general peak data between samples and batches
```{r combine_spectra, echo=TRUE, eval = FALSE}
#' Combine spectra
processingChunkSize(nafld@spectra) <- 100000
#' Combine spectra
bps <- spectra(nafld) |>
bin(binSize = 0.01, zero.rm = TRUE) |>
combineSpectra(f = fromFile(nafld), p = fromFile(nafld),
intensityFun = max, ppm = 5)
```
```{r compare_spectra, echo=TRUE, eval = FALSE}
sim_matrix <- compareSpectra(bps)
```
```{r heatmap_sim_matrix, fig.height=8, fig.width=7, include=FALSE, eval = FALSE}
pheatmap(sim_matrix, annotation_row = row_hm, annotation_col = col_hm,
annotation_colors = ann_color, annotation_names_row = FALSE,
annotation_names_col = FALSE, show_rownames = FALSE,
show_colnames = FALSE, annotation_legend = TRUE)
processingChunkSize(nafld@spectra) <- Inf
```
```{r}
save(nafld, file = "nafld_after_visu.RData")
```
# Preprocessing
## Chromatographic peak detection
finding cwp parameter
- peakwidth: observing previous EIC, expecting between 2 to 20s
- ppm:
```{r ppm_parameter}
#' choose a nice compound here
cystine_mz <- calculateMass("C6H12N2O4S2") |>
mass2mz("[M+H]+")
cystine_mz <- cystine_mz[1, 1]
#' plot to see rt range for one sample
cst <- chromatogram(nafld[2],
mz = cystine_mz + c(-0.01, 0.01),
rt = c(200, 250))
plot(cst)
#' Restrict the data to signal from Cystine
cst <- nafld[2L] |>
spectra() |>
filterRt(rt = c(210, 220)) |>
filterMzRange(mz = cystine_mz + c(-0.01, 0.01))
lengths(cst)
#' Calculate the difference in m/z values between scans
mz_diff <- cst |>
mz() |>
unlist() |>
diff() |>
abs()
#' Express it in ppm
range(mz_diff * 1e6 / mean(unlist(mz(cst))))
```
Chose larger ppm of 30
But can also see very strong right skew on the EIC. So choose a larger
peak width to accommodate.
```{r}
#' extract test ion
#' for cystine
eic_cystine <- chromatogram(nafld,
rt = c(200, 235),
mz = cystine_mz + c(-0.01, 0.01),
chunkSize = 10)
#' histidine
his_mz <- calculateMass("C6H9N3O2") |>
mass2mz("[M+H]+")
his_mz <- his_mz[1, 1]
eic_his <- chromatogram(nafld,
rt = c(170, 210),
mz = his_mz + c(-0.01, 0.01),
chunkSize = 10)
```
```{r echo=TRUE, warning=FALSE}
param <- CentWaveParam(peakwidth = c(2, 20), ppm = 50, snthresh = 7,
integrate = 2)
# i tested other param these where the best in my opinion
```
```{r include=FALSE}
#' test for some compounds:
#' cystine
cystine_test <- findChromPeaks(eic_cystine, param = param, chunkSize = 10L)
head(chromPeaks(cystine_test))
#' histidine
his_test <- findChromPeaks(eic_his, param = param, chunkSize = 10L)
head(chromPeaks(his_test))
```
```{r include=FALSE}
#' Plot test chromatogram
par(mfrow = c(1, 2))
plot(cystine_test,
main = "Cystine",
col = paste0(col_sample, 80),
peakCol = col_sample[chromPeaks(cystine_test)[, "column"]],
peakBg = paste0(col_sample, 40)[chromPeaks(cystine_test)[, "column"]])
grid()
plot(his_test,
main = "Histidine",
col = paste0(col_sample, 80),
peakCol = col_sample[chromPeaks(his_test)[, "column"]],
peakBg = paste0(col_sample, 40)[chromPeaks(his_test)[, "column"]])
grid()
legend("topright", col = col_phenotype, cex = 0.50,
horiz = TRUE,inset = c(-0.18, -0.1), xpd = TRUE,
text.width = 7, bty = "n",
legend = names(col_phenotype), lty = 1)
```
In my opinion looks pretty good, should apply to all data:
```{r findchrompeaks_all_data, echo=TRUE, eval = !file.exists("nafld_after_peakdetect.RData")}
nafld <- findChromPeaks(nafld, param = param, chunkSize = 10L)
save(nafld, file = "nafld_after_peakdetect.RData")
```
```{r, echo = FALSE, eval = file.exists("nafld_after_peakdetect.RData")}
#' Loading the already peak-detected data
load("nafld_after_peakdetect.RData")
```
We next remove samples in which a much lower number of peaks was detected.
```{r, results = "asis"}
#' remove samples that have overall low intensity/peak detected
index <- as.vector(table(chromPeaks(nafld)[, "sample"]) < 1500)
sampleData(nafld)[index, c("year", "sample_type", "batch_id")] |>
as.data.frame() |>
pandoc.table(
style = "rmarkdown",
caption = "Samples removed because of too few detected peaks.")
nafld <- nafld[!index]
#' Update indices and colors.
col_sample <- col_phenotype[sampleData(nafld)$sample_type]
col_batches <- col_batch_id[sampleData(nafld)$batch_id]
pool_index <- which(sampleData(nafld)$sample_type == "Pool")
batches_pool <- col_batch_id[sampleData(nafld)$batch_id][pool_index]
```
```{r, include=FALSE}
#' test for ions of interest
eic_cystine <- chromatogram(nafld,
rt = c(202, 217),
mz = cystine_mz + c(-0.01, 0.01),
aggregationFun = "max",
chunkSize = 10)
eic_his <- chromatogram(nafld,
rt = c(172, 203),
mz = his_mz + c(-0.01, 0.01),
aggregationFun = "max",
chunkSize = 10)
par(mfrow = c(1, 2))
plot(eic_cystine, main = "Cystine", col = paste0(col_sample, 80),
peakCol = col_sample[chromPeaks(eic_cystine)[, "sample"]],
peakBg = paste0(col_sample[chromPeaks(eic_cystine)[, "sample"]], 40))
grid()
plot(eic_his, main = "Histidine", col = paste0(col_sample, 80),
peakCol = col_sample[chromPeaks(eic_his)[, "sample"]],
peakBg = paste0(col_sample[chromPeaks(eic_his)[, "sample"]], 40))
grid()
legend("topright", col = col_phenotype, cex = 0.50,
horiz = TRUE,inset = c(-0.18, -0.1), xpd = TRUE,
text.width = 7, bty = "n",
legend = names(col_phenotype), lty = 1)
```
```{r, include=FALSE}
#' All EICs in pool
eics <- chromatogram(nafld[pool_index],
mz = as.matrix(intern_standard[, c("mzmin", "mzmax")]),
rt = as.matrix(intern_standard[, c("rtmin", "rtmax")]),
chunkSize = 10)
dr <- "EIC_IS/Pool_batch/afterchrompeak/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(intern_standard))) {
png(paste0(dr, "EIC_", intern_standard$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
plot(eics[i], main = intern_standard$name[i], col = paste0(batches_pool,80),
peakCol = col_batches[chromPeaks(eics[i])[, "sample"]],
peakBg = paste0(col_batches[chromPeaks(eics[i])[, "sample"]], 40))
grid()
legend("topright", col = col_batch_id,
legend = names(col_batch_id), lty = 1)
legend("topleft",
legend = paste0("m/z: ", format(fData(eics)$mzmin[i], 4),
" - ", format(fData(eics)$mzmax[i], 4)))
abline(v = intern_standard$RT[i], col = "red", lty = 3)
dev.off()
}
eics_s <- chromatogram(nafld[pool_index],
mz = as.matrix(standards_all[, c("mzmin", "mzmax")]),
rt = as.matrix(standards_all[, c("rtmin", "rtmax")]),
chunkSize = 10)
dr <- "EIC_standard/Pool_batch/afterchrompeak/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(standards_all))) {
png(paste0(dr, "EIC_", standards_all$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
eic <- eics_s[i, ]
plot(eic, main = standards_all$name[i],
col = paste0(batches_pool, 80),
peakCol = paste0(batches_pool[chromPeaks(eic)[, "sample"]], 80),
peakBg = paste0(batches_pool[chromPeaks(eic)[, "sample"]], 40))
grid()
legend("topright",
col = col_batch_id,
legend = names(col_batch_id),
lty = 1)
legend("topleft",
legend = paste0("m/z: ", format(fData(eic)$mzmin, 4),
" - ", format(fData(eic)$mzmax, 4)))
abline(v = standards_all$RT[i], col = "red", lty = 3)
dev.off()
}
```
Look at the nb of peak per files
```{r, fig.cap = "Numbers of detected peaks per sample."}
#' Count peaks per file
chromPeaks(nafld)[, "sample"] |>
table() |>
barplot(border = col_sample, col = col_sample)
grid()
```
### Refine chromatographic peaks
```{r refine_chrom_peaks, message = FALSE, eval = !file.exists("nafld_after_refine.RData")}
#' set up the parameter
param <- MergeNeighboringPeaksParam(expandRt = 5,
expandMz = 0.001,
ppm = 5,
minProp = 0.75)
#' apply to all dataset
nafld <- refineChromPeaks(nafld, param = param, chunkSize = 10)
save(nafld, file = "nafld_after_refine.RData")
```
```{r load_refine_chrom_peaks, include=FALSE, eval = file.exists("nafld_after_refine.RData")}
load("nafld_after_refine.RData")
```
```{r echo=TRUE, fig.cap = "Numbers of detected peaks per sample after peak refinement."}
#' Count peaks per file
chromPeaks(nafld)[, "sample"] |>
table() |>
barplot(border = col_sample, col = col_sample)
grid()
```
```{r include=FALSE}
#' All EICs in pool
eics <- chromatogram(nafld[pool_index],
mz = as.matrix(intern_standard[, c("mzmin", "mzmax")]),
rt = as.matrix(intern_standard[, c("rtmin", "rtmax")]),
chunkSize = 10)
dr <- "EIC_IS/Pool_batch/afterrefine/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(intern_standard))) {
png(paste0(dr, "EIC_", intern_standard$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
eic <- eics[i]
plot(eic, main =intern_standard$name[i], col = paste0(batches_pool, 80),
peakCol = col_batches[chromPeaks(eic)[, "sample"]],
peakBg = paste0(col_batches[chromPeaks(eic)[, "sample"]], 40))
grid()
legend("topright", col = col_batch_id,
legend = names(col_batch_id), lty = 1)
legend("topleft",
legend = paste0("m/z: ", format(fData(eic)$mzmin, 4),
" - ", format(fData(eic)$mzmax, 4)))
abline(v = intern_standard$RT[i], col = "red", lty = 3)
dev.off()
}
eics_s <- chromatogram(nafld[pool_index],
mz = as.matrix(standards_all[, c("mzmin", "mzmax")]),
rt = as.matrix(standards_all[, c("rtmin", "rtmax")]),
chunkSize = 10)
dr <- "EIC_standard/Pool_batch/afterrefine/"
dir.create(dr, recursive = TRUE, showWarnings = FALSE)
for (i in seq_len(nrow(standards_all))) {
png(paste0(dr, "EIC_", standards_all$abbreviation[i], ".png"),
width = 12, height = 8, units = "cm", res = 600, pointsize = 4)
eic <- eics_s[i, ]
plot(eic, main = standards_all$name[i],
col = paste0(batches_pool, 80),
peakCol = paste0(batches_pool[chromPeaks(eic)[, "sample"]], 80),
peakBg = paste0(batches_pool[chromPeaks(eic)[, "sample"]], 40))
grid()
legend("topright",
col = col_batch_id,
legend = names(col_batch_id),
lty = 1)
legend("topleft",
legend = paste0("m/z: ", format(fData(eic)$mzmin, 4),
" - ", format(fData(eic)$mzmax, 4)))
abline(v = standards_all$RT[i], col = "red", lty = 3)
dev.off()
}
```
## Retention time alignment
Multiple strategies were tested in a separate Rmd file. The current approach
based on a single alignment based on retention times of internal standards and
manually selected standards. This approach outperformed also a two-step
alignment setup in which a *standard* alignment was performed after the initial
alignment based on the above mentioned standards.
```{r reorder_data_set}
#' keep a raw nafld object to compare before/after alignment
nafld_raw <- nafld
#' Reorganising samples order for alignment
#' saving old order
sampleData(nafld)$original_index <- seq_along(nafld)
#' determining new order
sd <- as.data.frame(sampleData(nafld))
tmp <- lapply(split(sd, sd$batch_id), function(batch){
qcs <- which(batch$sample_type == "Pool")
indices <- batch$original_index
first <- min(qcs)
last <- max(qcs)
c(indices[first], indices[-c(first, last)], indices[last])
})
index_qc <- unlist(tmp, use.names = FALSE)
#' applying it
nafld <- nafld[index_qc]
#' redefine the index of the pool and all colors
pool_index <- which(sampleData(nafld)$sample_type == "Pool")
col_sample <- col_phenotype[sampleData(nafld)$sample_type]
col_batches <- col_batch_id[sampleData(nafld)$batch_id]
batches_pool <- col_batch_id[sampleData(nafld)$batch_id][pool_index]
```
One run based on a pre-defined peak matrix of IS standards and manually selected
standards with rt for each Pool samples. Below we define this peak matrix and
extract the retention times for the selected chromatographic peak for each
sample.
```{r alignment_using_selected_standards}
#' creating matrix for rt alignment
standard <- read.delim("Mix_alignment.txt", comment.char = "#")
standard <- standard[order(standard$RT),]
#' loop results
ID_table <- matrix(
ncol = length(nafld),
nrow = nrow(standard),
dimnames = list(c(row.names(standard)), c(seq_len(length(nafld))))
)
cpks <- as.data.frame(chromPeaks(nafld))
cpks$peak_id <- rownames(cpks)
#' get ID for peaks matching with IS for each samples (minus Blanks)
for (i in which(sampleData(nafld)$sample_type != "Blank")) {
tmp <- cpks[cpks$sample == i, ]
match_intern_standard <- matchValues(
query = standard,
target = tmp,
mzColname = c("mz", "mz"),
rtColname = c("RT", "rt" ),
param = MzRtParam(ppm = 0, tolerance = 0.01, toleranceRt = 10))
#' Select the chrom peak with the largest apex signal
match_intern_standard <- filterMatches(
match_intern_standard, SingleMatchParam(duplicates = "top_ranked",
decreasing = TRUE,
column = "target_maxo"))
ID_table[, i] <- match_intern_standard$target_peak_id
}
#' Function to create rt dataframe;
#' avoiding subset with NA turns out to be much more efficient
rtdf <- function(nafld, ID_table) {
index <- as.vector(ID_table)
nna <- !is.na(index)
x <- rep(NA, length(index))
x[nna] <- chromPeaks(nafld)[index[nna], "rt"]
dim(x) <- dim(ID_table)
rownames(x) <- rownames(ID_table)
colnames(x) <- colnames(ID_table)
x
}
#' run for nafld
RT_raw <- rtdf(nafld, ID_table)
```
We repeat the same for the full set of standards (which are not used for the
alignment) to allow an independent evaluation of the alignment performance.
```{r define_rtimes_all_standards}
#' Identify chromPeaks for all standards
standards_all_cpeaks <- matrix(
ncol = length(nafld),
nrow = nrow(standards_all),
dimnames = list(rownames(standards_all), seq_len(length(nafld)))
)
#' get ID for peaks matching with standard for each samples (minus Blanks)
for (i in which(sampleData(nafld)$sample_type != "Blank")) {
tmp <- cpks[cpks$sample == i, ]
match_standard <- matchValues(
query = standards_all,
target = tmp,
mzColname = c("mz", "mz"),
rtColname = c("RT", "rt" ),
param = MzRtParam(ppm = 0, tolerance = 0.01, toleranceRt = 10))
match_standard <- filterMatches(
match_standard, SingleMatchParam(duplicates = "top_ranked",
decreasing = TRUE,
column = "target_maxo"))
standards_all_cpeaks[, i] <- match_standard$target_peak_id
}
#' Remove those that are already included in Mix_standard
standards_all_cpeaks <- standards_all_cpeaks[
!rownames(standards_all_cpeaks) %in% rownames(standard), ]
#' run for nafld
standards_all_rtime_raw <- rtdf(nafld, standards_all_cpeaks)
```
Next we perform the alignment based on retention times of internal standards and
manually selected standards (to cover a larger retention time range). We perform
the alignment on all samples (except blanks, which will be aligned based on all
study or QC samples). A subset-based alignment on QC (pool) samples performed
less well.
```{r perform_alignment_on_standards}
#' Subset to all samples except blanks
is_blank <- sampleData(nafld)$sample_type == "Blank"
final_table <- RT_raw[, !is_blank]
#' Order by median RT
final_table <- final_table[order(rowMedians(final_table, na.rm = TRUE)), ]
#' run with that first
#' Define parameters of choice
param <- PeakGroupsParam(span = 0.5,
peakGroupsMatrix = final_table,
subset = which(!is_blank),
subsetAdjust = "average")
nafld <- adjustRtime(nafld, param = param, chunkSize = 10L)
#' Define color, less transparency for the Pool samples
alpha <- rep("60", length(col_sample))
alpha[pool_index] <- "CE"
cols <- paste0(col_sample, alpha)
plotAdjustedRtime(nafld, col = cols)
grid()
legend("topright", col = col_phenotype,
legend = names(col_phenotype), lty = 1)
cols <- paste0(col_batches, alpha)
plotAdjustedRtime(nafld, col = cols)
grid()
legend("topright", col = col_batch_id,
legend = names(col_batch_id), lty = 1)
#' Replace the Rtime by the adjusted ones
nafld <- applyAdjustedRtime(nafld)
```
Next we evaluate the result of the alignment on the set of standards on which
the alignment was based. These are listed in the table below.
```{r, results = "asis"}
#' get RT table after alignment
RT_aligned <- rtdf(nafld, ID_table)
#' Get RT table only for study samples
index_s <- sampleData(nafld)$sample_type == "Study"
Sdsdf <- data.frame(
Raw_pool = rowSds(RT_raw[, pool_index], na.rm = TRUE),
Aligned_pool = rowSds(RT_aligned[, pool_index], na.rm = TRUE),
Raw_study = rowSds(RT_raw[, index_s], na.rm = TRUE),
Aligned_study = rowSds(RT_aligned[, index_s], na.rm = TRUE)
)
pandoc.table(
Sdsdf, style = "rmarkdown", split.table = Inf,
caption = paste0("Standards on which the alignment was based along with ",
"the standard deviation of their retention times before ",
"and after alignment in QC and study samples."))
```
```{r}
par(mar = c(1.3, 4.5, 1, 0.5))
vioplot(Sdsdf, las = 2, ylab = "RT standard deviation",
main = "Standards used for alignment")
grid()
```
Looks pretty cool
In addition, we base the evaluation of the alignment also on compounds not used
as anchor peaks hence allowing an independent evaluation of the performance.
```{r, results = "asis"}
#' get RT table after alignment
standards_all_rtime_adj <- rtdf(nafld, standards_all_cpeaks)
tmp <- data.frame(
Raw_pool = rowSds(standards_all_rtime_raw[, pool_index], na.rm = TRUE),
Aligned_pool = rowSds(standards_all_rtime_adj[, pool_index], na.rm = TRUE),
Raw_study = rowSds(standards_all_rtime_raw[, index_s], na.rm = TRUE),
Aligned_study = rowSds(standards_all_rtime_adj[, index_s], na.rm = TRUE)
)
pandoc.table(
tmp, style = "rmarkdown", split.table = Inf,
caption = paste0("Standards not used for alignment along with ",
"the standard deviation of their retention times before ",
"and after alignment in QC and study samples."))
```
```{r}
par(mar = c(1.3, 4.5, 1, 0.5))
vioplot(tmp, las = 2, ylab = "RT standard deviation",
main = "Standards not used for alignment")
grid()
```
```{r bpc-before-and-after, echo=FALSE}
#' replace value to not have problems when indexing
if (hasAdjustedRtime(nafld))
nafld <- applyAdjustedRtime(nafld)
#' remove reordering
nafld <- nafld[order(sampleData(nafld)$original_index),
keepFeatures = TRUE,
keepAdjustedRtime = TRUE]
#' Update indices and colors.
col_sample <- col_phenotype[sampleData(nafld)$sample_type]
col_batches <- col_batch_id[sampleData(nafld)$batch_id]
pool_index <- which(sampleData(nafld)$sample_type == "Pool")
batches_pool <- col_batch_id[sampleData(nafld)$batch_id][pool_index]
nafld_pool <- nafld[pool_index, keepAdjustedRtime = TRUE]
nafld_raw_pool <- nafld_raw[pool_index, keepAdjustedRtime = TRUE]
#' Plot the BPC before and after alignment
par(mfrow = c(2, 1), mar = c(2, 1, 1, 0.5))
chromatogram(nafld_raw_pool,
aggregationFun = "max",
chromPeaks = "none",
chunkSize = 10) |>
plot(main = "BPC of pool before alignment",
col = paste0(batches_pool, 60))