R/Classes.R

Defines functions setCluster

Documented in setCluster

#Avoids R CMD CHECK notes on data.table package
if(getRversion() >= "2.15.1")  utils::globalVariables(c("."))

#' @title ExpParam
#' @family Params
#' @description ExpParam holds all experimental data as well as database-related
#'  info generated during the processing steps. Use setExpParams to save it into
#'  your RHermesExp object
#' @slot ppm The mass spectrometer (MS) mass error in
#'  parts per million (ppm)
#' @slot res The MS resolution at m/z = 200
#' @slot nthr The noise threshold to consider. Any signal
#'  weaker than it will NOT be considered in the PL. Useful to filter
#'  'grass-like' peaks in a Q-TOF instrument. Defaults to 1000.
#' @slot minmz Minimum mz registered in the MS1 experiment.
#' Defaults to 80
#' @slot maxmz Maximum mz registered in the MS1 experiment.
#' Defaults to 1000.
#' @slot ion Polarity used in the experiment. RHermes currently
#'  only supports  one polarity at a time per RHermesExp, so if you're
#'  performing both + and - polarity you will have to use 2 different
#'  RHermesExp objects, one for each. Important: must be described ONLY as
#'  '+' or '-'.
#' @slot instr MS instrument type used to acquire the data. It can be
#' either QTOF' or 'Orbitrap'.
#' @slot DB Formula database
#' @slot adlist Adduct list
#' @slot ionF Ionic formula list. Formed by all formula-adduct
#'  combinations
#' @slot isoList Isotopic pattern exploration results.
#' @export ExpParam
#' @return A ExpParam object
#' @examples
#'
#'  #Default object
#'  exp <- ExpParam()
#'  #Setting some values - check all possible slots above
#'  exp2 <- ExpParam(ppm = 3, res = 150000, instr = "Orbitrap")
#'
ExpParam <- setClass("ExpParam", slots = list(ppm = "numeric",
    res = "numeric", nthr = "numeric", minmz = "numeric", maxmz = "numeric",
    ion = "character", instr = "character", DB = "list", adlist = "data.frame",
    ionF = "list", isoList = "list"), prototype = list(ppm = 5,
    res = 30000, nthr = 1000, minmz = 80, maxmz = 1200, ion = "+",
    instr = "QTOF", DB = list(), adlist = data.frame(), ionF = list(),
    isoList = list()))

#'@title SOIParam
#'@family Params
#'@description The SOIParam class contains all details regarding SOI detection,
#'  such as the number of RT bins and their width, minimum data point intensity,
#'  usage of blank substraction, etc.
#'@details It's a part of the RHermesSOI object, and is an input for findSOI().
#'  This object is usually generated by getSOIParam(), which features
#'  already-made templates.
#'@slot specs A data frame containing the RT bin information. Each row
#'  represents a binning step that will be applied to the annotated data points
#'  to detect the SOIs.
#'@slot maxlen Maximum SOI length in seconds. If the SOI is longer tha maxlen, a
#'  broad peak picking will divide the long SOI into smaller sized SOIs.
#'@slot minint Minimum data point intensity. If a point is smaller than minint,
#'  it will not be considered in the SOI detection.
#'@slot blanksub Logical. Whether to perform blanksub. It should NOT be entered
#'  by the user in this point, since findSOI will fill in this information.
#'@slot blankname Character. The corresponding blank file name. As before, it
#'  should not be entered by the user, findSOI will fill it automatically.
#'@author Roger Gine
#'@seealso RHermesSOI findSOI getSOIParam
#'@return A SOIParam object
#'@examples SOIParam()
#'@export SOIParam
SOIParam <- setClass("SOIParam",
    slots = list(specs = "data.frame",
                maxlen = "numeric",
                minint = "numeric",
                blanksub = "logical",
                blankname = "character",
                mode = "character",
                cwp = "CentWaveParam"
                ),
    prototype = list(specs = data.frame(),
                maxlen = 30,
                minint = 1000,
                blanksub = FALSE,
                blankname = "None",
                mode = "regular",
                cwp = xcms::CentWaveParam(ppm = 6,
                                    peakwidth = c(8,60), prefilter = c(0,100),
                                    snthresh = 0, noise = 0, fitgauss = FALSE,
                                    firstBaselineCheck = FALSE)
                ))



