-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxcms-preprocessing.Rmd
2355 lines (1913 loc) · 101 KB
/
xcms-preprocessing.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: "Exploring and Analyzing LC-MS Data with Spectra and xcms"
author:
- name: "Philippine Louail, Johannes Rainer"
affiliation: "Eurac Research, Bolzano, Italy; [email protected] github: jorainer"
graphics: yes
date: "February 2024"
output:
BiocStyle::html_document:
number_sections: true
toc_float: true
toc_depth: 2
vignette: >
%\VignetteIndexEntry{Exploring and Analyzing LC-MS Data with Spectra and xcms}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding[utf8]{inputenc}
%\VignettePackage{xcmsTutorials}
%\VignetteDepends{xcms,Spectra,BiocStyle,MetaboCoreUtils,knitr,png,MsCoreUtils,msdata,MsExperiment,pheatmap,MSnbase}
bibliography: references.bib
---
```{r style, message = FALSE, echo = FALSE, warning = FALSE, results = "asis"}
#' Pre-loading libraries and define settings for rendering
library("BiocStyle")
library("knitr")
library("rmarkdown")
library("xcms")
register(SerialParam())
set.seed(123)
opts_chunk$set(message = FALSE, error = FALSE, warning = FALSE,
cache = FALSE, fig.width = 10, fig.height = 7)
```
# Abstract
In this document we discuss liquid chromatography (LC) mass spectrometry (MS)
data handling and exploration using the `r Biocpkg("MsExperiment")` and
`r Biocpkg("Spectra")` Bioconductor packages and perform the preprocessing of a
small LC-MS data set using the `r Biocpkg("xcms")` package. Functionality from
the `r Biocpkg("MetaboCoreUtils")` and `r Biocpkg("MsCoreUtils")` packages are
used for general tasks frequently performed during metabolomics data
analysis. Ultimately, the functionality from these packages can be combined to
build custom, data set-specific (and reproducible) analysis workflows.
In the present workshop, we first focus on data import, access and visualization
which is followed by the description of a simple data centroiding approach and
finally we present an *xcms*-based LC-MS data preprocessing that comprises
chromatographic peak detection, alignment and correspondence. Data normalization
procedures, compound identification and differential abundance analysis are not
covered here. Particular emphasis is given on deriving and defining data
set-dependent values for the most critical *xcms* preprocessing parameters.
# Introduction
Preprocessing is the first step in the analysis of *untargeted* LC-MS or gas
chromatography (GC)-MS data. The aim of the preprocessing is the quantification
of signals from ions measured in a sample, adjusting for any potential retention
time drifts between samples followed by the matching of the quantified signal
across samples within an experiment. The resulting two-dimensional matrix with
abundances of the so called *LC-MS features* in all samples can then be further
processed, e.g. by normalizing the data to remove differences due to sample
processing, batch effects or injection order-dependent signal drifts. LC-MS
features are usually only characterized by their mass-to-charge ratio (*m/z*)
and retention time and hence need to be annotated to the actual ions and
metabolites they represent. Data normalization and annotation are not covered by
this tutorial but links to related tutorials and workshops are provided at the
end of the document.
## Mass spectrometry
Mass spectrometry allows to measure abundances of charged molecules (ions) in a
sample. Abundances are determined as ion counts for a specific mass-to-charge
ratio *m/z*. The measured signal is represented as a spectrum: intensities along
*m/z*.

Many ions will result, when measured with MS alone, in a very similar
*m/z*. Thus, making it difficult or impossible to discriminate them. MS is
therefore frequently coupled with a second technology to separate ions prior
quantification based on properties other than their mass (e.g. based on their
polarity). Common choices are gas chromatography (GC) or liquid chromatography
(LC). In a typical LC-MS setup a sample gets injected into the system, the
molecules in the sample are separated in the LC column, get ionized and then
measured (at discrete time points) by the MS instrument (see Figure below for a
simple visualization). Molecules get thus separated on two different dimensions,
the retention time dimension (from the LC) and the mass-to-charge dimension
(from the MS) making it easier to measure and identify molecules in more complex
samples.

