## ----setup, include = FALSE---------------------------------------------------
knitr::opts_knit$set(
    root.dir = dirname(getwd())
)

knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>")

## ----init, message = FALSE, echo = FALSE, results = "hide"--------------------
library(BiocStyle)
library(faahKO)
library(MsExperiment)
library(lcmsPlot)

## ----install, eval=FALSE------------------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE))
#     install.packages("BiocManager")
# BiocManager::install("lcmsPlot")

## ----load-data, message=FALSE-------------------------------------------------
library(faahKO)
library(MsExperiment)
library(patchwork)
library(lcmsPlot)

BiocParallel::register(BiocParallel::SerialParam())

sample_indices <- c(1, 2, 5, 6, 7, 8, 11, 12)
cdfs <- dir(
    system.file("cdf", package = "faahKO"),
    full.names = TRUE,
    recursive = TRUE)[sample_indices]

sample_names <- sub(
    basename(cdfs),
    pattern = ".CDF",
    replacement = "",
    fixed = TRUE)

pd <- data.frame(
    sample_name = sample_names,
    sample_group = c(rep("KO", 4), rep("WT", 4)),
    stringsAsFactors = FALSE)

faahko <- readMsExperiment(spectraFiles = cdfs, sampleData = pd)
faahko

## ----lcmsPlot-object----------------------------------------------------------
p = lcmsPlot(faahko, sample_id_column = "sample_name")
print(p)

## ----bpc, fig.height=6, fig.width=10------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(aggregation_fun = "max") +
    lp_facets(facets = "sample_name", ncol = 4)

## ----bpc-overlapped-----------------------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(aggregation_fun = "max") +
    lp_arrange(group_by = "sample_group") +
    lp_labels(title = "Base peak chromatograms", legend = "Sample group") +
    lp_legend(position = "bottom")

## ----tic, fig.height=6, fig.width=10------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(aggregation_fun = "sum") +
    lp_facets(facets = "sample_name", ncol = 4)

## ----total-ion-current--------------------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_total_ion_current(type = "violin") +
    lp_arrange(group_by = "sample_group") +
    lp_labels(title = "Total ion current", legend = "Sample group")

## ----intensity-maps-----------------------------------------------------------
pparam <- BiocParallel::MulticoreParam(workers = 2)
lcmsPlot(faahko, sample_id_column = "sample_name", BPPARAM = pparam) +
    lp_intensity_map(
        sample_ids = c("ko15", "wt15"),
        mz_range = c(200, 600),
        rt_range = c(4200, 4500),
        density = TRUE) +
    lp_facets(facets = "sample_id", ncol = 2)

## ----peak-detection-----------------------------------------------------------
cwp <- xcms::CentWaveParam(
    peakwidth = c(20, 80),
    noise = 5000,
    prefilter = c(6, 5000))
faahko <- xcms::findChromPeaks(faahko, param = cwp)

## ----plot-xics----------------------------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(features = rbind(c(
        mzmin = 334.9,
        mzmax = 335.1,
        rtmin = 2700,
        rtmax = 2900))) +
    lp_arrange(group_by = "sample_group") +
    lp_labels(legend = "Sample group")

## ----plot-xic-faceted, fig.height=4, fig.width=8------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(
        features = rbind(c(
            mzmin = 334.9,
            mzmax = 335.1,
            rtmin = 2700,
            rtmax = 2900)),
        highlight_peaks = TRUE,
        highlight_peaks_color = "#121212",
        highlight_apices = list(top_n = 1)
    ) +
    lp_facets(facets = c('feature_id', 'sample_id'), ncol = 4) +
    lp_labels(legend = "Sample") +
    lp_legend(position = "bottom")

## ----plot-xic-highlight-peaks, fig.height=4, fig.width=8----------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = rbind(
            c(mzmin = 334.9, mzmax = 335.1, rtmin = 2700, rtmax = 2900),
            c(mzmin = 278.99721, mzmax = 279.00279, rtmin = 2740, rtmax = 2840)
        ),
        highlight_peaks = TRUE,
        highlight_peaks_color = '#f00') +
    lp_grid(rows = 'feature_id', cols = 'sample_id', free_y = TRUE)