#'@title RHermesPL
#'@family Containers
#'@description The RHermesPL class contains all the annotation details from a
#'  single MS1 mzML file, as well as some raw information that is useful for
#'  other steps of the workflow. RHermesPL objects are generated by processMS1
#'  and should not be declared manually.
#'@slot peaklist Data.table containing all annotated data points. It stores, rt
#'  values, mz, intensities, ionic formulas and isotope annotations.
#'@slot header Dataframe with headers from the mzML file. Extracted with
#'  mzR::header() and filtered empty scans (if any).
#'@slot raw Dataframe of raw data points from the mzML file. Extracted with
#'  mzR::peaks() and filtered by the noise parameter from ExpParam.
#'@slot labelled Logical. Whether all possible 13C isotopologues were searched
#'  for in the data. Usually FALSE, only TRUE if you're dealing with 13C
#'  labelled data. Should not be set by the user here. Instead, tell processMS1
#'  using labelled = TRUE.
#'@slot filename Filename of the original mzML file.
#'@author Roger Gine
#'@seealso processMS1 ExpParam
#'@export RHermesPL
#'@return An RHermesPL object
#'@examples
#'\dontshow{struct <- readRDS(system.file("extdata", "exampleObject.rds",
#'                              package = "RHermes"))}
#'PL(struct, 1) #Access the object using the getter function.
RHermesPL <- setClass("RHermesPL", slots = list(peaklist = "data.table",
    header = "data.frame", raw = "data.table", labelled = "logical",
    filename = "character"))



#'@title RHermesSOI
#'@family Containers
#'@description The RHermesSOI class contains the SOI list, some precalculated
#'  information for plotting (in functions such as plotSOI)
#'@slot SOIList The SOI list itself.
#'@slot PlotDF A dataframe contaning all SOI data points with annotations, ready
#'  to be plotted when needed.
#'@slot SOIParam A SOIParam object containing all information about SOI generation
#'@slot filename The filename of the mzML used to generate the SOI list.
#'@author Roger Gine
#'@seealso findSOI plotSOI plotIso
#'@export RHermesSOI
#'@return An RHermesSOI object
#'@examples
#'\dontshow{struct <- readRDS(system.file("extdata", "exampleObject.rds",
#'                              package = "RHermes"))}
#'RHermesSOI() #Do NOT generate a SOI object directly, use findSOI
#'SOI(struct, 1) #Access the object using the getter function.
RHermesSOI <- setClass("RHermesSOI", slots = list(SOIList = "data.table",
    PlotDF = "data.table", SOIParam = "SOIParam", filename = "character"))


#'@title ILParam
#'@family Params
#'@description The ILParam class contains all details regarding IL generation,
#'  such as m/z window for grouping close SOIs, whether to prioritize or
#'  restrict the inclusion list to a subset of adducts, etc.
#'@details It's a part of the RHermesIL object and is an input for generateIL().
#'@slot filtermz Deltamz used to group SOIs with similar RTs. Defaults to
#'  +-0.5Da. It should be matched with the m/z isolation window of your MS2
#'  method settings.
#'@slot filterrt Delta RT used to group SOIs with similar RTs. Defaults to 10s.
#'@slot rtmargin Similar to filterrt. Defaults to 5s.
#'@slot priorization Whether to prioritze adducts or not. Options are "only" to
#'  select only a set of adduct annotations, "full" to cover all SOIs
#'  independently of the adduct annotations or "yes" to specify some adducts to
#'  be prioritized in order.
#'@slot ad The specified adducts. See priorization.
#'@author Roger Gine
#'@seealso RHermesIL generateIL
#'@export ILParam
#'@return An ILParam object
#'@examples ILParam()
ILParam <- setClass("ILParam", slots = list(filtermz = "numeric",
    filterrt = "numeric", rtmargin = "numeric", priorization = "character",
    ad = "character"), prototype = list(filtermz = 0.5, filterrt = 10,
    rtmargin = 5, priorization = "only", ad = c("M+H")))


#'@title RHermesIL
#'@family Containers
#'@description The RHermesIL contains an inclusion list (IL) to perform the MS2
#'  experiment with it. It also contains information about whether adduct
#'  annotations have been prioritized over others, restricted, etc.
#'@details Should not be created directly by the user. Instead, use generateIL.
#'@slot IL The inclusion list itself
#'@slot annotation A list of the SOIs corresponding to each IL entry
#'@slot SOInum Which SOI list was used to generate the IL
#'@slot ILParam An ILParam object containing all IL generation parameters
#'@author Roger Gine
#'@seealso generateIL exportIL plotIL filterIL ILParam
#'@export RHermesIL
#'@return An RHermesIL object
#'@examples
#'\dontshow{struct <- readRDS(system.file("extdata", "exampleObject.rds",
#'                              package = "RHermes"))}
#'RHermesIL() #Do NOT generate an IL object directly
#'IL(struct, 1) #Access the object using the getter function.
#'
RHermesIL <- setClass("RHermesIL", slots = list(IL = "data.table",
    annotation = "list", SOInum = "numeric", ILParam = "ILParam"))


