R/AllClasses.R

library(R6)

source('./R/utils.R')

Kegg <- R6Class(
    'Kegg',
    public = list(

        kid    = NULL,
        tax    = NULL,
        org    = NULL,
        genes  = NULL,
        pathways = NULL,
        compounds = NULL,

        print = function(...) {
            cat(
                'Object <Kegg>\n\u26C7 Organism: ',
                self$org,
                '\n\u26D3 KEGG id: ',
                self$kid,
                '\n\u26D3 Tax id: ',
                self$tax,
                '\n\u269B Compounds: ',
                self$compounds |> unique() |> nrow(),
                '\n\u26D5 Pathways: ',
                self$pathways |> unique() |> nrow()
            )
        },

        initialize = function(kid = NA) {
            self$kid <- kid
            private$db_path = private$dbInit()
            self$tax <- private$db(query = 'SELECT taxid FROM org')$taxid
            self$org <- private$db(query = 'SELECT orgname FROM org')$orgname
            self$compounds  <- private$db(query = 'SELECT * FROM cpd')
            self$pathways <- private$db(query = 'SELECT * FROM path')

        }
    ),

    active = list(

    ),

    private = list(

        db_path = NULL,

        dbInit = function() {
            path <- tempfile(pattern = 'kegg', fileext = '.db')
            con <- DBI::dbConnect(RSQLite::SQLite(), path)
            org <- kegg('list', db = 'organism') |>
                dplyr::filter(kid == self$kid)
            DBI::dbWriteTable(con, 'org', org, overwrite = TRUE)
            cpd <- kegg('list', db = 'compound')
            pth <- kegg('list', db = 'pathway', option  = self$kid)
            DBI::dbWriteTable(con, 'cpd', cpd, overwrite = TRUE)
            DBI::dbWriteTable(con, 'path', pth, overwrite = TRUE)
            DBI::dbDisconnect(con)
            return(path)
        },

        db = function(query) {
            con <- DBI::dbConnect(RSQLite::SQLite(), private$db_path)
            req <- DBI::dbSendQuery(con, query)
            res <- DBI::fetch(req)
            DBI::dbClearResult(req)
            DBI::dbDisconnect(con)
            return(res)
        }
    )
)
utubun/keggr documentation built on Jan. 29, 2022, 5:08 a.m.