-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMTXQCvX_part1_template_params.Rmd
1619 lines (1221 loc) · 56.8 KB
/
MTXQCvX_part1_template_params.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: 'MTXQCvX2 - Part1: Standards and Reprod.'
author:
- affiliation: Kempa Lab, BIMSB/MDC Berlin-Buch
name: Christin Zasada
params:
spath:
input: text
label: "Run on MTXQC-subfolder:"
value: ""
data:
input: select
choices: [maui, metmax]
label: 'Input file format:'
value: metmax
updated:
input: select
choices: [none, PeakArea, Incorporation, both]
label: "Incorporation manualy validated data:"
value: none
output:
pdf_document:
citation_package: natbib
fig_caption: yes
keep_tex: yes
latex_engine: pdflatex
template: config_files/textemplate.tex
toc: yes
html_document: default
fontfamily: mathpazo
fontsize: 9pt
geometry: margin = 1in
keywords: MTXQCvX, GC-MS, metabolomics, data analysis and processing
biblio-style: apsr
thanks: Kempa Lab - Template MTXQCvX part1 - processed '`r format(Sys.Date(), "%B %d, %Y")`'
abstract: The herein presented report includes the manual validated peak areas of Itaconic acid. Absolute quantities have been determined by additional quantification standards.
---
# MTXQCvX part1
## General project settings
```{r setup_output, echo=FALSE}
#set path for figure export and size
set_input = "input/"
set_output = "output/"
## subfolder for postprocessing
#directory definition and figure_name definition
if (params$spath == "") {
path_setup = ""
set_fig = paste0(path_setup, 'figure/MTXQCp1-')
} else {
path_setup = paste0(params$spath, "/")
set_fig = paste0(path_setup, 'figure/MTXQCp1-')
}
knitr::opts_chunk$set(fig.width = 8, fig.align = 'center', fig.height = 7,
fig.path = set_fig,
echo = FALSE, #TRUE - show R code
warning = FALSE, #show warnings
message = TRUE,
eval = TRUE) #show messages
```
```{r source_rfiles}
source("R/MTXQC_pck.R")
source('R/MTXQC_fcn.R')
source('R/MTXQC_fcn_absQ.R')
source('R/MTXQC_fcn_gcperformance.R')
source('R/MTXQC_fcn_incorp.R')
source('R/MTXQC_fcn_metabolicprofile.R')
source('R/MTXQC_fcn_part3.R')
source('R/MTXQC_colors.R')
source('R/MTXQC_theme.R')
source('R/MTXQC_config.R')
```
## Data import
```{r import_datafiles, tidy = TRUE}
#tracking import errors
imp_error = 0
#import parameter: MTXQCsetup
if (file.exists(paste0(path_setup, "MTXQC_params.csv"))) {
setup_params <- read.csv(paste0(path_setup, "MTXQC_params.csv"), TRUE)
message("MTXQCparams.csv imported!")
} else {
message("Please run MTXQCvX_ExperimentalSetup in order to create MTXQC_params.csv")
knitr::knit_exit()
}
#import parameter for input files:
if (params$data == "metmax") {
if (file.exists(paste0(path_setup, "Metmax_params.csv"))) {
id_settings = read.csv(paste0(path_setup, "Metmax_params.csv"))
message("Metmax_params.csv imported.")
} else {
message("Metmax_params.csv not detected! Check defined input format!")
knitr::knit_exit()
}
} else {
if (file.exists(paste0(path_setup, "Maui_params.csv"))) {
id_settings = read.csv(paste0(path_setup, "Maui_params.csv"))
message("Maui_params.csv imported.")
} else {
message("Maui_params.csv not detected! Check defined input format!")
knitr::knit_exit()
}
}
#check if addq-values exits if required
#Check if this whole addQ-file thing is needed!!!
nick_addq_file <- as.character(file_spec[which(file_spec$AssociatedFile == "addQ_file"), "Filename"])
idx_addq <- as.character(setup_params[which(setup_params$Parameter == "addQ"), "Value"])
if (idx_addq == "yes") {
if (!file.exists(file.path(paste0(path_setup, set_input, "add_quant/", nick_addq_file)))) {
message("Please specify the correct file containing additional Quant1-values in the ExperimentalSetup!")
knitr::knit_exit()
} else {
message("Required table containing additional Quant1-values detected!", nick_addq_file)
}
} else {
message("Experimental setup does not include additional quantification standards!")
}
#### Annotation files ####
## File annotation
ann_idx <- as.character(setup_params[which(setup_params$Parameter == "ann"), "Value"])
if (file.exists(file.path(paste0(path_setup, set_input, ann_idx)))) {
ann <- read.csv(paste0(path_setup, set_input, ann_idx), T)
if (ncol(ann) == 1) {
ann = read.csv(paste0(path_setup, set_input, ann_idx), T, sep = ";")
message("colon separator detected: ", ann_idx)
}
} else {
message("FATAL ERROR: Annotation file missing: ", ann_idx)
knitr::knit_exit()
}
check_emptyfile(ann, TRUE, ann_idx)
#Cell count / extract
se_idx <- as.character(setup_params[which(setup_params$Parameter == "sample_ext"), "Value"])
if (file.exists(file.path(paste0(path_setup, set_input, se_idx)))) {
data_extracts <- read.csv(paste0(path_setup, set_input, se_idx), T)
if (ncol(data_extracts) == 1) {
data_extracts = read.csv(paste0(path_setup, set_input, se_idx), T, sep = ";")
message("colon separator detected: ", se_idx)
}
} else {
message("FATAL ERROR: Sample_extracts file missing: ", se_idx)
knitr::knit_exit()
}
check_emptyfile(data_extracts, TRUE, se_idx)
##### (1) GC-MS performance files ####
## import (i) cinnamic acid peak areas, (ii) alkane intensities,
## (iii) mz 73 intensities and (iv) total peak densities from Chromatof
ca_idx <- setup_params[which(setup_params$Parameter == "instd"), "Value"]
mm_ca_idx <- id_settings[which(id_settings$Parameter == "intstd"), "Value"]
if (ca_idx == TRUE) {
if (mm_ca_idx == TRUE) {
nick_ca <- as.character(file_spec[which(file_spec$AssociatedFile == "cin_acid"), "Filename"])
ca_path <- paste0(path_setup, set_input,'gc/', nick_ca)
if (file.exists(ca_path) == TRUE) {
cinacid <- read.csv(ca_path, T, sep = ',')
if (ncol(cinacid) == 1) {
cinacid <- read.csv(ca_path, T, sep = ';')
}
#Which internalstandard exported in InternalStandard.csv
intstd = unique(cinacid$Metabolite)
message("Defined Internal Standard: ", intstd)
check_emptyfile(cinacid, FALSE, "InternalStandard.csv")
is_exit = 0
} else {
message("WARNING: No file detected: InternalStandard.csv")
is_exit = 1
}
} else {
imp_error = imp_error + 1
is_exit = 1
message("WARNING: No internal standard for data input format defined!")
}
} else {
is_exit = 1
message("No internal standard in Experimental Setup defined!")
}
alkane_idx <- as.character(id_settings[which(id_settings$Parameter == "alkanes"), "Value"])
nick_alk <- as.character(file_spec[which(file_spec$AssociatedFile == "alkane_int"), "Filename"])
if (alkane_idx == TRUE) {
data_alk <- read.csv(paste0(path_setup, set_input,'gc/', nick_alk), T, sep = ',')
colnames(data_alk)[grepl("file", colnames(data_alk))] = "File"
check_emptyfile(data_alk, FALSE, nick_alk)
} else {
imp_error = imp_error + 1
message("WARNING: No alkane file defined for this input format!")
}
#m/z 73 Table
nick_73 <- as.character(file_spec[which(file_spec$AssociatedFile == "mz_73"), "Filename"])
mm_73_idx <- id_settings[which(id_settings$Parameter == "mz"), "Value"]
if (mm_73_idx != "") {
if (!file.exists(file.path(paste0(path_setup, set_input,'gc/', nick_73)))) {
message("WARNING: File missing: ", nick_73)
message("Please review MTXQC_ExperimentalSetup!")
soa_73_exit = 1
} else {
data_73 <- read.csv(paste0(path_setup, set_input,'gc/', nick_73), T, sep = ",")
check_emptyfile(data_73, FALSE, nick_73)
soa_73_exit = 0
}
} else {
imp_error = imp_error + 1
soa_73_exit = 1
message("WARNING: No file with m/z 73 values defined for this input format!")
}
### Peak-Chroma Table
nick_peaks <- as.character(file_spec[which(file_spec$AssociatedFile == "peak_densities"), "Filename"])
mm_peaks_idx <- id_settings[which(id_settings$Parameter == "peakchroma"), "Value"]
if (mm_peaks_idx == TRUE) {
if (!file.exists(file.path(paste0(path_setup, set_input,'gc/', nick_peaks)))) {
message("WARNING: File missing: ", nick_peaks)
message("Please review MTXQC_ExperimentalSetup!")
soa_exit = 1
} else {
total_peaks <- read.csv(paste0(path_setup, set_input,'gc/', nick_peaks), T)
check_emptyfile(total_peaks, FALSE, nick_peaks)
soa_exit = 0
}
} else {
imp_error = imp_error + 1
soa_exit = 1
message("WARNING: No file defined for this input format! No sum of area normalisation! ", nick_peaks)
}
#### (2) Absolute quantification ####
## (2.1) Exported peak areas according to top5 or pTop5 approach
if ((params$updated == "PeakArea") | (params$updated == "both")) {
#incorporation of manualy validated data
nick_samples <- as.character(file_spec_manVal[which(file_spec_manVal$AssociatedFile == "sample_area"), "Filename"])
if (!file.exists(file.path(paste0(path_setup, set_input, 'quant/', nick_samples)))) {
message("FATAL ERROR: Manual validated peak area file not detected: ", nick_samples)
knitr::knit_exit()
} else {
data_area <- read.csv(paste0(path_setup, set_input, 'quant/', nick_samples), T)
if (ncol(data_area) == 1) {
data_area <- read.csv(paste0(path_setup, set_input, 'quant/', nick_samples), T, sep = ";")
}
check_emptyfile(data_area, TRUE, nick_samples)
}
} else {
#only original data
nick_samples <- as.character(file_spec[which(file_spec$AssociatedFile == "sample_area"), "Filename"])
if (!file.exists(file.path(paste0(path_setup, set_input, 'quant/', nick_samples)))) {
message("FATAL ERROR: Peak area table not detected: ", nick_samples)
knitr::knit_exit()
} else {
data_area <- read.csv(paste0(path_setup, set_input, 'quant/', nick_samples), T)
if (ncol(data_area) == 1) {
data_area <- read.csv(paste0(path_setup, set_input, 'quant/', nick_samples), T, sep = ";")
}
check_emptyfile(data_area, TRUE, nick_samples)
}
}
#### (3) Incorporation data ####
## only needed for pSIRM experiment
## (i) MID exports and (ii) calculated isotope incorporation
inc_idx <- setup_params[which(setup_params$Parameter == "data"), "Value"]
evalinc_idx <- setup_params[which(setup_params$Parameter == "substr"), "Value"]
mm_inc_idx <- id_settings[which(id_settings$Parameter == "inc"), "Value"]
if ((params$updated == "none") | (params$updated == "PeakArea")) { #run if not Inc manually validated
if (inc_idx != "qMTX") {
if (mm_inc_idx != FALSE) {
if (evalinc_idx != FALSE | evalinc_idx == "none") {
#Mass isotopomer distributions
nick_psirm <- as.character(file_spec[which(file_spec$AssociatedFile == "pSIRM_se"), "Filename"])
if (!file.exists(file.path(paste0(path_setup, set_input,'inc/', nick_psirm)))) {
message("FATAL ERROR: Essential file not detected: ", nick_psirm)
knitr::knit_exit()
} else {
data_mid <- read.csv(paste0(path_setup, set_input,'inc/', nick_psirm), T)
if (ncol(data_mid) == 1) {
data_mid <- read.csv(paste0(path_setup, set_input, 'inc/', nick_psirm), T, sep = ";")
}
check_emptyfile(data_mid, TRUE, nick_psirm)
}
#13C-Incorporation
nick_inc <- as.character(file_spec[which(file_spec$AssociatedFile == "inc"), "Filename"])
if (!file.exists(file.path(paste0(path_setup, set_input,'inc/', nick_inc)))) {
message("FATAL ERROR: Essential file missing! ", nick_inc)
message("Are you sure it's a pSIRM experiment???")
knitr::knit_exit()
} else {
data_inc <- read.csv(paste0(path_setup, set_input,'inc/', nick_inc), T)
if (ncol(data_inc) == 1) {
data_inc <- read.csv(paste0(path_setup, set_input, 'inc/', nick_inc), T, sep = ";")
}
check_emptyfile(data_inc, TRUE, nick_inc)
}
} else {
message("No stable isotope incorporation evaluated.")
}
} else (
message("No MID and 13Inc-calculation defined for this input format.")
)
} else {
message("It's not a pSIRM experiment!")
}
} else {
#run if Inc == manually validated
if (inc_idx != "qMTX") {
if (mm_inc_idx != FALSE) {
if (evalinc_idx != FALSE | evalinc_idx == "none") {
#Mass isotopomer distributions
nick_psirm <- as.character(file_spec_manVal[which(file_spec_manVal$AssociatedFile == "pSIRM_se"), "Filename"])
if (!file.exists(file.path(paste0(path_setup, set_input,'inc/', nick_psirm)))) {
message("FATAL ERROR: Essential file missing: ", nick_psirm)
message("Did you really validated the incorporation data?")
knitr::knit_exit()
} else {
data_mid <- read.csv(paste0(path_setup, set_input,'inc/', nick_psirm), T)
if (ncol(data_mid) == 1) {
data_mid <- read.csv(paste0(path_setup, set_input, 'inc/', nick_psirm), T, sep = ";")
}
check_emptyfile(data_mid, TRUE, nick_psirm)
}
#13C-Incorporation
nick_inc <- as.character(file_spec_manVal[which(file_spec_manVal$AssociatedFile == "inc"), "Filename"])
if (!file.exists(file.path(paste0(path_setup, set_input,'inc/', nick_inc)))) {
message("FATAL ERROR: Essential file missing: ", nick_inc)
message("Did you really validated the incorporation data?")
knitr::knit_exit()
} else {
data_inc <- read.csv(paste0(path_setup, set_input,'inc/', nick_inc), T)
if (ncol(data_inc) == 1) {
data_inc <- read.csv(paste0(path_setup, set_input, 'inc/', nick_inc), T, sep = ";")
}
check_emptyfile(data_inc, TRUE, nick_inc)
}
} else {
message("No stable isotope incorporation evaluated.")
}
} else {
message("No MID and 13Inc-calculation defined for this input format.")
}
} else {
message("It's not a pSIRM experiment!")
}
}
```
```{r check_input_files}
imp_error <- MTXQCp1_checkinput(data_extracts, ann)
if (imp_error != 0) {
message("Check the imported files messages! Number of files without import: ", imp_error)
} else {
message("Annotation and Sample_extract.csv correctly imported!")
}
```
# MTXQC - GC-MS perfomance
## Alkane standards
```{r alkanes_QCmetric}
if (alkane_idx == TRUE) {
data_alk = file_shaping(data_alk, shape = "long", ann, type = "sample")
alk_qc = gc_metric_calc(data_alk, title = "alkanes")
}
```
```{r alkanes, fig.height = 5, fig.width = 5, fig.cap = "Distribution of Alkanes (c10 - c36)"}
if (alkane_idx == TRUE) {
if (!nrow(data_alk) == 0) {
ggplot(data_alk, aes(File, intensity)) +
geom_boxplot() +
coord_flip() +
facet_wrap(~Batch_Id, scales = "free") +
#ggtitle('Distribution of Alkanes (#c10 - #c36)') +
geom_point(aes(color = metabolite)) +
scale_color_manual(values = brewer.pal(9, "Paired"),guide = guide_legend(title = 'Alkane')) +
xlab('File') +
ylab('Peak area in (-)') +
theme(text = element_text(size = 8))
} else {
message("This data frame is empty!")
}
} else {
message("Evaluation of alkanes not activated and data present.")
}
```
## Data normalization
### Internal standard evaluation
```{r internalstandard_qc, tidy = TRUE}
if (is_exit != 1) {
if (mm_ca_idx == TRUE) {
if (ca_idx == TRUE) {
cin_data = file_shaping(cinacid, shape = "wide",
file_annotation = ann,
type = "sample",
inc = FALSE)[,c("File", "PeakArea", "Batch_Id")]
cinacid_qc = gc_metric_calc(cin_data, title = "internalstandard")
} else {
Batch_Id = unique(alk_qc$Batch_Id)
cinacid_qc = data.frame(Batch_Id, qc_metric = rep(NA, length(Batch_Id)))
write.csv(cinacid_qc, paste0(path_setup,'output/gc/qcmetric_IntStandard.csv'), row.names = F)
}
}
}
```
```{r internalstandard_plot, echo = F, fig.cap = "Quantification of internal extraction standard", fig.width = 5, fig.height = 5}
if (ca_idx == TRUE && mm_ca_idx == TRUE && is_exit == 0) {
cinacid_statistics = read.csv(paste0(path_setup, 'output/gc/IntStandard_stats.csv'), TRUE)
if (nrow(cinacid_statistics) != 0) {
cin_f = c('below','within','above')
cinacid_statistics$CA_eval = factor(cinacid_statistics$IntStd_eval, levels = cin_f)
ggplot(cinacid_statistics, aes(File, PeakArea, color = IntStd_eval)) +
geom_point() +
#geom_bar(stat = "identity", size = .3, color = "black") +
coord_flip() +
geom_hline(aes(yintercept = mean_batch), color = 'red', linetype = 'dotdash') +
geom_hline(aes(yintercept = mean_batch - sd_batch), color = c('black'), linetype = 'dotdash') +
geom_hline(aes(yintercept = mean_batch + sd_batch), color = c('black'), linetype = 'dotdash') +
theme_bw() +
theme(text = element_text(size = 8)) +
facet_wrap(~ Batch_Id, scales = "free") +
scale_color_manual(values = color_ca,
guide = guide_legend(title = 'Eval: Internal Standard')) +
ylab('PeakArea in (-)') +
theme(legend.position = "bottom")
} else {
message("Empty data frame OR no peak areas for internal standard detectable!")
}
} else {
message("Empty data frame OR no peak areas for internal standard detectable!")
}
```
### Sum of Area of annotated metabolites
```{r sumArea_qc, tidy = TRUE}
if (mm_peaks_idx == TRUE) {
suma_data <- file_shaping(data_area, shape = 'wide',
ann, type = "sample",
inc = FALSE)
suma_qc <- gc_metric_calc(suma_data, title = 'sumofarea')
#50% of annotated values level
nmin = read.csv(paste0(path_setup, 'output/gc/Min_Annotation.csv'), TRUE)
knitr::kable(nmin, format = 'markdown', caption = '50& quartile of annotated metabolites per batch.')
} else {
message("SumOfArea normalisation has not been selected in MTXQC part 4!")
}
```
```{r nb_annotation, echo = F, fig.cap = "Count N: Annotated intermediates per file. Evaluate careful for SumOfArea normalisation.", fig.width = 5, fig.height = 5}
if (mm_peaks_idx == TRUE) {
area_plot = read.csv(paste0(path_setup, 'output/gc/SumArea_stats.csv'), TRUE)
if (nrow(area_plot != 0)) {
ggplot(area_plot, aes(File, n_area)) +
geom_point(size = 2) +
ggtitle("Count: Annotated metabolites per file") +
coord_flip() +
facet_wrap(~ Batch_Id, scales = "free_y") +
geom_hline(aes(yintercept = n_50), color = "red",linetype = "dashed") +
ylab("Count N (-)") +
xlab('File') +
theme(legend.position = "bottom") +
theme(text = element_text(size = 8))
} else {
message("No SumArea_stats.csv file detected!")
}
}
```
```{r SumofArea, echo = F, fig.cap = "Total peak area of all annotated metabolite per file.", fig.width = 5, fig.height = 5}
if (mm_peaks_idx == TRUE) {
area_plot = read.csv(paste0(path_setup, 'output/gc/SumArea_stats.csv'), TRUE)
if (nrow(area_plot != 0)) {
ggplot(area_plot, aes(File, sum_area)) +
geom_bar(stat = "identity") +
ggtitle('Normalization: SumOfArea') +
coord_flip() +
geom_hline(aes(yintercept = mean_batch), color = 'red', linetype = 'dotdash') +
geom_hline(aes(yintercept = mean_batch - sd_batch), color = c('black'), linetype = 'dotdash') +
geom_hline(aes(yintercept = mean_batch + sd_batch), color = c('black'), linetype = 'dotdash') +
ylab('Total peak area in (-)') +
facet_wrap(~ Batch_Id, scales = "free_y") +
theme(legend.position = "bottom") +
theme(text = element_text(size = 8))
} else {
message("No SunArea_stats.csv file detected!")
}
}
```
## Derivatization check
```{r mass73_stats, tidy = TRUE}
#m/z 73 and total peaks data
if (mm_73_idx != "none" && mm_peaks_idx == TRUE) {
data_deriv = file_shaping(data_73, shape = 'long', ann, type = "sample", inc = FALSE)
total_peaks = file_shaping(total_peaks, 'long', ann, type = "sample", inc = FALSE)
deriv_comb = gc_metric_calc(dataframe = data_deriv, dataframe2 = total_peaks, title = 'mz73')
} else {
message("No input files detected. Either MassSum-73.csv or PeakDensities-Chroma.csv")
}
```
## HeatMap - GC-MS performance
```{r HM_GC, fig.height = 2, fig.width = 4, fig.cap = "Heatmap summarising parameters of GC-MS performance"}
#import qcm_metrics
qcm_values = do.call(rbind, lapply(list.files(path = paste0(path_setup, 'output/gc'),
pattern = "qcmetric_",
recursive = TRUE,
full.names = TRUE), read.csv, header = TRUE))
write.csv(qcm_values, paste0(path_setup,'output/gc/HM_GC_values.csv'), row.names = F)
knitr::kable(qcm_values, caption = "Summary of parameter evaluating GC-Performance", format = "pandoc")
message('Export of GC-Performance values done!')
#plot: range [0,1] = [white, dodgerblue4], NA = grey30
p <- ggplot(qcm_values, aes(Batch_Id, title)) +
geom_tile(aes(fill = qc_metric), color = 'white') +
coord_flip() +
scale_fill_gradient2(mid = 'ghostwhite', high = '#d94801', limits = c(0,1),
na.value = 'ghostwhite',
guide = guide_legend(title = 'Score'))
base_size = 7
p_gc <- p + theme_bw(base_size = base_size) +
labs(x = '', y = '') +
scale_y_discrete(expand = c(0,0)) +
scale_x_discrete(expand = c(0,0)) +
theme(axis.text.x = element_text(size = base_size, angle = 330, hjust = 0, colour = 'grey50')) +
#theme(axis.text.y = element_blank()) +
#theme(legend.position = 'none') +
ggtitle('GC-Performance') +
theme(text = element_text(size = 8))
```
\newpage
# MTXQC - Quantitative metabolomics
## Generation of ManualQuantTable: Quant-Standards (Qstd)
```{r import_quant1_std}
#import Quant1-values for Quant-Mix
quant1 = read.csv("config_mtx/quant1_values.csv", header = T)
check_emptyfile(quant1, TRUE, "quant1_values.csv")
#which quant-version has been used
q_idx = as.character(setup_params[which(setup_params$Parameter == "quant"), "Value"])
quant_table = quant1[,c("Letter_Derivate", q_idx)]
quant_table = merge(quant_table, pathway_profile)[,c("Letter_Derivate", "Lettercode", as.character(q_idx))]
```
```{r check_mqt}
if (params$data == "maui") {
#check ManualQuantTable.tsv and defined Batch-Ids in annotation file
batch_id_def = check_mqt_batchids(ann, path_setup)
nb_id = length(batch_id_def)
#extract tsv-file names
file_names <- dir(paste0(path_setup, set_input, "quant/"), pattern = ".tsv")
#combine all tsv-files, add Batch-Id
cual <- do.call(rbind, lapply(file_names,
function(x) cbind(read.csv(paste0(path_setup, set_input,
"quant/", x), sep = "\t"),
Batch_Id = strsplit(x,'\\.')[[1]][1])))
write.csv(cual, paste0(path_setup, set_input, "quant/MQT_combined.csv"), row.names = FALSE)
#generate ManualQuantTable
mqt_std = create_manualquanttable(cual, q1_values = quant_table, con_se, FALSE)
message("ManualQuantTable generated and exported!")
}
if (params$data == "metmax") {
cual = read.csv(paste0(path_setup, set_input, "quant/ManualQuantTable_calc_", q_idx,".csv"))
message("ManualQuantTable imported!")
}
```
## Generation of ManualQuantTable: Additional calibration curves (Qadd)
```{r add_calcurves, fig.height = 2.5, fig.width =5, fig.cap = "Additional Calibration curves"}
#identify param settings
addq_idx = as.character(setup_params[which(setup_params$Parameter == "addQ"), "Value"])
nick_addq = as.character(file_spec[which(file_spec$AssociatedFile == "addQ"), "Filename"])
addq_integration = as.character(setup_params[which(setup_params$Parameter == "addQ_Int"), "Value"])
if (addq_idx == 'yes') {
#additional quant1_1 values > check for column names
quant_1add <- read.csv(paste0(path_setup, set_input, "add_quant/", nick_addq), T)
message(paste("Additional quant1-values imported for metabolites: ", length(unique(quant_1add$Lettercode)) ))
if (ncol(quant_1add) == 1) {
quant_1add <- read.csv(paste0(path_setup, set_input, "add_quant/", nick_addq), T, sep = ";")
message(paste0("Colon separator detected in: ", nick_addq))
}
#select Q_sel == "x" -> requires to check all metabolites that should be checked for absolute quantification
con_se_quant = subset(con_se, con_se$Q_sel == "x")
#Extract quant1-values for additional substances defined input/add_quant/ nick_addq
quant_1add <- merge(quant_1add, con_se_quant[,c("Lettercode", "Metabolite")])
knitr::kable(quant_1add, format = 'pandoc',
caption = 'Quant1:1-values for additional calibration curves.')
#Check annotation file for "addQ"
#identifer phrase in annotation file for additional Quant-samples
addq_phrase <- "addQ"
ann_addq <- extract_addQ_annotation(annotation_file = ann, phrase = "addQ")
addq_batchid = create_batchid(ann_addq)
#check if addq contains all batch ids from the complete setup
if (length(addq_batchid) == nb_id) {
message("Additional calibration curves have been defined for all included batches!")
} else {
message("Additional calibration curves have been not defined for all batches included in the annotation file!")
missing_ids = c(addq_batchid[!(addq_batchid %in% batch_id_def)], batch_id_def[!(batch_id_def %in% addq_batchid)])
message("Batch Id containing additional calibration curves: ", addq_batchid)
}
#peak areas from quantmassareamatrix
df_peakareas <- file_shaping(data_area,
shape = 'wide',
file_annotation = ann_addq,
complete_ann = TRUE,
type = "addQ",
inc = FALSE)
#add annotation lists for metabolite names
df_peakareas <- merge(df_peakareas, con_se[,c("Metabolite","Lettercode")])
#select intermediates based on additional quant1_1 values
addq_sel <- subset(df_peakareas, Lettercode %in% unique(quant_1add$Lettercode))
#duplicate values for each batch -> addq_integration == "yes"
if (addq_integration == "yes") {
#remove column Bacth Id
idx_batchid = which(grepl("Batch_Id", colnames(addq_sel)))
trial = addq_sel[,-idx_batchid]
#create new dataframe containing Batch Ids and Origin Qadd
merge_sets = data.frame(Batch_Id = batch_id_def, Origin = rep("Qadd", length(batch_id_def)))
trial_c = merge(trial, merge_sets)
addq_sel = trial_c
message("Additional calibration curves have been duplicated and added for all batches!")
}
###### Create ManualQuantTable with additional measurements
mqt_addq <- create_manualquanttable(addq_sel, quant_1add, met_translation = con_se,
plot = TRUE)
}
```
```{r merge_mqts}
if (addq_idx == 'yes') {
#prepare Quant-Standards
colnames(mqt_std)[grep("Quant", colnames(mqt_std))] <- "Quant1"
#mqt_std$Origin = rep("Qstd", length(mqt_std$Lettercode))
#prepare add-Quants
colnames(mqt_addq)[grepl("Quant", colnames(mqt_addq))] <- "Quant1"
#mqt_addq$Origin = rep("Qadd", length(mqt_addq$Lettercode))
mqt_addq = subset(mqt_addq, mqt_addq$Batch_Id %in% batch_id_def)
mqt_combined = rbind(mqt_std, mqt_addq)
write.csv(mqt_combined, paste0(path_setup, set_input,
"quant/ManualQuantTable_integrated.csv"), row.names = FALSE)
message("Additional Quant-Standards have been added to MQT_integrated.csv")
}
```
## Determination of calibration curves
```{r cal_curves, tidy = TRUE, warning=FALSE}
#calibration curve data
#cual = read.delim(paste0(path_setup,'input/quant/ManualQuantTable.tsv'), sep = '\t', header = T)
if (addq_idx == 'yes') {
cal_data = read.csv(paste0(path_setup, set_input, "quant/ManualQuantTable_integrated.csv"))
} else {
cal_data = read.csv(paste0(path_setup, set_input, "quant/ManualQuantTable_calc_", q_idx,".csv"))
}
#add annotation: Metabolite_short
cal_data <- merge(cal_data, con_se[,c("Lettercode", "Metabolite_short", "Q_sel")])
#clean-up
cal_clean <- subset(cal_data, !is.na(cal_data$Concentration))
cal_clean <- subset(cal_clean, cal_clean$ChromIntensities != -99)
cal_clean <- subset(cal_clean, cal_clean$Q_sel == "x")
#calculate adj. Rsquare, intercept and slope
qcurve_top5_rsquare(cal_clean, path_setup)
#read updated file (containing adj. r-square, slope and intercept)
qt <- read.table(file = paste0(path_setup, 'output/quant/top5_QMQcurveInfo.csv'), T)
#check empty file
if (is.data.frame(qt) && !nrow(qt == 0)) {
message("Empty file detected: quant/top5QMQcurveInfo.csv")
message("Please check the annotation of your metabolites.")
knitr::knit_exit()
} else {
message("top5_QMQcurveInfo.csv imported!")
#Determine QC-params for Quantification
qc_calcurve <- quant_metric_calc_new(qt)
}
```
```{r calcurve_par, fig.height = 5, fig.width = 5, fig.cap = "Calibration curves: Nb. of data points."}
if (is.data.frame(qc_calcurve) && nrow(qc_calcurve != 0)) {
ggplot(qc_calcurve, aes(Lettercode, Par_value, color = Parameter)) +
geom_point(aes(shape = Parameter), size = 3) +
coord_flip() +
ggtitle('Calibration curve: adj. R square and nb of data points') +
ylim(0,1) +
geom_hline(aes(yintercept = 0.75), linetype = 'dashed', color = 'grey30') +
scale_color_manual(values = c('tomato3','black')) +
scale_shape_manual(values = c(17,20)) +
facet_grid(Origin ~ Batch_Id, scales = "free_y") +
xlab('Derivate') +
ylab('Parameter value in (-)') +
theme(legend.position = "bottom")
}
```
```{r limits}
qt_limits = melt(qt, id = c('Lettercode', 'Batch_Id', 'Origin'), measure.vars = c('max','min'),
variable.name = "Param", value.name = "Limits")
qt_limits = unique(qt_limits)
```
```{r calcurve_linrange, echo = FALSE, fig.width = 5, fig.height = 5, fig.cap = "Limits of quantifiable range per metabolite"}
ggplot(qt_limits, aes(Lettercode, Limits)) +
geom_point(aes(shape = Param)) +
ggtitle('Limits of quantification (pmol)') +
scale_shape_manual(values = c(17,21), guide = guide_legend(title = 'Quant. Range')) +
coord_flip() +
scale_y_log10() +
facet_grid(Origin ~ Batch_Id, scales = "free_y") +
xlab('Derivate') +
ylab('Quantity in (pmol)') +
theme(legend.position = "bottom") +
theme(text = element_text(size = 8))
```
## Evaluation of experimental data
### Determination extraction factor
```{r extr_fac, tidy = TRUE}
extr_fac = eval_extractionfactor(setup_params)
```
### Quantification range and limits
```{r pools_linrange, tidy = TRUE}
#area import
#data = read.csv(paste0(path_setup, 'input/quant/quantMassAreasMatrix.csv'), header = T, sep = ',')
data_exp = file_shaping(data_area, shape = 'wide', ann, FALSE, type = "sample", inc = FALSE)
data_ann = merge(data_exp, con_se)
#clean-up: Q_sel == "x" or nopsirm == "x" (its required to remove technical replicates due to pSIRM)
data_clean = subset(data_ann, data_ann$Q_sel == "x" | data_ann$nopsirm == "x")
```
```{r samples_lincheck, tidy = TRUE, warning=FALSE}
#add a column to state if there is an calibration curve available
uni_qt = unique(qt[,c("Metabolite", "Batch_Id", "Origin")])
qt_check = unique(qt[,c('Metabolite', 'Batch_Id', 'Origin','adj_r_squared',
'slope', 'intercept')])
data_qt_check = merge(data_clean, qt_check, all.x = T)
data_qt_check$calc_curve = factor(ifelse(is.na(data_qt_check$adj_r_squared),
'no_cal', 'yes_cal'),
levels = c('yes_cal', 'no_cal'))
#Check linearity range
lin_cal = evaluate_qt_lin(data_qt_check)
```
```{r samples_range, echo = FALSE, fig.width = 5, fig.height = 7, fig.cap = "Distribution of data points regarding linear range of the calibration curve"}
if (nrow(lin_cal != 0)) {
if (addq_idx == "yes") {
print(
#ggplot(subset(lin_cal, lin_cal$Origin == "Qstd" | lin_cal$Origin == NA),
ggplot(subset(lin_cal, lin_cal$Origin == "Qstd" | is.na(lin_cal$Origin)),
aes(x = Lettercode, y = prop, fill = islinear)) +
geom_bar(stat = 'identity', size = .25, color = 'black') +
scale_fill_manual(values = color_linearity,
guide = guide_legend(title = 'Evaluation')) +
coord_flip() +
facet_wrap(Origin ~ Batch_Id, scales = "free_y") +
xlab('Derivate') +
ylab('Fraction of data points (%)') +
theme(legend.position = "bottom") +
theme(text = element_text(size = 8))
)
print(
ggplot(subset(lin_cal, lin_cal$Origin == "Qadd"),
aes(x = Lettercode, y = prop, fill = islinear)) +
geom_bar(stat = 'identity', size = .25, color = 'black') +
scale_fill_manual(values = color_linearity,
guide = guide_legend(title = 'Evaluation')) +
coord_flip() +
facet_wrap(Origin ~ Batch_Id, scales = "free_y") +
xlab('Derivate') +
ylab('Fraction of data points (%)') +
theme(legend.position = "bottom") +
theme(text = element_text(size = 8))
)
} else {
ggplot(lin_cal, aes(x = Lettercode, y = prop, fill = islinear)) +
geom_bar(stat = 'identity', size = .25, color = 'black') +
scale_fill_manual(values = color_linearity,
guide = guide_legend(title = 'Evaluation')) +
#ggtitle('Fraction of measurements regarding quantification curve') +
coord_flip() +
facet_wrap(Origin ~ Batch_Id, scales = "free_y") +
xlab('Derivate') +
ylab('Fraction of data points (%)') +
theme(legend.position = "bottom") +
theme(text = element_text(size = 8))
}
} else {
message("Empty data frame: Linear range")
}
```
### Absolute quantification samples
```{r calc_quantity, tidy = TRUE}
#Check linearity range
data_calcheck = read.csv(paste0(path_setup, set_output, 'quant/calcheck_linearity.csv'), TRUE)
data_quantified = data_calcheck
data_quantified$absconc = data_quantified$slope * data_quantified$PeakArea + data_quantified$intercept
#consider extraction and preparation factors
data_quantified$extr_fac = rep(extr_fac, length(data_quantified$Lettercode))
data_quantified$corr_absconc = data_quantified$absconc * data_quantified$extr_fac
data_q_plot = data_quantified
data_q_plot <- data_q_plot %>%
mutate(corr_absconc = replace(corr_absconc, is.na(corr_absconc), 0))
```
```{r calcurve_sample, fig.width = 6, fig.height = 6}