--- title: "Safely Store `MsExperiment` Objects in a Portable Stash" output: BiocStyle::html_document: toc_float: true vignette: > %\VignetteIndexEntry{Safely Store MsExperiment Objects in a Portable Stash} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} %\VignettePackage{MsExperimentStash} %\VignetteDepends{MsExperiment,Spectra,SpectraStash,BiocStyle,alabaster.base,fs,SummarizedExperiment} --- ```{r style, echo = FALSE, message = FALSE} knitr::opts_chunk$set(echo = TRUE, message = FALSE) library(BiocStyle) ``` # Introduction Data objects in R can be serialized to disk in R's *rds* or *RData* format using the base R `save()` function and re-imported using the `load()` function. This R-specific binary data format can however not be used easily in other programming languages preventing the exchange of R data objects between software. The `r Biocpkg("MsStash")` package defines basic classes and generic methods to export and import mass spectrometry (MS) data objects in various storage formats aiming to facilitate data exchange between software. The *MsExperimentStash* package implements portable data storage formats (stashes) for data classes from the `r Biocpkg("MsExperiment")` package, including the `MsExperiment` object. Supported stash formats are, next to storage in simple plain text files, also Bioconductor's *alabaster* format defined in the `r Biocpkg("alabaster.base")` and related packages. # Installation The package can be installed with the *BiocManager* package. To install *BiocManager* use `install.packages("BiocManager")` and, after that, install *MsExperimentStash* including all dependencies with: ```{r install, eval = FALSE} BiocManager::install("MsExperimentStash") ``` # A stash for `MsExperiment` objects MS data objects can be saved and restored through the `saveMsObject()` and `readMsObject()` functions to (or from) MS data stashes. Supported stash formats and their respective parameter objects are: - `AlabasterParam`: storage of MS data using Bioconductor's `r Biocpkg("alabaster.base")` framework using files in HDF5 and JSON format. MS stashes in this format also fully support the `saveObject()` and `readObject()` functions from *alabaster.base*. - `PlainTextParam`: storage of data in (a custom) plain text file format. Note that this format currently does not support all data structures potentially present in an `MsExperiment` and hence the alabaster format is preferred. For examples on this format see the `?MsExperiment` documentation. See also the vignette from the `r Biocpkg("MsStash")` for details on the formats and implementation notes. As an example we create below a `MsExperiment` object with MS data two example MS data files from the *MsDataHub* package. ```{r example-data, message = FALSE} library(MsExperiment) library(MsExperimentStash) library(MsDataHub) #' Define the MS data files (provided by MsDataHub) fls <- c(X20171016_POOL_POS_1_105.134.mzML(), X20171016_POOL_POS_3_105.134.mzML()) #' Define a data.frame providing information on samples d <- data.frame(name = c("QC 1", "QC 2"), sample_type = c("QC POOL", "QC POOL"), injection_index = c(1, 8)) #' Read the data as an MsExperiment object mse <- readMsExperiment(fls, sampleData = d) mse ``` We next create a `SummarizedExperiment` and add that to the `MsExperiment` object. In a real-world use case this would contain quantitative feature abundances after e.g. preprocessing the data with the `r Biocpkg("xcms")` package. For our example we fill the `SummarizedExperiment` with random abundance values. ```{r example-se} #' Define a SummarizedExperiment with quantification data library(SummarizedExperiment) se <- SummarizedExperiment( list(raw = matrix(rnorm(8), ncol = 2)), rowData = data.frame(feature_id = c("F01", "F02", "F03", "F04"), mzmed = c(127.2, 232.1, 321.2, 134.5), rtmed = c(38.5, 127.3, 219.8, 64.3)), colData = d) rownames(se) <- c("F01", "F02", "F03", "F04") colnames(se) <- c("QC_1", "QC_2") #' Add the SummarizedExperiment to the MsExperiment qdata(mse) <- se mse ``` We next store this `MsExperiment` object to a *MsExperimentStash* using the `saveMsObject()` function. We use an alabaster format and define the location of the stash with the `path` parameter of `AlabasterParam`. For the present example we save it to a temporary folder. ```{r save-alabaster} #' Define the location of the stash d <- file.path(tempfile(), "mse_stash") #' Configure the format and location ap <- AlabasterParam(d) #' Save the `MsExperiment` object to the stash saveMsObject(mse, ap) ``` The content of the stash folder is: ```{r stash-content} library(fs) dir_tree(d) ``` In alabaster format, each slot of the `MsExperiment` object is stored into its own sub directory. The `Spectra` object representing the experiment's MS data is stored for example (as a *SpectraStash*) into a sub-folder *spectra*. In general, users will not interact directly with the files in this stash, but will restore the stashed `MsExperiment` from such a *MsExperimentStash* using the `readMsObject()` function: ```{r alabaster-read} #' Load the `MsExperiment` from the stash res <- readMsObject(MsExperiment(), ap) res ``` For `readMsObject()` we need to specify the type of the object to restore from the stash with the first parameter of the function - in our case `MsExperiment()`. *MsExperimentStash* provides full support for *alabaster*-based serialization formats to `MsExperiment` objects and we can therefore also use the `readObject()` from the `r Biocpkg("alabaster.base")` package to restore the object. ```{r pure-alabaster-read} library(alabaster.base) res <- readObject(d) res ``` Due to the modular structure of the *MsExperimentStash* we can load also only a single component of the `MsExperiment`. We can for example restore the `Spectra` object from the *spectra* sub-folder: ```{r alabaster-read-spectra} #' Read the `Spectra` object with the MS data from the stash library(Spectra) sps <- readMsObject(Spectra(), AlabasterParam(file.path(d, "spectra"))) sps ``` Or only the `SummarizedExperiment` from the *qdata* sub-folder (using *alabaster.base* functions): ```{r alabaster-read-qdata} #' Read the `SummarizedExperiment` from the stash readObject(file.path(d, "qdata")) ``` ## Creating self-contained stashes The MS data from our example `MsExperiment` is represented by a `Spectra` object using an `MsBackendMzR` backend. ```{r show-spectra} spectra(mse) ``` This type of backend keeps only the spectra metadata in memory while the mass peaks data (*m/z* and intensity values) are retrieved on demand from the original MS data files. By default, when saved to a stash, only the metadata and the **reference** to the original MS data tiles are serialized to disk. If the MS data files are moved to another folder, or if the MsExperimentStash is moved to another computer, the data can not be fully restored (unless the path to the new location of the MS data files is provided with parameter `spectraPath` in the `readMsObject()` call). The stash functionality for most `Spectra` backend implementation supports however a parameter `consolidate` which, if set to `TRUE` will copy **all** data **into** the stash hence generating a self-contained and portable MsExperimentStash: ```{r alabaster-save-consolidate} #' Save the `MsExperiment` to a stash which includes the full data d <- file.path(tempdir(), "portable_stash") saveMsObject(mse, AlabasterParam(d), consolidate = TRUE) ``` The SpectraStash within the MsExperimentStash contains now also the original MS data files (which have in this case random names without the expected *mzML* file ending, because the data was provided through the *MsDataHub* package): ```{r alabaster-content-consolidate} #' Directory content of the spectra subfolder dir_tree(file.path(d, "spectra", "backend")) ``` While being self-contained, the size of such a stash might become very large, depending on the number and the size of the original MS data files. Alternatively, we could also change the backend of the `Spectra` within the `MsExperiment` to an *in-memory* backend and create a stash from that object. ```{r alabaster-save-in-mem, warning = FALSE} #' Change the Spectra backend to MsBackendMemory: load all MS data #' into memory spectra(mse) <- setBackend(spectra(mse), MsBackendMemory()) #' Save the MsExperiment to a stash d <- file.path(tempdir(), "memory_stash") saveMsObject(mse, AlabasterParam(d)) ``` The full MS data is now stored in a *peaks.h5* file (in HDF5 file format) within the stash. ```{r alabaster-content-in-mem} dir_tree(file.path(d, "spectra", "backend")) ``` Again, because the full MS data is included in the stash, the size of the folder might be large. # Retrieve MS experiments from MetaboLights *MetaboLights* is one of the main repositories to deposit metabolomics data sets and experiments. With `readMsObject()` and a `MetaboLightsParam` it is possible to retrieve and load the data set from a MetaboLights study directly as an `MsExperiment` object from the repository into R. Sample and protocol/metadata information is loaded into the object's `sampleData()` while the MS data files are downloaded and locally cached through the `r Biocpkg("MsBackendMetaboLights")` package. This data is available through the object's `spectra()` data. Below, we demonstrate how to load the dataset with the ID: *MTBLS575*. We also use the `assayName` parameter to specify which assay we want to load, and the `filePattern` parameter to indicate which assay files to load. Defining the assay name is required for studies that have more than one *assay* (e.g., data measured in positive and negative polarity modes or using different chromatographic setups). The `filePattern` on the other hand allows to restrict downloading only selected files; for our example we load only data files with a file ending *cdf*. It is recommended to adjust these settings according to your specific study. ```{r read-metabolights} library(MsExperiment) #' Prepare parameter param <- MetaboLightsParam( mtblsId = "MTBLS575", assayName = paste0("a_MTBLS575_POS_INFEST_CTRL_mass_spectrometry.txt"), filePattern = "cdf$") #' Load MsExperiment object mse <- readMsObject(MsExperiment(), param) ``` Next, we examine the `sampleData()` of our `mse` object: ```{r sampledata} sampleData(mse) ``` A large number of columns were loaded. Several parameters are available in the `readMsObject()` function to simplify and restrict the content loaded into the `sampleData`. Setting `keepOntology = FALSE` will for example remove columns related to ontology terms, while `keepProtocol = FALSE` will remove columns related to protocol information. The `simplify = TRUE` option (the default) removes columns containing only missing values (`NA`) and merges columns with different names but duplicate contents. Set to `simplify = FALSE` to retain all columns. Below, we load the object again, this time simplifying the `sampleData`: ```{r read-metabolights-less} mse <- readMsObject(MsExperiment(), param, keepOntology = FALSE, keepProtocol = FALSE, simplify = TRUE) ``` Note that the MS data files were loaded from the local cache and not downloaded again. Now, if we examine the `sampleData` information: ```{r sampledata-less} sampleData(mse) ``` We can see that it is much simpler. # Retrieve MS experiments from Metabolomics Workbench *Metabolomics Workbench* is another major repository for metabolomics studies and experimental data. With `readMsObject()` and a `MwbParam` it is possible to retrieve a study from Metabolomics Workbench and load it directly into R as an `MsExperiment` object. The study's sample information and metadata are loaded into the object's `sampleData()`, while the MS data files are downloaded and locally cached through the `r Biocpkg("MsBackendMetabolomicsWorkbench")` package. The MS data is then available through the object's `spectra()`. Below, we demonstrate how to load the study with the ID *ST002115*. We use the `analysisId` parameter to specify which analysis we want to load, and the `filePattern` parameter to indicate which of the study's raw data files should be loaded. Defining the analysis is required for studies that contain more than one *analysis*. If `analysisId` is not provided and the study contains several analyses, the user is prompted to choose one interactively. The `filePattern` allows to load only MS data file from the repository with their file names matching the provided pattern. ```{r read-mwb} library(MsExperiment) #' Prepare parameter param <- MwbParam(mwbId = "ST002115", analysisId = "AN003514", filePattern = "01_HILIC.mzXML") #' Load MsExperiment object mse <- readMsObject(MsExperiment(), param) mse ``` Next, we examine the `sampleData()` of our `mse` object: ```{r mwb-sampledata} sampleData(mse) ``` The `sampleData()` combines the information on the selected analysis with the sample factors defined for the study. Columns that contain only missing values (`NA`) or empty strings are automatically removed. The samples are linked to the MS data by matching the `raw_data` column in the metadata, that should contain the file names, with the names of the downloaded files. Since the file names in the metadata are not always complete or consistent with the actual file names, it can happen that no match is found. In that case a warning is issued and the sample data is not linked to the spectra. The next section explains how to manually link spectra (respectively raw MS data files) to samples. The MS data of the experiment was downloaded and cached locally and is available through `spectra()`: ```{r mwb-spectra} spectra(mse) ``` ## Manual linkage between metadata and spectra files If the automatic link fails, the sample data and the MS data can be linked manually. In this case, the `sampleData()` still contains the complete metadata of the selected analysis, but it lacks a `file_name` column and is not linked to the `spectra()`. To perform the linkage, we need to carry out three steps: 1. Filter the `sampleData()`, keeping only the rows corresponding to our files. 2. Add a column (e.g. `file_name`) to the metadata table with the correct file names. 3. Call `linkSampleData()` to define the link between `sampleData` and `spectra`. To show how this works, we use the same study, but instead of downloading the *HILIC* samples, we download the *reversed-phase* samples. The names of these files have the suffix `"_RP"`, which is missing from the metadata column `raw_data`. ```{r mwb-manual-link} #' Prepare parameter param <- MwbParam(mwbId = "ST002115", analysisId = "AN003513", filePattern = "01_RP.mzXML") #' Load MsExperiment object mse_to_link <- readMsObject(MsExperiment(), param) mse_to_link #' Correct file name unique(spectraData(spectra(mse_to_link))$file_name) #' File name in `raw_data` column sd <- sampleData(mse_to_link) sd$raw_data #' Correct matching index between file name and metadata idx <- c("HT1080_DMSO_01_RP.mzXML" = 1, "HT1080_ML162_01_RP.mzXML" = 4, "HT1080_ML210_01_RP.mzXML" = 7, "HT1080_RSL3_01_RP.mzXML" = 10) #' Subset the sample data sd <- sd[idx, ] #' Add the file names sd$file_name <- names(idx) #' Update `sampleData()` sampleData(mse_to_link) <- sd #' Link to the spectra mse_linked <- linkSampleData(mse_to_link, with = "sampleData.file_name = spectra.file_name") mse_linked ``` # License This vignette is distributed under a [CC BY-SA license](https://creativecommons.org/licenses/by-sa/4.0/). # Session information ```{r session-info} sessionInfo() ```