In such GC/LC-MS based untargeted metabolomics experiments, the data is analyzed
along the retention time dimension and *chromatographic* peaks (which are
supposed to represent the signal from ions of a certain type of molecule) are
quantified.
## Goals of this workshop
- Learn how R/*xcms* and the packages from the [RforMassSpectrometry
initiative](https://rformassspectrometry.org) can be used to inspect, evaluate
and analyze LC-MS data.
- Learn the basis to build reproducible analysis workflows, tailored and
customized for individual data sets.
## Definitions and common naming convention
Naming conventions and terms used in this document are:
- *chromatographic peak*: peak containing the signal from an ion in retention
time dimension (different from a *mass* peak that represents the signal along
the *m/z* dimension within a spectrum).
- *chromatographic peak detection*: process in which chromatographic peaks are
identified within a sample (file).
- *alignment*: process that adjusts for retention time differences
(i.e. possible signal drifts from the LC) between measurements/samples.
- *correspondence*: grouping of chromatographic peaks (presumably from the same
ion) across samples/files into *LC-MS features*.
- *feature* (or *LC-MS features*): entity representing signal from the same type
of ion/molecule, characterized by its specific retention time and *m/z*. In
*xcms*, features represent identified chromatographic peaks grouped across
samples/files.
# Data import and exploration
The example data set of this workflow consists of two files in mzML format with
signals from pooled human serum samples measured with a ultra high performance
liquid chromatography (UHPLC) system (Agilent 1290) coupled with a Q-TOF MS
(TripleTOF 5600+ AB Sciex) instrument. Chromatographic separation was based on
hydrophilic interaction liquid chromatography (HILIC) separating metabolites
depending on their polarity. The input files contain all signals measured by the
MS instrument (so called *profile mode* data). To reduce file sizes, the data
set was restricted to an *m/z* range from 105 to 134 and retention times from 0
to 260 seconds. Both QC pool samples were taken from a larger experiment and
were injected in the same measurement run at different time points (injected in
position 1 and 19 of the measurement run).
In the code block below we first load all required libraries and define the
location of the mzML files, which are distributed through the *msdata* R
package. We also define a `data.frame` with the names of the mzML files, an
arbitrary sample name, the index in which the respective sample was measured
within the LC-MS run and the sample *group* of the samples. It is generally
suggested to provide all experiment-relevant phenotypic and technical
information through such a data frame. Also, the data frame could be defined in
an xls sheet that could then be imported with the `read_xlsx` function from the
*readxl* R package. This data frame is then passed, along with the file names,
to the `readMsExperiment()` call to import the data.
```{r load-data}
#' Load required libraries
library(xcms)
library(MsExperiment)
library(Spectra)
#' Define the file names.
fls <- dir(system.file("sciex", package = "msdata"), full.names = TRUE)
#' Define a data.frame with additional information on these files.
pd <- data.frame(file = basename(fls),
sample = c("POOL_1", "POOL_2"),
injection_index = c(1, 19),
group = "POOL")
#' Import the data of the experiment
mse <- readMsExperiment(fls, sampleData = pd)
mse
```
The MS data of the experiment is now *represented* by an `MsExperiment` object.
## Basic data access
The `MsExperiment` object manages the *linkage* between samples and spectra.
The `length()` of an `MsExperiment` is defined by the number of samples (files)
within the object.
```{r general-access}
#' Number of samples
length(mse)
```
Subset the `MsExperiment` will restrict (all) data within the object to the
selected sample(s). To restrict to data from the second sample we use:
```{r}
#' Subset the data
mse_2 <- mse[2]
mse_2
```
This did subset the full data, including sample information and spectra data
to those of the second file. Phenotype information can be retrieved with the
`sampleData()` function from an `MsExperiment` object.
```{r}
#' Extract sample information
sampleData(mse_2)
```
The MS data is stored as a `Spectra` object within the `MsExperiment` and can be
accessed using the `spectra()` function.
```{r show-fData}
#' Access the MS data
spectra(mse)
```
From version 4 on, *xcms* supports the more modern and flexible infrastructure
for MS data analysis provided by the `r Biocpkg("Spectra")` package. While it is
still possible to use *xcms* together with the `r Biocpkg("MSnbase")` package,
users are advised to switch to the newer infrastructure as it provides more
flexibility and a higher performance. Also, through additional packages such as
the `r Biocpkg("MsBackendRawFileReader")`, the new infrastructure would allow to
import MS data also from other files than mzML, mzXML or CDF files.
In the next few examples we briefly explain the `Spectra` object and illustrate
the use of such objects using some simple examples. More information on
`Spectra` objects can be found in the package's
[documentation](https://RforMassSpectrometry.github.io/Spectra) or the
[SpectraTutorials](https://jorainer.github.io/SpectraTutorials).
The `Spectra` object contains the full MS data of the experiment. It's length is
thus equal to the total number of spectra within the experiment. Below we
determine this number for our example data set. To avoid nested function calls
and hence improve the readability of the code, we use the R pipe operator `|>`
that allows to concatenate consecutive calls in a more readable fashion.
```{r}
#' Get the total number of spectra
spectra(mse) |>
length()
```
The `Spectra` object itself is agnostic of any sample information, it simply
contains all spectra from the experiment, first all spectra from the first file,
followed by the spectra from the second. The mapping of spectra to samples is
defined in the `MsExperiment` object. To access spectra from a specific sample
we either subset the `MsExperiment` to that particular sample (as done in the
example above) or we use the `spectraSampleIndex()` function that returns for
each spectrum the index of the file within the `MsExperiment` to which it
belongs. Below we use `spectraSampleIndex()` to determine the total number of
spectra per sample.
```{r}
#' Get the number of spectra per file.
spectraSampleIndex(mse) |>
table()
```
Such basic data summaries can be helpful for a first initial quality assessment
to identify potentially problematic data files with e.g. a unexpected low number
of spectra.
Besides the peak data (*m/z* and intensity values) also additional spectra
variables (metadata) are available in a `Spectra` object. These can be listed
using the `spectraVariables()` function that we call on our example MS data
below.
```{r}
#' List available spectra variables
spectra(mse) |>
spectraVariables()
```
Thus, for all spectra we have general information such as the MS level
(`"msLevel"`) or the retention time (`"rtime"`) available. For most of these
spectra variables dedicated accessor functions are available (such as `msLevel`,
`rtime`). In addition it is possible to access any variable using `$` and the
name of the variable (similar to accessing the columns of a `data.frame`). As an
example we extract below the `msLevel` spectra variable and use the `table()`
function on the result to get an overview of the number of spectra from
different MS levels available in the object.
```{r}
#' List number of spectra per MS level
spectra(mse) |>
msLevel() |>
table()
```
The present data set contains thus 1,862 spectra, all from MS level 1.
We could also check the number of peaks per spectrum in the different data
files. The number of peaks per spectrum can be extracted with the `lengths()`
function. Below we extract these values, split them by file and then calculate
the quartiles of the peak counts using the `quantile()` function.
```{r}
#' Get the distribution of peak counts per file
spectra(mse) |>
lengths() |>
split(fromFile(mse)) |>
lapply(quantile)
```
Thus, for the present data set, the number of spectra and also the average
number of peaks per spectra are comparable.
Individual MS spectra can be accessed by subsetting the `Spectra` object
returned by `spectra()`. As an example we below subset the data to the second
sample, extract the spectra from that sample and subset to the spectrum number
123.
```{r}
#' Extract one spectrum from the second file
sp <- spectra(mse[2])[123]
sp
```
*m/z* and intensity values can be extracted from a `Spectra` using the `mz()`
and `intensity()` functions that (always) return a list of `numeric` vectors
with the respective values:
```{r}
#' Extract m/z values
mz(sp)
#' Extract intensity values
intensity(sp)
```
As an alternative, the `peaksData()` function could be used to extract both the
*m/z* and intensity values (as two-column numeric matrix) with a single function
call.
The total ion signal of a spectrum could be calculated by simply summing the
intensities of all peaks in the spectrum. Below we perform that operation on the
spectrum extracted above.
```{r}
#' Calculate total ion signal for the extracted spectrum
intensity(sp) |>
sum()
```
The same operation can also be applied to the full data set. As an example we
calculate below the total ion signal for each spectrum in the first file and
determine the distribution of these using the `quantile()` function.
```{r}
#' Calculate the distribution of total ion signal of the first file
mse[1] |>
spectra() |>
intensity() |>
sum() |>
quantile()
```
We repeat the operation for the second file.
```{r}
#' Repeat for the second file
mse[2] |>
spectra() |>
intensity() |>
sum() |>
quantile()
```
The total ion signals of the two data files is (as expected) similar. Through
the `Spectra` object we have thus the possibility to inspect and explore the
(raw) MS data of an experiment and use its functionality to create own quality
assessment functions. Alternatively, also the `r Biocpkg("MsQuality")` package
[@naake_msquality_2023] could be used to calculate core MS quality metrics on a
full experiment (`MsExperiment`) or individual data files (`Spectra`).
## Data visualization
### General data overview
Visualization is crucial for quality assessment of MS data. For LC-MS data
visualizing a base peak chromatogram (BPC) or total ion chromatogram (TIC) would
for example allow to evaluate the performance of the liquid chromatography of
the various samples in an experiment. To create such a plot we below extract the
BPC from our data. The BPC extracts the maximum peak signal from each spectrum
in a data file and allows thus to plot this information (on the y-axis) against
the retention time for that spectrum. While we could also extract these values
similarly to the total ion intensity in the previous section, we use below the
`chromatogram()` function that allows extraction of chromatographic data from MS
data (e.g. from an `MsExperiment` object). With parameter `aggregationFun =
"max"` we define to report the maximum signal per spectrum (setting
`aggregationFun = "sum"` would in contrast sum up all intensities of a spectrum
and hence return a TIC).
```{r}
#' Extract and plot a BPC
bpc <- chromatogram(mse, aggregationFun = "max")
plot(bpc)
```
This plot shows the BPC for each of the two data files (each line representing
one sample) and provides the information at what retention times signal was
measured (thus at what retention times compounds eluted from the LC column). We
can clearly spot regions along the retention time in which more signal/compounds
eluted. Also, the BPC of the two data files look similar, which is expected
since both represent the same sample.
In addition to a visual inspection it is, especially for larger data sets,
important to also *quantitatively* compare the data and derive quality metrics
of a data set. For our base peak signals, however, retention times will be
slightly different between the samples preventing thus a direct comparison and
evaluation of this data. An easy solution to this is to *bin* the data along the
retention time axis into equal sized bins and aggregate the measured intensities
within each bin (per sample). Below we bin the data with a bin size of 1 second
reporting the maximal signal per bin.
```{r}
#' Bin the BPC
bpc_bin <- bin(bpc, binSize = 1)
```
After binning, the two chromatograms have the same retention times (and number
of intensities) and we can thus *bind* their intensity vectors as columns of a
new numeric matrix using `cbind()`:
```{r}
#' Create an intensity matrix
bpc_mat <- do.call(cbind, lapply(bpc_bin, intensity))
```
We could now for example calculate the correlation between the intensities of
the two samples, which can be used as a measure for the *similarity* of the
LC-MS runs.
```{r}
#' Assess similarity between the numerical vectors using a simple
#' Pearson correlation.
cor(bpc_mat[, 1], bpc_mat[, 2])
```
We could also create a correlation matrix with the pairwise correlation
coefficients of all samples against all samples. This would be particularly
helpful for data sets with more than two samples.
```{r}
#' Create a pairwise correlation matrix
cor(bpc_mat)
```
Such a correlation matrix could also be easily visualized as a *heatmap* -
with the additional possibility to cluster samples with similar BPC. While for
the present, two-sample data set, this is not very informative, for larger data
sets it can help to evaluate differences between batches or to spot outlier
samples (or rather outlier LC-MS measurement runs).
```{r, fig.cap = "Heatmap for similarity of the BPC of the two data files"}
#' Create a heatmap of the correlation matrix
library(pheatmap)
cor(bpc_mat) |>
pheatmap()
```
This also exemplifies the power of an R-based analysis workflow that allows us
to combine LC-MS specific analysis methods provided by e.g. the *xcms* package
with build-in R functions or (statistical) data analysis methods provided by any
other R package.
The BPC collapsed the 3-dimensional LC-MS data (*m/z* by retention time by
intensity) into 2 dimensions (retention time by intensity). An orthogonal
visualization to this would be a *base peak spectrum* (BPS) that collapses the
data in retention time dimension. Such a visualization could provide information
on the most abundant masses (or rather mass-to-charge values) in the data set
(regardless of the retention time in which they were measured). In contrast to
the BPC it is however not straight forward to create such a visualization: mass
peaks, even if representing signal from the same ion, will never be identical
between consecutive spectra, but will slightly differ based on the measurement
error/resolution of the instrument.
Below we plot the spectra for 2 consecutive scans.
```{r, fig.cap = "Spectra from two consecutive scan of the first file"}
#' Plot two consecutive spectra
plotSpectra(spectra(mse)[123:124], xlim = c(105, 130))
```
These two spectra could now be merged by reporting for each *m/z* (or rather for
peaks with very similar *m/z* in consecutive spectra) the maximal signal
observed. In *Spectra*, the `combineSpectra()` function allows to
aggregate/combine sets of spectra into a single spectrum. By default, this
function will combine sets of spectra (that can be defined with parameter `f`)
creating an union of the peaks present in spectra of a set. For mass peaks with
a similar *m/z* value (depending on parameter `ppm`) the peaks' intensities are
aggregated using the function defined with parameter `intensityFun` to result in
a single value per (aggregated) peak. With the setting below we combine all
spectra from one file (by using `f = fromFile(mse)`) into a single spectrum
containing mass peaks present in any of the spectra of that file. Mass peaks
with a difference in their *m/z* that is smaller than `ppm` (parts-per-million
of the *m/z* value) are combined into one peak for which the maximal intensity
of the grouped peaks is reported. Note that it is suggested to use a small value
for `ppm` to combine MS1 spectra with `combineSpectra()`.
```{r}
#' Combine all spectra of one file into a single spectrum
bps <- spectra(mse) |>
combineSpectra(f = fromFile(mse), ppm = 5, intensityFun = max)
bps
```
`bps` is thus a `Spectra` with two spectra representing the BPS of the two data
files. Below we plot these.
```{r, fig.cap = "Base peak spectrum for each of the two samples."}
#' Plot the BPS
plotSpectra(bps)
```
These BPS thus show the most common ions present in each of the two
samples. Apparently there seems to be quite some overlap in ion content between
the two files. Also here, we can calculate similarities between these
spectra. As before, we could either bin the spectra and calculate a correlation
matrix between their intensities:
```{r}
#' Bin the spectra and calculate similarity between their intensities
bps_bin <- bin(bps, binSize = 0.01)
do.call(cbind, intensity(bps_bin)) |>
cor()
```
Alternatively, we can also directly calculate the similarity between the base
peak spectra using the `compareSpectra()` function and one of the available peak
similarity measures. Below we use the normalized dot product to calculate the
similarity between the two spectra matching peaks using an *m/z* tolerance of 10
ppm.
```{r}
#' Calculate normalized dot product similarity between the spectra
compareSpectra(bps, ppm = 10, FUN = MsCoreUtils::ndotproduct)
```
These measures thus allow us to get some general information on a data set and
evaluate similarities between the samples of an experiment.
### Detailed data inspection
Apart from such general data overview it is also possible (and also suggested)
to explore the data in more detail. To this end we next focus on a specific
subset of the data were we expect signal for a compound that should be present
in serum samples (such as ions of the molecule serine). With the particular
LC-MS setup used for the present samples, ions for this metabolite are expected
to elute at about 180 seconds (this retention time was determined by measuring a
pure standard for this compound on the same LC-MS setup). We thus filter below
the spectra data using the `filterRt()` function extracting only spectra
measured between 180 and 181 seconds.
```{r}
#' Extract all spectra measured between 180 and 181 seconds
sps <- spectra(mse) |>
filterRt(c(180, 181))
sps
```
For the present data set there are `r length(sps)` spectra measured within this
one second in both samples. By extracting the data as a `Spectra` object we
have however lost now the direct (inherent) association between spectra and
samples of the experiment. We could extract the name of the original data file
from which the data was imported (see example below) and use that to determine
the originating sample, but that would involve additional R code.
```{r}
#' List the original data file for each spectrum
basename(dataOrigin(sps))
```
Alternatively, we could use the `filterSpectra()` function on the `MsExperiment`
object passing the filter function (in our case `filterRt()`) to that
function. This filters the `Spectra` object *within* the `MsExperiment`
retaining all associations (links) between samples and subset spectra. While
some of the most commonly used filter functions, such as `filterRt()` or
`filterMsLevel()`, are also implemented for `MsExperiment`, the
`filterSpectra()` function allows to apply any of the many filter functions
available for `Spectra` objects to the data.
```{r}
#' Subset the whole MsExperiment
mse_sub <- filterSpectra(mse, filter = filterRt, rt = c(180, 181))
#' Extract spectra from the subset for the first sample
spectra(mse_sub[1])
```
For the present purpose it is however not important to keep the sample
association intact and we thus proceed to plot the previously extracted spectra.
```{r, fig.cap = "MS1 spectra measured between 180 and 181 seconds"}
#' Plot the spectra
plotSpectra(sps)
```
We can immediately spot several mass peaks in the spectrum, with the largest one
at an *m/z* of about 130 and the second largest at about 106, which
could represent signal for an ion of
[Serine](https://en.wikipedia.org/wiki/Serine). Below we calculate the exact
(monoisotopic) mass for serine from its chemical formula *C3H7NO3* using the
`calculateMass()` function from the `r Biocpkg("MetaboCoreUtils")` package.
```{r}
#' Calculate the (monoisotopic) mass of serine
library(MetaboCoreUtils)
mass_serine <- calculateMass("C3H7NO3")
mass_serine
```
The *native* serine molecule is however uncharged and can thus not be measured
by mass spectrometry. In order to be detectable, molecules need to be ionized
before being injected in an MS instrument. While different ions can (and will)
be generated for a molecule, one of the most commonly generated ions in positive
polarity is the *[M+H]+* ion (protonated ion). To calculate the *m/z* values for
specific ions/adducts of molecules, we can use the `mass2mz()` function, also
from the *MetaboCoreUtils* package. Below we calculate the *m/z* for the
*[M+H]+* ion of serine providing the monoisotopic mass of that molecule and
specifying the adduct we are interested in. Also other types of adducts are
supported. These could be listed with the `adductNames` function
(`adductNames()` for all positively charged and `adductNames("negative")` for
all negatively charge ions).
```{r}
#' Calculate the m/z for the [M+H]+ ion of serine
serine_mz <- mass2mz(mass_serine, "[M+H]+")
serine_mz
```
The `mass2mz()` function **always** returns a `matrix` with columns reporting
the *m/z* for the requested adduct(s) of the molecule(s) which are available in
the rows. Since we requested a single ion we reduce this `matrix` to a single
`numeric` value.
```{r}
serine_mz <- serine_mz[1, 1]
```
We can now use this information to subset the MS data to the signal recorded for
all ions with that particular *m/z*. We use again the `chromatogram()` function
and provide the *m/z* range of interest with the `mz` parameter of that
function. Note that alternatively we could also first filter the data set by
*m/z* using the `filterMzRange()` function and then extract the chromatogram.
```{r, fig.cap = "Ion trace for an ion of serine"}
#' Extract a full RT chromatogram for ions with an m/z similar than serine
serine_chr <- chromatogram(mse, mz = serine_mz + c(-0.005, 0.005))
plot(serine_chr)
```
A strong signal is visible around a retention time of 180 seconds which very
likely represents signal for the *[M+H]+* ion of serine. Note that, if the
retention time of a molecule for a specific LC-MS setup is not known beforehand,
extracting such chromatograms for the *m/z* of interest and the full retention
time range can help determining its likely retention time.
The object returned by the `chromatogram()` function arranges the individual
`MChromatogram` objects (each representing the chromatographic data consisting
of pairs of retention time and intensity values of one sample) in a
two-dimensional array, columns being samples (files) and rows data slices (i.e.,
*m/z* - rt ranges). Note that this type of data representation, defined in the
`r Biocpkg("MSnbase")` package, is likely to be replaced in future with a more
efficient and flexible data structure similar to `Spectra`.
Data from the individual chromatograms can be accessed using the `intensity()`
and `rtime()` functions (similar to the `mz()` and `intensity()` functions for a
`Spectra` object).
```{r chromatogram}
#' Get intensity values for the chromatogram of the first sample
intensity(serine_chr[1, 1]) |>
head()
#' Get the respective retention times of the first sample
rtime(serine_chr[1, 1]) |>
head()
```
Note that an `NA` is reported if in the *m/z* range from which the
chromatographic data was extracted no intensity was measured at the given
retention time (i.e. in a spectrum).
At last we further focus on the tentative signal of serine extracting the ion
chromatogram restricting on the retention time range containing its
signal. While we could also pass the retention time and *m/z* range with
parameters `rt` and `mz` to the `chromatogram()` function we instead filter the
whole experiment by retention time and *m/z* before calling `chromatogram()` on
the such created data subset. With the example code below we thus create an
extracted ion chromatogram (EIC, sometimes also referred to as XIC) for the
*[M+H]+* ion of serine.
```{r, fig.cap = "Extracted ion chromatogram for serine."}
#' Create an EIC for serine
mse |>
filterRt(rt = c(175, 189)) |>
filterMzRange(mz = serine_mz + c(-0.005, 0.005)) |>
chromatogram() |>
plot()
```
The area of such a chromatographic peak is supposed to be proportional to the
amount of the corresponding ion in the respective sample and identification and
quantification of such peaks is one of the goals of the LC-MS data
preprocessing.
While we inspected here the signal measured for ions of serine, this workflow
could (and should) also be repeated for other potentially present ions (or
internal standards) to evaluate the LC-MS data of an experiment.
# Centroiding of profile MS data
MS instruments allow to export data in profile or centroid mode. Profile data
contains the signal for all discrete *m/z* values (and retention times) for
which the instrument collected data [@Smith:2014di]. MS instruments continuously
sample and record signals, therefore a mass peak for a single ion in one
spectrum will consist of multiple intensities at discrete *m/z* values. The
process to reduce this distribution of signals to a single representative mass
peak (the centroid) is called centroiding. This process results in much smaller
file sizes, with only little information loss. *xcms*, specifically the
*centWave* chromatographic peak detection algorithm, was designed for centroided
data, thus, prior to data analysis, profile data, such as the example data used
here, has to be centroided.
Below we inspect the profile data for one of the spectra extracted above and
focus on the mass peak for serine.
```{r, fig.cap = "Profile-mode mass peak for the [M+H]+ ion of serine. The theoretical *m/z* of that ion is indicated with a dotted red line."}
#' Visualize the profile-mode mass peak for [M+H]+ of serine
sps[1] |>
filterMzRange(c(106.02, 106.07)) |>
plotSpectra(lwd = 2)
abline(v = serine_mz, col = "#ff000080", lty = 3)
```
Instead of a single peak, several mass peaks were recorded by the MS instrument
with an *m/z* very close to the theoretical *m/z* for the *[M+H]+* ion of serine
(indicated with a red dotted line).
We can also visualize this information differently: the `plot()` function for
`MsExperiment` generates a two-dimensional visualization of the
three-dimensional LC-MS data: peaks are drawn at their respective location in
the two-dimensional *m/z* *vs* retention time plane with their intensity being
color coded. Below we subset the data to the *m/z* - retention time region
containing signal for serine and visualize the full MS data measured for that
region in both data files.
```{r serine-profile-mode-data, fig.cap = "Profile data for Serine."}
#' Visualize the full MS data for a small m/z - rt area
mse |>
filterRt(rt = c(175, 189)) |>
filterMzRange(mz = c(106.02, 106.07)) |>
plot()
```
The lower panel of the plot shows all mass peaks measured by the instrument:
each point represents one mass peak with its intensity being color coded (blue
representing low, yellow high intensity). Each column of data points represents
data from the same spectrum. The upper panel of the plot shows a chromatographic
visualization of the data from the lower panel, i.e., for each retention time
(spectrum) the sum of intensities within the *m/z* range is shown.
Note that, while it would be possible to create such a plot for the full MS data
of an experiment, this type of visualization works best for small *m/z* -
retention time regions.
Next, we *smooth* the data in each spectrum using a Savitzky-Golay filter, which
usually improves data quality by reducing noise. Subsequently we perform the
centroiding of the data based on a simple peak-picking strategy that reports the
maximum signal for each mass peak in each spectrum. Finally, we replace the
spectra in the data (`MsExperiment`) object with the centroided spectra and
visualize the result repeating the visualization from above.
```{r centroiding, fig.cap = "Centroided data for Serine."}
#' Smooth and centroid the spectra data
sps_cent <- spectra(mse) |>
smooth(method = "SavitzkyGolay", halfWindowSize = 6L) |>
pickPeaks(halfWindowSize = 2L)
#' Replace spectra in the original data object
spectra(mse) <- sps_cent
#' Plot the centroided data for Serine
mse |>
filterRt(rt = c(175, 189)) |>
filterMzRange(mz = c(106.02, 106.07)) |>
plot()
```
The impact of the centroiding is clearly visible: each signal for an ion in a
spectrum was reduced to a single data point. For more advanced centroiding
options, that can also fine-tune the *m/z* value of the reported centroid, see
the documentation of the `pickPeaks()` function or the centroiding vignette of
the `r Biocpkg("MSnbase")` package.
While we could now simply proceed with the data analysis, we below save the
centroided MS data to mzML files to also illustrate how the *Spectra* package
can be used to export MS data.
```{r export-centroided-prepare, echo = FALSE, results = "hide"}
#' Silently removing exported mzML files if they do already exist.
lapply(basename(unique(dataOrigin(spectra(mse)))), function (z) {
if (file.exists(z))
file.remove(z)
})
```
We use the `export()` function for data export of the centroided `Spectra`
object. Parameter `backend` allows to specify the MS data backend that should be
used for the export, and that will also define the data format (use
`backend = MsBackendMzR()` to export data in mzML format). Parameter `file`
defines, for each spectrum, the name of the file to which its data should be
exported.
```{r export-centroided}
#' Export the centroided data to new mzML files.
export(spectra(mse), backend = MsBackendMzR(),
file = basename(dataOrigin(spectra(mse))))
```
We can then import the centroided data again from the newly generated mzML files
and proceed with the analysis.
```{r}
#' Re-import the centroided data.
fls <- basename(fls)
#' Read the centroided data.
mse <- readMsExperiment(fls, sampleData = pd)
```
Thus, with few lines of R code we performed MS data centroiding in R which gives
us possibly more, and better, control over the process and enable also
(parallel) batch processing.
# Preprocessing of LC-MS data
Preprocessing of (untargeted) LC-MS data aims at detecting and quantifying the
signal from ions generated from all molecules present in a sample. It consists
of the following 3 steps: chromatographic peak detection, retention time
alignment and correspondence (also called peak grouping). The resulting matrix
of feature abundances can then be used as an input in downstream analyses
including data normalization, identification of features of interest and
annotation of features to metabolites. In the following sections we perform such
preprocessing of our test data set, adapting the settings for the preprocessing
algorithms to our data.
## Chromatographic peak detection
Chromatographic peak detection aims to identify peaks along the retention time
axis that represent the signal from individual compounds' ions. This involves
identifying and quantifying such signals as shown in the sketch below.

Such peak detection can be performed with the `r Biocpkg("xcms")` package using
its `findChromPeaks()` function. Several peak detection algorithms are available
that can be selected and configured with their respective parameter objects:
- `MatchedFilterParam` to perform peak detection as described in the original
*xcms* article [@Smith:2006ic],
- `CentWaveParam` to perform a continuous wavelet transformation (CWT)-based
peak detection [@Tautenhahn:2008fx] and
- `MassifquantParam` to perform a Kalman filter-based peak detection
[@Conley:2014ha].
Additional peak detection algorithms for direct injection data are also
available in *xcms*, but not discussed here.
In our example we use the *centWave* algorithm that performs peak detection in
two steps: first it identifies *regions of interest* in the *m/z* - retention
time space and subsequently detects peaks in these regions using a continuous
wavelet transform (see the original publication [@Tautenhahn:2008fx] for more
details). The algorithm can be configured with several parameters (see
`?CentWaveParam`), with the most important being `peakwidth` and
`ppm`. `peakwidth` defines the minimal and maximal expected width of the peak in
retention time dimension and depends thus on the setup of the employed LC-MS
system making this parameter highly data set dependent. `ppm` on the other hand
depends on the precision of the MS instrument. In this section we describe how
settings for these parameters can be empirically determined for a data set.
Generally, it is strongly discouraged to blindly use the default parameters for
any of the peak detection algorithms. To illustrate this we below extract the
EIC for serine and run a *centWave*-based peak detection on that data using
*centWave*'s default settings.
```{r centWave-default}
#' Get the EIC for serine in all files
serine_chr <- chromatogram(mse, rt = c(164, 200),
mz = serine_mz + c(-0.005, 0.005),
aggregationFun = "max")
#' Get default centWave parameters
cwp <- CentWaveParam()
#' "dry-run" peak detection on the EIC.
res <- findChromPeaks(serine_chr, param = cwp)
chromPeaks(res)
```
The peak matrix returned by `chromPeaks()` is empty, thus, with the default
settings *centWave* failed to identify any chromatographic peak in the EIC for
serine. The default values for the parameters are shown below:
```{r centWave-default-parameters}
#' Default centWave parameters
cwp
```
Particularly the setting for `peakwidth` does not fit our data. The default for
this parameter expects chromatographic peaks between 20 and 50 seconds
wide. When we plot the extracted ion chromatogram (EIC) for serine we can
however see that these values are way too large for our UHPLC-based data set
(see below).
```{r, fig.cap = "Extracted ion chromatogram for serine."}
#' Plot the EIC
plot(serine_chr)
```
For serine, the chromatographic peak is about 5 seconds wide. We thus adapt the
`peakwidth` for the present data set and repeat the peak detection using these
settings. In general, the lower and upper peak width should be set to include
most of the expected chromatographic peak widths. A good rule of thumb is to set
it to about half to about twice the average expected peak width. For the present
data set we thus set `peakwidth = c(2, 10)`. In addition, by setting `integrate
= 2`, we select a different peak boundary estimation algorithm. This works
particularly well for non-gaussian peak shapes and ensures that also signal from
the peak's tail is integrated (eventually re-run the code with the default
`integrate = 1` to compare the two approaches).
```{r centWave-adapted, fig.cap = "EIC for Serine with detected chromatographic peak", results = "hide"}
#' Adapt centWave parameters
cwp <- CentWaveParam(peakwidth = c(2, 10), integrate = 2)
#' Run peak detection on the EIC
serine_chr <- findChromPeaks(serine_chr, param = cwp)
#' Plot the data and higlight identified peak area
plot(serine_chr)
```
Acceptable values for parameter `peakwidth` can thus be derived through visual
inspection of EICs for ions known to be present in the sample (e.g. of internal
standards). Ideally, this should be done for several compounds/ions. *Tip*:
ensure that the EIC contains also enough signal left and right of the actual
chromatographic peak to allow *centWave* to properly estimate the background
noise. Alternatively, or in addition, reduce the value for the `snthresh`
parameter for peak detection performed on EICs.
With our data set-specific `peakwidth` we were able to detect the peak for
serine (highlighted in grey in the plot above). We can now use the
`chromPeaks()` function to extract the information on identified chromatographic
peaks from our object.
```{r chromPeaks-chromatogram}
#' Extract identified chromatographic peaks from the EIC
chromPeaks(serine_chr)
```
The result is returned as a `matrix` with each row representing one identified
chromatographic peak. The retention time ranges of the peaks are provided in
columns `"rtmin"` and `"rtmax"`, the integrated peak area (i.e., the *abundance*
of the ion) in column `"into"`, the maximal signal of the peak in column
`"maxo"` and the signal to noise ratio in column`"sn"`. With our adapted
settings we were thus able to identify a chromatographic peak for the serine ion
in each of the two samples.
The second important parameter for *centWave* is `ppm` which is used in the
initial definition of the *regions of interest* (ROI) in which the actual peak
detection is then performed. To define these ROI, the algorithm evaluates for
each mass peak in a spectrum whether a mass peak with a similar *m/z* (and a
reasonably high intensity) is also found in the subsequent spectrum. For this,
only mass peaks with a difference in their *m/z* smaller than `ppm` in
consecutive scans are considered. To illustrate this, we plot again the full
MS data for the data subset containing signal for serine.
```{r Serine-mz-scattering-plot}
#' Restrict to data containing signal from serine
srn <- mse |>
filterRt(rt = c(179, 186)) |>
filterMzRange(mz = c(106.04, 106.07))
#' Plot the data
plot(srn)
```
We can observe some scattering of the data points around an *m/z* of 105.05 in
the lower panel of the above plot. This scattering also decreases with
increasing signal intensity (as for many MS instruments the precision of the
signal increases with the intensity). To quantify the observed differences in
*m/z* values for the signal of serine we restrict the data to a *bona fide*