## ----install_package, eval = FALSE--------------------------------------------
# install.packages("BiocManager")
# BiocManager::install("RmzTabM")


## ----load_package-------------------------------------------------------------
library(RmzTabM)


## ----load_required_package----------------------------------------------------
#| message: FALSE
#' required packages
library(SummarizedExperiment)


## ----load_se------------------------------------------------------------------
#' Load the Metabonaut preprocessing result
data(se)
se


## ----coldata_se, results = "asis"---------------------------------------------
library(pander)
pandoc.table(colData(se) |> as.data.frame(),
             style = "rmarkdown", split.table = Inf)


## ----rowdata_se, results = "asis"---------------------------------------------
pandoc.table(rowData(se) |> as.data.frame() |> head(),
             style = "rmarkdown", split.table = Inf)


## ----assayname_se-------------------------------------------------------------
assayNames(se)


## ----species_and_tissue_se----------------------------------------------------
colData(se)$species
colData(se)$tissue


## ----polarity_se--------------------------------------------------------------
colData(se)$polarity


## ----sampleCols_se------------------------------------------------------------
colData(se)$sample_name
#' define mapping of `colData()` column names to mzTab-M sample fields
scols <- sampleCols(sample = "sample_name", species = "species",
                    tissue = "tissue", sample_type = "sample_type")


## ----msRunCols_assayCols_se---------------------------------------------------
#' Define columns for MS run and assays
mscols <- msRunCols(location = "derived_spectra_data_file",
                    instrument_ref = "instrument", scan_polarity = "polarity")
acols <- assayCols(assay = "derived_spectra_data_file")


## ----derived_spectra_data_file_se---------------------------------------------
colData(se)$derived_spectra_data_file


## ----study_variable_group_se--------------------------------------------------
#' technical variable: the sample matrix
colData(se)$blood_sample_type
#' phenotype of study samples or QC for QC samples
colData(se)$phenotype
#' age of study participants; NA for QC samples
colData(se)$age


## ----mztabm_mtd---------------------------------------------------------------
mzt <- MzTabM(se,
              id = "MTBLS8735",
              sampleCols = scols,
              msRunCols = mscols,
              assayCols = acols,
              groups = c("age", "phenotype", "blood_sample_type"))
mzt


## ----rowdata_se_smf, results = "asis"-----------------------------------------
pandoc.table(rowData(se) |> as.data.frame() |> head(),
            style = "rmarkdown", split.table = Inf)


## ----feature_id_se------------------------------------------------------------
rowData(se)$feature_id <- rownames(se)


## ----smfCols------------------------------------------------------------------
smf_cols <- smfCols(exp_mass_to_charge = "mzmed",
                    retention_time_in_seconds = "rtmed",
                    feature_id = "feature_id")


## ----mztabm_mtd_smf-----------------------------------------------------------
#' Create a MTD+SMF mzTab-M object from the SummarizedExperiment
mzt <- MzTabM(se,
              id = "MTBLS8735",
              sampleCols = scols,
              msRunCols = mscols,
              assayCols = acols,
              groups = c("age", "phenotype", "blood_sample_type"),
              smfCols. = smf_cols,
              assayName = "raw_filled")
mzt


## ----mtd_head, results = "asis"-----------------------------------------------
pandoc.table(mtd(mzt) |> head(),
            style = "rmarkdown", split.table = Inf, justify = "ll")


## ----smf_head, results = "asis"-----------------------------------------------
pandoc.table(smf(mzt) |> head(),
            style = "rmarkdown", split.table = Inf)


## ----getmtdcv-----------------------------------------------------------------
getMtdCv(mzt)


## ----setmtdcv-----------------------------------------------------------------
mzt <- setMtdCv(mzt, label = c("BTO", "NCBITaxon"),
                full_name = c("The BRENDA Tissue Ontology (BTO)",
                              "NCBI organismal classification"),
                version = c("2021-10-26", "2025-12-03"),
                uri = c("https://www.ebi.ac.uk/ols4/ontologies/bto",
                        "https://www.ebi.ac.uk/ols4/ontologies/ncbitaxon"))