#'@title RHermesMS2Exp
#'@family Containers
#'@description The RHermesMS2Exp contains global information about the MS2 steps
#'  of the workflow. Particularly, it contains the inclusion list to be used,
#'  the MS2Data that has been acquired according to the IL and a list of
#'  purified MS2 spectra and identifications against a reference MS2 database
#'  (if performed)
#'@slot IL An RHermesIL object
#'@slot MS2Data A list that contains header and peaks of the MS2 data acquired
#'  for each IL entry. It gets its information after running processMS2.
#'@slot Ident A list of different relevant information about the deconvoluted
#'  MS2 spectra generated by processMS2.
#'@author Roger Gine
#'@seealso processMS2 generateIL IL Ident
#'@export RHermesMS2Exp
#'@return An RHermesMS2Exp object
#' @examples RHermesMS2Exp() #Do not generate the object manually
RHermesMS2Exp <- setClass("RHermesMS2Exp", slots = list(IL = "RHermesIL",
    MS2Data = "list", Ident = "list"))


#' @title setCluster
#' @description Returns the most appropriate BiocParallel backend for RHermes
#'   according to your OS and RAM. It is entirely optional, but recommended
#'   nonetheless.
#' @author Roger Gine
#' @import BiocParallel
#' @examples
#' BiocParallel::register(setCluster()) #Registers the most appropriate backend
#' @return A BiocParallel backend
#' @export
setCluster <- function(){
    if (Sys.info()[1] == "Windows") {
        ram <- system2("wmic", args =  "OS get FreePhysicalMemory /Value",
                        stdout = TRUE)
        ram <- ram[grepl("FreePhysicalMemory", ram)]
        ram <- gsub("FreePhysicalMemory=", "", ram, fixed = TRUE)
        ram <- gsub("\r", "", ram, fixed = TRUE)
        ram <- as.integer(ram)

        #Suppose max 2GB per worker
        nwork <- min(floor(ram/2e6), BiocParallel::snowWorkers())
        if (nwork <= 1) {
            warning(paste("Maybe you have too little available RAM.",
                            "Proceeding with SerialParam()"))
            return(backend <- BiocParallel::SerialParam(progressbar = TRUE))
        }
        return(backend <- BiocParallel::SnowParam(nwork, progressbar = TRUE))
    } else {
        backend <- BiocParallel::MulticoreParam(
            BiocParallel::multicoreWorkers() - 2,
            progressbar = TRUE)
    }
    return(backend)
}

#'@title RHermesMeta
#'@description The metadata storage class. It holds the experimental parameters,
#'  all the names of the processed files and the timestamps for all operations
#'  performed on the parental RHermesExp object
#'@slot ExpParam  Contains all experimental information (ppm error, resolution,
#'  polarity, etc.), as well as the formula and adduct databases used.
#'@slot filenames All filenames of the processed files. This info is also
#'  available for individual PL and SOI objects in their respective slot.
#'@slot timestamps Timestamps generated when any operation was performed on the
#'  parental object. You can easily check them with readTime().
#'@author Roger Gine
#'@seealso ExpParam readTime setTime setCluster Cluster
RHermesMeta <- setClass("RHermesMeta",
    slots = list(
        ExpParam = "ExpParam",
        filenames = "character",
        timestamps = "character"
    ), prototype = list(
        ExpParam = ExpParam(),
        filenames = character(0),
        timestamps = c(paste("System info:",
                    paste(Sys.info(), collapse = "/")),
                    paste("RHermes version:",
                    packageVersion("RHermes")))
    )
)

#'@title RHermesData
#'@author Roger Gine
#'@description The experimental data storage class. Holds all
#'  information of the peaklists, SOI lists, inclusion lists, MS2
#'  data and identifications.
#'@slot PL A list object that holds all RHermesPL objects
#'  containing a PL each.
#'@slot SOI List that holds RHermesSOI objects with a SOI list
#'  inside each.
#'@slot MS2Exp List to hold inclusion lists, MSMS experimental
#'  data and compound identifications.
#'@seealso RHermesPL RHermesSOI
RHermesData <- setClass("RHermesData",
                        slots = list(PL = "list", SOI = "list",
                                        MS2Exp = "list")
)

#' @title RHermesExp
#' @author Roger Gine
#' @description  The main RHermes class: The RHermesExp. It is a container for
#'   all generated information. All main RHermes functions use it and return an
#'   updated version of the object.
#' @slot metadata Where all the complementary info is stored (experimental
#'   parameters, timestamps, databases, etc.). See [RHermes]{RHermesMeta} for
#'   more info.
#' @slot data All experimental info is stored in data. It is divided into PL
#'   (peaklist) SOI (scans of interest) and MS2Exp (for the IL, MS2 data and
#'   identifications). See [RHermes]{RHermesData} for more info.
#' @seealso setDB setExpParam processMS1
#' @return An RHermesExp object
#' @export RHermesExp
#' @examples
#' if(FALSE){
#'  myHermes <- RHermesExp() #Initializing empty object
#' }
RHermesExp <- setClass("RHermesExp",
                        slots = list(metadata = "RHermesMeta",
                                        data = "RHermesData")
)
RogerGinBer/RHermes documentation built on Nov. 6, 2022, 11:34 a.m.