## ----plot-xic-rt-line, fig.height=4, fig.width=8------------------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(features = rbind(c(
        mzmin = 334.9,
        mzmax = 335.1,
        rtmin = 2700,
        rtmax = 2900))) +
    lp_facets(facets = 'sample_id', ncol = 4) +
    lp_rt_line(intercept = 2800, line_type = 'solid', color = 'red') +
    lp_rt_line(intercept = 2750, line_type = 'dashed', color = 'blue') +
    lp_rt_line(intercept = 2850, line_type = 'dashed', color = 'blue')

## ----plot-XChromatograms, message=FALSE, warning=FALSE, fig.height=4, fig.width=10----
mzr <- matrix(c(344, 344, 360, 360), ncol = 2, byrow = TRUE)

rtr <- matrix(c(2500, 2880, 2600, 2880), ncol = 2, byrow = TRUE)

chrs <- chromatogram(faahko, mz = mzr, rt = rtr)

lcmsPlot(chrs) +
    lp_chromatogram(na.rm = TRUE) +
    lp_grid(rows = "feature_id", cols = "sample_id")

## ----plot-xcmsRaw-------------------------------------------------------------
raw_paths <- sampleData(faahko)$spectraOrigin[c(1, 5)]

xl <- create_xcms_raw_list(raw_paths)

lcmsPlot(xl) +
    lp_chromatogram(
        features = rbind(
            c(mzmin = 334.9, mzmax = 335.1, rtmin = 2700, rtmax = 2900),
            c(mzmin = 344.0, mzmax = 344.1, rtmin = 2600, rtmax = 2800)
        )
    ) +
    lp_grid(rows = "feature_id", cols = "sample_id", free_y = TRUE)

## ----rt-alignment, message=FALSE, warning=FALSE-------------------------------
faahko <- xcms::adjustRtime(faahko, param = xcms::ObiwarpParam(binSize = 0.6))

## ----plot-bpc-comparison------------------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(
        ppm = 5,
        rt_tol = 10,
        aggregation_fun = "max",
        rt_type = "both") +
    lp_arrange(group_by = "sample_group") +
    lp_facets("rt_type", ncol = 1) +
    lp_labels(legend = "Sample group") +
    lp_legend(position = "bottom")

## ----plot-rt-alignment-effect-------------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_rt_diff_plot() +
    lp_arrange(group_by = "sample_group") +
    lp_labels(legend = "Sample group")

## ----peak-grouping------------------------------------------------------------
pdp <- xcms::PeakDensityParam(
    sampleGroups = sampleData(faahko)$sample_group,
    minFraction = 0.4,
    bw = 30)
faahko <- xcms::groupChromPeaks(faahko, param = pdp)

## ----plot-features------------------------------------------------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = c('M205T2792', 'M207T2719', 'M279T2791', 'M284T2719'),
        ppm = 10,
        rt_tol = 80,
        highlight_peaks = TRUE,
        highlight_peaks_factor = "sample_group") +
    lp_arrange(group_by = 'sample_group') +
    lp_facets(facets = 'feature_id', ncol = 2, free_x = TRUE, free_y = TRUE) +
    lp_labels(title = "Four selected features", legend = "Sample") +
    lp_legend(position = "bottom")

## ----peak-density-------------------------------------------------------------
lcmsPlot(faahko, sample_id_column = "sample_name") +
    lp_chromatogram(
        sample_ids = c("ko15", "ko16", "wt16", "wt21"),
        features = rbind(c(mzmin = 334.9, mzmax = 335.1, rtmin = 2700, rtmax = 2900)),
        highlight_peaks = TRUE
    ) +
    lp_peak_density(
        bw = 30,
        min_fraction = 0.5
    ) +
    lp_labels(legend = "Sample ID")