## ----setSW--------------------------------------------------------------------
mzt <- setMtdField(mzt, "software", "[MS, MS:1001582, xcms, 4.10.0]")
getMtdField(mzt, "software")


## ----setinstrument------------------------------------------------------------
#' Adding MS instrument information.
mzt <- setMtdInstrument(
    mzt, name = "[MS, MS:1002584, AB Sciex TripleTOF 5600+, ]",
    source = "[MS, MS:1000073, ESI, ]",
    analyzer = c(`analyzer[1]` =
                     "[MS, MS:1003763, quadrupole time-of-flight instrument, ]"),
    detector = "[,,null,null]")


## ----setcontact---------------------------------------------------------------
mzt <- setMtdContact(
    mzt, name = c("Johannes Rainer", "Philippine Louail"),
    affiliation= c("Institute for Biomedicine, Eurac Research, Bolzano, Italy",
                   "Institute for Biomedicine, Eurac Research, Bolzano, Italy"),
    email = c("johannes.rainer@eurac.edu", "philippine.louail@eurac.edu"),
    orcid = c("0000-0002-6977-7147", "0009-0007-5429-6846"))


## ----writemztabm--------------------------------------------------------------
writeMzTabM(mzt, path = file.path(tempdir(), "MTBLS8735_mtd_smf.mzTab"))


## ----readmztabm---------------------------------------------------------------
mzt_r <- readMzTabM(file.path(tempdir(), "MTBLS8735_mtd_smf.mzTab"))
mzt_r


## ----make_se------------------------------------------------------------------
se_r <- makeSummarizedExperimentFromMzTabM(
    mzt_r,
    rowIdCol = "opt_global_feature_id",
    smfCols. = smf_cols,
    assayName = "raw_filled"
)
se_r


## ----experiment, results = "asis"---------------------------------------------
#' Define a simple data.frame of the measured samples of an experiment
exp <- data.frame(
    sample_name = c("S1_T1", "S1_T2", "S2_T1", "S2_T2", "S3_T1", "S3_T2"),
    sample_id = c("S1", "S1", "S2", "S2", "S3", "S3"),
    timepoint = c("0h", "6h", "0h", "6h", "0h", "6h"),
    genotype = c("WT", "WT", "KO", "KO", "KO", "KO"),
    operator = c("BB", "BB", "BB", "BB", "FB", "FB"),
    file_name = c("s1-t1.mzML", "s1-t2.mzML", "s2-t1.mzML", "s2-t2.mzML",
                  "s3-t1.mzML", "s3-t2.mzML")
)

pandoc.table(exp, style = "rmarkdown", split.table = Inf)


## ----mtdskeleton--------------------------------------------------------------
mtd <- mtdSkeleton(
    id = "EXP_001",
    software = "[MS, MS:1001582, xcms, 4.1.0]"
)


