-
Notifications
You must be signed in to change notification settings - Fork 0
/
pilot_study_analysis.Rmd
1553 lines (1261 loc) · 50.4 KB
/
pilot_study_analysis.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: "pilot_study"
author: "Philippine Louail"
date: "2024-05-03"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
#library
```{r packages, message=FALSE, warning=FALSE}
library(MsExperiment)
library(xcms)
library(Spectra)
library(RColorBrewer)
library(pander)
library(readxl)
library(MetaboCoreUtils)
library(pheatmap)
library(MsBackendSql)
library(readxl)
library(Biobase)
library(SummarizedExperiment)
library(openxlsx)
library(gridExtra)
library(ggfortify)
library(vioplot)
```
# intro
Below we load the data with its respective phenodata. We then filter the data
based on the retention time.
Note that we also remove every second injection of each vial for all samples
and QCs. This was performed because of lack of enough material during that
second injection, which created uncertainty in signals.
```{r load-data}
# get filenames in the pd
MZML_PATH <- "/home/plouail/pilot_study/mzmL files/"
#' No Phenodata - to be added
pd <- read_xlsx("phenodata.xlsx") |>
as.data.frame()
full <- readMsExperiment(paste0(MZML_PATH, pd$filename), sampleData = pd)
full
#remove second injection of each vial for all (also QCs)
idx <- duplicated(pd$Vial)
idx[pd$sample_type == "blank"] <- FALSE
full <- full[!idx]
sampleData(full)|>
as.data.frame() |>
head() |>
pandoc.table(style = "simple", caption = "Samples from the data set.")
# filter retention time
full <- filterRt(full, c(40, 840))
```
We set up parallel processing using 6 cores.
```{r parallel-process}
#' Set up parallel processing using 6 cores
if (.Platform$OS.type == "unix") {
register(MulticoreParam(6))
} else
register(SnowParam(6))
```
```{r echo=TRUE}
#' Define colors for the different sample types
leg_sample <- brewer.pal(8, name = "Set1")[c(2, 3, 4)]
names(leg_sample) <- unique(sampleData(full)$sample_type)
col_sample <- leg_sample[sampleData(full)$sample_type]
#' Define colors for the differenT device
leg_device<- brewer.pal(8, name = "Dark2")[c(4, 1, 5, 3, 6, 2)]
names(leg_device) <- c("NA", "Whatman", "Capitainer", "Mitra", "Plasma", "Mix")
col_device <- leg_device[sampleData(full)$device]
# color for QCs
leg_qc <- brewer.pal(12, name = "Set3")[1:12]
names(leg_qc) <- paste0("QC", 1:6)
# color for devices ONLY
leg_device_only<- brewer.pal(8, name = "Dark2")[c(1, 5, 3, 6)]
names(leg_device_only) <- c("Whatman", "Capitainer", "Mitra", "Plasma")
```
Below is the number of spectra of a specific MS level per file.
```{r echo=TRUE}
#' Count the number of spectra
spectra(full) |>
msLevel() |>
split(fromFile(full)) |>
lapply(table) |>
do.call(what = cbind)
```
Below we compute a similarity matrix of the BPS of the whole dataset. BPS
collapses data in the retention time dimension, providing insights into the
most abundant mass-to-charge values (m/z) in the dataset. We then plot this
matrix as a heatmap. this allows us to compare the MS signal similarity between
samples.
```{r bps, echo=TRUE, fig.height=7, fig.width=12}
# set chunksise
chunksize <- 1000
processingChunkSize(spectra(full)) <- chunksize
#' Combining all spectra per file into a single spectrum
bps <- spectra(full) |>
bin(binSize = 0.01) |>
combineSpectra(f = fromFile(full), intensityFun = max, ppm = 3)
#' Calculate similarities between BPS
sim_matrix <- compareSpectra(bps)
#' Add rownames and colnames
rownames(sim_matrix) <- colnames(sim_matrix) <- sampleData(full)$sample_id
ann <- data.frame(devices = sampleData(full)$device)
rownames(ann) <- rownames(sim_matrix)
#' plot the heatmap
pheatmap(sim_matrix, annotation_col = ann,
annotation_colors = list(devices = leg_device), show_rownames = F,
show_colnames = F)
```
# internal standard
The internal standards in this file have been spiked in all samples. We will
use them to follow how well the the preprocessing of the data is going.
```{r is}
is <- read.xlsx("IS.xlsx") |>
as.data.frame()
is$rtmin <- is$rt - 25
is$rtmax <- is$rt + 25
is$mzmin <- is$mz - 0.005
is$mzmax <- is$mz + 0.005
is
```
# chromatogrpahic data
Below we plot the base peak chromatogram (BPC) of the whole datasets and
subsets of the dataset
```{r bpc1, echo=TRUE}
#QC
idx_QC <- sampleData(full)$sample_type == "QC"
chromatogram(full[idx_QC], aggregationFun = "max", msLevel = 1, chunkSize = 6) |>
plot(main = "BPC QC", col = leg_qc, lwd = 1)
# all sample
chromatogram(full, aggregationFun = "max", msLevel = 1, chunkSize = 6) |>
plot(main = "BPC", col = col_sample, lwd = 1)
grid()
legend("topright", col = leg_sample,
legend = names(leg_sample), lty = 1, horiz = TRUE, bty = "n")
chromatogram(full, aggregationFun = "max", msLevel = 1, chunkSize = 6) |>
plot(main = "BPC", col = col_device, lwd = 1)
grid()
legend("topright", col = leg_device,
legend = names(leg_device), lty = 1, horiz = TRUE, bty = "n")
```
We then look at EICs of our internal standards and evaluate them regarding:
- peak shape, width
- intensity variation related to sample-type,...
- retention time variation
```{r eic1, echo=FALSE}
# plot eic and coloring per device - see if I need to extend rtmin and rtmax
# full
eics <- chromatogram(
full,
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]), msLevel = 1, chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(col_sample, 80))
grid()
legend("topright", col = leg_sample,
legend = names(leg_sample), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
eics <- chromatogram(
full[idx_QC],
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]), msLevel = 1, chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = leg_qc)
grid()
legend("topright", col = leg_qc,
legend = names(leg_qc), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
```
# preprocessing
We will now preprocess the data. We will first perform peak picking, for this
we set up the followings parameters of the CentWaveParam method:
- `peakwidth`: the expected peak width in seconds. Here looking at our internal
standard and other peaks in the dataset we estimate that they are between 10
to 20 second wide
- `ppm`: The accepted m/z deviation in ppm. We set it to 50 ppm.
- some peaks did not have enough datapoints and therefor we use
`extendLengthMSW = TRUE` to extend these signals.
```{r pp, eval=!file.exists("full_pp.RData")}
#' Peakpicking
param <- CentWaveParam(peakwidth = c(10, 20), ppm = 50, integrate = 2,
snthresh = 5, extendLengthMSW = TRUE)
full <- findChromPeaks(full, param = param, chunkSize = 6L)
save(full, file = "full_pp.RData")
```
```{r}
load("full_pp.RData")
```
Refinement: merge neighboring peaks. Remove artifacts that can be created
during peak picking.
- `expandRt` and `expandMz` are the maximum allowed distance between two peaks
in the retention time and m/z dimensions, respectively. We set them up based
on the peakwidth set up from the peak picking step and observing how well the
peak picking step performed.
- The other parameters are left as default and their definitions can be found
in `?MergeNeighboringPeaksParam` documentation
```{r refine, eval=!file.exists("full_ref.RData")}
param <- MergeNeighboringPeaksParam(expandRt = 10,
expandMz = 0.01,
ppm = 10,
minProp = 0.75)
full <- refineChromPeaks(full, param = param, chunkSize = 6)
chromPeakData(full)$merged |>
table()
save(full, file = "full_ref.RData")
```
```{r eic2, eval=FALSE, include=FALSE}
load("full_ref.RData")
#full
eics <- chromatogram(
full,
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(col_sample, 80),
peakBg = paste0(col_sample, 40)[chromPeaks(eics[i])[, "column"]])
grid()
legend("topright", col = leg_sample,
legend = names(leg_sample), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
# qc
eics <- chromatogram(
full[idx_QC],
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = leg_qc,
peakBg = paste0(leg_qc, 40)[chromPeaks(eics[i])[, "column"]])
grid()
legend("topright", col = leg_qc,,
legend = names(leg_qc), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
```
# Alignment
before alignment we can see some retention time variation between samples.
Especially towards the first half of the run.
```{r eval=FALSE, include=FALSE}
# BPC qc
chromatogram(full[idx_QC], aggregationFun = "max",
msLevel = 1, chunkSize = 6) |>
plot(main = "BPC QC", col = col_sample[2], lwd = 0.8, peakType = "none")
```
For this dataset two alignment round were run. The first one was done using
automatic selection of anchor peaks. The second one was done using manual
selection of anchor peaks and was targeting specifically the area between 150
to 400 seconds.
- Using QC samples:
We first need to run a correspondence analysis using QC samples. This will allow
us to select the best anchor peaks for the alignment. For this we set
`minFraction = 5/6` meaning that we want to keep peaks that are present in at
least 5 out of 6 of the QC samples.
We subsequentely perform a subset-based alignment.
```{r echo=TRUE, eval=!file.exists("full_align.RData")}
f <- factor(sampleData(full)$sample_type, levels = "QC")
param <- PeakDensityParam(sampleGroups = f,
minFraction = 5/6,
binSize = 0.01, ppm = 10,
bw = 4)
full <- groupChromPeaks(full, param = param)
#' align the data
subset <- which(idx_QC)
param <- PeakGroupsParam(minFraction = 0.9, extraPeaks = 50, span = 0.5,
subsetAdjust = "average",
subset = subset)
#' Input in the function
full <- adjustRtime(full, param = param)
#' See retention time variation
plotAdjustedRtime(full, col = paste0(col_sample, 80), peakGroupsPch = 1)
grid()
legend("topright", col = leg_sample,
legend = names(leg_sample), lty = 1, bty = "n")
```
We evaluate the efficacy of the alignment on our internal standard
```{r eval=FALSE, include=FALSE}
full <- applyAdjustedRtime(full)
# BPC qc
chromatogram(full[idx_QC], aggregationFun = "max",
msLevel = 1, chunkSize = 6) |>
plot(main = "BPC QC after alignment", col = leg_qc, lwd = 1,
peakType = "none")
#eic full
eics <- chromatogram(
full,
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(col_sample, 80),
peakBg = paste0(col_sample, 40)[chromPeaks(eics[i])[, "column"]])
grid()
legend("topright", col = leg_sample,
legend = names(leg_sample), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
# eics QC
eics <- chromatogram(
full[idx_QC],
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(leg_qc, 80))
grid()
legend("topright", col = leg_qc,
legend = names(leg_qc), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
```
Unfortunately this first run was not good enough to fix some retention time
area with strong shifts we therefore now do a second round this time targetting
this area.
Below we create a table with peaks found in most samples in the 100 to 400s RT
area. We then use this table to manually select the peaks to be used as anchor
peaks for the alignment. We also plot their EICs before and after alignemnt to
visually evaluate the alignment.
```{r alignment_using_selected_standards, echo=TRUE, eval=!file.exists("full_align.RData")}
#' creating matrix for rt alignment
standard <- read.xlsx("alignment.xlsx") |>
as.data.frame()
standard <- standard[order(standard$rt),]
#lets also plot all of them before and after alignmet
standard$rtmin <- standard$rt - 25
standard$rtmax <- standard$rt + 25
standard$mzmin <- standard$mz - 0.005
standard$mzmax <- standard$mz + 0.005
eics <- chromatogram(
full[idx_QC],
rt = as.matrix(standard[, c("rtmin", "rtmax")]),
mz = as.matrix(standard[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- standard$mz
fData(eics)$rt <- standard$rt
fData(eics)$name <- standard$name
rownames(eics) <- standard$name
dir <- paste0("eic_", format(Sys.time(), "%Y-%m-%d_%H-%M-%S/before_alignment/"))
dir.create(dir, showWarnings = FALSE, recursive = TRUE)
for (i in seq_len(nrow(standard))) {
png(paste0(dir, standard$name[i], ".png"))
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(leg_qc, 80))
grid()
legend("topright", col = leg_qc,
legend = names(leg_qc), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
dev.off()
}
#' loop results
ID_table <- matrix(
ncol = length(full),
nrow = nrow(standard),
dimnames = list(c(row.names(standard)), c(seq_len(length(full))))
)
cpks <- as.data.frame(chromPeaks(full))
cpks$peak_id <- rownames(cpks)
library(MetaboAnnotation)
#' get ID for peaks matching with IS for each samples (minus Blanks)
for (i in which(sampleData(full)$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 = 20))
#' 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(full, ID_table) {
index <- as.vector(ID_table)
nna <- !is.na(index)
x <- rep(NA, length(index))
x[nna] <- chromPeaks(full)[index[nna], "rt"]
dim(x) <- dim(ID_table)
rownames(x) <- rownames(ID_table)
colnames(x) <- colnames(ID_table)
x
}
#' run for full
final_table <- rtdf(full, ID_table)
#' remove blanks
blank_idx <- sampleData(full)$sample_type == "blank"
final_table <- final_table[, !blank_idx]
```
```{r echo=TRUE, eval=!file.exists("full_align.RData")}
final_table <- final_table[order(rowMedians(final_table, na.rm = TRUE)), ]
param <- PeakGroupsParam(span = 0.5,
peakGroupsMatrix = final_table,
subset = which(!blank_idx),
subsetAdjust = "average")
full <- adjustRtime(full, param = param, chunkSize = 6L)
plotAdjustedRtime(full, col = paste0(col_sample, 80), peakGroupsPch = 1)
```
```{r echo=TRUE, eval=!file.exists("full_align.RData")}
full <- applyAdjustedRtime(full)
#bpc
chromatogram(full[idx_QC], aggregationFun = "max", msLevel = 1, chunkSize = 6) |>
plot(main = "BPC", col = leg_qc, lwd = 1, peakType = "none")
#check eic full
eics <- chromatogram(
full,
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(col_sample, 80),
peakBg = paste0(col_sample, 40)[chromPeaks(eics[i])[, "column"]])
grid()
legend("topright", col = leg_sample,
legend = names(leg_sample), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
# eic qc
eics <- chromatogram(
full[idx_QC],
rt = as.matrix(is[, c("rtmin", "rtmax")]),
mz = as.matrix(is[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- is$mz
fData(eics)$rt <- is$rt
fData(eics)$name <- is$name
rownames(eics) <- is$name
for (i in seq_len(nrow(is))) {
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(leg_qc, 80))
grid()
legend("topright", col = leg_qc,
legend = names(leg_qc), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
}
save(full, file = "full_align.RData")
```
```{r}
load("full_align.RData")
```
```{r eval=FALSE, include=FALSE}
#lets also lot all of them before and after alignment
eics <- chromatogram(
full[idx_QC],
rt = as.matrix(standard[, c("rtmin", "rtmax")]),
mz = as.matrix(standard[, c("mzmin", "mzmax")]),
msLevel = 1,
chunkSize = 6)
fData(eics)$mz <- standard$mz
fData(eics)$rt <- standard$rt
fData(eics)$name <- standard$name
rownames(eics) <- standard$name
dir <- paste0("eic_", format(Sys.time(), "%Y-%m-%d_%H-%M-%S/after_alignment/"))
dir.create(dir, showWarnings = FALSE, recursive = TRUE)
for (i in seq_len(nrow(standard))) {
png(paste0(dir, standard$name[i], ".png"))
plot(eics[i, ], main = fData(eics)$name[i],
col = paste0(leg_qc, 80))
grid()
legend("topright", col = leg_qc,
legend = names(leg_qc), lty = 1)
abline(v = fData(eics)$rt[i], col = "red", lty = 3)
dev.off()
}
```
We seem to have manage to align the problem area of the data as well as
possible.
# Correspondence
Correspodence is the step were features are defined based on how often a peak
is repeated in the dataset. We will based the correspondence on their presence
in the different devices. we set up the following parameters:
- `sampleGroups`: the factor to group the samples. Here we separate the dataset
per devices and remove blanks from neing considered in this step.
- `minFraction`: the minimum fraction of samples of a certain device in which a
peak must be present to be considered a feature. We set it to 0.5. which mean
in this case that a peak must be present in at least 10 out of 20 samples of
a device to be considered a feature.
- `bw`: the bandwidth of the kernel density estimation. We set it to 2 after
testing a checking that is it wide enough to capture the peaks for one
feature.
```{r, eval=!file.exists("full_preprocessing.RData")}
blank_idx <- sampleData(full)$sample_type == "blank"
f <- factor(sampleData(full)$device)
f[blank_idx] <- NA
param <- PeakDensityParam(sampleGroups = f,
minFraction = 0.5,
binSize = 0.01, ppm = 10,
bw = 2)
full <- groupChromPeaks(full, param = param)
# where are the feature
table(cut(featureDefinitions(full)$rtmed, breaks = 10))
# total number of features
nrow(featureDefinitions(full))
```
# gapfilling
We will now use gapfilling to fill in missing values in the dataset. We will
use the `ChromPeakAreaParam` method with defualt parameters for this.
```{r, eval=!file.exists("full_preprocessing.RData")}
#' Number of missing values
sum(is.na(featureValues(full)))
full <- fillChromPeaks(full, param = ChromPeakAreaParam(), chunkSize = 6)
#' How many missing values after
sum(is.na(featureValues(full)))
```
# flag features in blanks
We will now flag features that are highly present in blanks. We will use the
`filterFeatures` with the `BlankFlag` method to do this. By setting up a
`threshold = 2` we will flag the features that have an intensity in the blanks
that is at least half the intensity in the study samples.
```{r, eval=!file.exists("full_preprocessing.RData")}
idx_blank <- sampleData(full)$sample_type == "blank"
full <- filterFeatures(full, BlankFlag(blankIndex = idx_blank, qcIndex = idx_QC),
threshold = 2)
featureDefinitions(full)$possible_contaminants[is.na(featureDefinitions(full)$possible_contaminants)] <- FALSE
featureDefinitions(full)$possible_contaminants <- as.logical(featureDefinitions(full)$possible_contaminants)
```
# summarized experiment
We finalize preprocessing by generating a summarizedExperiment object. We also
remove the previously flagged features from the data for subsequent analysis.
```{r, eval=!file.exists("full_preprocessing.RData")}
library(SummarizedExperiment)
res_full <- quantify(full, method = "sum", filled = FALSE)
assays(res_full)$raw_filled <- featureValues(full, method = "sum",
filled = TRUE )
# we actually remove flagged features data them for downstream analysis in
# the sumexp object
nrow(res_full)
res_full <- res_full[!featureDefinitions(full)$possible_contaminants, ]
nrow(res_full)
save(res_full, file = "SumExp_full_preprocessing.RData")
save(full, file = "full_preprocessing.RData")
```
```{r}
load(file = "SumExp_full_preprocessing.RData")
load(file = "full_preprocessing.RData")
# export full and filled data
de <- list(values = as.data.frame(featureValues(full)), definitions = featureDefinitions(full))
write.xlsx(de, "feature_results.xlsx", rowNames = TRUE)
```
```{r echo=TRUE}
#' Define colors for the different sample types
leg_sample <- brewer.pal(8, name = "Set1")[c(2, 3, 4)]
names(leg_sample) <- unique(sampleData(full)$sample_type)
col_sample <- leg_sample[sampleData(full)$sample_type]
#' Define colors for the differenT device
leg_device<- brewer.pal(8, name = "Dark2")[c(4, 1, 5, 3, 6, 2)]
names(leg_device) <- c("NA", "Whatman", "Capitainer", "Mitra", "Plasma", "Mix")
col_device <- leg_device[sampleData(full)$device]
# color for QCs
leg_qc <- brewer.pal(12, name = "Set3")[1:6]
names(leg_qc) <- paste0("QC", 1:6)
# color for devices ONLY
leg_device_only<- brewer.pal(8, name = "Set1")[c(2, 3, 4, 7)]
names(leg_device_only) <- c("Whatman", "Capitainer", "Mitra", "Plasma")
```
## noise comparison
Below we compare the noise signals between devices. We first calculate the
overall signal in the dataset and then calculate the signal that is in the
chromatographic peaks detection. We then subtract the two to get the noise
signal.
```{r echo=TRUE}
# overall signal in the dataset
#' - for each file calculate the sum of intensities
background <- spectra(full) |>
split(fromFile(full)) |>
lapply(tic) |>
lapply(sum) |>
unlist()
# Overall signal that is in the chromatographic peaks detection
# - check "into" definition first, mioght need to multiply it by something
detected <- apply(assay(res_full), 2, function(x) sum(x, na.rm = TRUE))
# substract and plot ? Also i'm removing blanks bc i think we don't need it
names(background) <- names(detected) <- res_full$device
idx_bl_qc <- sampleData(full)$sample_type %in% c("blank", "QC")
col_device_only <- leg_device_only[sampleData(full)$device[!idx_bl_qc]]
#remove blanks
noise <- background[!idx_bl_qc] - detected[!idx_bl_qc]
f <- factor(names(noise), levels = unique(names(noise)))
group <- split(noise, f)
plot(NULL, xlim = c(1, length(group)), ylim = range(unlist(group)),
xaxt = "n", xlab = "Devices", ylab = "Noise",
main = "Noise comparison between Devices")
for (i in seq_along(group)) {
points(rep(i, length(group[[i]])), group[[i]], pch = 19, col = leg_device_only[i])
}
axis(1, at = seq_along(group), labels = names(group))
```
```{r}
library(ggfortify)
library(SummarizedExperiment)
library(RColorBrewer)
```
# Data exploration and comparison
We remove blank and QC samples from the study samples
```{r}
blank <- full[sampleData(full)$sample_type == "blank", keepFeatures = TRUE]
res_blank <- res_full[, res_full$sample_type == "blank"]
QC <- full[sampleData(full)$sample_type == "QC", keepFeatures = TRUE]
res_QC <- res_full[, res_full$sample_type == "QC"]
full <- full[!sampleData(full)$sample_type %in% c("blank", "QC"),
keepFeatures = TRUE]
res_full <- res_full[, !res_full$sample_type %in% c("blank", "QC")]
```
```{r echo=TRUE}
#' Define colors for the differenT device
leg_device <- brewer.pal(8, name = "Set1")[c(2, 3, 4, 7)]
names(leg_device) <- c("Whatman", "Capitainer", "Mitra", "Plasma")
col_device <- leg_device[sampleData(full)$device]
```
Plot all the PCA to observe the data structure and grouping of the different
samples.
```{r echo=TRUE, fig.height=5, fig.width=10}
#' Impute missing values using an uniform distribution
na_unidis <- function(z) {
na <- is.na(z)
if (any(na)) {
min = min(z, na.rm = TRUE)
z[na] <- runif(sum(na), min = min/2, max = min)
}
z
}
#' Row-wise impute missing values and add the data as a new assay
tmp <- apply(assay(res_, "raw_filled"), MARGIN = 1, na_unidis)
assays(res)$raw_filled_imputed <- t(tmp)
#' Log2 transform and scale data
vals <- assay(res_full, "raw_filled_imputed") |>
log2() |>
t() |>
scale(center = TRUE, scale = TRUE)
#' Perform the PCA
pca_res <- prcomp(vals, scale = FALSE, center = FALSE)
#' Plot the results
vals_st <- cbind(vals, device = res_full$device)
pca_12 <- autoplot(pca_res, data = vals_st , colour = 'device', scale = 0) +
scale_color_manual(values = col_device_only)
pca_34 <- autoplot(pca_res, data = vals_st, colour = 'device',
x = 3, y = 4, scale = 0) +
scale_color_manual(values = col_device_only)
grid.arrange(pca_12, pca_34, ncol = 2)
```
```{r echo=TRUE, fig.height=5, fig.width=10}
#' check injection index
vals_st <- cbind(vals, injection_index = res_full$injection_index)
pca_12 <- autoplot(pca_res, data = vals_st , colour = 'injection_index', scale = 0)
pca_34 <- autoplot(pca_res, data = vals_st, colour = 'injection_index',
x = 3, y = 4, scale = 0)
grid.arrange(pca_12, pca_34, ncol = 2)
```
```{r echo=TRUE, fig.height=5, fig.width=10}
#' check injection index
res_full$injection <- duplicated(res_full$Vial)
vals_st <- cbind(vals, injection = res_full$injection)
pca_12 <- autoplot(pca_res, data = vals_st , colour = 'injection', scale = 0) +
theme(legend.position = "none")
pca_34 <- autoplot(pca_res, data = vals_st, colour = 'injection',
x = 3, y = 4, scale = 0) +
theme(legend.position = "none")
grid.arrange(pca_12, pca_34, ncol = 2)
```
NOTES: the chunks below were used to justify the removal of the 2nd injection
of each vials. They are not to be run for the final report.
```{r eval=FALSE, fig.height=5, fig.width=10, include=FALSE}
#' Log2 transform and scale data
vals <- assay(res_QC, "norm_imputed") |>
log2() |>
t() |>
scale(center = TRUE, scale = TRUE)
colData(res_QC)$injection <- rep(c(1,2), ncol(res_QC)/2)
#' Perform the PCA
pca_res <- prcomp(vals, scale = FALSE, center = FALSE)
#' Plot the results
vals_st <- cbind(vals, injection = res_QC$injection)
pca_12 <- autoplot(pca_res, data = vals_st, colour = 'injection' ,scale = 0) +
theme(legend.position = "none")
pca_34 <- autoplot(pca_res, data = vals_st, colour = 'injection',
x = 3, y = 4, scale = 0) +
theme(legend.position = "none")
grid.arrange(pca_12, pca_34, ncol = 2)
```
```{r eval=FALSE, include=FALSE}
#' Log2 transform and scale data
vals <- assay(res_QC, "raw_filled_imputed") |>
log2() |>
t() |>
scale(center = TRUE, scale = TRUE)
#' Perform the PCA
pca_res <- prcomp(vals, scale = FALSE, center = FALSE)
#' Plot the results
vals_st <- cbind(vals, injection = res_QC$injection)
pca_12 <- autoplot(pca_res, data = vals_st, colour = 'injection', scale = 0) +
theme(legend.position = "none")
pca_34 <- autoplot(pca_res, data = vals_st, colour = 'injection',
x = 3, y = 4, scale = 0) +
theme(legend.position = "none")
grid.arrange(pca_12, pca_34, ncol = 2)
```
- compare intensity of QC1 vs QC2
```{r eval=FALSE, fig.height=6, fig.width=5, include=FALSE}
qc1 <- res_QC[, res_QC$injection == 1]
qc2 <- res_QC[, res_QC$injection == 2]
qc1_int <- apply(assay(qc1, "norm"), MARGIN = 1, mean, na.rm = TRUE)
qc2_int <- apply(assay(qc2, "norm"), MARGIN = 1, mean, na.rm = TRUE)
combine_df <- data.frame(QC1 = qc1_int, QC2 = qc2_int)
par(mfrow = c(2, 1), mar = c(1, 4, 3, 1))
barplot(apply(is.na(combine_df),MARGIN = 2, sum), col = c("blue", "lightblue"),
ylab = "Number of missing values", xaxt = "n", main = "QC1 vs QC2")
boxplot(log2(combine_df), col = c("blue", "lightblue"),
ylab = "Log2 intensity", xaxt = "n", main = "QC1 vs QC2")
```
```{r eval=FALSE, fig.height=6, fig.width=5, include=FALSE}
qc1 <- res_QC[, res_QC$injection == 1]
qc2 <- res_QC[, res_QC$injection == 2]
qc1_int <- apply(assay(qc1, "raw_filled"), MARGIN = 1, mean, na.rm = TRUE)
qc2_int <- apply(assay(qc2, "raw_filled"), MARGIN = 1, mean, na.rm = TRUE)
combine_df <- data.frame(QC1 = qc1_int, QC2 = qc2_int)
par(mfrow = c(2, 1), mar = c(1, 4, 3, 1))
barplot(apply(is.na(combine_df),MARGIN = 2, sum), col = c("blue", "lightblue"),
ylab = "Number of missing values", xaxt = "n", main = "QC1 vs QC2")
boxplot(log2(combine_df), col = c("blue", "lightblue"),
ylab = "Log2 intensity", xaxt = "n", main = "QC1 vs QC2")
```
- intensity vs injection index : just plot the QCs in injection order
```{r eval=FALSE, fig.height=6, fig.width=5, include=FALSE}
par(mar = c(4, 4, 3, 2))
boxplot(log2(assay(res_QC, "raw_filled")),
ylab = expression(log[2]~abundance~filled~data), xaxt = "n",
col = c("blue", "lightblue"), outline=FALSE, medlty = "blank",
border = c("blue", "lightblue"), varwidth = TRUE,
main = "Raw filled data", xlab = "Injection order")
points(colMedians(log2(assay(res_QC, "raw_filled")),
na.rm = TRUE), type = "b", pch = 16)
grid(nx = NA, ny = NULL)
axis(1, labels = FALSE)
boxplot(log2(assay(res_QC, "norm")), xaxt = "n",
ylab = expression(log[2]~abundance~filled~data),
col = c("blue", "lightblue"), outline=FALSE, medlty = "blank",
border = c("blue", "lightblue"), varwidth = TRUE,
main = "Normalised data")
points(colMedians(log2(assay(res_QC, "norm")),
na.rm = TRUE), type = "b", pch = 16)
grid(nx = NA, ny = NULL)
```
# poster and paper plots
- summary plot: the plot below is one of the summary plot that compare results
after prepossessing and normalization.
```{r echo=TRUE, fig.height=8, fig.width=5}
# Intensity and missing values
res_m <- res_full[, res_full$device == "Mitra"]
res_c <- res_full[, res_full$device == "Capitainer"]
res_w <- res_full[, res_full$device == "Whatman"]
res_p <- res_full[, res_full$device == "Plasma"]