## ----plot-chroms-with-mass-traces---------------------------------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = 'M205T2792',
        sample_ids = c('ko15', 'ko16', 'wt15', 'wt16'),
        ppm = 10,
        rt_tol = 50,
        highlight_peaks = TRUE) +
    lp_mass_trace() +
    lp_arrange(group_by = 'sample_id') +
    lp_labels(title = "Feature M205T2792", legend = "Sample") +
    lp_legend(position = "bottom")

## ----plot-chroms-with-mass-traces-faceted-------------------------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = c('M283T3890', 'M205T2792'),
        sample_ids = c('ko15', 'ko16', 'wt15', 'wt16'),
        ppm = 10,
        rt_tol = 50,
        highlight_peaks = TRUE) +
    lp_mass_trace() +
    lp_arrange(group_by = "sample_id") +
    lp_facets(facets = 'feature_id', ncol = 2) +
    lp_labels(legend = "Sample") +
    lp_legend(position = "bottom")

## ----plot-chroms-with-mass-traces-faceted-factors, fig.height=12, fig.width=6----
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = c('M283T3890', 'M205T2792'),
        sample_ids = c('ko15', 'ko16', 'wt15', 'wt16'),
        ppm = 10,
        rt_tol = 50,
        highlight_peaks = TRUE,
        highlight_peaks_color = '#343434') +
    lp_mass_trace() +
    lp_facets(facets = c('feature_id', 'sample_id'))

## ----plot-chroms-raw-files----------------------------------------------------
raw_files <- sampleData(faahko)$spectraOrigin[1:4]

lcmsPlot(raw_files) +
    lp_chromatogram(features = rbind(c(
        mzmin = 334.9,
        mzmax = 335.1,
        rtmin = 2700,
        rtmax = 2900))) +
    lp_arrange(group_by = "sample_id") +
    lp_legend(position = "bottom") +
    lp_labels(legend = "Sample")

## ----plot-chroms-raw-files-with-metadata--------------------------------------
raw_files <- sampleData(faahko)$spectraOrigin[c(1, 2, 5, 6)]

metadata <- data.frame(
    sample_type = c("KO", "KO", "WT", "WT"),
    sample_id = c("S1", "S2", "S3", "S4")
)

lcmsPlot(raw_files, sample_id_column = "sample_id", metadata = metadata) +
    lp_chromatogram(
        features = rbind(
            c(mzmin = 334.9, mzmax = 335.1, rtmin = 2700, rtmax = 2900),
            c(mzmin = 278.99721, mzmax = 279.00279, rtmin = 2740, rtmax = 2840)
        )
    ) +
    lp_grid(rows = 'feature_id', cols = 'sample_type', free_y = TRUE)

## ----plot-raw, eval=FALSE-----------------------------------------------------
# raw_files <- c("sample1.raw", "sample2.raw", "sample3.raw")
# 
# lcmsPlot(raw_files) +
#     lp_chromatogram(aggregation_fun = "max") +
#     lp_arrange(group_by = "sample_id")

## ----plot-raw-spectra, eval=FALSE, fig.height=9, fig.width=5------------------
# raw_files <- c("sample1.raw", "sample2.raw", "sample3.raw")
# 
# lcmsPlot(raw_files) +
#     lp_chromatogram(features = rbind(c(mz = 181.0706641)), ppm = 10) +
#     lp_spectra(rt = 120, mode = "closest") +
#     lp_facets(facets = "sample_id", ncol = 1)

## ----plot-spectra-scan-closest-rt, fig.height=4, fig.width=9------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = 'M283T3890',
        sample_ids = 'ko15',
        ppm = 5,
        rt_tol = 50,
        highlight_peaks = TRUE) +
    lp_spectra(rt = 3860, mode = "closest", ms_level = 1) +
    lp_labels(title = "Feature M283T3890", legend = "Sample") +
    lp_legend(position = "bottom")