## ----mtd_base_show, results = "asis"------------------------------------------
pandoc.table(mtd, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_add_title_description------------------------------------------------
mtd <- rbind(
    mtd,
    c("title", "Experiment 1 preprocessed data"),
    c("description", "The preprocessed data of the experiment 1.")
)


## ----mtd_build_instrument-----------------------------------------------------
instr <- mtdFields(
    name = "[MS, MS:1000449, LTQ Orbitrap,]",
    source = "[MS, MS:1000073, ESI,]",
    `analyzer[1]` = "[MS, MS:1000291, linear ion trap,]",
    detector = "[MS, MS:1000253, electron multiplier,]",
    field_prefix = "instrument"
)


## ----mtd_show_instrument, results = "asis"------------------------------------
pandoc.table(instr, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_add_instrument-------------------------------------------------------
mtd <- rbind(mtd, instr)


## ----mtd_build_sample---------------------------------------------------------
mtd_s <- mtdSample(
    sample = unique(exp$sample_id),
    species = "[NCBITaxon, NCBITaxon:9606, Homo sapiens, ]",
    tissue = "[BTO, BTO:0000759, liver, ]",
    cell_type = "[CL, CL:0000182, hepatocyte, ]",
    c("[,,Extraction date, 2011-12-21]",
      "[,,Extraction date, 2011-12-22]",
      "[,,Extraction date, 2011-12-23]")
    )


## ----mtd_show_sample, results = "asis"----------------------------------------
pandoc.table(mtd_s, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_build_cv, results = "asis"-------------------------------------------
add_cv <- mtdFields(
    label = c("BTO", "NCBITaxon"),
    full_name = c("The BRENDA Tissue Ontology (BTO)",
                  "NCBI organismal classification"),
    version = c("2021-10-26", "2025-12-03"),
    uri = c("https://www.ebi.ac.uk/ols4/ontologies/bto",
            "https://www.ebi.ac.uk/ols4/ontologies/ncbitaxon"),
    field_prefix = "cv")

pandoc.table(add_cv, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_add_cv---------------------------------------------------------------
add_cv[, 1L] <- sub("1", "4", add_cv[, 1L])
add_cv[, 1L] <- sub("2", "5", add_cv[, 1L])
mtd <- rbind(mtd, add_cv)


## ----mtd_add_sample-----------------------------------------------------------
mtd <- rbind(mtd, mtd_s)


## ----mtd_build_msrun----------------------------------------------------------
mtd_msr <- mtdMsRun(
    location = exp$file_name,
    format = "[MS, MS:1000584, mzML file, ]",
    id_format = "[MS, MS:1000530, mzML unique identifier, ]",
    scan_polarity = "positive")


## ----mtd_show_msrun, results = "asis"-----------------------------------------
pandoc.table(mtd_msr, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_add_msrun------------------------------------------------------------
mtd <- rbind(mtd, mtd_msr)


## ----mtd_build_assay----------------------------------------------------------
mtd_a <- mtdAssay(
    assay = exp$sample_name,
    sample_ref = c("sample[1]", "sample[1]", "sample[2]", "sample[2]",
                   "sample[3]", "sample[3]"),
    ms_run_ref = paste0("ms_run[", seq_len(nrow(exp)), "]")
)


## ----mtd_show_assay, results = "asis"-----------------------------------------
pandoc.table(mtd_a, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_add_assay------------------------------------------------------------
mtd <- rbind(mtd, mtd_a)


## ----mtd_build_studyVar-------------------------------------------------------
mtd_svar <- mtdStudyVariables(
    exp, groups = c("timepoint", "genotype", "operator"),
    group_unit = c("[, , hours, ]", "", ""))


## ----mtd_show_studyVar, results = "asis"--------------------------------------
pandoc.table(mtd_svar, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----mtd_add_studyVar---------------------------------------------------------
mtd <- rbind(mtd, mtd_svar)


## ----mtdsort------------------------------------------------------------------
mtd <- mtdSort(mtd)


## ----mtd_final_show, results = "asis"-----------------------------------------
pandoc.table(mtd, style = "rmarkdown", split.table = Inf, justify = "ll")


## ----abundances---------------------------------------------------------------
abundances <- cbind(c(200.1, 1232.1, 54.3, 399.1, 599.8, 23.1, NA),
                    c(260.2, 39.5, 177.4, 599.5, 5344.1, 332.1, 43.0),
                    c(256.1, 904.2, 56.9, 533.1, 489.9, 3231.22, 23.4),
                    c(232.1, 43.3, 201.4, 434.2, 5154.1, 43.4, 324.3),
                    c(264.2, 1102.4, 43.5, 514.5, 583.1, 432.3, 43.3),
                    c(246.2, 52.1, 187.2, 508.3, 601.5, 432.2, 34.5))
colnames(abundances) <- exp$sample_name
rownames(abundances) <- c("FT01", "FT02", "FT03", "FT04", "FT05",
                          "FT06", "FT07")


## ----feature_info-------------------------------------------------------------
feature_info <- data.frame(
    mzmed = c(195.088, 127.1, 299.2, 181.07, 218.077, 343.123, 148.06),
    rtmed = c(25.6, 128.4, 67.2, 127.3, 25.7, 167.2, 76.34),
    rtmin = c(23.1, 125.1, 65.1, 122.3, 23.3, 162.3, 71.3),
    rtmax = c(26.9, 130.3, 69.1, 134.2, 26.8, 172.1, 81.2),
    adduct = c("[M+H]+", NA, NA, "[M+Na]+", "[M+Na]+", "[M+H]+", "[M+H]+"),
    charge = c(1L, NA, NA, 1L, 1L, 1L, 1L)
)
rownames(feature_info) <- rownames(abundances)


## ----smfCreate----------------------------------------------------------------
smf <- smfCreate(
    x = abundances,
    exp_mass_to_charge = feature_info$mzmed,
    retention_time_in_seconds = feature_info$rtmed,
    retention_time_in_seconds_start = feature_info$rtmin,
    retention_time_in_seconds_end = feature_info$rtmax,
    charge = feature_info$charge,
    adduct_ion = feature_info$adduct,
    feature_id = rownames(feature_info))


## ----smf_show, results = "asis"-----------------------------------------------
pandoc.table(smf, style = "rmarkdown", split.table = Inf)


## ----annotation---------------------------------------------------------------
anns <- data.frame(
    id = c("HMDB:HMDB0001847",
           "HMDB:HMDB0000122|HMDB:HMDB0000169",
           "HMDB:HMDB0000258",
           "HMDB:HMDB0060475"),
    formula = c("C8H10N4O2",
                "C6H12O6|C6H12O6",
                "C12H22O11",
                "C5H9NO4"),
    neutral_mass = c(194.0804,
                     "180.0634|180.0634",
                     342.1162,
                     147.0531),
    name = c("caffeine",
             "glucose|mannose",
             "sucrose",
             "DL-glutamate"),
    adduct = c("[M+H]1+",
               "[M+Na]1+",
               "[M+H]1+",
               "[M+H]1+"),
    uri = c("http://www.hmdb.ca/metabolites/HMDB0001847",
            "http://www.hmdb.ca/metabolites/HMDB0000122|http://www.hmdb.ca/metabolites/HMDB0000169",
            "http://www.hmdb.ca/metabolites/HMDB0000258",
            "http://www.hmdb.ca/metabolites/HMDB0060475"),
    note = c("manual curation")
)


## ----sml_filter---------------------------------------------------------------
abundances_sml <- abundances[c(1, 4, 6, 7), ]


## ----smlCreate, results = "asis"----------------------------------------------
sml <- smlCreate(x = abundances_sml,
                 database_identifier = anns$id,
                 chemical_formula = anns$formula,
                 theoretical_neutral_mass = anns$neutral_mass,
                 adduct_ions = anns$adduct,
                 uri = anns$uri,
                 note = anns$note)
pandoc.table(sml, style = "rmarkdown", split.table = Inf)


## ----smf_id_refs--------------------------------------------------------------
sml$SMF_ID_REFS = c("1|5", "4", "6", "7")


## ----sml_add_study_var, results = "asis"--------------------------------------
sml <- smlAddStudyVariableColumns(sml, mtd)
pandoc.table(sml, style = "rmarkdown", split.table = Inf)


## ----sme_df-------------------------------------------------------------------
ev_df <- data.frame(
    evidence_input_id = c("ms_run[1]:mass=700.5255;rt=20·5",
                          "ms_run[2]:mass=452.2782;rt=35.1",
                          "ms_run[3]:mass=882.6210;rt=40.0"),
    exp_mass_to_charge = c(700.5255, 452.2782, 882.6210),
    charge = c(1, 1, 1),
    theoretical_mass_to_charge = c(700.5281, 452.2777, 882.6224),
    spectra_ref = c("ms_run[1]:index=7646", "ms_run[2]:index=7640",
                    "ms_run[3]:index=7671|ms_run[3]:index=7725"),
    identification_method = "[, , LipidDataAnalyzer, 2.11.1]",
    ms_level = "[MS, MS:1000511, ms level, 2]")


## ----smeCreate----------------------------------------------------------------
sme <- smeCreate(
    evidence_input_id = ev_df$evidence_input_id,
    exp_mass_to_charge = ev_df$exp_mass_to_charge,
    charge = ev_df$charge,
    theoretical_mass_to_charge = ev_df$theoretical_mass_to_charge,
    spectra_ref = ev_df$spectra_ref,
    identification_method = ev_df$identification_method,
    ms_level = ev_df$ms_level,
    mtd = mtd
)
pandoc.table(sme, style = "rmarkdown", split.table = Inf)


## ----sessionInfo--------------------------------------------------------------
sessionInfo()