## ----plot-spectra-scan-closest-apex, fig.height=5, fig.width=10, fig.small=FALSE----
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = rbind(
            c(mzmin = 362.0982, mzmax = 362.1018, rtmin = 3130, rtmax = 3200),
            c(mzmin = 357.1946, mzmax = 357.2054, rtmin = 3800, rtmax = 3900)
        ),
        sample_ids = 'ko15',
        highlight_peaks = TRUE) +
    lp_spectra(mode = "closest_apex", ms_level = 1) +
    lp_facets(facets = "feature_id", ncol = 2) +
    lp_labels(legend = "Sample") +
    lp_legend(position = "bottom") +
    lp_layout(design = "C\nS\nS")

## ----plot-spectra-across-peak, fig.height=10, fig.width=6---------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_chromatogram(
        features = "M205T2792",
        sample_ids = 'ko15',
        ppm = 5,
        rt_tol = 50,
        highlight_peaks = TRUE) +
    lp_spectra(mode = "across_peak", interval = 10, ms_level = 1) +
    lp_labels(legend = "Sample") +
    lp_legend(position = "bottom") +
    lp_layout(design = "C\nS\nS\nS\nS\nS\nS\nS")

## ----plot-standalone-spectra--------------------------------------------------
lcmsPlot(faahko, sample_id_column = 'sample_name') +
    lp_spectra(
        sample_ids = c('ko15', 'wt15'),
        rt = 2740,
        mode = "closest",
        ms_level = 1) +
    lp_legend(position = "bottom")

## ----plot-compound-discoverer-results, eval=FALSE-----------------------------
# lcmsPlot("example_cd.cdResult") +
#     lp_compound_discoverer(
#         compounds_query = 'name %in% c("Proline", "Betaine")',
#         rt_extend = 5
#     ) +
#     lp_chromatogram(highlight_peaks = TRUE) +
#     lp_grid(rows = "sample_id", cols = "name", free_x = TRUE) +
#     lp_labels(title = "Compound Discoverer example", legend = "Sample") +
#     lp_legend(position = "bottom")

## ----plot-mzmine-results, eval=FALSE------------------------------------------
# mzmine_dataset_example <- MZmineFeatureListsSource(
#     feature_lists_paths = c(
#         "path/to/feature_list_1.csv",
#         "path/to/feature_list_2.csv"
#     ),
#     sample_paths = c(
#         "path/to/sample_path_1.mzML",
#         "path/to/sample_path_2.mzML"
#     ),
#     metadata_path = "path/to/metadata.csv"
# )
# 
# lcmsPlot(mzmine_dataset_example, sample_id_column = 'filename') +
#     lp_chromatogram(
#         features = rbind(c(mz = 222.09864, rt = 213.636)),
#         sample_ids = c("sample_1", "sample_2"),
#         rt_tol = 50,
#         ppm = 10,
#         highlight_peaks = TRUE,
#         highlight_peaks_color = "#894545") +
#     lp_facets(facets = "sample_id") +
#     lp_labels(title = "MZmine example", legend = "Sample") +
#     lp_legend(position = "bottom")

## ----plot-ms-dial-results, eval=FALSE-----------------------------------------
# msdial_dataset_example <- MsDialPeaksSource(
#     peaks_paths = c(
#         "path/to/peaks_1.csv",
#         "path/to/peaks_2.csv"
#     ),
#     sample_paths = c(
#         "path/to/sample_path_1.mzML",
#         "path/to/sample_path_2.mzML"
#     ),
#     metadata_path = "path/to/metadata.csv"
# )
# 
# lcmsPlot(msdial_dataset_example, sample_id_column = 'filename') +
#     lp_chromatogram(
#         features = rbind(c(mz = 222.09864, rt = 213.636)),
#         sample_ids = c("sample_1", "sample_2"),
#         rt_tol = 50,
#         ppm = 10,
#         highlight_peaks = TRUE,
#         highlight_peaks_color = "#894545") +
#     lp_facets(facets = "sample_id") +
#     lp_labels(title = "MS-DIAL example", legend = "Sample") +
#     lp_legend(position = "bottom")

## ----session-info-------------------------------------------------------------
sessionInfo()

