content
stringlengths
0
14.9M
filename
stringlengths
44
136
rpc_typeof <- function(x) UseMethod("rpc_typeof", x) rpc_typeof.logical <- function(x) "boolean" rpc_typeof.integer <- function(x) "i4" rpc_typeof.double <- function(x) "double" rpc_typeof.character <- function(x) "string" rpc_typeof.raw <- function(x) "base64" rpc_typeof.POSIXt <- function(x) "dateTime.iso8601" rpc_typeof.POSIXct <- function(x) "dateTime.iso8601" rpc_typeof.Date <- function(x) "dateTime.iso8601" to_rpc <- function(x) UseMethod("to_rpc", x) to_rpc.default <- identity to_rpc.Date <- function(x) format(x, "%Y%m%dT%H:%H:%S") to_rpc.POSIXt <- function(x) format(as.POSIXct(x), "%Y%m%dT%H:%H:%S") # ----------------------------------------------------------- # rpc_serialize # ============= #' Convert \R Objects into the \code{XML-RPC} Format #' @description Serialize \R Objects so they can be passed to #' \code{to_xmlrpc} as parameters. #' @param x an \R object. #' @param ... additional optional arguments (currently ignored). #' @return an object of class \code{"xml_node"}. #' @examples #' rpc_serialize(1L) #' rpc_serialize(1:2) #' rpc_serialize(LETTERS[1:2]) #' @export rpc_serialize <- function(x, ...) UseMethod("rpc_serialize", x) #' @noRd #' @export rpc_serialize.NULL <- function(x, ...) { node <- new_xml_node("array") xml_add_child(node, "data") node } #' @noRd #' @export rpc_serialize.raw <- function(x, ...) { node <- new_xml_node("value") ## xml_add_child(node, "base64", RCurl::base64Encode(x)) xml_add_child(node, "base64", base64encode(x)) node } rpc_serialize_vector <- function(x, ...) { type <- rpc_typeof(x) x <- unname(x) if ( length(x) == 1 ) { to_value(x, type) } else { vec_to_array(x, type) } } #' @noRd #' @export rpc_serialize.logical <- function(x, ...) rpc_serialize_vector(as.integer(x)) #' @noRd #' @export rpc_serialize.integer <- rpc_serialize_vector #' @noRd #' @export rpc_serialize.numeric <- rpc_serialize_vector #' @noRd #' @export rpc_serialize.character <- rpc_serialize_vector #' @noRd #' @export rpc_serialize.Date <- rpc_serialize_vector #' @noRd #' @export rpc_serialize.POSIXt <- rpc_serialize_vector #' @noRd #' @export rpc_serialize.list <- function(x, ...) { list_to_array(unname(x)) } to_value <- function(x, type, cdata = FALSE) { value <- new_xml_node("value") if (cdata) { xml_add_child(value, type) ty <- xml_children(value)[[1L]] xml_add_child(ty, xml_cdata(x)) } else { xml_add_child(value, type, to_rpc(x)) } value } new_xml_node <- function(key, value = NULL) { root <- read_xml("<root></root>") if ( is.null(value) ) { xml_add_child(root, key) } else { xml_add_child(root, key, value) } xml_children(root)[[1L]] } new_xml_array <- function() { read_xml("<root><value><array><data></data></array></value></root>") } vec_to_array <- function(x, type) { root <- new_xml_array() value <- xml_children(root)[[1L]] data <- xml_children(xml_children(value)[[1L]])[[1L]] for ( i in seq_along(x) ) { xml_add_child(data, to_value(x[i], type, type == "string")) } value } ## Only supports non nested lists list_to_array <- function(x) { if ( any(lengths(x) > 1) ) stop("nested lists are not supported!") root <- new_xml_array() value <- xml_children(root)[[1L]] data <- xml_children(xml_children(value)[[1L]])[[1L]] for ( i in seq_along(x) ) { type <- rpc_typeof(x[i]) xml_add_child(data, to_value(x[i], type, type == "string")) } value } # ----------------------------------------------------------- # from_xmlrpc # =========== #' Convert from the \code{XML-RPC} Format into an \R Object. #' @description Convert an object of class \code{"xml_code"} or #' a character in the \code{XML-RPC} Format into an \R Object. #' @param xml a character string containing \code{XML} in the #' remote procedure call protocol format. #' @param raise_error a logical controling the behavior if the #' \code{XML-RPC} signals a fault. If \code{TRUE} #' an error is raised, if \code{FALSE} an #' object inheriting from \code{"c("xmlrpc_error", "error")"} #' is returned. #' @return an R object derived from the input. #' @examples #' params <- list(1L, 1:3, rnorm(3), LETTERS[1:3], charToRaw("A")) #' xml <- to_xmlrpc("some_method", params) #' from_xmlrpc(xml) #' @export from_xmlrpc <- function(xml, raise_error = TRUE) { stopifnot( inherits(xml, c("xml_node", "character")) ) if ( inherits(xml, "character") ) xml <- read_xml(xml) fault <- xml_children(xml_find_all(xml, "//methodResponse/fault")) if ( length(fault) ) { ans <- unlist(lapply(fault, from_rpc)) if (raise_error) { stop(paste(paste(names(ans), ans, sep = ": "), collapse = "\n")) } else { return(structure(ans, class = c("xmlrpc_error", "error"))) } } values <- xml_children(xml_find_all(xml, "//param/value")) ans <- lapply(values, from_rpc) if ( length(ans) == 1L ) { ans[[1L]] } else { ans } } from_rpc <- function(x) { if ( is.null(x) ) return(NULL) if ( xml_name(x) == "value" ) ## do I really need this? x <- xml_children(x)[[1L]] type <- xml_name(x) switch(type, 'array' = from_rpc_array(x), 'struct' = from_rpc_struct(x), 'i4' = as.integer(xml_text(x)), 'int' = as.integer(xml_text(x)), 'boolean' = if(xml_text(x) == "1") TRUE else FALSE, 'double' = as.numeric(xml_text(x)), 'string' = xml_text(x), 'dateTime.iso8601' = as.POSIXct(strptime(xml_text(x), "%Y%m%dT%H:%M:%S")), 'base64' = base64decode(xml_text(x)), xml_text(x) ) } ## from_rpc_struct <- function(x) { ## keys <- xml_text(xml_find_all(x, "//name")) ## get_values <- function(rec) { ## xml_children(rec)[xml_name(xml_children(rec)) == "value"] ## } ## values <- lapply(xml_children(x), function(rec) from_rpc(get_values(rec))) ## names(values) <- keys ## list(names = keys, values = values) ## } from_rpc_struct <- function(x) { keys <- xml_text(xml_find_all(x, ".//name")) values <- lapply(xml_find_all(x, ".//value"), from_rpc) names(values) <- keys values } from_rpc_array <- function(x) { values <- lapply(xml_children(xml_children(x)[[1L]]), from_rpc) if ( all_same_type(values) ) { unlist(values, FALSE, FALSE) } else { values } values } all_same_type <- function(x) { isTRUE(length(unique(sapply(x, typeof))) == 1L) }
/scratch/gouwar.j/cran-all/cranData/xmlrpc2/R/serialize.R
#' @import base64enc #' @import xml2 #' @import curl # ----------------------------------------------------------- # xmlrpc # ======= #' @title Call the Remote Procedure #' @description Call a reomte procedure with the \code{XML-RPC} protocol. #' @param url a character string giving the url to the server. #' @param method a character string giving the name of the method #' to be invoked. #' @param params a list containing the parmeters which are added to #' the \code{XML} file sent via the remote procedure call. #' @param handle a object of class \code{"curl_handle"}. #' @param opts a list of options passed to the function \code{"handle_setopt"}. #' @param convert a logical, if convert is \code{TRUE} (default) #' the \code{curl} response is converted else it is #' left unchanged. #' @param useragent a character string giving the name of the \code{"User-Agent"}. #' @param raise_error a logical controling the behavior if the status code #' of \code{curl_fetch_memory} signals an error. #' If \code{raise_error} is \code{TRUE} an error is raised, #' if \code{raise_error} is \code{FALSE} #' no error is raised and an object inheriting from #' \code{c("fetch_error", error")} is returned. #' This object is the return value from \code{curl_fetch_memory} #' where just the class \code{c("fetch_error", error")} #' is added. #' @return the reponse of \code{curl} or the response converted to #' \R objects. #' @examples #' \dontrun{ #' url <- "https://www.neos-server.org" #' xmlrpc(url, "listAllSolvers") #' xmlrpc(url, "listSolversInCategory", params = list(category = "socp")) #' } #' @export xmlrpc <- function(url, method, params = list(), handle = NULL, opts = list(), convert = TRUE, useragent = "xmlrpc", raise_error = TRUE) { stopifnot(is.character(url), is.character(method), all(nchar(names(opts)) > 0), is.logical(convert)) body <- to_xmlrpc(method, params) if ( is.null(handle) ) { handle <- new_handle() handle_setopt(handle, port = 3333) } else { stopifnot(inherits(handle, "curl_handle")) } handle_setopt(handle, customrequest = "POST") handle_setopt(handle, followlocation = TRUE) handle_setopt(handle, postfields = as.character(body)) handle_setheaders(handle, "Content-Type" = "text/xml", "User-Agent" = useragent) if ( length(opts) ) { handle_setopt(handle, .list = opts) } response <- curl_fetch_memory(url, handle) if ( !is_successful_request(response$status_code) ) { if (raise_error) { stop(request_error_msg(response$content)) } else { class(response) <- c("fetch_error", "error", class(response)) return(response) } } if ( isTRUE(convert) ) { from_xmlrpc( rawToChar(response$content), raise_error = raise_error ) } else { response } } ## NOTE: ## See https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html ## for more information about status codes. is_successful_request <- function(x) { if ( !is.numeric(x) ) return(FALSE) (x >= 200) & (x < 300) } request_error_msg <- function(x) { tryCatch(xml_text(read_html(rawToChar(x))), error = function(e) "The request was not successful!") } # ----------------------------------------------------------- # to_xmlrpc # ========= #' @title Create a \code{XML-RPC} Call #' @description abc #' @param method a character string giving the name of the method #' to be invoked. #' @param params a list containing the parmeters which are added to #' the \code{XML} file sent via the remote procedure call. #' @return an object of class \code{"xml_node"} containing a \code{XML-RPC} call. #' @examples #' params <- list(1L, 1:3, rnorm(3), LETTERS[1:3], charToRaw("A")) #' cat(as.character(to_xmlrpc("some_method", params))) #' @export to_xmlrpc <- function(method, params) { root <- read_xml("<methodCall></methodCall>") xml_add_child(root, "methodName", method) xml_add_child(root, "params") parameters <- xml_children(root)[[2L]] for (i in seq_along(params)) { xml_add_child(parameters, "param") parameter <- xml_children(parameters)[[i]] xml_add_child(parameter, rpc_serialize(params[[i]])) } root }
/scratch/gouwar.j/cran-all/cranData/xmlrpc2/R/xmlrpc2.R
# SPDX-License-Identifier: MIT #' Coerce to docinfo objects #' #' `as_docinfo()` coerces objects into a [docinfo()] object. #' #' @param x An object that can reasonably be coerced to a [docinfo()] object. #' @param ... Further arguments passed to or from other methods. #' @return A [docinfo()] object. #' @examples #' x <- xmp(`dc:Creator` = "John Doe", `dc:Title` = "A Title") #' as_docinfo(x) #' #' @export as_docinfo <- function(x, ...) { UseMethod("as_docinfo") } #' @export as_docinfo.docinfo <- function(x, ...) { x } #' @export as_docinfo.default <- function(x, ...) { l <- as.list(x) d <- docinfo() for (key in names(l)) d$set_item(key, l[[key]]) d } #' @rdname as_docinfo #' @export as_docinfo.xmp <- function(x, ...) { d <- docinfo() d$title <- x$title[["x-default"]] d$author <- stri_join(x$creator, collapse = " and ") d$subject <- x$description[["x-default"]] d$producer <- x$producer d$keywords <- x$keywords d$creation_date <- x$create_date d$creator <- x$creator_tool d$mod_date <- x$modify_date d }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/as_docinfo.R
# SPDX-License-Identifier: MIT #' Coerce to XMP "language alternative" structure #' #' `as_lang_alt()` coerces to an XMP "language alternative" structure #' suitable for use with [xmp()] objects. #' #' @param x Object suitable for coercing #' @param ... Ignored #' @param default_lang Language tag value to copy as the "x-default" #' @seealso [xmp()], [as_xmp()], [get_xmp()], and [set_xmp()]. #' For more information about the XMP "language alternative" structure see #' <https://github.com/adobe/xmp-docs/blob/master/XMPNamespaces/XMPDataTypes/CoreProperties.md#language-alternative>. #' @return A named list of class "lang_alt". #' @name as_lang_alt #' @examples #' as_lang_alt("A single title") #' as_lang_alt(c(en = "An English Title", fr = "A French Title")) #' as_lang_alt(c(en = "An English Title", fr = "A French Title"), default_lang = "en") #' as_lang_alt(list(en = "An English Title", fr = "A French Title")) NULL #' @rdname as_lang_alt #' @export as_lang_alt <- function(x, ...) { UseMethod("as_lang_alt") } #' @rdname as_lang_alt #' @export as_lang_alt.character <- function(x, ..., default_lang = getOption("xmpdf_default_lang")) { if (is.null(names(x))) { stopifnot(length(x) == 1L) as_lang_alt.list(list(`x-default` = x)) } else { as_lang_alt.list(as.list(x), default_lang = default_lang) } } #' @rdname as_lang_alt #' @export as_lang_alt.lang_alt <- function(x, ...) { x } #' @rdname as_lang_alt #' @export as_lang_alt.list <- function(x, ..., default_lang = getOption("xmpdf_default_lang")) { if (is.null(names(x))) { stopifnot(length(x) == 1L) as_lang_alt.list(list(`x-default` = x[[1]])) } else { stopifnot(all(sapply(x, is.character)), sum(names(x) %in% c("", "x-default")) <= 1) names(x) <- ifelse(names(x) == "", "x-default", names(x)) if (!is.null(default_lang) && default_lang %in% names(x) && !("x-default" %in% names(x))) { x <- c(list(`x-default` = x[[default_lang]]), x) } if ("x-default" %in% names(x) && names(x)[1] != "x-default") { i <- which(names(x) == "x-default") x <- c(x[i], x[-i]) } class(x) <- "lang_alt" x } }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/as_lang_alt.R
# SPDX-License-Identifier: MIT #' Coerce to xmp objects #' #' `as_xmp()` coerces objects into an [xmp()] object. #' #' @param x An object that can reasonably be coerced to a [xmp()] object. #' @param ... Further arguments passed to or from other methods. #' @return An [xmp()] object. #' @examples #' di <- docinfo(author = "John Doe", title = "A Title") #' as_xmp(di) #' #' l <- list(`dc:creator` = "John Doe", `dc:title` = "A Title") #' as_xmp(l) #' @export as_xmp <- function(x, ...) { UseMethod("as_xmp") } #' @export as_xmp.default <- function(x, ...) { as_xmp(as.list(x)) } #' @rdname as_xmp #' @export as_xmp.docinfo <- function(x, ...) { x$xmp() } #' @rdname as_xmp #' @export as_xmp.list <- function(x, ...) { xmp <- xmp() for (key in names(x)) xmp$set_item(key, x[[key]]) xmp } #' @export as_xmp.xmp <- function(x, ...) { x }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/as_xmp.R
# SPDX-License-Identifier: MIT #' Set/get pdf bookmarks #' #' `get_bookmarks()` gets pdf bookmarks from a file. #' `set_bookmarks()` sets pdf bookmarks for a file. #' #' `get_bookmarks()` will try to use the following helper functions in the following order: #' #' 1. `get_bookmarks_pdftk()` which wraps `pdftk` command-line tool #' 2. `get_bookmarks_pdftools()` which wraps [pdftools::pdf_toc()] #' #' `set_bookmarks()` will try to use the following helper functions in the following order: #' #' 1. `set_bookmarks_gs()` which wraps `ghostscript` command-line tool #' 2. `set_bookmarks_pdftk()` which wraps `pdftk` command-line tool #' #' @param filename Filename(s) (pdf) to extract bookmarks from. #' @param use_names If `TRUE` (default) use `filename` as the names of the result. #' @param bookmarks A data frame with bookmark information with the following columns:\describe{ #' \item{title}{Title for bookmark (mandatory, character)} #' \item{page}{Page number for bookmark (mandatory, integer)} #' \item{level}{Level of bookmark e.g. 1 top level, 2 second level, etc. (optional, integer). #' If missing will be inferred from `count` column else will be assumed to be `1L`.} #' \item{count}{Number of bookmarks immediately subordinate (optional, integer). #' Excludes subordinates of subordinates. #' Positive count indicates bookmark should start open while #' negative count indicates that this bookmark should start closed. #' If missing will be inferred from `level` column #' and (if specified) the `open` column else will be assumed to be `0L`. #' Note some pdf viewers quietly ignore the initially open/closed feature.} #' \item{open}{Whether the bookmark starts open or closed if it has #' subordinate bookmarks (optional, logical). #' If missing will default to open. #' Ignored if the `count` column is specified (instead use a negative count #' if the bookmark should start closed). #' Note some pdf viewers quietly ignore the initially open/closed feature.} #' \item{fontface}{Font face of the bookmark (optional, integer). #' If `NA_character_` or `NA_integer_` will be unset (defaults to "plain"). #' "plain" or 1 is plain, "bold" or 2 is bold, "italic" or 3 is italic, #" "bold.italic" or 4 is bold and italic. #' Note many pdf viewers quietly ignore this feature.} #' \item{color}{Color of the bookmark (optional, character). #' If `NA_character_` will be unset (presumably defaults to "black"). #' Note many pdf viewers quietly ignore this feature.} #' } #' @param input Input pdf filename. #' @param output Output pdf filename. #' @return `get_bookmarks()` returns a list of data frames with bookmark info (see `bookmarks` parameter for details about columns) plus "total_pages", "filename", and "title" attributes. #' `NA` values in the data frame indicates that the backend doesn't report information about this pdf feature. #' `set_bookmarks()` returns the (output) filename invisibly. #' @section Known limitations: #' #' * `get_bookmarks_pdftk()` doesn't report information about bookmarks color, fontface, and whether the bookmarks #' should start open or closed. #' * `get_bookmarks_pdftools()` doesn't report information about bookmarks page number, #' color, fontface, and whether the bookmarks should start open or closed. #' * `set_bookmarks_gs()` supports most bookmarks features including color and font face but #' only action supported is to view a particular page. #' * `set_bookmarks_pdftk()` only supports setting the title, page number, and level of bookmarks. #' #' @seealso [supports_get_bookmarks()], [supports_set_bookmarks()], [supports_gs()], and [supports_pdftk()] to detect support for these features. For more info about the pdf bookmarks feature see <https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#bookmarks-out>. #' @examples #' # Create 2-page pdf using `pdf)` and add some bookmarks to it #' if (supports_set_bookmarks() && supports_get_bookmarks() && require("grid", quietly = TRUE)) { #' f <- tempfile(fileext = ".pdf") #' pdf(f, onefile = TRUE) #' grid.text("Page 1") #' grid.newpage() #' grid.text("Page 2") #' invisible(dev.off()) #' #' print(get_bookmarks(f)[[1]]) #' \dontshow{cat("\n")} #' #' bookmarks <- data.frame(title = c("Page 1", "Page 2"), page = c(1, 2)) #' #' set_bookmarks(bookmarks, f) #' print(get_bookmarks(f)[[1]]) #' unlink(f) #' } #' @name bookmarks NULL #' @rdname bookmarks #' @export get_bookmarks <- function(filename, use_names = TRUE) { if (supports_pdftk()) { get_bookmarks_pdftk(filename, use_names = use_names) } else if (supports_pdftools()) { get_bookmarks_pdftools(filename, use_names = use_names) } else { abort(msg_get_bookmarks(), class = "xmpdf_suggested_package") } } #' @rdname bookmarks #' @export get_bookmarks_pdftk <- function(filename, use_names = TRUE) { l <- lapply(filename, get_bookmarks_pdftk_helper) use_filenames(l, use_names, filename) } #' @rdname bookmarks #' @export get_bookmarks_pdftools <- function(filename, use_names = TRUE) { l <- lapply(filename, get_bookmarks_pdftools_helper) use_filenames(l, use_names, filename) } #' Concatenate pdf bookmarks #' #' `cat_bookmarks()` concatenates a list of bookmarks #' into a single bookmarks data frame while updating the page numbers. #' Useful if wanting to concatenate multiple pdf files together and #' would like to preserve the bookmarks information. #' @param l A list of bookmark data frames as returned by [get_bookmarks()]. #' Each data frame should have a "total_pages" attribute. #' If `method = "filename"` each data frame should have a "filename" attribute. #' If `method = "title"` each data frame should have a "title" attribute. #' @param method If "flat" simply concatenate the bookmarks while updating page numbers. #' If "filename" place each file's bookmarks a level under a new bookmark matching #' the (base)name of the filename and then concatenate the bookmarks while updating page numbers. #' If "title" place each file's bookmarks a level under a new bookmark matching #' the title of the file and then concatenate the bookmarks while updating page numbers. #' @param open If `method = "filename"` or `method = "title"` a logical for whether the new top level bookmarks should start open? #' If missing will default to open. #' Note some pdf viewers quietly ignore the initially open/closed feature. #' @param color If `method = "filename"` or `method = "title"` the color of the new top level bookmarks. #' If `NA_character_` will be unset (presumably defaults to "black"). #' Note many pdf viewers quietly ignore this feature. #' @param fontface If `method = "filename"` or `method = "title"` should the fontface of the new top level bookmarks. #' If `NA_character_` or `NA_integer_` will be unset (defaults to "plain"). #' "plain" or 1 is plain, "bold" or 2 is bold, "italic" or 3 is italic, #" "bold.italic" or 4 is bold and italic. #' Note many pdf viewers quietly ignore this feature. #' @return A data frame of bookmark data (as suitable for use with [set_bookmarks()]). #' A "total_pages" attribute will be set for the theoretical total pages of #' the concatenated document represented by the concatenated bookmarks. #' @examples #' if (supports_get_bookmarks() && #' supports_set_bookmarks() && #' supports_pdftk() && #' require("grid", quietly = TRUE)) { #' # Create two different two-page pdf files #' make_pdf <- function(f, title) { #' pdf(f, onefile = TRUE, title = title) #' grid.text(paste(title, "Page 1")) #' grid.newpage() #' grid.text(paste(title, "Page 2")) #' invisible(dev.off()) #' } #' f1 <- tempfile(fileext = "_doc1.pdf") #' on.exit(unlink(f1)) #' make_pdf(f1, "Document 1") #' #' f2 <- tempfile(fileext = "_doc2.pdf") #' on.exit(unlink(f2)) #' make_pdf(f2, "Document 2") #' #' # Add bookmarks to the two two-page pdf files #' bookmarks <- data.frame(title = c("Page 1", "Page 2"), #' page = c(1L, 2L)) #' set_bookmarks(bookmarks, f1) #' set_bookmarks(bookmarks, f2) #' l <- get_bookmarks(c(f1, f2)) #' print(l) #' #' bm <- cat_bookmarks(l, method = "flat") #' cat('\nmethod = "flat":\n') #' print(bm) #' #' bm <- cat_bookmarks(l, method = "filename") #' cat('\nmethod = "filename":\n') #' print(bm) #' #' bm <- cat_bookmarks(l, method = "title") #' cat('\nmethod = "title":\n') #' print(bm) #' #' # `cat_bookmarks()` is useful for setting concatenated pdf files #' # created with `cat_pages()` #' if (supports_cat_pages()) { #' fc <- tempfile(fileext = "_cat.pdf") #' on.exit(unlink(fc)) #' cat_pages(c(f1, f2), fc) #' set_bookmarks(bm, fc) #' unlink(fc) #' } #' #' unlink(f1) #' unlink(f2) #' } #' @seealso [get_bookmarks()] and [set_bookmarks()] for setting bookmarks. #' [cat_pages()] for concatenating pdf files together. #' @export cat_bookmarks <- function(l, method = c("flat", "filename", "title"), open = NA, color = NA_character_, fontface = NA_character_) { stopifnot(length(l) > 0L) method <- match.arg(method, c("flat", "filename", "title")) l <- lapply(l, as_bookmarks) v_total_pages <- vapply(l, function(x) attr(x, "total_pages"), integer(1L), USE.NAMES = FALSE) cum_pages <- cumsum(v_total_pages) n_docs <- length(l) if (method == "filename") { titles <- vapply(l, function(x) basename(attr(x, "filename")), character(1L), USE.NAMES = FALSE) } else if (method == "title") { titles <- vapply(l, function(x) attr(x, "title") %||% "Untitled", character(1L), USE.NAMES = FALSE) } if (method %in% c("filename", "title")) { if (hasName(l[[1]], "level")) l[[1]]$level <- l[[1]]$level + 1L l[[1]] <- rbind(data.frame(title = basename(titles[1L]), page = 1L, level = 1L, count = NA_integer_, open = open, color = color, fontface = fontface, stringsAsFactors = FALSE), l[[1]]) } if (n_docs == 1L) { return(l[[1L]]) } for (i in seq.int(2L, n_docs)) { if (hasName(l[[i]], "page")) l[[i]]$page <- l[[i]]$page + cum_pages[i - 1L] if (method %in% c("filename", "title")) { if (hasName(l[[i]], "level")) l[[i]]$level <- l[[i]]$level + 1L l[[i]] <- rbind(data.frame(title = basename(titles[i]), page = cum_pages[i - 1L] + 1L, level = 1L, count = NA_integer_, open = open, color = color, fontface = fontface, stringsAsFactors = FALSE), l[[i]]) } } df <- do.call(function(...) rbind(..., make.row.names = FALSE), l) df$count <- get_count(df$level, df$open) attr(df, "total_pages") <- sum(v_total_pages) df } df_bookmarks_empty <- data.frame(title = character(0), page = integer(0), level = integer(0), count = integer(0), open = logical(0), color = character(), fontface = integer(0), stringsAsFactors = FALSE) get_bookmarks_pdftk_helper <- function(filename) { meta <- get_pdftk_metadata(filename) n_bookmarks <- length(grep("^BookmarkBegin", meta)) stopifnot(length(grep("^BookmarkTitle", meta)) == n_bookmarks, length(grep("^BookmarkLevel", meta)) == n_bookmarks, length(grep("^BookmarkPageNumber", meta)) == n_bookmarks) df <- if (n_bookmarks > 0) { title <- gsub("^BookmarkTitle: ", "", grep("^BookmarkTitle", meta, value = TRUE)) level <- gsub("^BookmarkLevel: ", "", grep("^BookmarkLevel", meta, value = TRUE)) page <- gsub("^BookmarkPageNumber: ", "", grep("^BookmarkPageNumber", meta, value = TRUE)) data.frame(title = title, page = as.integer(page), level = as.integer(level), count = NA_integer_, open = NA, color = NA_character_, fontface = NA_character_, stringsAsFactors = FALSE) } else { df_bookmarks_empty } tot_pages <- grep("^NumberOfPages:", meta, value=TRUE) if (length(id <- grep("^InfoKey: Title", meta))) title <- gsub("^InfoValue: ", "", meta[id + 1]) else title <- NULL attr(df, "filename") <- filename attr(df, "title") <- title attr(df, "total_pages") <- as.integer(strsplit(tot_pages, ":")[[1]][2]) df } gbph_helper <- function(l, level = 0L) { if (level == 0L) { df <- data.frame(title = character(0), level = integer(0)) } else { df <- data.frame(title = l$title, level = level) } if (length(l[["children"]]) > 0L) { df_children <- do.call(rbind, lapply(l[["children"]], gbph_helper, level = level + 1L)) df <- rbind(df, df_children) } df } get_bookmarks_pdftools_helper <- function(filename) { toc <- pdftools::pdf_toc(filename) df <- if (length(toc) > 0L) { df <- gbph_helper(toc) data.frame(title = df$title, page = NA, level = as.integer(df$level), count = NA_integer_, open = NA, color = NA_character_, fontface = NA_character_, stringsAsFactors = FALSE) } else { df_bookmarks_empty } info <- pdftools::pdf_info(filename) if (!is.null(info$keys) && !is.null(info$keys$Title)) title <- info$keys$Title else title <- NULL attr(df, "filename") <- filename attr(df, "title") <- title attr(df, "total_pages") <- as.integer(info$pages) df } #' @rdname bookmarks #' @export set_bookmarks <- function(bookmarks, input, output = input) { if (supports_gs()) { set_bookmarks_gs(bookmarks, input, output) } else if (supports_pdftk()) { set_bookmarks_pdftk(bookmarks, input, output) } else { abort(msg_set_bookmarks(), class = "xmpdf_suggested_package") } } should_pdftk_message <- function(bookmarks) { any(bookmarks$count < 0) || any(!is.na(bookmarks$color)) || any(!is.na(bookmarks$fontface)) } #' @rdname bookmarks #' @export set_bookmarks_pdftk <- function(bookmarks, input, output = input) { bookmarks <- as_bookmarks(bookmarks) if (should_pdftk_message(bookmarks)) { msg <- c("!" = paste(sQuote("set_bookmarks_pdftk()"), "will ignore certain requested bookmarks features:")) if (any(bookmarks$count < 0)) msg <- c(msg, "*" = paste(sQuote("set_bookmarks_pdftk()"), "treats negative", sQuote("count"), "values as positive ones.")) if (any(!is.na(bookmarks$color))) msg <- c(msg, "*" = paste(sQuote("set_bookmarks_pdftk()"), "ignores non-missing", sQuote("color"), "values.")) if (any(!is.na(bookmarks$fontface))) msg <- c(msg, "*" = paste(sQuote("set_bookmarks_pdftk()"), "ignores non-missing", sQuote("fontface"), "values.")) msg <- c(msg, "i" = paste(sQuote("set_bookmarks_gs()"), "can handle these features"), "i" = paste("You can suppress these messages with", sQuote('suppressMessages(expr, classes = "xmpdf_inform")'))) inform(msg, class = "xmpdf_inform") } cmd <- pdftk() meta <- get_pdftk_metadata(input) input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) if (input == output) { target <- tempfile(fileext = ".pdf") on.exit(unlink(target)) } else { target <- output } id_info <- grep("^Bookmark", meta) if (length(id_info)) meta <- meta[-id_info] bookmarks_pdftk <- unlist(purrr::pmap(bookmarks, bookmark_pdftk)) meta <- append(bookmarks_pdftk, meta) metafile <- tempfile(fileext = ".txt") metafile <- normalizePath(metafile, mustWork = FALSE) on.exit(unlink(metafile)) f <- file(metafile, encoding = "UTF-8") open(f, "w") brio::write_lines(meta, metafile) close(f) args <- c(shQuote(input), "update_info_utf8", shQuote(metafile), "output", shQuote(target)) xmpdf_system2(cmd, args) if (input == output) file.copy(target, output, overwrite = TRUE) invisible(output) } #' @rdname bookmarks #' @export set_bookmarks_gs <- function(bookmarks, input, output = input) { bookmarks <- as_bookmarks(bookmarks) cmd <- gs() input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) if (input == output) { target <- tempfile(fileext = ".pdf") on.exit(unlink(target)) } else { target <- output } metafile <- tempfile(fileext = ".bin") metafile <- normalizePath(metafile, mustWork = FALSE) on.exit(unlink(metafile)) if (any(is.na(iconv(bookmarks$title, to = "latin1")))) { # Has non-Latin-1 characters bookmarks_raw <- unlist(purrr::pmap(bookmarks, bookmark_gs_raw)) writeBin(bookmarks_raw, metafile, endian = "big") } else { # Latin-1 bookmarks_gs <- unlist(purrr::pmap(bookmarks, bookmark_gs)) f <- file(metafile, encoding = "latin1") open(f, "w") brio::write_lines(bookmarks_gs %||% character(0), metafile) close(f) } args <- c("-q", "-o", shQuote(target), "-sDEVICE=pdfwrite", "-sAutoRotatePages=None", "-dNO_PDFMARK_OUTLINES", shQuote(input), shQuote(metafile)) stdout <- xmpdf_system2(cmd, args) if (input == output) { file.copy(target, output, overwrite = TRUE) } invisible(output) } #### open/closed as_bookmarks <- function(bookmarks) { bookmarks <- as.data.frame(bookmarks) if (nrow(bookmarks) == 0) { bookmarks$title <- character() bookmarks$page <- integer() bookmarks$level <- integer() bookmarks$count <- integer() bookmarks$open <- logical() bookmarks$color <- character() bookmarks$fontface <- character() return(bookmarks) } stopifnot(hasName(bookmarks, "title"), !any(is.na(bookmarks$title)), hasName(bookmarks, "page"), !any(is.na(bookmarks$page))) bookmarks[["title"]] <- as.character(bookmarks[["title"]]) bookmarks[["page"]] <- as.integer(bookmarks[["page"]]) if (hasName(bookmarks, "open")) { bookmarks[["open"]] <- as.logical(bookmarks[["open"]]) } else if (hasName(bookmarks, "count")) { count <- as.integer(bookmarks[["count"]]) if (any(is.na(count))) count[which(is.na(count))] <- 0L open <- rep_len(NA, nrow(bookmarks)) if (length(which(count > 0))) open[which(count > 0)] <- TRUE if (length(which(count < 0))) open[which(count < 0)] <- FALSE bookmarks[["open"]] <- open } else { bookmarks[["open"]] <- NA } if (hasName(bookmarks, "level") && hasName(bookmarks, "count")) { bookmarks[["level"]] <- as.integer(bookmarks[["level"]]) bookmarks[["count"]] <- as.integer(bookmarks[["count"]]) if (any(is.na(bookmarks[["count"]]))) bookmarks[["count"]] <- get_count(bookmarks[["level"]], bookmarks[["open"]]) } else if (hasName(bookmarks, "level")) { bookmarks[["level"]] <- as.integer(bookmarks[["level"]]) bookmarks[["count"]] <- get_count(bookmarks[["level"]], bookmarks[["open"]]) } else if (hasName(bookmarks, "count")) { bookmarks[["count"]] <- as.integer(bookmarks[["count"]]) if (any(is.na(bookmarks[["count"]]))) bookmarks[["count"]][which(is.na(bookmarks[["count"]]))] <- 0L bookmarks[["level"]] <- get_level(bookmarks[["count"]]) } else { bookmarks[["level"]] <- 1L bookmarks[["count"]] <- 0L } if (hasName(bookmarks, "color")) bookmarks[["color"]] <- as.character(bookmarks[["color"]]) else bookmarks[["color"]] <- NA_character_ if (hasName(bookmarks, "fontface")) { bookmarks[["fontface"]] <- as.character(bookmarks[["fontface"]]) if (isTRUE(any(bookmarks[["fontface"]] == "1"))) bookmarks[["fontface"]][which(bookmarks[["fontface"]] == "1")] <- "plain" if (isTRUE(any(bookmarks[["fontface"]] == "2"))) bookmarks[["fontface"]][which(bookmarks[["fontface"]] == "2")] <- "bold" if (isTRUE(any(bookmarks[["fontface"]] == "3"))) bookmarks[["fontface"]][which(bookmarks[["fontface"]] == "3")] <- "italic" if (isTRUE(any(bookmarks[["fontface"]] == "4"))) bookmarks[["fontface"]][which(bookmarks[["fontface"]] == "4")] <- "bold.italic" fontface_nonmissing <- Filter(Negate(is.na), bookmarks[["fontface"]]) stopifnot(all(fontface_nonmissing %in% c("plain", "bold", "italic", "bold.italic"))) } else { bookmarks[["fontface"]] <- NA_character_ } reordered <- bookmarks[, c("title", "page", "level", "count", "open", "color", "fontface")] attr(reordered, "filename") <- attr(bookmarks, "filename") attr(reordered, "title") <- attr(bookmarks, "title") attr(reordered, "total_pages") <- attr(bookmarks, "total_pages") reordered } # get_count(c(1, 2, 3, 2)) == c(2, 1, 0, 0) get_count <- function(levels, open) { closed <- vapply(open, isFALSE, logical(1)) levels <- as.integer(levels) n <- length(levels) counts <- integer(n) for (i in seq_len(n)) { if (i < n) { count <- 0 for (j in seq(i + 1L, n)) { if (levels[j] == levels[i]) break else if (levels[j] == levels[i] + 1L) count <- count + 1L } if (count > 0) counts[i] <- count } } if (any(closed)) counts[which(closed)] <- -counts[which(closed)] counts } # get_level(c(2, 1, 0, 0)) == c(1, 2, 3, 2) get_level <- function(counts) { counts <- as.integer(abs(counts)) n <- length(counts) levels <- rep_len(1L, n) for (i in seq_len(n)) { if (counts[i] == 0) next n_left <- counts[i] n_subordinate <- counts[i] j <- i + 1L while (n_left > 0 && j <= n) { if (counts[j] > 0) { n_left <- n_left + counts[j] n_subordinate <- n_subordinate + counts[j] } n_left <- n_left - 1L j <- j + 1L } indices <- seq.int(i + 1L, i + n_subordinate) if (max(indices) > n) { msg <- c(paste(sQuote("count"), "column seems mis-specified"), i = paste("The count should be number of immediate subordinates", "excluding any subordinates of subordinates")) abort(msg) } levels[indices] <- levels[indices] + 1L } levels } bookmark_pdftk <- function(title, level, page, ...) { c("BookmarkBegin", stri_join("BookmarkTitle:", title), stri_join("BookmarkLevel:", level), stri_join("BookmarkPageNumber:", page)) } bookmark_gs <- function(title, page, count, fontface, color, ...) { otc <- bookmark_gs_helper(title, page, count, fontface, color) stri_join(unlist(otc), collapse = "") } bookmark_gs_raw <- function(title, page, count, fontface, color, ...) { otc <- bookmark_gs_helper(title, page, count, fontface, color) do.call(raw_pdfmark_entry, otc) } bookmark_gs_helper <- function(title, page, count, fontface, color) { if (count == 0) count_str <- "" else count_str <- stri_join(" /Count ", count) if (is.na(fontface)) { style_str <- "" } else { style <- switch(fontface, "plain" = 0L, "italic" = 1L, "bold" = 2L, "bold.italic" = 3L) style_str <- stri_join(" /F ", style, "\n") } if (is.na(color)) { color_str <- "" } else { rgb <- grDevices::col2rgb(color) color_str <- sprintf("/C [%f %f %f]\n", rgb[1] / 255, rgb[2] / 255, rgb[3] / 255) } open <- sprintf("[%s /Page %d /View [/XYZ null null null]\n /Title (", count_str, page) close <- sprintf(")\n%s%s /OUT pdfmark", color_str, style_str) list(open = open, value = title, close = close) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/bookmarks.R
# SPDX-License-Identifier: MIT #' Concatenate pdf documents together #' #' `cat_pages()` concatenates pdf documents together. #' #' `cat_pages()` will try to use the following helper functions in the following order: #' #' 1. `cat_pages_qpdf()` which wraps [qpdf::pdf_combine()] #' 2. `cat_pages_pdftk()` which wraps `pdftk` command-line tool #' 3. `cat_pages_gs()` which wraps `ghostscript` command-line tool #' #' @param input Filename(s) (pdf) to concatenate together #' @param output Filename (pdf) to save concatenated output to #' @return The (output) filename invisibly. #' @seealso [supports_cat_pages()], [supports_gs()], and [supports_pdftk()] to detect support for these features. #' [cat_bookmarks()] for generating bookmarks for concatenated files. #' @examples #' if (supports_cat_pages() && require("grid", quietly = TRUE)) { #' # Create two different two-page pdf files #' make_pdf <- function(f, title) { #' pdf(f, onefile = TRUE, title = title) #' grid.text(paste(title, "Page 1")) #' grid.newpage() #' grid.text(paste(title, "Page 2")) #' invisible(dev.off()) #' } #' f1 <- tempfile(fileext = "_doc1.pdf") #' on.exit(unlink(f1)) #' make_pdf(f1, "Document 1") #' #' f2 <- tempfile(fileext = "_doc2.pdf") #' on.exit(unlink(f2)) #' make_pdf(f2, "Document 2") #' #' fc <- tempfile(fileext = "_cat.pdf") #' on.exit(unlink(fc)) #' cat_pages(c(f1, f2), fc) #' #' # Use `cat_bookmarks()` to create pdf bookmarks for concatenated output files #' if (supports_get_bookmarks() && supports_set_bookmarks()) { #' l <- get_bookmarks(c(f1, f2)) #' bm <- cat_bookmarks(l, "title") #' set_bookmarks(bm, fc) #' print(get_bookmarks(fc)[[1]]) #' } #' unlink(f1) #' unlink(f2) #' unlink(fc) #' } #' @export cat_pages <- function(input, output) { if (supports_qpdf()) { cat_pages_qpdf(input, output) } else if (supports_pdftk()) { cat_pages_pdftk(input, output) } else if (supports_gs()) { cat_pages_gs(input, output) } else { abort(msg_cat_pages(), class = "xmpdf_suggested_package") } } #' @rdname cat_pages #' @export cat_pages_gs <- function(input, output) { cmd <- gs() input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) args <- c("-q", "-o", shQuote(output), "-sDEVICE=pdfwrite", "-sAutoRotatePages=None", shQuote(input)) xmpdf_system2(cmd, args) invisible(output) } #' @rdname cat_pages #' @export cat_pages_pdftk <- function(input, output) { cmd <- pdftk() input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) args <- c(shQuote(input), "cat", "output", shQuote(output)) xmpdf_system2(cmd, args) invisible(output) } #' @rdname cat_pages #' @export cat_pages_qpdf <- function(input, output) { assert_suggested("qpdf") input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) qpdf::pdf_combine(input, output) invisible(output) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/cat_pages.R
# SPDX-License-Identifier: MIT #' SPDX License List data #' #' `spdx_licenses` is a data frame of SPDX License List data. #' #' @seealso See \url{https://spdx.org/licenses/} for more information. #' @format a data frame with eight variables: #' \describe{ #' \item{id}{SPDX Identifier.} #' \item{name}{Full name of license. #' For Creative Commons licenses these have been tweaked from the SPDX version #' to more closely match the full name used by Creative Commons Foundation. } #' \item{url}{URL for copy of license located at `spdx.org`} #' \item{fsf}{Is this license considered Free/Libre by the FSF?} #' \item{osi}{Is this license OSI approved?} #' \item{deprecated}{Has this SPDFX Identifier been deprecated by SPDX?} #' \item{url_alt}{Alternative URL for license. #' Manually created for a subset of Creative Commons licenses. #' Others taken from \url{https://github.com/sindresorhus/spdx-license-list}. #' } #' \item{pd}{Is this license a "public domain" license? Manually created.} #' } "spdx_licenses"
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/data.R
# SPDX-License-Identifier: MIT #' PDF documentation info dictionary object #' #' `docinfo()` creates a PDF documentation info dictionary object. #' Such objects can be used with [set_docinfo()] to edit PDF documentation info dictionary entries #' and such objects are returned by [get_docinfo()]. #' @param author The document's author. Matching xmp metadata tag is `dc:creator`. #' @param creation_date The date the document was created. #' Will be coerced by [datetimeoffset::as_datetimeoffset()]. #' Matching xmp metadata tag is `xmp:CreateDate`. #' @param creator The name of the application that originally created the document (if converted to pdf). #' Matching xmp metadata tag is `xmp:CreatorTool`. #' @param producer The name of the application that converted the document to pdf. #' Matching xmp metadata tag is `pdf:Producer`. #' @param title The document's title. Matching xmp metadata tag is `dc:title`. #' @param subject The document's subject. Matching xmp metadata tag is `dc:description`. #' @param keywords Keywords for this document (for cross-document searching). #' Matching xmp metadata tag is `pdf:Keywords`. #' Will be coerced into a string by `stringi::stri_join(keywords, collapse = ", ")`. #' @param mod_date The date the document was last modified. #' Will be coerced by [datetimeoffset::as_datetimeoffset()]. #' Matching xmp metadata tag is `xmp:ModifyDate`. #' @seealso [get_docinfo()] and [set_docinfo()] for getting/setting such information from/to PDF files. #' [as_docinfo()] for coercing to this object. #' [as_xmp()] can be used to coerce `docinfo()` objects into [xmp()] objects. #' @section Known limitations: #' #' * Currently does not support arbitrary info dictionary entries. #' #' @section `docinfo` R6 Class Methods:\describe{ #' \item{`get_item(key)`}{Get documentation info value for key `key`. #' Can also use the relevant active bindings to get documentation info values.} #' \item{`set_item(key, value)`}{Set documentation info key `key` with value `value`. #' Can also use the relevant active bindings to set documentation info values.} #' \item{`update(x)`}{Update documentation info key entries #' using non-`NULL` entries in object `x` coerced by [as_docinfo()].} #' } #' @section `docinfo` R6 Active Bindings:\describe{ #' \item{`author`}{The document's author.} #' \item{`creation_date`}{The date the document was created.} #' \item{`creator`}{The name of the application that originally created the document (if converted to pdf).} #' \item{`producer`}{The name of the application that converted the document to pdf.} #' \item{`title`}{The document's title.} #' \item{`subject`}{The document's subject.} #' \item{`keywords`}{Keywords for this document (for cross-document searching).} #' \item{`mod_date`}{The date the document was last modified.} #' } #' @examples #' if (supports_set_docinfo() && supports_get_docinfo() && require("grid", quietly = TRUE)) { #' f <- tempfile(fileext = ".pdf") #' pdf(f, onefile = TRUE) #' grid.text("Page 1") #' grid.newpage() #' grid.text("Page 2") #' invisible(dev.off()) #' #' cat("\nInitial documentation info\n") #' d <- get_docinfo(f)[[1]] #' print(d) #' #' d <- update(d, #' author = "John Doe", #' title = "Two Boring Pages", #' keywords = "R, xmpdf") #' set_docinfo(d, f) #' #' cat("\nDocumentation info after setting it\n") #' print(get_docinfo(f)[[1]]) #' #' unlink(f) #' } #' @export docinfo <- function(author = NULL, creation_date = NULL, creator = NULL, producer = NULL, title = NULL, subject = NULL, keywords = NULL, mod_date = NULL) { DocInfo$new(author = author, creation_date = creation_date, creator = creator, producer = producer, title = title, subject = subject, keywords = keywords, mod_date = mod_date) } DocInfo <- R6Class("docinfo", public = list( initialize = function(author = NULL, creation_date = NULL, creator = NULL, producer = NULL, title = NULL, subject = NULL, keywords = NULL, mod_date = NULL) { if (!is.null(author)) self$author <- author if (!is.null(creation_date)) self$creation_date <- creation_date if (!is.null(creator)) self$creator <- creator if (!is.null(producer)) self$producer <- producer if (!is.null(title)) self$title <- title if (!is.null(subject)) self$subject <- subject if (!is.null(keywords)) self$keywords <- keywords if (!is.null(mod_date)) self$mod_date <- mod_date invisible(NULL) }, print = function() { text <- c(stri_join("Author: ", d_format(self$author)), stri_join("CreationDate: ", d_format(self$creation_date)), stri_join("Creator: ", d_format(self$creator)), stri_join("Producer: ", d_format(self$producer)), stri_join("Title: ", d_format(self$title)), stri_join("Subject: ", d_format(self$subject)), stri_join("Keywords: ", d_format(self$keywords)), stri_join("ModDate: ", d_format(self$mod_date))) invisible(cat(text, sep="\n")) }, get_item = function(key) { if (key %in% c("author", "Author")) { self$author } else if (key %in% c("creation_date", "CreationDate")) { self$creation_date } else if (key %in% c("creator", "Creator")) { self$creator } else if (key %in% c("producer", "Producer")) { self$producer } else if (key %in% c("title", "Title")) { self$title } else if (key %in% c("subject", "Subject")) { self$subject } else if (key %in% c("keywords", "Keywords")) { self$keywords } else if (key %in% c("mod_date", "ModDate")) { self$mod_date } else { msg <- sprintf("We don't support key '%s' yet.", key) abort(msg) } }, set_item = function(key, value) { if (key %in% c("author", "Author")) { self$author <- value } else if (key %in% c("creation_date", "CreationDate")) { self$creation_date <- value } else if (key %in% c("creator", "Creator")) { self$creator <- value } else if (key %in% c("producer", "Producer")) { self$producer <- value } else if (key %in% c("title", "Title")) { self$title <- value } else if (key %in% c("subject", "Subject")) { self$subject <- value } else if (key %in% c("keywords", "Keywords")) { self$keywords <- value } else if (key %in% c("mod_date", "ModDate")) { self$mod_date <- value } else { msg <- sprintf("We don't support key '%s' yet.", key) abort(msg) } }, update = function(x) { di <- as_docinfo(x) for (key in x$get_nonnull_keys()) self$set_item(key, x$get_item(key)) invisible(NULL) }, get_nonnull_keys = function() { keys <- character(0) if (!is.null(self$author)) keys <- append(keys, "Author") if (!is.null(self$creation_date)) keys <- append(keys, "CreationDate") if (!is.null(self$creator)) keys <- append(keys, "Creator") if (!is.null(self$producer)) keys <- append(keys, "Producer") if (!is.null(self$title)) keys <- append(keys, "Title") if (!is.null(self$subject)) keys <- append(keys, "Subject") if (!is.null(self$keywords)) keys <- append(keys, "Keywords") if (!is.null(self$mod_date)) keys <- append(keys, "ModDate") keys }, exiftool_tags = function() { tags <- list() if (!is.null(self$author)) tags[["PDF:Author"]] <- self$author if (!is.null(self$creation_date)) tags[["PDF:CreateDate"]] <- to_date_pdfmark_exiftool(self$creation_date) if (!is.null(self$creator)) tags[["PDF:Creator"]] <- self$creator if (!is.null(self$producer)) tags[["PDF:Producer"]] <- self$producer if (!is.null(self$title)) tags[["PDF:Title"]] <- self$title if (!is.null(self$subject)) tags[["PDF:Subject"]] <- self$subject if (!is.null(self$keywords)) tags[["PDF:Keywords"]] <- self$keywords if (!is.null(self$mod_date)) tags[["PDF:ModifyDate"]] <- to_date_pdfmark_exiftool(self$mod_date) tags }, pdfmark = function(raw = FALSE) { if (raw) private$pdfmark_raw() else private$pdfmark_character() }, pdftk = function() { tags <- character() if (!is.null(self$author)) tags <- append(tags, entry_pdftk("Author", self$author)) if (!is.null(self$creation_date)) tags <- append(tags, entry_pdftk("CreationDate", to_date_pdfmark(self$creation_date))) if (!is.null(self$creator)) tags <- append(tags, entry_pdftk("Creator", self$creator)) if (!is.null(self$producer)) tags <- append(tags, entry_pdftk("Producer", self$producer)) if (!is.null(self$title)) tags <- append(tags, entry_pdftk("Title", self$title)) if (!is.null(self$subject)) tags <- append(tags, entry_pdftk("Subject", self$subject)) if (!is.null(self$keywords)) tags <- append(tags, entry_pdftk("Keywords", self$keywords)) if (!is.null(self$mod_date)) tags <- append(tags, entry_pdftk("ModDate", to_date_pdfmark(self$mod_date))) tags }, xmp = function() { # these are the XMP tags that `ghostscript` chooses as equivalent # to the eight documentation info dictionary entries tags <- list() if (!is.null(self$title)) tags[["dc:title"]] <- self$title if (!is.null(self$author)) tags[["dc:creator"]] <- self$author if (!is.null(self$subject)) tags[["dc:description"]] <- self$subject if (!is.null(self$producer)) tags[["pdf:Producer"]] <- self$producer if (!is.null(self$keywords)) tags[["pdf:Keywords"]] <- self$keywords if (!is.null(self$creation_date)) tags[["xmp:CreateDate"]] <- self$creation_date if (!is.null(self$creator)) tags[["xmp:CreatorTool"]] <- self$creator if (!is.null(self$mod_date)) tags[["xmp:ModifyDate"]] <- self$mod_date as_xmp(tags) } ), active = list( author = function(value) { if (missing(value)) { private$val$author } else { private$val$author <- as_character_value(value) } }, creation_date = function(value) { if (missing(value)) { private$val$creation_date } else { private$val$creation_date <- as_datetime_value(value) } }, creator = function(value) { if (missing(value)) { private$val$creator } else { private$val$creator <- as_character_value(value) } }, producer = function(value) { if (missing(value)) { private$val$producer } else { private$val$producer <- as_character_value(value) } }, title = function(value) { if (missing(value)) { private$val$title } else { private$val$title <- as_character_value(value) } }, subject = function(value) { if (missing(value)) { private$val$subject } else { private$val$subject <- as_character_value(value) } }, keywords = function(value) { if (missing(value)) { private$val$keywords } else { private$val$keywords <- stri_join(value, collapse = ", ") } }, mod_date = function(value) { if (missing(value)) { private$val$mod_date } else { private$val$mod_date <- as_datetime_value(value) } } ), private = list( val = list(), pdfmark_character = function() { tags <- "[" if (!is.null(self$author)) tags <- append(tags, sprintf(" /Author (%s)\n", self$author)) if (!is.null(self$creation_date)) tags <- append(tags, sprintf(" /CreationDate (%s)\n", to_date_pdfmark(self$creation_date))) if (!is.null(self$creator)) tags <- append(tags, sprintf(" /Creator (%s)\n", self$creator)) if (!is.null(self$producer)) tags <- append(tags, sprintf(" /Producer (%s)\n", self$producer)) if (!is.null(self$title)) tags <- append(tags, sprintf(" /Title (%s)\n", self$title)) if (!is.null(self$subject)) tags <- append(tags, sprintf(" /Subject (%s)\n", self$subject)) if (!is.null(self$keywords)) tags <- append(tags, sprintf(" /Keywords (%s)\n", stri_join(self$keywords, collapse = ", "))) if (!is.null(self$mod_date)) tags <- append(tags, sprintf(" /ModDate (%s)\n", to_date_pdfmark(self$mod_date))) tags <- append(tags, " /DOCINFO pdfmark\n") stri_join(tags, collapse="") }, pdfmark_raw = function() { tags <- iconv("[", to = "latin1", toRaw = TRUE)[[1]] if (!is.null(self$author)) tags <- append(tags, raw_pdfmark_entry(" /Author (", self$author, ")\n")) if (!is.null(self$creation_date)) { creation_date <- sprintf(" /CreationDate (%s)\n", to_date_pdfmark(self$creation_date)) tags <- append(tags, iconv(creation_date, to = "latin1", toRaw = TRUE)[[1]]) } if (!is.null(self$creator)) tags <- append(tags, raw_pdfmark_entry(" /Creator (", self$creator, ")\n")) if (!is.null(self$producer)) tags <- append(tags, raw_pdfmark_entry(" /Producer (", self$producer, ")\n")) if (!is.null(self$title)) tags <- append(tags, raw_pdfmark_entry(" /Title (", self$title, ")\n")) if (!is.null(self$subject)) tags <- append(tags, raw_pdfmark_entry(" /Subject (", self$subject, ")\n")) if (!is.null(self$keywords)) { keywords <- stri_join(self$keywords, collapse = ", ") tags <- append(tags, raw_pdfmark_entry(" /Keywords (", keywords, ")\n")) } if (!is.null(self$mod_date)) { mod_date <- sprintf(" /ModDate (%s)\n", to_date_pdfmark(self$mod_date)) tags <- append(tags, iconv(mod_date, to = "latin1", toRaw = TRUE)[[1]]) } tags <- append(tags, iconv(" /DOCINFO pdfmark\n", to = "latin1", toRaw = TRUE)[[1]]) tags } ) ) #' @export as.list.docinfo <- function(x, ...) { l <- list() if (!is.null(x$author)) l$author <- x$author if (!is.null(x$creation_date)) l$creation_date <- x$creation_date if (!is.null(x$creator)) l$creator <- x$creator if (!is.null(x$producer)) l$producer <- x$producer if (!is.null(x$title)) l$title <- x$title if (!is.null(x$subject)) l$subject <- x$subject if (!is.null(x$keywords)) l$keywords <- x$keywords if (!is.null(x$mod_date)) l$mod_date <- x$mod_date l } #' @export update.docinfo <- function(object, ...) { d <- object$clone() d$update(as_docinfo(list(...))) d } to_date_pdfmark <- function(date) { if (is.null(date)) { NULL } else { datetimeoffset::format_pdfmark(date) } } to_date_pdfmark_exiftool <- function(date) { s <- datetimeoffset::format_pdfmark(date) #### Update when {datetimeoffset} allows suppressing prefix substr(s, 3L, nchar(s)) } raw_pdfmark_entry <- function(open, value, close) { r <- iconv(open, to = "latin1", toRaw = TRUE)[[1]] l1 <- iconv(value, to = "latin1") if (is.na(l1)) { # Unicode needs to be "UTF-16BE" while rest needs to be "latin1" # Replacing `paste0()` with `stringi::stri_join()` causes an error here r <- append(r, iconv(paste0("\ufeff", value), to = "UTF-16BE", toRaw = TRUE)[[1]]) } else { r <- append(r, iconv(value, to = "latin1", toRaw = TRUE)[[1]]) } append(r, iconv(close, to = "latin1", toRaw = TRUE)[[1]]) } d_format <- function(value) { if (is.null(value)) { "NULL" } else if (length(value) > 1) { stri_join(value, collapse = ", ") } else if (is.character(value)) { value } else { format(value) } } entry_pdftk <- function(key, value) { c("InfoBegin", stri_join("InfoKey: ", key), stri_join("InfoValue: ", value)) } as_character_value <- function(value) { if (is.null(value)) NULL else value } as_datetime_value <- function(value) { if (is.null(value)) { NULL } else { datetimeoffset::as_datetimeoffset(value) } }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/docinfo.R
# SPDX-License-Identifier: MIT #' Set/get pdf document info dictionary #' #' `get_docinfo()` gets pdf document info from a file. #' `set_docinfo()` sets pdf document info for a file. #' #' `get_docinfo()` will try to use the following helper functions in the following order: #' #' 1. `get_docinfo_pdftk()` which wraps `pdftk` command-line tool #' 2. `get_docinfo_exiftool()` which wraps `exiftool` command-line tool #' 3. `get_docinfo_pdftools()` which wraps [pdftools::pdf_info()] #' #' `set_docinfo()` will try to use the following helper functions in the following order: #' #' 1. `set_docinfo_exiftool()` which wraps `exiftool` command-line tool #' 2. `set_docinfo_gs()` which wraps `ghostscript` command-line tool #' 3. `set_docinfo_pdftk()` which wraps `pdftk` command-line tool #' #' @param filename Filename(s) (pdf) to extract info dictionary entries from. #' @param use_names If `TRUE` (default) use `filename` as the names of the result. #' @param docinfo A "docinfo" object (as returned by [docinfo()] or [get_docinfo()]). #' @param input Input pdf filename. #' @param output Output pdf filename. #' @return `docinfo()` returns a "docinfo" R6 class. #' `get_docinfo()` returns a list of "docinfo" R6 classes. #' `set_docinfo()` returns the (output) filename invisibly. #' @section Known limitations: #' #' * Currently does not support arbitrary info dictionary entries. #' * As a side effect `set_docinfo_gs()` seems to also update in previously set matching XPN metadata #' while `set_docinfo_exiftool()` and `set_docinfo_pdftk()` don't update #' any previously set matching XPN metadata. #' Some pdf viewers will preferentially use the previously set document title from XPN metadata #' if it exists instead of using the title set in documentation info dictionary entry. #' Consider also manually setting this XPN metadata using [set_xmp()]. #' * Old metadata information is usually not deleted from the pdf file by these operations. #' If deleting the old metadata is important one may want to try #' `qpdf::pdf_compress(input, linearize = TRUE)`. #' * `get_docinfo_exiftool()` will "widen" datetimes to second precision. #' * `get_docinfo_pdftools()`'s datetimes may not accurately reflect the embedded datetimes. #' * `set_docinfo_pdftk()` may not correctly handle documentation info entries with newlines in them. #' #' @examples #' if (supports_set_docinfo() && supports_get_docinfo() && require("grid", quietly = TRUE)) { #' f <- tempfile(fileext = ".pdf") #' pdf(f, onefile = TRUE) #' grid.text("Page 1") #' grid.newpage() #' grid.text("Page 2") #' invisible(dev.off()) #' #' cat("\nInitial documentation info:\n\n") #' d <- get_docinfo(f)[[1]] #' print(d) #' #' d <- update(d, #' author = "John Doe", #' title = "Two Boring Pages", #' keywords = c("R", "xmpdf")) #' set_docinfo(d, f) #' #' cat("\nDocumentation info after setting it:\n\n") #' print(get_docinfo(f)[[1]]) #' #' unlink(f) #' } #' @seealso [docinfo()] for more information about the documentation info objects. [supports_get_docinfo()], [supports_set_docinfo()], [supports_gs()], and [supports_pdftk()] to detect support for these features. For more info about the pdf document info dictionary see #' <https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#document-info-dictionary-docinfo>. #' @name edit_docinfo NULL #' @rdname edit_docinfo #' @export get_docinfo <- function(filename, use_names = TRUE) { if (supports_pdftk()) { get_docinfo_pdftk(filename, use_names = use_names) } else if (supports_exiftool()) { get_docinfo_exiftool(filename, use_names = use_names) } else if (supports_pdftools()) { get_docinfo_pdftools(filename, use_names = use_names) } else { abort(msg_get_docinfo(), class = "xmpdf_suggested_package") } } #' @rdname edit_docinfo #' @export get_docinfo_pdftools <- function(filename, use_names = TRUE) { assert_suggested("pdftools") l <- lapply(filename, get_docinfo_pdftools_helper) use_filenames(l, use_names, filename) } get_docinfo_pdftools_helper <- function(filename) { info <- pdftools::pdf_info(filename) dinfo <- docinfo() for (i in seq_along(info$keys)) { key <- names(info$keys)[i] if (key %in% c("Author", "Creator", "Producer", "Title", "Subject", "Keywords")) { dinfo$set_item(names(info$keys)[i], info$keys[[i]]) } else { msg <- sprintf("We don't support key '%s' yet.", key) warn(msg) } } if (!is.null(info$created)) dinfo$creation_date <- info$created if (!is.null(info$modified)) dinfo$mod_date <- info$modified dinfo } #' @rdname edit_docinfo #' @export get_docinfo_exiftool <- function(filename, use_names = TRUE) { l <- lapply(filename, get_docinfo_exiftool_helper) use_filenames(l, use_names, filename) } get_docinfo_exiftool_helper <- function(filename) { md <- get_exiftool_metadata(filename, tags="-PDF:all") md <- md[grep("^PDF:", names(md))] names(md) <- gsub("^PDF:", "", names(md)) dinfo <- docinfo() for (i in seq_along(md)) { key <- names(md)[i] if (key %in% c("Author", "Creator", "Producer", "Title", "Subject", "Keywords")) { dinfo$set_item(names(md)[i], md[[i]]) } else if (key %in% c("PDFVersion", "Linearized", "PageCount", "CreateDate", "ModifyDate")) { next } else { msg <- sprintf("We don't support key '%s' yet.", key) warn(msg) } } if (!is.null(md$CreateDate)) dinfo$creation_date <- md$CreateDate if (!is.null(md$ModifyDate)) dinfo$mod_date <- md$ModifyDate dinfo } #' @rdname edit_docinfo #' @export set_docinfo_exiftool <- function(docinfo, input, output = input) { docinfo <- as_docinfo(docinfo) tags <- docinfo$exiftool_tags() set_exiftool_metadata(tags, input, output, mode = "pdf") } #' @rdname edit_docinfo #' @export get_docinfo_pdftk <- function(filename, use_names = TRUE) { l <- lapply(filename, get_docinfo_pdftk_helper) use_filenames(l, use_names, filename) } get_docinfo_pdftk_helper <- function(filename) { info <- get_pdftk_metadata(filename) dinfo <- docinfo() if (length(id <- grep("^InfoKey: Author", info))) { dinfo$author <- pdftk_string_value(info, id) } if (length(id <- grep("^InfoKey: CreationDate", info))) { dinfo$creation_date <- datetimeoffset::as_datetimeoffset(gsub("^InfoValue: ", "", info[id + 1])) } if (length(id <- grep("^InfoKey: Creator", info))) { dinfo$creator <- pdftk_string_value(info, id) } if (length(id <- grep("^InfoKey: Producer", info))) { dinfo$producer <- pdftk_string_value(info, id) } if (length(id <- grep("^InfoKey: Title", info))) { dinfo$title <- pdftk_string_value(info, id) } if (length(id <- grep("^InfoKey: Subject", info))) { dinfo$subject <- pdftk_string_value(info, id) } if (length(id <- grep("^InfoKey: Keywords", info))) { dinfo$keywords <- pdftk_string_value(info, id) } if (length(id <- grep("^InfoKey: ModDate", info))) { dinfo$mod_date <- datetimeoffset::as_datetimeoffset(gsub("^InfoValue: ", "", info[id + 1])) } dinfo } pdftk_string_value <- function(info, id) { v <- gsub("^InfoValue: ", "", info[id + 1]) i_x <- id + 2 while ((i_x) < length(info) && is_pdftk_newline(info[i_x])) { v <- stri_join(v, info[i_x], sep = "\n") i_x <- i_x + 1 } v } is_pdftk_newline <- function(line) { if (grepl("^[[:alnum:]]+:", line) || grepl("^[[:alpha:]]+Begin$", line)) FALSE else TRUE } #' @rdname edit_docinfo #' @export set_docinfo <- function(docinfo, input, output = input) { if (supports_exiftool()) { set_docinfo_exiftool(docinfo, input, output) } else if (supports_gs()) { set_docinfo_gs(docinfo, input, output) } else if (supports_pdftk()) { set_docinfo_pdftk(docinfo, input, output) } else { abort(msg_set_docinfo(), class = "xmpdf_suggested_package") } } #' @rdname edit_docinfo #' @export set_docinfo_gs <- function(docinfo, input, output = input) { docinfo <- as_docinfo(docinfo) cmd <- gs() input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) if (input == output) { target <- tempfile(fileext = ".pdf") on.exit(unlink(target)) } else { target <- output } metafile <- tempfile(fileext = ".bin") on.exit(unlink(metafile)) pmc <- docinfo$pdfmark(raw = FALSE) pmc_l1 <- iconv(pmc, to = "latin1") if (is.na(pmc_l1)) { # Has non-Latin-1 characters writeBin(docinfo$pdfmark(raw = TRUE), metafile, endian = "big") } else { # Just Latin-1 characters f <- file(metafile, encoding = "latin1") open(f, "w") writeLines(pmc_l1, f) close(f) } metafile <- normalizePath(metafile, mustWork = TRUE) args <- c("-q", "-o", shQuote(target), "-sDEVICE=pdfwrite", "-sAutoRotatePages=None", shQuote(input), shQuote(metafile)) xmpdf_system2(cmd, args) if (input == output) file.copy(target, output, overwrite = TRUE) invisible(output) } #' @rdname edit_docinfo #' @export set_docinfo_pdftk <- function(docinfo, input, output = input) { docinfo <- as_docinfo(docinfo) cmd <- pdftk() meta <- get_pdftk_metadata(input) input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) if (input == output) { target <- tempfile(fileext = ".pdf") on.exit(unlink(target)) } else { target <- output } id_info <- grep("^Info", meta) if (length(id_info)) meta <- meta[-id_info] meta <- append(docinfo$pdftk(), meta) metafile <- tempfile(fileext = ".txt") on.exit(unlink(metafile)) brio::write_lines(meta, metafile) metafile <- normalizePath(metafile, mustWork = TRUE) args <- c(shQuote(input), "update_info_utf8", shQuote(metafile), "output", shQuote(target)) xmpdf_system2(cmd, args) if (input == output) file.copy(target, output, overwrite = TRUE) invisible(output) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/edit_docinfo.R
# SPDX-License-Identifier: MIT #' Set/get xmp metadata #' #' `get_xmp()` gets xmp metadata from a file. #' `set_xmp()` sets xmp metadata for a file. #' #' `get_xmp()` will try to use the following helper functions in the following order: #' #' 1. `get_xmp_exiftool()` which wraps `exiftool` command-line tool #' #' `set_xmp()` will try to use the following helper functions in the following order: #' #' 1. `set_xmp_exiftool()` which wraps `exiftool` command-line tool #' #' @param filename Filename(s) to extract xmp metadata from. #' @param use_names If `TRUE` (default) use `filename` as the names of the result. #' @param xmp An [xmp()] object. #' @param input Input filename. #' @param output Output filename. #' @return `get_xmp()` returns a list of [xmp()] objects. #' `set_xmp()` returns the (output) filename invisibly. #' @seealso [xmp()] for more information about xmp metadata objects. #' [supports_get_xmp()], [supports_set_xmp()], and [supports_exiftool()] to detect support for these features. For more info about xmp metadata see <https://www.exiftool.org/TagNames/XMP.html>. #' @examples #' x <- xmp(attribution_url = "https://example.com/attribution", #' creator = "John Doe", #' description = "An image caption", #' date_created = Sys.Date(), #' spdx_id = "CC-BY-4.0") #' print(x) #' print(x, mode = "google_images", xmp_only = TRUE) #' print(x, mode = "creative_commons", xmp_only = TRUE) #' #' if (supports_set_xmp() && #' supports_get_xmp() && #' capabilities("png") && #' requireNamespace("grid", quietly = TRUE)) { #' #' f <- tempfile(fileext = ".png") #' png(f) #' grid::grid.text("This is an image!") #' invisible(dev.off()) #' set_xmp(x, f) #' print(get_xmp(f)[[1]]) #' } #' @name edit_xmp NULL #' @rdname edit_xmp #' @export get_xmp <- function(filename, use_names = TRUE) { if (supports_exiftool()) { get_xmp_exiftool(filename, use_names = use_names) } else { abort(msg_get_xmp(), class = "xmpdf_suggested_package") } } #' @rdname edit_xmp #' @export get_xmp_exiftool <- function(filename, use_names = TRUE) { l <- lapply(filename, get_xmp_exiftool_helper) use_filenames(l, use_names, filename) } get_xmp_exiftool_helper <- function(filename) { md <- get_exiftool_metadata(filename, tags="-XMP:all") md <- md[grep("^XMP-", names(md))] names(md) <- gsub("^XMP-", "", names(md)) names(md) <- gsub("^iptc", "Iptc4xmp", names(md)) names(md) <- ifelse(grepl("^dc:", names(md)), tolower(names(md)), names(md)) if (any(grepl("-", names(md)))) { md <- extract_lang_alt(md) } x <- as_xmp(md) x$auto_xmp <- NULL x } #### lang_alt extract_lang_alt <- function(x) { tags <- unique(gsub("^([[:alnum:]:]+)-(.*)$", "\\1", grep("-", names(x), value = TRUE))) for (tag in tags) { names(x) <- ifelse(names(x) == tag, stri_join(tag, "-x-default"), names(x)) i <- grep(stri_join("^", tag), names(x)) x_tag <- x[i] names(x_tag) <- substr(names(x_tag), nchar(tag) + 2L, nchar(names(x_tag))) x_la <- list(as_lang_alt(x_tag)) names(x_la) <- tag x <- c(x[-i], x_la) } x } #' @rdname edit_xmp #' @export set_xmp <- function(xmp, input, output = input) { if (supports_exiftool()) { set_xmp_exiftool(xmp, input, output) } else { abort(msg_set_xmp(), class = "xmpdf_suggested_package") } } #' @rdname edit_xmp #' @export set_xmp_exiftool <- function(xmp, input, output = input) { xmp <- as_xmp(xmp) set_exiftool_metadata(xmp$exiftool_tags(), input, output, mode = "xmp") }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/edit_xmp.R
# SPDX-License-Identifier: MIT #' Messages for how to enable feature #' #' `enable_feature_message()` returns a character vector with the information #' needed to install the requested feature. #' Formatted for use with [rlang::abort()], [rlang::warn()], or [rlang::inform()]. #' #' @param feature Which `xmpdf` feature to give information for. #' @return A character vector formatted for use with [rlang::abort()], [rlang::warn()], or [rlang::inform()]. #' @examples #' rlang::inform(enable_feature_message("get_bookmarks")) #' @export enable_feature_message <- function(feature = c("cat_pages", "get_bookmarks", "get_docinfo", "get_xmp", "n_pages", "set_bookmarks", "set_docinfo", "set_xmp")) { feature <- match.arg(feature) switch(feature, cat_pages = msg_cat_pages(), get_bookmarks = msg_get_bookmarks(), get_docinfo = msg_get_docinfo(), get_xmp = msg_get_xmp(), n_pages = msg_n_pages(), set_bookmarks = msg_set_bookmarks(), set_docinfo = msg_set_docinfo(), set_xmp = msg_set_xmp() ) } msg_cat_pages <- function() { c(need_to_install_str("cat_pages()"), install_package_str("qpdf"), install_pdftk_str(), install_gs_str() ) } msg_get_bookmarks <- function() { c(need_to_install_str("get_bookmarks()"), install_pdftk_str() ) } msg_get_docinfo <- function() { c(need_to_install_str("get_docinfo()"), install_exiftool_str(), install_pdftk_str(), install_package_str("pdftools") ) } msg_get_xmp <- function() { c(need_to_install_str("get_xmp()"), install_exiftool_str() ) } msg_n_pages <- function() { c(need_to_install_str("n_pages()"), install_package_str("qpdf"), install_exiftool_str(), install_pdftk_str(), install_gs_str() ) } msg_set_bookmarks <- function() { c(need_to_install_str("set_bookmarks()"), install_gs_str(), install_pdftk_str() ) } msg_set_docinfo <- function() { c(need_to_install_str("set_docinfo()"), install_gs_str(), install_exiftool_str(), install_pdftk_str() ) } msg_set_xmp <- function() { c(need_to_install_str("set_xmp()"), install_exiftool_str() ) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/msg.R
# SPDX-License-Identifier: MIT #' Get number of pages in a document #' #' `n_pages()` returns the number of pages in the (pdf) file(s). #' #' `n_pages()` will try to use the following helper functions in the following order: #' #' 1. `n_pages_qpdf()` which wraps [qpdf::pdf_length()] #' 2. `n_pages_exiftool()` which wraps `exiftool` command-line tool #' 3. `n_pages_pdftk()` which wraps `pdftk` command-line tool #' 4. `n_pages_gs()` which wraps `ghostscript` command-line tool #' #' @param filename Character vector of filenames. #' @param use_names If `TRUE` (default) use `filename` as the names of the result. #' @examples #' if (supports_n_pages() && require("grid", quietly = TRUE)) { #' f <- tempfile(fileext = ".pdf") #' pdf(f, onefile = TRUE) #' grid.text("Page 1") #' grid.newpage() #' grid.text("Page 2") #' invisible(dev.off()) #' print(n_pages(f)) #' unlink(f) #' } #' @return An integer vector of number of pages within each file. #' @seealso [supports_n_pages()] detects support for this feature. #' @export n_pages <- function(filename, use_names = TRUE) { if (supports_qpdf()) { n_pages_qpdf(filename, use_names = use_names) } else if (supports_exiftool()) { n_pages_exiftool(filename, use_names = use_names) } else if (supports_pdftk()) { n_pages_pdftk(filename, use_names = use_names) # } else if (has_cmd("pdfinfo")) { # n_pages_pdfinfo(filename, use_names = use_names) } else if (supports_gs()) { n_pages_gs(filename, use_names = use_names) } else { abort(msg_n_pages(), class = "xmpdf_suggested_package") } } #' @rdname n_pages #' @export n_pages_exiftool <- function(filename, use_names = TRUE) { filename <- normalizePath(filename, mustWork = TRUE) sapply(filename, USE.NAMES = use_names, FUN = function(f) { md <- get_exiftool_metadata(f, "-pdf:pagecount") as.integer(md[["PDF:PageCount"]]) }) } #' @rdname n_pages #' @export n_pages_qpdf <- function(filename, use_names = TRUE) { assert_suggested("qpdf") filename <- normalizePath(filename, mustWork = TRUE) sapply(filename, USE.NAMES = use_names, FUN = function(f) qpdf::pdf_length(f)) } # #' @rdname n_pages # #' @export # n_pages_pdfinfo <- function(filename, use_names = TRUE) { # cmd <- Sys.which("pdfinfo") # filename <- shQuote(normalizePath(filename, mustWork = TRUE)) # sapply(filename, USE.NAMES = use_names, FUN = function(f) { # pdfinfo <- xmpdf_system2(cmd, f) # pdfinfo <- grep("^Pages:", pdfinfo, value=TRUE) # as.integer(strsplit(pdfinfo, " +")[[1]][2]) # }) # } #' @rdname n_pages #' @export n_pages_pdftk <- function(filename, use_names = TRUE) { cmd <- pdftk() filename <- shQuote(normalizePath(filename, mustWork = TRUE)) sapply(filename, USE.NAMES = use_names, FUN = function(f) { args <- c(f, "dump_data_utf8") pdfinfo <- xmpdf_system2(cmd, args) pdfinfo <- grep("^NumberOfPages:", pdfinfo, value=TRUE) as.integer(strsplit(pdfinfo, ":")[[1]][2]) }) } #' @rdname n_pages #' @export n_pages_gs <- function(filename, use_names = TRUE) { cmd <- gs() filename <- normalizePath(filename, winslash="/", mustWork = TRUE) sapply(filename, USE.NAMES = use_names, FUN = function(f) { args <- c("-q", "-dNODISPLAY", "-dNOSAFER", "-c", stri_join(stri_join('"(', f, ")"), ' (r) file runpdfbegin pdfpagecount = quit"')) as.integer(xmpdf_system2(cmd, args)) }) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/n_pages.R
# SPDX-License-Identifier: MIT #' Detect support for features #' #' `supports_get_bookmarks()`, `supports_set_bookmarks()`, #' `supports_get_docinfo()`, `supports_set_docinfo()`, #' `supports_get_xmp()`, `supports_set_xmp()`, #' `supports_cat_pages()`, and `supports_n_pages()` #' detects support for the functions #' [get_bookmarks()], [set_bookmarks()], #' [get_docinfo()], [set_docinfo()], #' [get_xmp()], [set_xmp()], #' [cat_pages()], and [n_pages()] respectively. #' `supports_exiftool()`, `supports_gs()` and `supports_pdftk()` #' detects support for the command-line tools #' `exiftool`, `ghostscript` and `pdftk` respectively as used by various lower-level functions. #' #' * `supports_exiftool()` detects support for the command-line tool `exiftool` which is #' required for [get_docinfo_exiftool()], [get_xmp_exiftool()], [set_xmp_exiftool()], and [n_pages_exiftool()]. #' * `supports_gs()` detects support for the command-line tool `ghostscript` which is #' required for [set_docinfo_gs()], [set_bookmarks_gs()], [cat_pages_gs()], and [n_pages_gs()]. #' * `supports_pdftk()` detects support for the command-line tool `pdftk` which is #' required for [get_bookmarks_pdftk()], [set_bookmarks_pdftk()], #' [get_docinfo_pdftk()], [set_docinfo_pdftk()], [cat_pages_pdftk()], and [n_pages_pdftk()]. #' * `requireNamespace("pdftools", quietly = TRUE)` detects support for the R packages `pdftools` #' which is required for [get_bookmarks_pdftools()] and [get_docinfo_pdftools()]. #' * `requireNamespace("qpdf", quietly = TRUE)` detects support for the R packages `qpdf` #' which is required for [cat_pages_qpdf()] and [n_pages_qpdf()]. #' @examples #' # Detect for higher-level features #' supports_get_docinfo() #' supports_set_docinfo() #' supports_get_bookmarks() #' supports_set_bookmarks() #' supports_get_xmp() #' supports_set_xmp() #' supports_cat_pages() #' supports_n_pages() #' #' # Detect support for lower-level helper features #' supports_exiftool() #' supports_gs() #' supports_pdftk() #' print(requireNamespace("pdftools", quietly = TRUE)) #' print(requireNamespace("qpdf", quietly = TRUE)) #' @name supports NULL #' @rdname supports #' @export supports_get_bookmarks <- function() { supports_pdftk() || supports_pdftools() } #' @rdname supports #' @export supports_set_bookmarks <- function() { supports_pdftk() || supports_gs() } #' @rdname supports #' @export supports_get_docinfo <- function() { supports_exiftool() || supports_pdftk() || supports_pdftools() } #' @rdname supports #' @export supports_set_docinfo <- function() { supports_pdftk() || supports_gs() } #' @rdname supports #' @export supports_get_xmp <- function() { supports_exiftool() } #' @rdname supports #' @export supports_set_xmp <- function() { supports_exiftool() } #' @rdname supports #' @export supports_cat_pages <- function() { supports_qpdf() || supports_pdftk() || supports_gs() } #' @rdname supports #' @export supports_n_pages <- function() { supports_exiftool() || supports_qpdf() || supports_pdftk() || supports_gs() } #' @rdname supports #' @export supports_exiftool <- function() { as.logical(find_exiftool_cmd() != "") } #' @rdname supports #' @export supports_gs <- function() { as.logical(find_gs_cmd() != "") } #' @rdname supports #' @export supports_pdftk <- function() { as.logical(find_pdftk_cmd() != "") } find_exiftool_cmd <- function() { if (getOption("xmpdf_disable_exiftool", FALSE)) { "" } else if (requireNamespace("exiftoolr", quietly = TRUE)) { cmd <- try(exiftoolr::configure_exiftoolr(quiet = TRUE), silent = TRUE) if (inherits(cmd, "try-error")) "" else cmd } else { Sys.which(Sys.getenv("ET_EXIFTOOL_PATH", "exiftool")) } } find_gs_cmd <- function() { if (getOption("xmpdf_disable_gs", FALSE)) "" else tools::find_gs_cmd() } find_pdftk_cmd <- function() { if (getOption("xmpdf_disable_pdftk", FALSE)) { "" } else { cmd <- Sys.which(Sys.getenv("PDFTK_PATH", "pdftk")) if (cmd == "") cmd <- Sys.which("pdftk-java") cmd } } supports_qpdf <- function() { requireNamespace("qpdf", quietly = TRUE) && !getOption("xmpdf_disable_qpdf", FALSE) } supports_pdftools <- function() { requireNamespace("pdftools", quietly = TRUE) && !getOption("xmpdf_disable_pdftools", FALSE) } gs <- function() { get_cmd("ghostscript", find_gs_cmd, install_gs_str) } pdftk <- function() { get_cmd("pdftk", find_pdftk_cmd, install_pdftk_str) } exiftool <- function() { get_cmd("exiftool", find_exiftool_cmd, install_exiftool_str) } get_cmd <- function(name, cmd_fn = function() Sys.which(name), msg_fn = function() install_cmd_str(name)) { cmd <- cmd_fn() if (cmd == "") abort(msg_fn(), class = "xmpdf_suggested_package") cmd }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/supports.R
# SPDX-License-Identifier: MIT get_exiftool_metadata <- function(filename, tags=NULL) { stopifnot(supports_exiftool()) filename <- normalizePath(filename, mustWork = TRUE) json_dir <- tempfile() on.exit(unlink(json_dir)) # Date format equivalent to R's "%Y-%m-%dT%H:%M:%S%z" args <- c(tags, "-G1", "-a", "-n", "-struct", "-j", "-w", stri_join(json_dir, "/%f.json"), filename) cmd <- exiftool() f_args <- tempfile(fileext = ".txt") on.exit(unlink(f_args)) brio::write_lines(args, f_args) args <- c("-@", shQuote(f_args)) if (length(cmd) == 2L) { # i.e. c("/path/to/perl", "path/to/exiftool") args <- c(cmd[-1L], args) cmd <- cmd[1L] } output <- xmpdf_system2(cmd, args) json_file <- list.files(json_dir, pattern = ".json", full.names = TRUE) if (length(json_file) == 0L) { # `exiftool` doesn't create json file if no metadata matching tags return(list()) } stopifnot(length(json_file) == 1L) jsonlite::fromJSON(brio::read_lines(json_file), simplifyDataFrame = FALSE)[[1]] } as_exif_value <- function(x, mode = "xmp") { if (inherits(x, c("datetimeoffset", "POSIXt"))) { datetimeoffset::format_exiftool(datetimeoffset::as_datetimeoffset(x), mode = mode) } else if (is.logical(x)) { n <- length(x) ifelse(x, rep_len("True", n), rep_len("False", n)) } else if (is.character(x)) { x } else { as.character(x) } } as_exif_name <- function(x, name) { if (inherits(x, "lang_alt")) { stri_join(name, "-", names(x)) } else { rep_len(name, length(x)) } } #' @param tags Named list of metadata tags to set #' @noRd set_exiftool_metadata <- function(tags, input, output = input, mode = "xmp") { stopifnot(supports_exiftool()) input <- normalizePath(input, mustWork = TRUE) output <- normalizePath(output, mustWork = FALSE) output_exists <- file.exists(output) if (output_exists) { target <- tempfile(fileext = stri_join(".", tools::file_ext(input))) on.exit(unlink(target)) } else { target <- output } nms <- character(0) values <- character(0) ops <- character(0) for (name in names(tags)) { value <- as_exif_value(tags[[name]], mode = mode) nm <- as_exif_name(tags[[name]], name) n <- length(value) values <- append(values, value) nms <- append(nms, nm) ops <- c(ops, rep_len("=", n)) } if (length(tags)) { args <- stri_join("-", nms, ops, values) # correctly handle any newlines if (any(gl <- grepl("\n", args))) { args <- ifelse(gl, stri_join("#[CSTR]", gsub("\n", "\\\\n", args)), args) } } else { args <- character(0) } args <- c(args, "-n", "-o", target, input) cmd <- exiftool() f <- tempfile(fileext = ".txt") on.exit(unlink(f)) brio::write_lines(args, f) args <- c("-@", shQuote(f)) if (length(cmd) == 2L) { # i.e. c("/path/to/perl", "path/to/exiftool") args <- c(cmd[-1L], args) cmd <- cmd[1L] } results <- xmpdf_system2(cmd, args) if (output_exists) file.copy(target, output, overwrite = TRUE) invisible(output) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/utils-exiftool.R
# SPDX-License-Identifier: MIT assert_suggested <- function(package) { calling_fn <- deparse(sys.calls()[[sys.nframe()-1]]) if (!requireNamespace(package, quietly = TRUE)) { msg <- c(sprintf("You need to install the suggested package %s to use %s.", sQuote(package), sQuote(calling_fn)), install_package_str(package)) abort(msg, class = "xmpdf_suggested_package") } } need_to_install_str <- function(fn_call) { c("!" = sprintf("You must install (only) one suggested R package or system command to use %s", sQuote(fn_call))) } install_package_str <- function(package) { c(x = sprintf("The suggested package %s is not installed", sQuote(package)), i = sQuote(sprintf('install.packages("%s")', package)) ) } install_cmd_str <- function(cmd) { c(x = sprintf("The system command %s is not installed (or detected)", sQuote(cmd))) } install_pdftk_str <- function() { c(install_cmd_str("pdftk"), i = "<https://gitlab.com/pdftk-java/pdftk> (Official)", i = paste(sQuote("sudo apt-get install pdftk-java"), "(Debian/Ubuntu)"), i = paste(sQuote("brew install pdftk-java"), "(Homebrew)"), i = paste(sQuote("choco install pdftk-java"), "(Chocolately)"), i = paste(sQuote('Sys.setenv(PDFTK_PATH = "/path/to/pdftk")'), "if installed but not detected on PATH") ) } install_gs_str <- function() { c(install_cmd_str("ghostscript"), i = "<https://www.ghostscript.com/releases/gsdnld.html> (Official)", i = paste(sQuote("sudo apt-get install ghostscript"), "(Debian/Ubuntu)"), i = paste(sQuote("brew install ghostscript"), "(Homebrew)"), i = paste(sQuote("choco install ghostscript"), "(Chocolately)"), i = paste(sQuote('Sys.setenv(R_GSCMD = "/path/to/gs")'), "if installed but not detected on PATH") ) } install_exiftool_str <- function() { c(install_cmd_str("exiftool"), i = "<https://exiftool.org/index.html> (Official)", i = paste(sQuote('install.packages("exiftoolr"); exiftoolr::install_exiftool()'), "(Cross-Platform)"), i = paste(sQuote("sudo apt-get install libimage-exiftool-perl"), "(Debian/Ubuntu)"), i = paste(sQuote("brew install exiftool"), "(Homebrew)"), i = paste(sQuote("choco install exiftool"), "(Chocolately)"), i = paste(sQuote('Sys.setenv(ET_EXIFTOOL_PATH = "/path/to/exiftool")'), "if installed but not detected on PATH") ) } use_filenames <- function(l, use_names, filename) { if (use_names) names(l) <- filename else names(l) <- NULL l } xmpdf_system2 <- function(cmd, args, stdout = TRUE) { output <- system2(cmd, args, stdout = stdout) if (!is.null(attr(output, "status"))) { msg <- c(paste(sQuote("system2()"), "command failed.")) abort(msg) } invisible(output) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/utils-misc.R
# SPDX-License-Identifier: MIT get_pdftk_metadata <- function(filename) { f <- tempfile(fileext = ".txt") on.exit(unlink(f)) cmd <- pdftk() filename <- shQuote(normalizePath(filename, mustWork = TRUE)) args <- c(filename, "dump_data_utf8", "output", f) results <- xmpdf_system2(cmd, args) brio::read_lines(f) }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/utils-pdftk.R
# SPDX-License-Identifier: MIT #' XMP metadata object #' #' `xmp()` creates an XMP metadata object. #' Such objects can be used with [set_xmp()] to edit XMP medata for a variety of media formats #' and such objects are returned by [get_xmp()]. #' #' @param alt_text Brief textual description that can be used as its "alt text" (XMP tag `Iptc4xmpCore:AltTextAccessibility`). #' Will be coerced by [as_lang_alt()]. #' Core IPTC photo metadata. #' @param attribution_name The name to be used when attributing the work (XMP tag `cc:attributionName`). #' Recommended by Creative Commons. #' If missing and `"cc:attributionName"` in `auto_xmp` and #' and `photoshop:Credit` non-missing will use that else if `dc:creator` non-missing #' then will automatically use `stringi::stri_join(creator, collapse = " and ")`. #' @param attribution_url The URL to be used when attributing the work (XMP tag `cc:attributionURL`). #' Recommended by Creative Commons. #' @param create_date The date the digital document was created (XMP tag `xmp:CreateDate`). #' Will be coerced by [datetimeoffset::as_datetimeoffset()]. #' Related pdf documentation info key is `CreationDate`. #' Not to be confused with `photoshop:DateCreated` which is the #' date the intellectual content was created. #' @param creator The document's author(s) (XMP tag `dc:creator`). #' Related pdf documentation info key is `Author`. #' Core IPTC photo metadata used by Google Photos. #' If `credit` is missing and `"photoshop:Credit"` in `auto_xmp` then #' we'll also use this for the `photoshop:Credit` XMP tag. #' @param creator_tool The name of the application that originally created the document (XMP tag `xmp:CreatorTool`). #' Related pdf documentation info key is `Creator`. #' @param credit Credit line field (XMP tag `photoshop:Credit`). #' Core IPTC photo metadata used by Google Photos. #' If missing and `"photoshop:Credit"` in `auto_xmp` and `dc:creator` non-missing #' then will automatically use `stringi::stri_join(creator, collapse = " and ")`. #' @param date_created The date the intellectual content was created (XMP tag `photoshop:DateCreated`). #' Will be coerced by [datetimeoffset::as_datetimeoffset()]. #' Core IPTC photo metadata. #' Not to be confused with `xmp:CreateDate` for when the digital document was created. #' @param description The document's subject (XMP tag `dc:description`). #' Will be coerced by [as_lang_alt()]. #' Core IPTC photo metadata. #' Related pdf documentation info key is `Subject`. #' @param ext_description An extended description (for accessibility) #' if the "alt text" is insufficient (XMP tag `Iptc4xmpCore:ExtDescrAccessibility`). #' Will be coerced by [as_lang_alt()]. #' Core IPTC photo metadata. #' @param headline A short synopsis of the document (XMP tag `photoshop:Headline`). #' Core IPTC photo metadata. #' @param keywords Character vector of keywords for this document (for cross-document searching). #' Related pdf documentation info key is `pdf:Keywords`. #' Will be coerced into a string by `stringi::stri_join(keywords, collapse = ", ")`. #' @param license The URL of (open source) license terms (XMP tag `cc:license`). #' Recommended by Creative Commons. #' Note `xmpRights:WebStatement` set in `web_statement` is a more popular XMP tag (e.g. used by Google Images) #' that can also hold the URL of license terms or a verifying web statement. #' If `cc:license` in `auto_xmp` and `spdx_id` is not `NULL` then #' we'll automatically use an URL from [spdx_licenses] corresponding to that license. #' @param marked Whether the document is a rights-managed resource (XMP tag `xmpRights:Marked`). #' Use `TRUE` if rights-managed, `FALSE` if public domain, and `NULL` if unknown. #' Creative Commons recommends setting this. #' If `xmpRights:Marked` in `auto_xmp` and `spdx_id` is not `NULL` then #' we can automatically set this for a subset of SPDX licenses (including all Creative Commons licenses). #' @param modify_date The date the document was last modified (XMP tag `xmp:ModifyDate`). #' Will be coerced by [datetimeoffset::as_datetimeoffset()]. #' Related pdf documentation info key is `ModDate`. #' @param more_permissions A URL for additional permissions beyond the `license` (XMP tag `cc:morePermissions`). #' Recommended by Creative Commons. #' Contrast with the `LicensorURL` property of `plus:Licensor` XMP tag. #' @param producer The name of the application that converted the document to pdf (XMP tag `pdf:Producer`). #' Related pdf documentation info key is `Producer`. #' @param rights (copy)right information about the document (XMP tag `dc:rights`). #' Will be coerced by [as_lang_alt()]. #' Core IPTC photo metadata used by Google Photos that Creative Commons also recommends setting. #' If `dc:rights` in `auto_xmp` and `creator` and `date_created` are not `NULL` then #' we can automatically generate a basic copyright statement with the help of `spdx_id`. #' @param subject List of description phrases, keywords, classification codes (XMP tag `dc:subject`). #' Core IPTC photo metadata. #' A character vector. #' Similar but less popular to the XMP tag `pdf:Keywords` which is a string. #' If `dc:subject` in `auto_xmp` and `keywords` is not NULL then we can #' automatically extract the keywords from it using `strsplit(keywords, ", ")[[1]]`. #' @param title The document's title (XMP tag `dc:title`). #' Will be coerced by [as_lang_alt()]. #' Related pdf documentation info key is `Title`. #' @param usage_terms A string describing legal terms of use for the document (XMP tag `xmpRights:UsageTerms`). #' Will be coerced by [as_lang_alt()]. #' Core IPTC photo metadata and recommended by Creative Commons. #' If `xmpRights:UsageTerms` in `auto_xmp` and `spdx_id` is not `NULL` then #' we can automatically set this with that license's name and URL. #' @param web_statement Web Statement of Rights (XMP tag `xmpRights:WebStatement`): #' a string of a full URL with license information about the page. #' If `xmpRights:WebStatement` in `auto_xmp` and `spdx_id` is not `NULL` then #' we'll automatically use an URL from [spdx_licenses] corresponding to that license. #' Core IPTC photo metadata used by Google Photos. #' Also recommended by Creative Commons (who also recommends using a "verifying" web statement). #' @param ... Entries of xmp metadata. The names are either the xmp tag names or alternatively the xmp namespace and tag names separated by ":". The values are the xmp values. #' @param spdx_id The id of a license in the SPDX license list. See [spdx_licenses]. #' @param auto_xmp Character vector of XMP metadata we should try to automatically determine #' if missing from other XMP metadata and `spdx_id`. #' @return An xmp object as can be used with [set_xmp()]. Basically a named list whose names are the (optional) xmp namespace and tag names separated by ":" and the values are the xmp values. #' Datetimes should be a datetime object such as [POSIXlt()]. #' @seealso [get_xmp()] and [set_xmp()] for getting/setting such information from/to a variety of media file formats. #' [as_xmp()] for coercing to this object. #' [as_docinfo()] can be used to coerce `xmp()` objects into [docinfo()] objects. #' @section `xmp` R6 Class Methods:\describe{ #' \item{`fig_process(..., auto = c("fig.alt", "fig.cap", "fig.scap"))`}{ #' Returns a function to embed XMP metadata suitable for use with #' `{knitr}`'s `fig.process` chunk option. #' `...` are local XMP metadata changes for this function. #' `auto` are which chunk options should be used to further update metadata values.} #' \item{`get_item(key)`}{Get XMP metadata value for key `key`. #' Can also use the relevant active bindings to get more common values.} #' \item{`print(mode = c("null_omit", "google_images", "creative_commons", "all"), xmp_only = FALSE)`}{ #' Print out XMP metadata values. If `mode` is "null_omit" print out #' which metadata would be embedded. If `mode` is "google images" print out #' values for the five fields Google Images uses. If `mode` is `creative_commons` #' print out the values for the fields Creative Commons recommends be set when #' using their licenses. If mode is `all` print out values for all #' XMP metadata that we provide active bindings for (even if `NULL`). #' If `xmp_only` is `TRUE` then don't print out `spdx_id` and `auto_xmp` values.} #' \item{`set_item(key, value)`}{Set XMP metadata key `key` with value `value`. #' Can also use the relevant active bindings to set XMP metadata values.} #' \item{`update(x)`}{Update XMP metadata entries #' using non-`NULL` entries in `x` coerced by [as_xmp()].} #' } #' @section `xmp` R6 Active Bindings:\describe{ #' \item{`alt_text`}{The image's alt text (accessibility).} #' \item{`attribution_name`}{The name to attribute the document.} #' \item{`attribution_url`}{The URL to attribute the document.} #' \item{`create_date`}{The date the document was created.} #' \item{`creator`}{The document's author.} #' \item{`creator_tool`}{The name of the application that originally created the document.} #' \item{`credit`}{Credit line.} #' \item{`date_created`}{The date the document's intellectual content was created} #' \item{`description`}{The document's description.} #' \item{`ext_description`}{An extended description for accessibility.} #' \item{`headline`}{A short synopsis of document.} #' \item{`keywords`}{String of keywords for this document (less popular than `subject`)).} #' \item{`license`}{URL of (open-source) license terms the document is licensed under.} #' \item{`marked`}{Boolean of whether this is a rights-managed document.} #' \item{`modify_date`}{The date the document was last modified.} #' \item{`more_permissions`}{URL for acquiring additional permissions beyond `license`.} #' \item{`producer`}{The name of the application that converted the document (to pdf).} #' \item{`rights`}{The document's copy(right) information.} #' \item{`subject`}{Vector of key phrases/words/codes for this document (more popular than `keywords`)).} #' \item{`title`}{The document's title.} #' \item{`usage_terms`}{The document's rights usage terms.} #' \item{`web_statement`}{A URL string for the web statement of rights for the document.} #' \item{`spdx_id`}{The id of a license in the SPDX license list. See [spdx_licenses].} #' \item{`auto_xmp`}{Character vector of XMP metadata we should try to automatically determine #' if missing from other XMP metadata and `spdx_id`.} #' } #' #' @section XMP tag recommendations: #' #' * <https://exiftool.org/TagNames/XMP.html> recommends "dc", "xmp", "Iptc4xmpCore", and "Iptc4xmpExt" schemas if possible #' * <https://github.com/adobe/xmp-docs/tree/master/XMPNamespaces> are descriptions of some common XMP tags #' * <https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata#xmp-namespaces-and-identifiers> is popular for photos #' * <https://developers.google.com/search/docs/appearance/structured-data/image-license-metadata#iptc-photo-metadata> are the subset of IPTC photo metadata which Google Photos uses (if no structured data on web page) #' * <https://wiki.creativecommons.org/wiki/XMP> are Creative Commons license recommendations #' #' @examples #' x <- xmp(attribution_url = "https://example.com/attribution", #' creator = "John Doe", #' description = "An image caption", #' date_created = Sys.Date(), #' spdx_id = "CC-BY-4.0") #' print(x) #' print(x, mode = "google_images", xmp_only = TRUE) #' print(x, mode = "creative_commons", xmp_only = TRUE) #' #' if (supports_set_xmp() && #' supports_get_xmp() && #' capabilities("png") && #' requireNamespace("grid", quietly = TRUE)) { #' #' f <- tempfile(fileext = ".png") #' png(f) #' grid::grid.text("This is an image!") #' invisible(dev.off()) #' set_xmp(x, f) #' print(get_xmp(f)[[1]]) #' } #' @name xmp #' @export xmp <- function(..., alt_text = NULL, attribution_name = NULL, attribution_url = NULL, create_date = NULL, creator = NULL, creator_tool = NULL, credit = NULL, date_created = NULL, description = NULL, ext_description = NULL, headline = NULL, keywords = NULL, license = NULL, marked = NULL, modify_date = NULL, more_permissions = NULL, producer = NULL, rights = NULL, subject = NULL, title = NULL, usage_terms = NULL, web_statement = NULL, auto_xmp = c("cc:attributionName", "cc:license", "dc:rights", "dc:subject", "photoshop:Credit", "xmpRights:Marked", "xmpRights:UsageTerms", "xmpRights:WebStatement"), spdx_id = NULL) { Xmp$new(..., creator = creator, description = description, rights = rights, subject = subject, title = title, # dc keywords = keywords, producer = producer, # pdf attribution_name = attribution_name, attribution_url = attribution_url, #cc license = license, more_permissions = more_permissions, alt_text = alt_text, ext_description = ext_description, # Iptc4xmpCore credit = credit, date_created = date_created, headline = headline, # photoshop create_date = create_date, creator_tool = creator_tool, modify_date = modify_date, # xmp marked = marked, usage_terms = usage_terms, web_statement = web_statement, # xmpRights spdx_id = spdx_id, auto_xmp = auto_xmp) } Xmp <- R6Class("xmp", public = list( initialize = function(...) { l <- list(...) for (key in names(l)) { value <- l[[key]] if (!is.null(value)) self$set_item(key, l[[key]]) } invisible(NULL) }, print = function(mode = c("null_omit", "google_images", "creative_commons", "all"), xmp_only = FALSE) { mode <- match.arg(mode) text <- character(0) tags <- switch(mode, google_images = c("dc:creator", "dc:rights", "photoshop:Credit", "xmpRights:WebStatement"), creative_commons = c("cc:attributionName", "cc:attributionURL", "cc:license", "cc:morePermissions", "dc:rights", "xmpRights:Marked", "xmpRights:UsageTerms", "xmpRights:WebStatement"), sort(c(KNOWN_XMP_TAGS, names(private$tags$other)))) for (key in tags) { value <- self$get_item(key) if (is.null(value) && mode == "null_omit") next if (private$is_auto(key)) text <- append(text, stri_join("=> ", key, " = ", x_format(value))) else text <- append(text, stri_join(" ", key, " := ", x_format(value))) } if (length(text)) { if (mode == "google_images") { text <- c(text[1:3], "X plus:Licensor (not currently supported by {xmpdf})", text[4]) } if (!xmp_only) { if (length(self$auto_xmp)) text <- c(stri_join("i auto_xmp (not XMP tag) := ", x_format(self$auto_xmp)), text) if (!is.null(self$spdx_id)) text <- c(stri_join("i spdx_id (not XMP tag) := ", x_format(self$spdx_id)), text) } invisible(cat(text, sep="\n")) } else { invisible(cat("No XMP metadata found\n")) } }, fig_process = function(..., auto = c("fig.alt", "fig.cap", "fig.scap")) { x <- update(self, ...) function(path, options) { if ("fig.alt" %in% auto && !is.null(options[["fig.alt"]])) x$alt_text <- options[["fig.alt"]] if ("fig.cap" %in% auto && !is.null(options[["fig.cap"]])) x$description <- options[["fig.cap"]] if ("fig.scap" %in% auto && !is.null(options[["fig.scap"]])) x$headline <- options[["fig.scap"]] xmpdf::set_xmp(x, path) invisible(path) } }, get_item = function(key) { lkey <- tolower(key) if (lkey %in% c("attribution_name", "attributionname", "cc:attributionname")) { self$attribution_name } else if (lkey %in% c("attribution_url", "attributionurl", "cc:attributionurl")) { self$attribution_url } else if (lkey %in% c("license", "cc:license")) { self$license } else if (lkey %in% c("creator", "dc:creator")) { self$creator } else if (lkey %in% c("description", "dc:description")) { self$description } else if (lkey %in% c("subject", "dc:subject")) { self$subject } else if (lkey %in% c("rights", "dc:rights")) { self$rights } else if (lkey %in% c("title", "dc:title")) { self$title } else if (lkey %in% c("alt_text", "alttextaccessibility", "iptccore:alttextaccessibility", "iptc4xmpcore:alttextaccessibility")) { self$alt_text } else if (lkey %in% c("ext_description", "extdescraccessibility", "iptccore:extdescraccessibility", "iptc4xmpcore:extdescraccessibility")) { self$ext_description } else if (lkey %in% c("producer", "pdf:producer")) { self$producer } else if (lkey %in% c("keywords", "pdf:keywords")) { self$keywords } else if (lkey %in% c("credit", "photoshop:credit")) { self$credit } else if (lkey %in% c("date_created", "datecreated", "photoshop:datecreated")) { self$date_created } else if (lkey %in% c("headline", "photoshop:headline")) { self$headline } else if (lkey %in% c("create_date", "createdate", "xmp:createdate")) { self$create_date } else if (lkey %in% c("creator_tool", "creatortool", "xmp:creatortool")) { self$creator_tool } else if (lkey %in% c("modify_date", "modifydate", "xmp:modifydate")) { self$modify_date } else if (lkey %in% c("marked", "xmprights:marked")) { self$marked } else if (lkey %in% c("more_permissions", "morepermissions", "cc:morepermissions")) { self$more_permissions } else if (lkey %in% c("usage_terms", "usageterms", "xmprights:usageterms")) { self$usage_terms } else if (lkey %in% c("web_statement", "webstatement", "xmprights:webstatement")) { self$web_statement } else if (lkey %in% c("spdx_id")) { self$spdx_id } else if (lkey %in% c("auto_xmp")) { self$auto_xmp } else { private$tags$other[[key]] } }, set_item = function(key, value) { lkey <- tolower(key) if (lkey %in% c("attribution_name", "attributionname", "cc:attributionname")) { self$attribution_name <- value } else if (lkey %in% c("attribution_url", "attributionurl", "cc:attributionurl")) { self$attribution_url <- value } else if (lkey %in% c("license", "cc:license")) { self$license <- value } else if (lkey %in% c("more_permissions", "morepermissions", "cc:morepermissions")) { self$more_permissions <- value } else if (lkey %in% c("creator", "dc:creator")) { self$creator <- value } else if (lkey %in% c("description", "dc:description")) { self$description <- value } else if (lkey %in% c("rights", "dc:rights")) { self$rights <- value } else if (lkey %in% c("subject", "dc:subject")) { self$subject <- value } else if (lkey %in% c("title", "dc:title")) { self$title <- value } else if (lkey %in% c("alt_text", "alttextaccessibility", "iptc4xmpcore:alttextaccessibility")) { self$alt_text <- value } else if (lkey %in% c("ext_description", "extdescraccessibility", "iptccore:extdescraccessibility", "iptc4xmpcore:extdescraccessibility")) { self$ext_description <- value } else if (lkey %in% c("producer", "pdf:producer")) { self$producer <- value } else if (lkey %in% c("keywords", "pdf:keywords")) { self$keywords <- value } else if (lkey %in% c("credit", "photoshop:credit")) { self$credit <- value } else if (lkey %in% c("date_created", "datecreated", "photoshop:datecreated")) { self$date_created <- value } else if (lkey %in% c("headline", "photoshop:headline")) { self$headline <- value } else if (lkey %in% c("create_date", "createdate", "xmp:createdate")) { self$create_date <- value } else if (lkey %in% c("creator_tool", "creatortool", "xmp:creatortool")) { self$creator_tool <- value } else if (lkey %in% c("modify_date", "modifydate", "xmp:modifydate")) { self$modify_date <- value } else if (lkey %in% c("marked", "xmprights:marked")) { self$marked <- value } else if (lkey %in% c("usage_terms", "usageterms", "xmprights:usageterms")) { self$usage_terms <- value } else if (lkey %in% c("web_statement", "webstatement", "xmprights:webstatement")) { self$web_statement <- value } else if (lkey %in% c("spdx_id")) { self$spdx_id <- value } else if (lkey %in% c("auto_xmp")) { self$auto_xmp <- value } else { private$tags$other[[key]] <- value } }, update = function(x) { x <- as_xmp(x) for (key in x$get_nonnull_keys()) self$set_item(key, x$get_item(key)) invisible(NULL) }, exiftool_tags = function() { tags <- list() if (!is.null(self$alt_text)) tags[["XMP-iptcCore:AltTextAccessibility"]] <- self$alt_text if (!is.null(self$attribution_name)) tags[["XMP-cc:attributionName"]] <- self$attribution_name if (!is.null(self$attribution_url)) tags[["XMP-cc:attributionURL"]] <- self$attribution_url if (!is.null(self$creator)) tags[["XMP-dc:creator"]] <- self$creator if (!is.null(self$create_date)) tags[["XMP-xmp:CreateDate"]] <- self$create_date if (!is.null(self$creator_tool)) tags[["XMP-xmp:CreatorTool"]] <- self$creator_tool if (!is.null(self$credit)) tags[["XMP-photoshop:Credit"]] <- self$credit if (!is.null(self$date_created)) tags[["XMP-photoshop:DateCreated"]] <- self$date_created if (!is.null(self$headline)) tags[["XMP-photoshop:Headline"]] <- self$headline if (!is.null(self$description)) tags[["XMP-dc:description"]] <- self$description if (!is.null(self$ext_description)) tags[["XMP-iptcCore:ExtDescrAccessibility"]] <- self$ext_description if (!is.null(self$keywords)) tags[["XMP-pdf:Keywords"]] <- self$keywords if (!is.null(self$license)) tags[["XMP-cc:license"]] <- self$license if (!is.null(self$marked)) tags[["XMP-xmpRights:Marked"]] <- self$marked if (!is.null(self$modify_date)) tags[["XMP-xmp:ModifyDate"]] <- self$modify_date if (!is.null(self$more_permissions)) tags[["XMP-cc:morePermissions"]] <- self$more_permissions if (!is.null(self$producer)) tags[["XMP-pdf:Producer"]] <- self$producer if (!is.null(self$rights)) tags[["XMP-dc:rights"]] <- self$rights if (!is.null(self$subject)) tags[["XMP-dc:subject"]] <- self$subject if (!is.null(self$title)) tags[["XMP-dc:title"]] <- self$title if (!is.null(self$usage_terms)) tags[["XMP-xmpRights:UsageTerms"]] <- self$usage_terms if (!is.null(self$web_statement)) tags[["XMP-xmpRights:WebStatement"]] <- self$web_statement for (key in names(private$tags$other)) { ekey <- gsub("Iptc4xmp", "iptc", key) ekey <- stri_join("XMP-", ekey) tags[[ekey]] <- private$tags$other[[key]] #### more formatting needed? } tags }, get_nonnull_keys = function() { keys <- character(0) if (!is.null(private$tags$alt_text)) keys <- append(keys, "Iptc4xmpCore:AltTextAccessibility") if (!is.null(private$tags$attribution_name)) keys <- append(keys, "cc:attributionName") if (!is.null(private$tags$attribution_url)) keys <- append(keys, "cc:attributionURL") if (!is.null(private$tags$creator)) keys <- append(keys, "dc:creator") if (!is.null(private$tags$create_date)) keys <- append(keys, "xmp:CreateDate") if (!is.null(private$tags$creator_tool)) keys <- append(keys, "xmp:CreatorTool") if (!is.null(private$tags$date_created)) keys <- append(keys, "photoshop:DateCreated") if (!is.null(private$tags$description)) keys <- append(keys, "dc:description") if (!is.null(private$tags$ext_description)) keys <- append(keys, "Iptc4xmpCore:ExtDescrAccessibility") if (!is.null(private$tags$headline)) keys <- append(keys, "photoshop:Headline") if (!is.null(private$tags$keywords)) keys <- append(keys, "pdf:Keywords") if (!is.null(private$tags$license)) keys <- append(keys, "cc:license") if (!is.null(private$tags$marked)) keys <- append(keys, "xmpRights:Marked") if (!is.null(private$tags$modify_date)) keys <- append(keys, "xmp:ModifyDate") if (!is.null(private$tags$more_permissions)) keys <- append(keys, "cc:morePermissions") if (!is.null(private$tags$producer)) keys <- append(keys, "pdf:Producer") if (!is.null(private$tags$rights)) keys <- append(keys, "dc:rights") if (!is.null(private$tags$subject)) keys <- append(keys, "dc:subject") if (!is.null(private$tags$title)) keys <- append(keys, "dc:title") if (!is.null(private$tags$usage_terms)) keys <- append(keys, "xmpRights:UsageTerms") if (!is.null(private$tags$web_statement)) keys <- append(keys, "xmpRights:WebStatement") keys <- append(keys, names(private$tags$other)) if (!is.null(self$spdx_id)) keys <- append(keys, "spdx_id") keys } ), active = list( alt_text = function(value) private$active_helper("alt_text", value, as_la_value), attribution_name = function(value) { if (missing(value)) { value <- private$tags$attribution_name if (is.null(value) && "cc:attributionName" %in% self$auto_xmp) value <- private$auto_credit() value } else { private$tags$attribution_name <- as_character_value(value) } }, attribution_url = function(value) private$active_helper("attribution_url", value, as_url_value), creator = function(value) private$active_helper("creator", value), create_date = function(value) private$active_helper("create_date", value, as_datetime_value), creator_tool = function(value) private$active_helper("creator_tool", value), credit = function(value) { if (missing(value)) { value <- private$tags$credit if (is.null(value) && "photoshop:Credit" %in% self$auto_xmp) value <- private$auto_credit() value } else { private$tags$credit <- as_character_value(value) } }, date_created = function(value) private$active_helper("date_created", value, as_datetime_value), description = function(value) private$active_helper("description", value, as_la_value), ext_description = function(value) private$active_helper("ext_description", value, as_la_value), headline = function(value) private$active_helper("headline", value), keywords = function(value) { if (missing(value)) private$tags$keywords else private$tags$keywords <- stri_join(value, collapse = ", ") }, license = function(value) { if (missing(value)) { value <- private$tags$license if (is.null(value) && "cc:license" %in% self$auto_xmp) value <- private$auto_spdx_url() value } else { private$tags$license <- as_url_value(value) } }, marked = function(value) { if (missing(value)) { value <- private$tags$marked if (is.null(value) && "xmpRights:Marked" %in% self$auto_xmp && !is.null(private$tags$spdx_id)) { value <- !xmpdf::spdx_licenses[self$spdx_id, "pd"] if (is.na(value)) value <- NULL } value } else { private$tags$marked <- as_logical_value(value) } }, modify_date = function(value) private$active_helper("modify_date", value, as_datetime_value), more_permissions = function(value) private$active_helper("more_permissions", value, as_url_value), producer = function(value) private$active_helper("producer", value), rights = function(value) { if (missing(value)) { value <- private$tags$rights if (is.null(value) && "dc:rights" %in% self$auto_xmp) value <- private$auto_rights() value } else { private$tags$rights <- as_la_value(value) } }, subject = function(value) { if (missing(value)) { value <- private$tags$subject if (is.null(value) && "dc:subject" %in% self$auto_xmp) { if (!is.null(private$tags$keywords)) value <- strsplit(private$tags$keywords, ", ")[[1]] } value } else { private$tags$subject <- as_character_value(value) } }, title = function(value) private$active_helper("title", value, as_la_value), usage_terms = function(value) { if (missing(value)) { value <- private$tags$usage_terms if (is.null(value) && "xmpRights:UsageTerms" %in% self$auto_xmp) value <- private$auto_usage_terms() value } else { private$tags$usage_terms <- as_la_value(value) } }, web_statement = function(value) { if (missing(value)) { value <- private$tags$web_statement if (is.null(value) && "xmpRights:WebStatement" %in% self$auto_xmp) value <- private$auto_spdx_url() value } else { private$tags$web_statement <- as_url_value(value) } }, spdx_id = function(value) { if (missing(value)) { private$tags$spdx_id } else { stopifnot(value %in% xmpdf::spdx_licenses$id) private$tags$spdx_id <- as_character_value(value) } }, auto_xmp = function(value) private$active_helper("auto_xmp", value) ), private = list( is_auto = function(key) { lkey <- tolower(key) if (lkey %in% c("attribution_name", "attributionname", "cc:attributionname")) { is.null(private$tags$attribution_name) } else if (lkey %in% c("credit", "photoshop:credit")) { is.null(private$tags$credit) } else if (lkey %in% c("license", "cc:license")) { is.null(private$tags$license) } else if (lkey %in% c("marked", "xmprights:marked")) { is.null(private$tags$marked) } else if (lkey %in% c("rights", "dc:rights")) { is.null(private$tags$rights) } else if (lkey %in% c("subject", "dc:subject")) { is.null(private$tags$subject) } else if (lkey %in% c("usage_terms", "usageterms", "xmprights:usageterms")) { is.null(private$tags$usage_terms) } else if (lkey %in% c("web_statement", "webstatement", "xmprights:webstatement")) { is.null(private$tags$web_statement) } else { FALSE } }, active_helper = function(key, value, as_fn = as_character_value) { if (missing(value)) private$tags[[key]] else private$tags[[key]] <- as_fn(value) }, auto_credit = function() { value <- private$tags$credit if (is.null(value) && !is.null(private$tags[["creator"]])) value <- stri_join(private$tags[["creator"]], collapse = " and ") value }, auto_rights = function() { #### Update if/when we support plus:CopyrightOwner value <- NULL if (!is.null(private$tags$creator) && !is.null(private$tags$date_created)) { owner <- stri_join(private$tags$creator, collapse = " and ") year <- datetimeoffset::format_iso8601(private$tags$date_created, precision = "year") if (is.null(self$spdx_id)) { value <- stri_join("\u00a9 ", year, " ", owner, ". All rights reserved.") } else if (isTRUE(xmpdf::spdx_licenses[self$spdx_id, "pd"])) { value <- "In the public domain. No rights reserved." } else { value <- stri_join("\u00a9 ", year, " ", owner, ". Some rights reserved.") } } value }, auto_spdx_url = function() { if (!is.null(private$tags$spdx_id)) { url <- xmpdf::spdx_licenses[self$spdx_id, "url_alt"] if (is.na(url)) url <- xmpdf::spdx_licenses[self$spdx_id, "url"] url } else { NULL } }, auto_usage_terms = function() { value <- NULL if (!is.null(private$tags$spdx_id)) { name <- xmpdf::spdx_licenses[self$spdx_id, "name"] url <- xmpdf::spdx_licenses[self$spdx_id, "url_alt"] if (is.na(url)) url <- xmpdf::spdx_licenses[self$spdx_id, "url"] value <- stri_join("This work is licensed to the public under the ", name, " license ", url) } value }, tags = list(other = list()) ) ) x_format <- function(value) { value <- d_format(value) stri_join(strwrap(value, exdent = 8L), collapse = "\n") } KNOWN_XMP_TAGS <- c("cc:attributionName", "cc:attributionURL", "cc:license", "cc:morePermissions", "dc:creator", "dc:description", "dc:rights", "dc:subject", "dc:title", "Iptc4xmpCore:AltTextAccessibility", "Iptc4xmpCore:ExtDescrAccessibility", "pdf:Keywords", "pdf:Producer", "photoshop:Credit", "photoshop:DateCreated", "photoshop:Headline", "xmp:CreateDate", "xmp:CreatorTool", "xmp:ModifyDate", "xmpRights:Marked", "xmpRights:UsageTerms", "xmpRights:WebStatement") #' @export update.xmp <- function(object, ...) { x <- object$clone() x$update(as_xmp(list(...))) x } as_la_value <- function(value) { if (is.null(value)) NULL else as_lang_alt(value) } as_logical_value <- function(value) { if (is.null(value)) NULL else as.logical(value) } #### Throw error if not a proper URL? as_url_value <- function(value) { if (is.null(value)) NULL else value }
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/xmp.R
#' @section Package options: #' The following `xmpdf` option may be set globally via [base::options()]: #' \describe{ #' \item{xmpdf_default_lang}{Set new default `default_lang` argument value for [as_lang_alt()].} #' } #' @name xmpdf "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/xmpdf-package.R
# SPDX-License-Identifier: MIT #' @importFrom rlang abort inform warn %||% #' @importFrom utils hasName #' @importFrom R6 R6Class #' @importFrom stringi stri_join NULL
/scratch/gouwar.j/cran-all/cranData/xmpdf/R/zzz.R
## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10", spdx_id = "CC-BY-4.0") print(x) ## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10", spdx_id = "CC-BY-4.0") x$auto_xmp <- base::setdiff(x$auto_xmp, c("dc:rights", "photoshop:Credit")) print(x) ## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10") x$rights <- "© 2023 A Corporation. Some rights reserved." print(x) ## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp() x$set_item("dc:contributor", c("John Doe", "Jane Doe")) x$get_item("dc:contributor") ## ----------------------------------------------------------------------------- library("datetimeoffset") library("xmpdf") transcript <- c(en = "An English Transcript", fr = "Une transcription française") |> as_lang_alt(default_lang = "en") last_edited <- "2020-02-04T10:10:10" |> as_datetimeoffset() x <- xmp() x$set_item("Iptc4xmpExt:Transcript", transcript) x$set_item("Iptc4xmpExt:IPTCLastEdited", last_edited) ## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "google_images", xmp_only = TRUE) ## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "creative_commons", xmp_only = TRUE) ## ----------------------------------------------------------------------------- library("xmpdf") x <- xmp() x$description <- "Description in only one default language" x$title <- c(en = "An English Title", fr = "Une titre française") # XMP tags without an active binding must be manually coerced by `as_lang_alt` transcript <- c(en = "An English Transcript", fr = "Une transcription française") |> as_lang_alt(default_lang = "en") x$set_item("Iptc4xmpExt:Transcript", transcript)
/scratch/gouwar.j/cran-all/cranData/xmpdf/inst/doc/xmp.R
--- title: "XMP FAQ" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{XMP FAQ} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ### Table of Contents * [How do I adjust the automatic guessing of missing XMP tags?](#auto) * [Which XMP tags have an active binding?](#active) * [How do I get or set XMP tags without an active binding?](#nonactive) * [What XMP tags are used to display informaton on Google Images?](#google) * [Which tags should I use for Creative Commons license information?](#cc) * [How do I embed XMP metadata in multiple languages?](#language) * [How do I enter in a "structured" tag?](#structure) * [Is there an easy way to embed XMP metadata when using {knitr}?](#knitr) * [What are some helpful XMP external links?](#links) ## <a name="auto">How do I adjust the automatic guessing of missing XMP tags?</a> The `auto_xmp` active binding for `xmp()` objects is a character vector of XMP tags that if missing `{xmpdf}` will try to automatically guess based on values of other XMP tags and the `spdx_id` active binding ([SPDX License List Identifer](https://spdx.org/licenses/)). When printing `xmp()` objects one can observe which XMP tags are guessed because they'll have a `=>` on their left. ```{r} library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10", spdx_id = "CC-BY-4.0") print(x) ``` If you remove an XMP tag from `auto_xmp` then `{xmpdf}` will no longer try to guess it: ```{r} library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10", spdx_id = "CC-BY-4.0") x$auto_xmp <- base::setdiff(x$auto_xmp, c("dc:rights", "photoshop:Credit")) print(x) ``` Alternatively you could explicitly set a missing XMP tag (which then would no longer need to be guessed): ```{r} library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10") x$rights <- "© 2023 A Corporation. Some rights reserved." print(x) ``` ## <a name="active">Which XMP tags have an active binding?</a> XMP tags with an active binding in `xmp()` objects will automatically be coerced into the right data type and are a little easier to get/set than XMP tags without an active binding. Here is a list of current active bindings provided by `xmp()` objects: | Active Binding | XMP tag | |---|---| | `alt_text` | `Iptc4xmpCore:AltTextAccessibility` | | `attribution_name` | `cc:attributionName` | | `attribution_url` | `cc:attributionURL` | | `create_date` | `xmp:CreateDate` | | `creator` | `dc:creator` | | `creator_tool` | `xmp:CreatorTool` | | `credit` | `photoshop:Credit` | | `date_created` | `photoshop:DateCreated` | | `description` | `dc:description` | | `ext_description` | `Iptc4xmpCore:ExtDescrAccessibility` | | `headline` | `photoshop:Headline` | | `keywords` | `pdf:Keywords` | | `license` | `cc:license` | | `marked` | `xmpRights:Marked` | | `modify_date` | `xmp:ModifyDate` | | `more_permissions` | `cc:morePermissions` | | `producer` | `pdf:Producer` | | `rights` | `dc:rights` | | `subject` | `dc:subject` | | `title` | `dc:title` | | `usage_terms` | `xmpRights:UsageTerms` | | `web_statement` | `xmpRights:WebStatement` | ## <a name="nonactive">How do I get or set XMP tags without an active binding?</a> If you want to set an XMP tag without an active binding you must use the `xmp()` objects `set_item()` method. To get an XMP without an active binding you must use the `xmp()` objects `get_item()` method. You may also use `get_item()` and `set_item()` for XMP tags with an active binding as well. ```{r} library("xmpdf") x <- xmp() x$set_item("dc:contributor", c("John Doe", "Jane Doe")) x$get_item("dc:contributor") ``` Depending on the value type of the XMP tag you may need to manually coerce it to a special R class: | XMP value type | R function to coerce | |---|---| | date | `datetimeoffset::as_datetimeoffset()` | | lang-alt | `xmpdf::as_lang_alt()` | ```{r} library("datetimeoffset") library("xmpdf") transcript <- c(en = "An English Transcript", fr = "Une transcription française") |> as_lang_alt(default_lang = "en") last_edited <- "2020-02-04T10:10:10" |> as_datetimeoffset() x <- xmp() x$set_item("Iptc4xmpExt:Transcript", transcript) x$set_item("Iptc4xmpExt:IPTCLastEdited", last_edited) ``` ## <a name="google">What XMP tags are used to display informaton on Google Images?</a> Google Images can show more details about an image when [certain metadata is specified](https://developers.google.com/search/docs/appearance/structured-data/image-license-metadata): 1) Structured data on the web page the image appears (takes priority over XMP tags if defined) 2) XMP tags embedded in the image * `dc:creator` * `photoshop:Credit` * `dc:rights` * `xmpRights:WebStatement` * the `Licensor URL` subfield of `plus:Licensor` structured XMP tag `xmp()` object's `print(mode = "google_images")` will tell what the Google Images XMP tags metadata would be: ```{r} library("xmpdf") x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "google_images", xmp_only = TRUE) ``` ## <a name="cc">Which tags should I use for Creative Commons license information?</a> [Creative Commons recommends](https://wiki.creativecommons.org/wiki/XMP) you specify the following XMP tags to indicate your license information: * `dc:rights` * `xmpRight:Marked` * `xmpRights:WebStatement` * `xmpRights:UsageTerms` * `cc:license` * `cc:morePermissions` * `cc:attributionURL` * `cc:attributionName` `xmp()` object's `print(mode = "creative_commons")` will tell what this XMP tags metadata would be: ```{r} library("xmpdf") x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "creative_commons", xmp_only = TRUE) ``` ## <a name="language">How do I embed XMP metadata in multiple languages?</a> Although some XMP metadata tags must be a string in a single language but some XMP metadata tags support ["language alternative aka "lang-alt"](https://github.com/adobe/xmp-docs/blob/master/XMPNamespaces/XMPDataTypes/CoreProperties.md#language-alternative) values which allow values for multiple languages to be specified: * `Iptc4xmpCore:AltTextAccessibility` * `dc:description` * `Iptc4xmpCore:ExtDescrAccessibility` * `dc:rights` * `dc:title` * `xmpRights:UsageTerms` * Plus [other XMP tags](https://exiftool.org/TagNames/XMP.html) which will need to be manually coerced by `as_lang_alt()` and set with the `xmp()` object's `set_item()` method See `?as_lang_alt` for more details but essentially create a character vector or list and name the entries with an RFC 3066 name tag. ```{r} library("xmpdf") x <- xmp() x$description <- "Description in only one default language" x$title <- c(en = "An English Title", fr = "Une titre française") # XMP tags without an active binding must be manually coerced by `as_lang_alt` transcript <- c(en = "An English Transcript", fr = "Une transcription française") |> as_lang_alt(default_lang = "en") x$set_item("Iptc4xmpExt:Transcript", transcript) ``` ## <a name="structure">How do I enter in a "structured" tag?</a> Currently `{xmpdf}` does not officially support entering in "struct" XMP tags (although it does support "lang-alt" tags and simple lists of basic XMP value types). If necessary you'll need to use an external program such as [exiftool](https://exiftool.org/) (perhaps via [{exiftoolr}](https://github.com/JoshOBrien/exiftoolr)) to [embed structured](https://exiftool.org/struct.html) XMP tags. ## <a name="knitr">Is there an easy way to embed XMP metadata when using {knitr}?</a> `{knitr}` supports the [chunk option](https://yihui.org/knitr/options/#plots) `fig.process` which accepts a function to post-process figure files. The first argument should be a path to the figure file and may optionally accept an `options` argument which will receive a list of chunk options. It should return a (possibly new) path to be inserted in the output. `xmp()` objects have a `fig_process()` method which return a **function** that can be used for this `fig.process` option to embed XMP metadat into images. Depending on the strings in its `auto` argument this function will also automatically map the following `{knitr}` chunk options to XMP tags: * `fig.cap` to `dc:description` * `fig.scap` to `photoshop:Headline` * `fig.alt` to `Iptc4xmpCore:AltTextAccessibility` ```Rmd .. {r setup, echo=FALSE} x <- xmpdf::xmp(creator = "John Doe", date_created = "2023", spdx_id = "CC-BY-4.0", attribution_url = "https://example.com/attribution") knitr::opts_chunk$set(fig.process = x$fig_process()) .. .. ``` ## <a name="links">What are some helpful XMP external links?</a> * [IPTC Photo Metadata Standard](https://iptc.org/standards/photo-metadata/iptc-standard/) (IPTC) is a popular XMP metadata standard for photos * [Quick guide to IPTC Photo Metadata on Google Images](https://iptc.org/standards/photo-metadata/quick-guide-to-iptc-photo-metadata-and-google-images/) (IPTC) describes the subset of the IPTC Photo Metadata Standard used by Google Photos to list photo credits and license information * [xmp-docs](https://github.com/adobe/xmp-docs/tree/master/XMPNamespaces) (Adobe) describes some common XMP tags * [XMP](https://wiki.creativecommons.org/wiki/XMP) (Creative Commons) describes a standard for using XMP to embed Creative Commons license information * [XMP tags](https://exiftool.org/TagNames/XMP.html) (exiftool) is a fairly comprehensive list of XMP tags
/scratch/gouwar.j/cran-all/cranData/xmpdf/inst/doc/xmp.Rmd
--- title: "Introduction to xmpdf" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to xmpdf} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ### Table of Contents * [Overview](#overview) * [Installation](#installation) * [Examples](#examples) + [Add XMP/docinfo metadata and bookmarks to a pdf](#pdfcreate) + [Add Google Images and Creative Commons license XMP metadata to a png image](#pnglicense) + [Concatenate pdf files and embed concatenated bookmarks](#pdfcat) * [Limitations by backend](#comparison) * [External links](#links) + [Metadata links](#standards) + [Related software](#similar) ## <a name="overview">Overview</a> `{xmpdf}` provides functions for getting and setting [Extensibe Metadata Platform (XMP)](https://en.wikipedia.org/wiki/Extensible_Metadata_Platform) metadata in a variety of media file formats as well as getting and setting PDF [documentation info](https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#document-info-dictionary-docinfo) entries and [bookmarks](https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#bookmarks-out) (aka outline aka table of contents). ## <a name="installation">Installation</a> Depending on what you'd like to do you'll need to install some additional R packages and/or command-line tools: * **[{qpdf}](https://cran.r-project.org/package=qpdf)** can be used to concatenate pdf files together as well as get the number of pages in a pdf. Note currently a dependency of [{pdftools}](https://docs.ropensci.org/pdftools/). + `install.packages("qpdf")` * **[{pdftools}](https://docs.ropensci.org/pdftools/)** can be used to get bookmarks and documentation info entries in pdf files. Note currently depends on [{qpdf}](https://cran.r-project.org/package=qpdf). + `install.packages("pdftools")` will probably install `{qpdf}` as well * **[exiftool](https://exiftool.org/)** can be used to get/set xmp metadata in a variety of media files as well as documentation info entries in pdf files. Can also be used to get the number of pages in a pdf. Note can be installed by [{exiftoolr}](https://github.com/JoshOBrien/exiftoolr). + `install.packages("exiftoolr"); exiftoolr::install_exiftool()` (Cross-Platform) + `sudo apt-get install libimage-exiftool-perl` (Debian/Ubuntu) + `brew install exiftool` (Homebrew) + `choco install exiftool` (Chocolately) * **[ghostscript](https://www.ghostscript.com/)** can be used to set bookmarks and documentation info entries in pdf files. Can also be used to concatenate pdf files together as well as get the number of pages in a pdf. + `sudo apt-get install ghostscript` (Debian/Ubuntu) + `brew install ghostscript` (Homebrew) + `choco install ghostscript` (Chocolately) * **[pdftk-java](https://gitlab.com/pdftk-java/pdftk)** or perhaps **[pdftk](https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/)** can be used to get/set bookmarks and documentation info entries in pdf files. Can also be used to concatenate pdf files together as well as get the number of pages in a pdf. + `sudo apt-get install pdftk-java` (Debian/Ubuntu) + `brew install pdftk-java` (Homebrew) + `choco install pdftk-java` (Chocolately) ## <a name="examples">Examples</a> ### <a name="pdfcreate">Add XMP/docinfo metadata and bookmarks to a pdf</a> A simple example where we create a two page pdf using `pdf()` and then add XMP metadata, PDF documentation info metadata, and PDF bookmarks to it: ```r library("xmpdf") # Create a two page pdf using `pdf()` f <- tempfile(fileext = ".pdf") pdf(f, onefile = TRUE) grid::grid.text("Page 1") grid::grid.newpage() grid::grid.text("Page 2") invisible(dev.off()) # See what default metadata `pdf()` created get_docinfo(f)[[1]] |> print() ``` ``` ## Author: NULL ## CreationDate: 2024-03-27T23:15:55 ## Creator: R ## Producer: R 4.3.3 ## Title: R Graphics Output ## Subject: NULL ## Keywords: NULL ## ModDate: 2024-03-27T23:15:55 ``` ```r get_xmp(f)[[1]] |> print() ``` ``` ## No XMP metadata found ``` ```r get_bookmarks(f)[[1]] |> print() ``` ``` ## [1] title page level count open color fontface ## <0 rows> (or 0-length row.names) ``` ```r # Edit PDF documentation info d <- get_docinfo(f)[[1]] |> update(author = "John Doe", subject = "A minimal document to demonstrate {xmpdf} features on", title = "Two Boring Pages", keywords = c("R", "xmpdf")) set_docinfo(d, f) get_docinfo(f)[[1]] |> print() ``` ``` ## Author: John Doe ## CreationDate: 2024-03-27T23:15:55 ## Creator: R ## Producer: R 4.3.3 ## Title: Two Boring Pages ## Subject: A minimal document to demonstrate {xmpdf} features on ## Keywords: R, xmpdf ## ModDate: 2024-03-27T23:15:55 ``` ```r # Edit XMP metadata x <- as_xmp(d) |> update(attribution_url = "https://example.com/attribution", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") set_xmp(x, f) get_xmp(f)[[1]] |> print() ``` ``` ## cc:attributionName := John Doe ## cc:attributionURL := https://example.com/attribution ## cc:license := https://creativecommons.org/licenses/by/4.0/ ## dc:creator := John Doe ## dc:description := A minimal document to demonstrate {xmpdf} features on ## dc:rights := © 2024 John Doe. Some rights reserved. ## dc:subject := R, xmpdf ## dc:title := Two Boring Pages ## pdf:Keywords := R, xmpdf ## pdf:Producer := R 4.3.3 ## photoshop:Credit := John Doe ## photoshop:DateCreated := 2024-03-27 ## x:XMPToolkit := Image::ExifTool 12.40 ## xmp:CreateDate := 2024-03-27T23:15:55 ## xmp:CreatorTool := R ## xmp:ModifyDate := 2024-03-27T23:15:55 ## xmpRights:Marked := TRUE ## xmpRights:UsageTerms := This work is licensed to the public under the Creative Commons ## Attribution 4.0 International license ## https://creativecommons.org/licenses/by/4.0/ ## xmpRights:WebStatement := https://creativecommons.org/licenses/by/4.0/ ``` ```r # Edit PDF bookmarks bm <- data.frame(title = c("Page 1", "Page 2"), page = c(1, 2)) set_bookmarks(bm, f) get_bookmarks(f)[[1]] |> print() ``` ``` ## title page level count open color fontface ## 1 Page 1 1 1 NA NA <NA> <NA> ## 2 Page 2 2 1 NA NA <NA> <NA> ``` ### <a name="pnglicense">Add Google Images and Creative Commons license XMP metadata to a png image</a> Besides pdf files with `exiftool` we can also edit the XMP metadata for [a large number of image formats](https://exiftool.org/#supported) including "gif", "png", "jpeg", "tiff", and "webp". In particular we may be interested in setting the subset of [IPTC Photo XMP metadata displayed by Google Images](https://iptc.org/standards/photo-metadata/quick-guide-to-iptc-photo-metadata-and-google-images/) as well as embedding [Creative Commons license XMP metadata](https://wiki.creativecommons.org/wiki/XMP). ```r library("xmpdf") f <- tempfile(fileext = ".png") png(f) grid::grid.text("This is an image!") dev.off() |> invisible() get_xmp(f)[[1]] |> print() ``` ``` ## No XMP metadata found ``` ```r x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "google_images", xmp_only = TRUE) ``` ``` ## dc:creator := John Doe ## => dc:rights = © 2024 John Doe. Some rights reserved. ## => photoshop:Credit = John Doe ## X plus:Licensor (not currently supported by {xmpdf}) ## => xmpRights:WebStatement = https://creativecommons.org/licenses/by/4.0/ ``` ```r print(x, mode = "creative_commons", xmp_only = TRUE) ``` ``` ## => cc:attributionName = John Doe ## cc:attributionURL := https://example.com/attribution ## => cc:license = https://creativecommons.org/licenses/by/4.0/ ## cc:morePermissions := NULL ## => dc:rights = © 2024 John Doe. Some rights reserved. ## => xmpRights:Marked = TRUE ## => xmpRights:UsageTerms = This work is licensed to the public under the Creative Commons ## Attribution 4.0 International license ## https://creativecommons.org/licenses/by/4.0/ ## => xmpRights:WebStatement = https://creativecommons.org/licenses/by/4.0/ ``` ```r set_xmp(x, f) get_xmp(f)[[1]] |> print() ``` ``` ## cc:attributionName := John Doe ## cc:attributionURL := https://example.com/attribution ## cc:license := https://creativecommons.org/licenses/by/4.0/ ## dc:creator := John Doe ## dc:description := An image caption ## dc:rights := © 2024 John Doe. Some rights reserved. ## photoshop:Credit := John Doe ## photoshop:DateCreated := 2024-03-27 ## x:XMPToolkit := Image::ExifTool 12.40 ## xmpRights:Marked := TRUE ## xmpRights:UsageTerms := This work is licensed to the public under the Creative Commons ## Attribution 4.0 International license ## https://creativecommons.org/licenses/by/4.0/ ## xmpRights:WebStatement := https://creativecommons.org/licenses/by/4.0/ ``` ### <a name="pdfcat">Concatenate pdf files and embed concatenated bookmarks</a> ```r # Create two multi-page pdfs and add bookmarks to them f_a <- tempfile(fileext = ".pdf") pdf(f_a, title = "Document A", onefile = TRUE) grid::grid.text("Document A: First Page") grid::grid.newpage() grid::grid.text("Document A: Second Page") dev.off() |> invisible() f_b <- tempfile(fileext = ".pdf") pdf(f_b, title = "Document B", onefile = TRUE) grid::grid.text("Document B: First Page") grid::grid.newpage() grid::grid.text("Document B: Second Page") dev.off() |> invisible() bm <- data.frame(title = c("First Page", "Second Page"), page = c(1, 2)) set_bookmarks(bm, f_a) set_bookmarks(bm, f_b) # Concatenate pdfs to a single pdf and add their concatenated bookmarks to it files <- c(f_a, f_b) f_cat <- tempfile(fileext = ".pdf") cat_pages(files, f_cat) cat_bookmarks(get_bookmarks(files), method = "title") |> set_bookmarks(f_cat) print(get_bookmarks(f_cat)[[1]]) ``` ``` ## title page level count open color fontface ## 1 Document A 1 1 NA NA <NA> <NA> ## 2 First Page 1 2 NA NA <NA> <NA> ## 3 Second Page 2 2 NA NA <NA> <NA> ## 4 Document B 3 1 NA NA <NA> <NA> ## 5 First Page 3 2 NA NA <NA> <NA> ## 6 Second Page 4 2 NA NA <NA> <NA> ``` ## <a name="comparison">Limitations by backend</a> `{xmpdf}` feature | `exiftool` | `pdftk` | `ghostscript` ---|---|---|---| Get XMP metadata | **Yes** | **No** | **No** Set XMP metadata | **Yes** | **No** | **Poor**: when documentation info metadata is set then as a side effect it seems the documentation info metadata will also be set as XMP metadata Get PDF bookmarks | **No** | **Okay**: can only get Title, Page number, and Level | **No** Set PDF bookmarks | **No** | **Okay**: can only set Title, Page number, and Level | **Good**: supports most bookmarks features including color and font face but only action supported is to view a particular page Get PDF documentation info | **Good**: may "widen" datetimes which are less than "second" precision | **Yes** | **No** Set PDF documentation info | **Yes** | **Good**: may not handle entries with newlines in them | **Yes**: as a side effect when documentation info metadata is set then it seems will also be set as XMP metadata Concatenate PDF files | **No** | **Yes** | **Yes** Known limitations: * `get_bookmarks_pdftk()` doesn't report information about bookmarks color, font face, and whether the bookmarks should start open or closed. * `get_bookmarks_pdftools()`'s doesn't report information about bookmarks pages, color, font face, and whether the bookmarks * `get_docinfo_exiftool()` "widens" datetimes to second precision. An hour-only UTC offset will be "widened" to minute precision. * `get_docinfo_pdftools()`'s datetimes may not accurately reflect the embedded datetimes. * `set_bookmarks_gs()` supports most bookmarks features including color and font face but only action supported is to view a particular page. * `set_bookmarks_pdftk()` only supports setting the title, page number, and level of bookmarks. * `set_docinfo_pdftk()` may not handle entries with newlines in them. * `set_bookmarks_pdftk()` and `set_docinfo_pdftk()` may not successfully write Unicode metadata in a non-Unicode locale. * All of the `set_docinfo()` methods currently do not support arbitrary info dictionary entries. * As a side effect `set_docinfo_gs()` seems to also update any matching XPN metadata while `set_docinfo_exiftool()` and `set_docinfo_pdftk()` don't update any previously set matching XPN metadata. Some pdf viewers will preferentially use the previously set document title from XPN metadata if it exists instead of using the title set in documentation info dictionary entry. Consider also manually setting this XPN metadata using `set_xmp()` * Old metadata information is usually not deleted from the files by these operations (i.e. these operations are often theoretically reversible). If deleting the old metadata is important one may want to consider calling `qpdf::pdf_compress(input, linearize = TRUE)` at the end. ## <a name="links">External links</a> ### <a name="standards">Metadata links</a> * [basic pdfmark features](https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#) (Adobe) documents "Documentation info dictionary" metadata and "Bookmarks" * [IPTC Photo Metadata Standard](https://iptc.org/standards/photo-metadata/iptc-standard/) (IPTC) is a popular XMP metadata standard for photos * [Quick guide to IPTC Photo Metadata on Google Images](https://iptc.org/standards/photo-metadata/quick-guide-to-iptc-photo-metadata-and-google-images/) (IPTC) describes the subset of the IPTC Photo Metadata Standard used by Google Photos to list photo credits and license information * [xmp-docs](https://github.com/adobe/xmp-docs/tree/master/XMPNamespaces) (Adobe) describes some common XMP tags * [XMP](https://wiki.creativecommons.org/wiki/XMP) (Creative Commons) describes a standard for using XMP to embed Creative Commons license information * [XMP tags](https://exiftool.org/TagNames/XMP.html) (exiftool) is a fairly comprehensive list of XMP tags ### <a name="similar">Related software</a> Note most of the R packages listed below are focused on **getting** metadata rather than **setting** metadata and/or only provide low-level wrappers around the relevant command-line tools. Please feel free to [open a pull request to add any missing relevant R packages](https://github.com/trevorld/r-xmpdf/edit/main/README.Rmd). #### exempi * [exempi](https://libopenraw.freedesktop.org/exempi/) #### exiftool * [{exifr}](https://github.com/paleolimbot/exifr) provides a high-level wrapper to read metadata as well as a low-level wrapper around the `exiftool` command-line tool. Can download `exiftool`. * [{exiftoolr}](https://github.com/JoshOBrien/exiftoolr) provides high-level wrapper to read metadata as well as a low-level wrapper around the `exiftool` command-line tool. Can download `exiftool`. * [exiftool](https://exiftool.org/) #### exiv2 * [{exiv}](https://github.com/hrbrmstr/exiv) read and write ‘Exif’, ‘ID3v1’ and ‘ID3v2’ image/media tags * [exiv2](https://github.com/Exiv2/exiv2) #### other exif tools * [{exif}](https://github.com/Ironholds/exif) reads EXIF from jpeg images * [{magick}](https://github.com/ropensci/magick) has `image_attributes()` which reads EXIF image tags. #### ghostscript * `{tools}` has `find_gs_cmd()` to find a GhostScript executable in a cross-platform way. * [ghostscript](https://www.ghostscript.com/) #### poppler * [{pdftools}](https://docs.ropensci.org/pdftools/) * [{Rpoppler}](https://cran.r-project.org/package=Rpoppler) * [poppler](https://poppler.freedesktop.org/) #### qpdf * [{qpdf}](https://cran.r-project.org/package=qpdf) * [qpdf](https://qpdf.sourceforge.io/) #### pdftk * [{animation}](https://yihui.org/animation/) has `pdftk()`, a low-level wrapper around the `pdftk` command-line tool. * [pdftk](https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/) * [pdftk-java](https://gitlab.com/pdftk-java/pdftk) #### tabula * [{tabulizer}](https://github.com/ropensci/tabulizer) * [tabula-java](https://github.com/tabulapdf/tabula-java/) #### xpdf * [xpdf](http://www.xpdfreader.com/about.html)'s `pdfinfo` tool
/scratch/gouwar.j/cran-all/cranData/xmpdf/inst/doc/xmpdf.Rmd
--- title: "XMP FAQ" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{XMP FAQ} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ### Table of Contents * [How do I adjust the automatic guessing of missing XMP tags?](#auto) * [Which XMP tags have an active binding?](#active) * [How do I get or set XMP tags without an active binding?](#nonactive) * [What XMP tags are used to display informaton on Google Images?](#google) * [Which tags should I use for Creative Commons license information?](#cc) * [How do I embed XMP metadata in multiple languages?](#language) * [How do I enter in a "structured" tag?](#structure) * [Is there an easy way to embed XMP metadata when using {knitr}?](#knitr) * [What are some helpful XMP external links?](#links) ## <a name="auto">How do I adjust the automatic guessing of missing XMP tags?</a> The `auto_xmp` active binding for `xmp()` objects is a character vector of XMP tags that if missing `{xmpdf}` will try to automatically guess based on values of other XMP tags and the `spdx_id` active binding ([SPDX License List Identifer](https://spdx.org/licenses/)). When printing `xmp()` objects one can observe which XMP tags are guessed because they'll have a `=>` on their left. ```{r} library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10", spdx_id = "CC-BY-4.0") print(x) ``` If you remove an XMP tag from `auto_xmp` then `{xmpdf}` will no longer try to guess it: ```{r} library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10", spdx_id = "CC-BY-4.0") x$auto_xmp <- base::setdiff(x$auto_xmp, c("dc:rights", "photoshop:Credit")) print(x) ``` Alternatively you could explicitly set a missing XMP tag (which then would no longer need to be guessed): ```{r} library("xmpdf") x <- xmp(creator = "John Doe", date_created = "2023-02-10") x$rights <- "© 2023 A Corporation. Some rights reserved." print(x) ``` ## <a name="active">Which XMP tags have an active binding?</a> XMP tags with an active binding in `xmp()` objects will automatically be coerced into the right data type and are a little easier to get/set than XMP tags without an active binding. Here is a list of current active bindings provided by `xmp()` objects: | Active Binding | XMP tag | |---|---| | `alt_text` | `Iptc4xmpCore:AltTextAccessibility` | | `attribution_name` | `cc:attributionName` | | `attribution_url` | `cc:attributionURL` | | `create_date` | `xmp:CreateDate` | | `creator` | `dc:creator` | | `creator_tool` | `xmp:CreatorTool` | | `credit` | `photoshop:Credit` | | `date_created` | `photoshop:DateCreated` | | `description` | `dc:description` | | `ext_description` | `Iptc4xmpCore:ExtDescrAccessibility` | | `headline` | `photoshop:Headline` | | `keywords` | `pdf:Keywords` | | `license` | `cc:license` | | `marked` | `xmpRights:Marked` | | `modify_date` | `xmp:ModifyDate` | | `more_permissions` | `cc:morePermissions` | | `producer` | `pdf:Producer` | | `rights` | `dc:rights` | | `subject` | `dc:subject` | | `title` | `dc:title` | | `usage_terms` | `xmpRights:UsageTerms` | | `web_statement` | `xmpRights:WebStatement` | ## <a name="nonactive">How do I get or set XMP tags without an active binding?</a> If you want to set an XMP tag without an active binding you must use the `xmp()` objects `set_item()` method. To get an XMP without an active binding you must use the `xmp()` objects `get_item()` method. You may also use `get_item()` and `set_item()` for XMP tags with an active binding as well. ```{r} library("xmpdf") x <- xmp() x$set_item("dc:contributor", c("John Doe", "Jane Doe")) x$get_item("dc:contributor") ``` Depending on the value type of the XMP tag you may need to manually coerce it to a special R class: | XMP value type | R function to coerce | |---|---| | date | `datetimeoffset::as_datetimeoffset()` | | lang-alt | `xmpdf::as_lang_alt()` | ```{r} library("datetimeoffset") library("xmpdf") transcript <- c(en = "An English Transcript", fr = "Une transcription française") |> as_lang_alt(default_lang = "en") last_edited <- "2020-02-04T10:10:10" |> as_datetimeoffset() x <- xmp() x$set_item("Iptc4xmpExt:Transcript", transcript) x$set_item("Iptc4xmpExt:IPTCLastEdited", last_edited) ``` ## <a name="google">What XMP tags are used to display informaton on Google Images?</a> Google Images can show more details about an image when [certain metadata is specified](https://developers.google.com/search/docs/appearance/structured-data/image-license-metadata): 1) Structured data on the web page the image appears (takes priority over XMP tags if defined) 2) XMP tags embedded in the image * `dc:creator` * `photoshop:Credit` * `dc:rights` * `xmpRights:WebStatement` * the `Licensor URL` subfield of `plus:Licensor` structured XMP tag `xmp()` object's `print(mode = "google_images")` will tell what the Google Images XMP tags metadata would be: ```{r} library("xmpdf") x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "google_images", xmp_only = TRUE) ``` ## <a name="cc">Which tags should I use for Creative Commons license information?</a> [Creative Commons recommends](https://wiki.creativecommons.org/wiki/XMP) you specify the following XMP tags to indicate your license information: * `dc:rights` * `xmpRight:Marked` * `xmpRights:WebStatement` * `xmpRights:UsageTerms` * `cc:license` * `cc:morePermissions` * `cc:attributionURL` * `cc:attributionName` `xmp()` object's `print(mode = "creative_commons")` will tell what this XMP tags metadata would be: ```{r} library("xmpdf") x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "creative_commons", xmp_only = TRUE) ``` ## <a name="language">How do I embed XMP metadata in multiple languages?</a> Although some XMP metadata tags must be a string in a single language but some XMP metadata tags support ["language alternative aka "lang-alt"](https://github.com/adobe/xmp-docs/blob/master/XMPNamespaces/XMPDataTypes/CoreProperties.md#language-alternative) values which allow values for multiple languages to be specified: * `Iptc4xmpCore:AltTextAccessibility` * `dc:description` * `Iptc4xmpCore:ExtDescrAccessibility` * `dc:rights` * `dc:title` * `xmpRights:UsageTerms` * Plus [other XMP tags](https://exiftool.org/TagNames/XMP.html) which will need to be manually coerced by `as_lang_alt()` and set with the `xmp()` object's `set_item()` method See `?as_lang_alt` for more details but essentially create a character vector or list and name the entries with an RFC 3066 name tag. ```{r} library("xmpdf") x <- xmp() x$description <- "Description in only one default language" x$title <- c(en = "An English Title", fr = "Une titre française") # XMP tags without an active binding must be manually coerced by `as_lang_alt` transcript <- c(en = "An English Transcript", fr = "Une transcription française") |> as_lang_alt(default_lang = "en") x$set_item("Iptc4xmpExt:Transcript", transcript) ``` ## <a name="structure">How do I enter in a "structured" tag?</a> Currently `{xmpdf}` does not officially support entering in "struct" XMP tags (although it does support "lang-alt" tags and simple lists of basic XMP value types). If necessary you'll need to use an external program such as [exiftool](https://exiftool.org/) (perhaps via [{exiftoolr}](https://github.com/JoshOBrien/exiftoolr)) to [embed structured](https://exiftool.org/struct.html) XMP tags. ## <a name="knitr">Is there an easy way to embed XMP metadata when using {knitr}?</a> `{knitr}` supports the [chunk option](https://yihui.org/knitr/options/#plots) `fig.process` which accepts a function to post-process figure files. The first argument should be a path to the figure file and may optionally accept an `options` argument which will receive a list of chunk options. It should return a (possibly new) path to be inserted in the output. `xmp()` objects have a `fig_process()` method which return a **function** that can be used for this `fig.process` option to embed XMP metadat into images. Depending on the strings in its `auto` argument this function will also automatically map the following `{knitr}` chunk options to XMP tags: * `fig.cap` to `dc:description` * `fig.scap` to `photoshop:Headline` * `fig.alt` to `Iptc4xmpCore:AltTextAccessibility` ```Rmd .. {r setup, echo=FALSE} x <- xmpdf::xmp(creator = "John Doe", date_created = "2023", spdx_id = "CC-BY-4.0", attribution_url = "https://example.com/attribution") knitr::opts_chunk$set(fig.process = x$fig_process()) .. .. ``` ## <a name="links">What are some helpful XMP external links?</a> * [IPTC Photo Metadata Standard](https://iptc.org/standards/photo-metadata/iptc-standard/) (IPTC) is a popular XMP metadata standard for photos * [Quick guide to IPTC Photo Metadata on Google Images](https://iptc.org/standards/photo-metadata/quick-guide-to-iptc-photo-metadata-and-google-images/) (IPTC) describes the subset of the IPTC Photo Metadata Standard used by Google Photos to list photo credits and license information * [xmp-docs](https://github.com/adobe/xmp-docs/tree/master/XMPNamespaces) (Adobe) describes some common XMP tags * [XMP](https://wiki.creativecommons.org/wiki/XMP) (Creative Commons) describes a standard for using XMP to embed Creative Commons license information * [XMP tags](https://exiftool.org/TagNames/XMP.html) (exiftool) is a fairly comprehensive list of XMP tags
/scratch/gouwar.j/cran-all/cranData/xmpdf/vignettes/xmp.Rmd
--- title: "Introduction to xmpdf" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to xmpdf} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ### Table of Contents * [Overview](#overview) * [Installation](#installation) * [Examples](#examples) + [Add XMP/docinfo metadata and bookmarks to a pdf](#pdfcreate) + [Add Google Images and Creative Commons license XMP metadata to a png image](#pnglicense) + [Concatenate pdf files and embed concatenated bookmarks](#pdfcat) * [Limitations by backend](#comparison) * [External links](#links) + [Metadata links](#standards) + [Related software](#similar) ## <a name="overview">Overview</a> `{xmpdf}` provides functions for getting and setting [Extensibe Metadata Platform (XMP)](https://en.wikipedia.org/wiki/Extensible_Metadata_Platform) metadata in a variety of media file formats as well as getting and setting PDF [documentation info](https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#document-info-dictionary-docinfo) entries and [bookmarks](https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#bookmarks-out) (aka outline aka table of contents). ## <a name="installation">Installation</a> Depending on what you'd like to do you'll need to install some additional R packages and/or command-line tools: * **[{qpdf}](https://cran.r-project.org/package=qpdf)** can be used to concatenate pdf files together as well as get the number of pages in a pdf. Note currently a dependency of [{pdftools}](https://docs.ropensci.org/pdftools/). + `install.packages("qpdf")` * **[{pdftools}](https://docs.ropensci.org/pdftools/)** can be used to get bookmarks and documentation info entries in pdf files. Note currently depends on [{qpdf}](https://cran.r-project.org/package=qpdf). + `install.packages("pdftools")` will probably install `{qpdf}` as well * **[exiftool](https://exiftool.org/)** can be used to get/set xmp metadata in a variety of media files as well as documentation info entries in pdf files. Can also be used to get the number of pages in a pdf. Note can be installed by [{exiftoolr}](https://github.com/JoshOBrien/exiftoolr). + `install.packages("exiftoolr"); exiftoolr::install_exiftool()` (Cross-Platform) + `sudo apt-get install libimage-exiftool-perl` (Debian/Ubuntu) + `brew install exiftool` (Homebrew) + `choco install exiftool` (Chocolately) * **[ghostscript](https://www.ghostscript.com/)** can be used to set bookmarks and documentation info entries in pdf files. Can also be used to concatenate pdf files together as well as get the number of pages in a pdf. + `sudo apt-get install ghostscript` (Debian/Ubuntu) + `brew install ghostscript` (Homebrew) + `choco install ghostscript` (Chocolately) * **[pdftk-java](https://gitlab.com/pdftk-java/pdftk)** or perhaps **[pdftk](https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/)** can be used to get/set bookmarks and documentation info entries in pdf files. Can also be used to concatenate pdf files together as well as get the number of pages in a pdf. + `sudo apt-get install pdftk-java` (Debian/Ubuntu) + `brew install pdftk-java` (Homebrew) + `choco install pdftk-java` (Chocolately) ## <a name="examples">Examples</a> ### <a name="pdfcreate">Add XMP/docinfo metadata and bookmarks to a pdf</a> A simple example where we create a two page pdf using `pdf()` and then add XMP metadata, PDF documentation info metadata, and PDF bookmarks to it: ```r library("xmpdf") # Create a two page pdf using `pdf()` f <- tempfile(fileext = ".pdf") pdf(f, onefile = TRUE) grid::grid.text("Page 1") grid::grid.newpage() grid::grid.text("Page 2") invisible(dev.off()) # See what default metadata `pdf()` created get_docinfo(f)[[1]] |> print() ``` ``` ## Author: NULL ## CreationDate: 2024-03-27T23:15:55 ## Creator: R ## Producer: R 4.3.3 ## Title: R Graphics Output ## Subject: NULL ## Keywords: NULL ## ModDate: 2024-03-27T23:15:55 ``` ```r get_xmp(f)[[1]] |> print() ``` ``` ## No XMP metadata found ``` ```r get_bookmarks(f)[[1]] |> print() ``` ``` ## [1] title page level count open color fontface ## <0 rows> (or 0-length row.names) ``` ```r # Edit PDF documentation info d <- get_docinfo(f)[[1]] |> update(author = "John Doe", subject = "A minimal document to demonstrate {xmpdf} features on", title = "Two Boring Pages", keywords = c("R", "xmpdf")) set_docinfo(d, f) get_docinfo(f)[[1]] |> print() ``` ``` ## Author: John Doe ## CreationDate: 2024-03-27T23:15:55 ## Creator: R ## Producer: R 4.3.3 ## Title: Two Boring Pages ## Subject: A minimal document to demonstrate {xmpdf} features on ## Keywords: R, xmpdf ## ModDate: 2024-03-27T23:15:55 ``` ```r # Edit XMP metadata x <- as_xmp(d) |> update(attribution_url = "https://example.com/attribution", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") set_xmp(x, f) get_xmp(f)[[1]] |> print() ``` ``` ## cc:attributionName := John Doe ## cc:attributionURL := https://example.com/attribution ## cc:license := https://creativecommons.org/licenses/by/4.0/ ## dc:creator := John Doe ## dc:description := A minimal document to demonstrate {xmpdf} features on ## dc:rights := © 2024 John Doe. Some rights reserved. ## dc:subject := R, xmpdf ## dc:title := Two Boring Pages ## pdf:Keywords := R, xmpdf ## pdf:Producer := R 4.3.3 ## photoshop:Credit := John Doe ## photoshop:DateCreated := 2024-03-27 ## x:XMPToolkit := Image::ExifTool 12.40 ## xmp:CreateDate := 2024-03-27T23:15:55 ## xmp:CreatorTool := R ## xmp:ModifyDate := 2024-03-27T23:15:55 ## xmpRights:Marked := TRUE ## xmpRights:UsageTerms := This work is licensed to the public under the Creative Commons ## Attribution 4.0 International license ## https://creativecommons.org/licenses/by/4.0/ ## xmpRights:WebStatement := https://creativecommons.org/licenses/by/4.0/ ``` ```r # Edit PDF bookmarks bm <- data.frame(title = c("Page 1", "Page 2"), page = c(1, 2)) set_bookmarks(bm, f) get_bookmarks(f)[[1]] |> print() ``` ``` ## title page level count open color fontface ## 1 Page 1 1 1 NA NA <NA> <NA> ## 2 Page 2 2 1 NA NA <NA> <NA> ``` ### <a name="pnglicense">Add Google Images and Creative Commons license XMP metadata to a png image</a> Besides pdf files with `exiftool` we can also edit the XMP metadata for [a large number of image formats](https://exiftool.org/#supported) including "gif", "png", "jpeg", "tiff", and "webp". In particular we may be interested in setting the subset of [IPTC Photo XMP metadata displayed by Google Images](https://iptc.org/standards/photo-metadata/quick-guide-to-iptc-photo-metadata-and-google-images/) as well as embedding [Creative Commons license XMP metadata](https://wiki.creativecommons.org/wiki/XMP). ```r library("xmpdf") f <- tempfile(fileext = ".png") png(f) grid::grid.text("This is an image!") dev.off() |> invisible() get_xmp(f)[[1]] |> print() ``` ``` ## No XMP metadata found ``` ```r x <- xmp(attribution_url = "https://example.com/attribution", creator = "John Doe", description = "An image caption", date_created = Sys.Date(), spdx_id = "CC-BY-4.0") print(x, mode = "google_images", xmp_only = TRUE) ``` ``` ## dc:creator := John Doe ## => dc:rights = © 2024 John Doe. Some rights reserved. ## => photoshop:Credit = John Doe ## X plus:Licensor (not currently supported by {xmpdf}) ## => xmpRights:WebStatement = https://creativecommons.org/licenses/by/4.0/ ``` ```r print(x, mode = "creative_commons", xmp_only = TRUE) ``` ``` ## => cc:attributionName = John Doe ## cc:attributionURL := https://example.com/attribution ## => cc:license = https://creativecommons.org/licenses/by/4.0/ ## cc:morePermissions := NULL ## => dc:rights = © 2024 John Doe. Some rights reserved. ## => xmpRights:Marked = TRUE ## => xmpRights:UsageTerms = This work is licensed to the public under the Creative Commons ## Attribution 4.0 International license ## https://creativecommons.org/licenses/by/4.0/ ## => xmpRights:WebStatement = https://creativecommons.org/licenses/by/4.0/ ``` ```r set_xmp(x, f) get_xmp(f)[[1]] |> print() ``` ``` ## cc:attributionName := John Doe ## cc:attributionURL := https://example.com/attribution ## cc:license := https://creativecommons.org/licenses/by/4.0/ ## dc:creator := John Doe ## dc:description := An image caption ## dc:rights := © 2024 John Doe. Some rights reserved. ## photoshop:Credit := John Doe ## photoshop:DateCreated := 2024-03-27 ## x:XMPToolkit := Image::ExifTool 12.40 ## xmpRights:Marked := TRUE ## xmpRights:UsageTerms := This work is licensed to the public under the Creative Commons ## Attribution 4.0 International license ## https://creativecommons.org/licenses/by/4.0/ ## xmpRights:WebStatement := https://creativecommons.org/licenses/by/4.0/ ``` ### <a name="pdfcat">Concatenate pdf files and embed concatenated bookmarks</a> ```r # Create two multi-page pdfs and add bookmarks to them f_a <- tempfile(fileext = ".pdf") pdf(f_a, title = "Document A", onefile = TRUE) grid::grid.text("Document A: First Page") grid::grid.newpage() grid::grid.text("Document A: Second Page") dev.off() |> invisible() f_b <- tempfile(fileext = ".pdf") pdf(f_b, title = "Document B", onefile = TRUE) grid::grid.text("Document B: First Page") grid::grid.newpage() grid::grid.text("Document B: Second Page") dev.off() |> invisible() bm <- data.frame(title = c("First Page", "Second Page"), page = c(1, 2)) set_bookmarks(bm, f_a) set_bookmarks(bm, f_b) # Concatenate pdfs to a single pdf and add their concatenated bookmarks to it files <- c(f_a, f_b) f_cat <- tempfile(fileext = ".pdf") cat_pages(files, f_cat) cat_bookmarks(get_bookmarks(files), method = "title") |> set_bookmarks(f_cat) print(get_bookmarks(f_cat)[[1]]) ``` ``` ## title page level count open color fontface ## 1 Document A 1 1 NA NA <NA> <NA> ## 2 First Page 1 2 NA NA <NA> <NA> ## 3 Second Page 2 2 NA NA <NA> <NA> ## 4 Document B 3 1 NA NA <NA> <NA> ## 5 First Page 3 2 NA NA <NA> <NA> ## 6 Second Page 4 2 NA NA <NA> <NA> ``` ## <a name="comparison">Limitations by backend</a> `{xmpdf}` feature | `exiftool` | `pdftk` | `ghostscript` ---|---|---|---| Get XMP metadata | **Yes** | **No** | **No** Set XMP metadata | **Yes** | **No** | **Poor**: when documentation info metadata is set then as a side effect it seems the documentation info metadata will also be set as XMP metadata Get PDF bookmarks | **No** | **Okay**: can only get Title, Page number, and Level | **No** Set PDF bookmarks | **No** | **Okay**: can only set Title, Page number, and Level | **Good**: supports most bookmarks features including color and font face but only action supported is to view a particular page Get PDF documentation info | **Good**: may "widen" datetimes which are less than "second" precision | **Yes** | **No** Set PDF documentation info | **Yes** | **Good**: may not handle entries with newlines in them | **Yes**: as a side effect when documentation info metadata is set then it seems will also be set as XMP metadata Concatenate PDF files | **No** | **Yes** | **Yes** Known limitations: * `get_bookmarks_pdftk()` doesn't report information about bookmarks color, font face, and whether the bookmarks should start open or closed. * `get_bookmarks_pdftools()`'s doesn't report information about bookmarks pages, color, font face, and whether the bookmarks * `get_docinfo_exiftool()` "widens" datetimes to second precision. An hour-only UTC offset will be "widened" to minute precision. * `get_docinfo_pdftools()`'s datetimes may not accurately reflect the embedded datetimes. * `set_bookmarks_gs()` supports most bookmarks features including color and font face but only action supported is to view a particular page. * `set_bookmarks_pdftk()` only supports setting the title, page number, and level of bookmarks. * `set_docinfo_pdftk()` may not handle entries with newlines in them. * `set_bookmarks_pdftk()` and `set_docinfo_pdftk()` may not successfully write Unicode metadata in a non-Unicode locale. * All of the `set_docinfo()` methods currently do not support arbitrary info dictionary entries. * As a side effect `set_docinfo_gs()` seems to also update any matching XPN metadata while `set_docinfo_exiftool()` and `set_docinfo_pdftk()` don't update any previously set matching XPN metadata. Some pdf viewers will preferentially use the previously set document title from XPN metadata if it exists instead of using the title set in documentation info dictionary entry. Consider also manually setting this XPN metadata using `set_xmp()` * Old metadata information is usually not deleted from the files by these operations (i.e. these operations are often theoretically reversible). If deleting the old metadata is important one may want to consider calling `qpdf::pdf_compress(input, linearize = TRUE)` at the end. ## <a name="links">External links</a> ### <a name="standards">Metadata links</a> * [basic pdfmark features](https://opensource.adobe.com/dc-acrobat-sdk-docs/library/pdfmark/pdfmark_Basic.html#) (Adobe) documents "Documentation info dictionary" metadata and "Bookmarks" * [IPTC Photo Metadata Standard](https://iptc.org/standards/photo-metadata/iptc-standard/) (IPTC) is a popular XMP metadata standard for photos * [Quick guide to IPTC Photo Metadata on Google Images](https://iptc.org/standards/photo-metadata/quick-guide-to-iptc-photo-metadata-and-google-images/) (IPTC) describes the subset of the IPTC Photo Metadata Standard used by Google Photos to list photo credits and license information * [xmp-docs](https://github.com/adobe/xmp-docs/tree/master/XMPNamespaces) (Adobe) describes some common XMP tags * [XMP](https://wiki.creativecommons.org/wiki/XMP) (Creative Commons) describes a standard for using XMP to embed Creative Commons license information * [XMP tags](https://exiftool.org/TagNames/XMP.html) (exiftool) is a fairly comprehensive list of XMP tags ### <a name="similar">Related software</a> Note most of the R packages listed below are focused on **getting** metadata rather than **setting** metadata and/or only provide low-level wrappers around the relevant command-line tools. Please feel free to [open a pull request to add any missing relevant R packages](https://github.com/trevorld/r-xmpdf/edit/main/README.Rmd). #### exempi * [exempi](https://libopenraw.freedesktop.org/exempi/) #### exiftool * [{exifr}](https://github.com/paleolimbot/exifr) provides a high-level wrapper to read metadata as well as a low-level wrapper around the `exiftool` command-line tool. Can download `exiftool`. * [{exiftoolr}](https://github.com/JoshOBrien/exiftoolr) provides high-level wrapper to read metadata as well as a low-level wrapper around the `exiftool` command-line tool. Can download `exiftool`. * [exiftool](https://exiftool.org/) #### exiv2 * [{exiv}](https://github.com/hrbrmstr/exiv) read and write ‘Exif’, ‘ID3v1’ and ‘ID3v2’ image/media tags * [exiv2](https://github.com/Exiv2/exiv2) #### other exif tools * [{exif}](https://github.com/Ironholds/exif) reads EXIF from jpeg images * [{magick}](https://github.com/ropensci/magick) has `image_attributes()` which reads EXIF image tags. #### ghostscript * `{tools}` has `find_gs_cmd()` to find a GhostScript executable in a cross-platform way. * [ghostscript](https://www.ghostscript.com/) #### poppler * [{pdftools}](https://docs.ropensci.org/pdftools/) * [{Rpoppler}](https://cran.r-project.org/package=Rpoppler) * [poppler](https://poppler.freedesktop.org/) #### qpdf * [{qpdf}](https://cran.r-project.org/package=qpdf) * [qpdf](https://qpdf.sourceforge.io/) #### pdftk * [{animation}](https://yihui.org/animation/) has `pdftk()`, a low-level wrapper around the `pdftk` command-line tool. * [pdftk](https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/) * [pdftk-java](https://gitlab.com/pdftk-java/pdftk) #### tabula * [{tabulizer}](https://github.com/ropensci/tabulizer) * [tabula-java](https://github.com/tabulapdf/tabula-java/) #### xpdf * [xpdf](http://www.xpdfreader.com/about.html)'s `pdfinfo` tool
/scratch/gouwar.j/cran-all/cranData/xmpdf/vignettes/xmpdf.Rmd
#'Generate the XMR data for any time-series data. #'@description Used to calculate XMR data. #' #'@param df The dataframe or tibble to calculate from. #'Data must be in a tidy format. #'At least one variable for time and one variable for measure. #'@param measure The column containing the measure. Must be in numeric format. #'@param recalc Logical: if you'd like it to recalculate bounds. Defaults to True #'@param reuse Logical: Should points be re-used in calculations? Defaults to False #'@param interval The interval you'd like to use to calculate the averages. #'Defaults to 5. #'@param longrun Used to determine rules for long run. First point is the 'n' of points used to recalculate with, and the second is to determine what qualifies as a long run. Default is c(5,8) which uses the first 5 points of a run of 8 to recalculate the bounds. If a single value is used, then that value is used twice i.e. c(6,6)) #'@param shortrun Used to determine rules for a short run. The first point is the minimum number of points within the set to qualify a shortrun, and the second is the length of a possible set. Default is c(3,4) which states that 3 of 4 points need to pass the test to be used in a calculation. If a single value is used, then that value is used twice i.e. c(3,3)) #'@param testing Logical to print test results #'@param prefer_longrun Logical if you want to first test for long-runs or for short-runs. #'@import dplyr #'@import ggplot2 #'@import tidyr #'@export xmr xmr <- function(df, measure, recalc = T, reuse, interval, longrun, shortrun, testing, prefer_longrun) { . <- "donotuse" `Order` <- . `Central Line` <- . `Average Moving Range` <- . `Lower Natural Process Limit` <- . `Upper Natural Process Limit` <- . if(missing(measure)){ measure <- names(df)[2] } if (missing(interval)){ interval <- 5 } if (missing(recalc)){ recalc <- T } if (missing(testing)){ testing <- F } if (missing(reuse)){ reuse <- T } if (missing(longrun)){ longrun <- c(5, 8) } if (missing(shortrun)){ shortrun <- c(3, 4) } if (missing(prefer_longrun)){ prefer_longrun <- F } sr_length = length(shortrun) if(length(shortrun) == 1){ shortrun <- c(shortrun, shortrun) } if(length(longrun) == 1){ longrun <- c(longrun, longrun) } if (longrun[1] > longrun[2]){ message("Invalid longrun argument. First digit must be less than or equal to the second.") } if (shortrun[1] > shortrun[2]){ message("Invalid shortrun argument. First digit must be less than or equal to the second.") } round2 <- function(x, n) { posneg <- sign(x) z <- abs(x) * 10 ^ n z <- z + 0.5 z <- trunc(z) z <- z / 10 ^ n z * posneg } interval <- round2(interval, 0) df$Order <- seq(1, nrow(df), 1) points <- seq(1, interval, 1) #limits calculator limits <- function(df){ df$`Lower Natural Process Limit` <- df$`Central Line` - (df$`Average Moving Range` * 2.66) df$`Lower Natural Process Limit`[1] <- NA df$`Lower Natural Process Limit` <- ifelse(df$`Lower Natural Process Limit` <= 0, 0, df$`Lower Natural Process Limit`) df$`Upper Natural Process Limit` <- df$`Central Line` + (df$`Average Moving Range` * 2.66) df$`Upper Natural Process Limit`[1] <- NA return(df) } #starting conditions starter <- function(dat){ original_cent <- mean(dat[[measure]][1:interval], na.rm = T) dat$`Central Line` <- original_cent #moving range dat$`Moving Range` <- abs(dat[[measure]] - dplyr::lag(dat[[measure]], 1)) for (i in 1:(nrow(dat) - 1)) { dat$`Moving Range`[i + 1] <- abs(dat[[measure]][i] - dat[[measure]][i + 1]) } dat$`Average Moving Range` <- mean(dat$`Moving Range`[2:(interval)], na.rm = T) dat$`Average Moving Range`[1] <- NA dat <- limits(dat) return(dat) } #testing for shortruns shortruns <- function(df, side, points){ if (side == "upper"){ df$Test <- NA df$Test <- ifelse( (abs(df[[measure]] - df$`Central Line`) > abs(df[[measure]] - df$`Upper Natural Process Limit`) & !(df$Order %in% points) ), "1", "0") return(df) } if (side == "lower"){ df$Test <- NA df$Test <- ifelse( (abs(df[[measure]] - df$`Central Line`) > abs(df[[measure]] - df$`Lower Natural Process Limit`) & !(df$Order %in% points) ), "1", "0") return(df) } } if(sr_length == 1){ #run subsetters shortrun_subset <- function(df, test, order, measure, points, int){ int <- int subsets <- c() value <- "1" run <- shortrun[2] percentage <- run * (shortrun[1]/shortrun[2]) for (i in int:nrow(df)){ pnts <- i:(i + shortrun[1]-1) q <- df[[test]][df[[order]] %in% pnts] r <- as.data.frame(table(q)) if (!any(is.na(q) == T) && (value %in% r$q)){ if (r$Freq[r$q == value] >= percentage && !(pnts %in% points)){ subset <- df[df[[order]] %in% pnts, ] df <- df[!(df[[order]] %in% pnts), ] subsets <- rbind(subsets, subset) } } } return(subsets[1:(shortrun[2]), ]) } } else { #run subsetters shortrun_subset <- function(df, test, order, measure, points, int){ int <- int subsets <- c() value <- "1" run <- shortrun[2] percentage <- run * (shortrun[1]/shortrun[2]) for (i in int:nrow(df)){ pnts <- i:(i + shortrun[1]) q <- df[[test]][df[[order]] %in% pnts] r <- as.data.frame(table(q)) if (!any(is.na(q) == T) && (value %in% r$q)){ if (r$Freq[r$q == value] >= percentage && !(pnts %in% points)){ subset <- df[df[[order]] %in% pnts, ] df <- df[!(df[[order]] %in% pnts), ] subsets <- rbind(subsets, subset) } } } return(subsets[1:(shortrun[2]), ]) } } run_subset <- function(subset, order, df, type, side, points){ if (missing(type)){ type <- "long" } if (missing(subset)){ subset <- df } if (type == "long"){ breaks <- c(0, which(diff(subset[[order]]) != 1), length(subset[[order]])) d <- sapply(seq(length(breaks) - 1), function(i) subset[[order]][(breaks[i] + 1):breaks[i + 1]]) if (is.matrix(d)){ d <- split(d, rep(1:ncol(d), each = nrow(d))) } if (length(d) > 1){ rns <- c() idx <- c() for (i in 1:length(d)){ a <- length(d[[i]]) rns <- c(rns, a) idx <- c(idx, i) } runs <- data.frame(idx, rns) idx <- unique(runs$idx[runs$rns == max(runs$rns)]) run <- d[idx] subset <- subset[subset[[order]] %in% run[[1]], ] } else { subset <- subset[subset[[order]] %in% d[[1]], ] } } if (type == "short" && side == "upper"){ df <- shortruns(df, "upper", points) subset <- shortrun_subset(df, "Test", "Order", measure, points, interval) } if (type == "short" && side == "lower"){ df_subset <- shortruns(df, "lower", points) subset <- shortrun_subset(df_subset, "Test", "Order", measure, points, interval) } return(subset) } #recalculator recalculator <- function(dat, subset, order, length, message, reuse){ if (length == longrun[2]){ int <- longrun[1] subset$Test <- 1 } else if (length == shortrun[2]){ int <- shortrun[2] } if (nrow(subset) >= length){ start <- min(subset[[order]], na.rm = T) if (length == longrun[2]){ end <- start + (int-1) } else if (length == shortrun[2]){ end <- start + (int-1) } lastrow <- max(dat[[order]], na.rm = T) if (length == longrun[2]){ new_cnt <- mean(subset[[measure]][1:int], na.rm = T) new_mv_rng <- subset$`Moving Range`[1:int] new_av_mv_rng <- mean(new_mv_rng, na.rm = T) dat$`Average Moving Range`[start:lastrow] <- new_av_mv_rng dat$`Central Line`[start:lastrow] <- new_cnt dat <- limits(dat) calcpoints <- start:end points <- c(points, calcpoints) assign("points", points, envir = parent.frame()) assign("calcpoints", calcpoints, envir = parent.frame()) return(dat) } else if (length == shortrun[2]){ new_cnt <- mean(subset[[measure]][subset$Test == 1], na.rm = T) new_mv_rng <- subset$`Moving Range`[subset$Test == 1] new_av_mv_rng <- mean(new_mv_rng, na.rm = T) start <- min(subset[[order]][subset$Test == 1], na.rm = T) end <- max(subset[[order]][subset$Test == 1], na.rm = T) dat$`Average Moving Range`[start:lastrow] <- new_av_mv_rng dat$`Central Line`[start:lastrow] <- new_cnt dat <- limits(dat) calcpoints <- start:end if (reuse == F){ points <- c(points, calcpoints) } assign("points", points, envir = parent.frame()) assign("calcpoints", calcpoints, envir = parent.frame()) return(dat) } } else { return(dat) } } #runs application runs <- function(dat, run = c("short", "long"), side = c("upper", "lower"), longrun, shortrun, calcpoints){ if (run == "short"){ l <- shortrun[2] } else if (run == "long"){ l <- longrun[2] } #upper longruns if (side == "upper" && run == "long"){ dat_sub <- dat %>% filter(., .[[measure]] > `Central Line` & !(Order %in% points)) %>% arrange(., Order) dat_sub <- run_subset(dat_sub, "Order") rep <- nrow(dat_sub) while (rep >= l){ mess <- paste0(run, ": ", side) dat <- recalculator(dat, dat_sub, "Order", l, mess, reuse) assign("points", points, envir = parent.frame()) if (testing == T){ print(mess) print(calcpoints) } dat_sub <- dat %>% filter(., .[[measure]] > `Central Line` & !(Order %in% points)) %>% arrange(., Order) dat_sub <- run_subset(dat_sub, "Order") rep <- nrow(dat_sub) } } #lower longruns else if (side == "lower" && run == "long"){ dat_sub <- dat %>% filter(., .[[measure]] < `Central Line` & #abs(.[[measure]] - `Central Line`) < #abs(.[[measure]] - `Lower Natural Process Limit`) & !(Order %in% points)) %>% arrange(., Order) dat_sub <- run_subset(dat_sub, "Order") rep <- nrow(dat_sub) while (rep >= l){ mess <- paste0(run, ": ", side) dat <- recalculator(dat, dat_sub, "Order", l, mess, reuse) assign("points", points, envir = parent.frame()) if (testing == T){ print(mess) print(calcpoints) } dat_sub <- dat %>% filter(., .[[measure]] < `Central Line` & !(Order %in% points)) %>% arrange(., Order) dat_sub <- run_subset(dat_sub, "Order") rep <- nrow(dat_sub) } } #upper shortruns else if (side == "upper" && run == "short"){ dat_sub <- run_subset(order = "Order", df = dat, type = "short", side = "upper", points = points) rep <- nrow(dat_sub) while (!is.null(rep) && !is.na(rep)){ mess <- paste0(run, ": ", side) dat <- recalculator(dat, dat_sub, "Order", l, mess, reuse) assign("points", points, envir = parent.frame()) if (testing == T){ print(mess) print(calcpoints) } dat_sub <- run_subset(order = "Order", df = dat, type = "short", side = "upper", points = points) rep <- nrow(dat_sub) } } ##lower shortrun else if (side == "lower" && run == "short"){ dat_sub <- run_subset(order = "Order", df = dat, type = "short", side = "lower", points = points) rep <- nrow(dat_sub) while (!is.null(rep) && !is.na(rep)){ mess <- paste0(run, ": ", side) dat <- recalculator(dat, dat_sub, "Order", l, mess, reuse) assign("points", points, envir = parent.frame()) if (testing == T){ print(mess) print(calcpoints) } dat_sub <- run_subset(order = "Order", df = dat, type = "short", side = "lower", points = points) rep <- nrow(dat_sub) } } return(dat) } if ((nrow(df)) >= interval){ #if no recalculation of limits is desired if (recalc == F){ df <- starter(df) } #if recalculation of limits desired if (recalc == T){ #calculate inital values df <- starter(df) if(prefer_longrun == T){ df <- runs(df, "long", "upper", longrun, shortrun) df <- runs(df, "long", "lower", longrun, shortrun) } df <- runs(df, "short", "upper", longrun, shortrun) df <- runs(df, "short", "lower", longrun, shortrun) df <- runs(df, "short", "upper", longrun, shortrun) df <- runs(df, "short", "lower", longrun, shortrun) df <- runs(df, "long", "upper", longrun, shortrun) df <- runs(df, "long", "lower", longrun, shortrun) df <- runs(df, "short", "upper", longrun, shortrun) df <- runs(df, "short", "lower", longrun, shortrun) df <- runs(df, "long", "upper", longrun, shortrun) df <- runs(df, "long", "lower", longrun, shortrun) df <- runs(df, "short", "upper", longrun, shortrun) df <- runs(df, "short", "lower", longrun, shortrun) df <- runs(df, "long", "upper", longrun, shortrun) df <- runs(df, "long", "lower", longrun, shortrun) df <- limits(df) } lastpoint <- max(df$Order) penpoint <- shortrun[1]-1 df$`Central Line`[c((lastpoint - penpoint) : lastpoint)] <- df$`Central Line`[c(lastpoint - penpoint)] df$`Average Moving Range`[c((lastpoint - penpoint) : lastpoint)] <- df$`Average Moving Range`[c(lastpoint - penpoint)] df <- limits(df) #rounding df$`Central Line` <- round2(df$`Central Line`, 3) df$`Moving Range` <- round2(df$`Moving Range`, 3) df$`Average Moving Range` <- round2(df$`Average Moving Range`, 3) df$`Lower Natural Process Limit` <- round2(df$`Lower Natural Process Limit`, 3) df$`Upper Natural Process Limit` <- round2(df$`Upper Natural Process Limit`, 3) } if ((nrow(df)) < interval) { df$`Central Line` <- NA df$`Moving Range` <- NA df$`Average Moving Range` <- NA df$`Lower Natural Process Limit` <- NA df$`Upper Natural Process Limit` <- NA } class(df) <- c(class(df), "xmr") return(df) }
/scratch/gouwar.j/cran-all/cranData/xmrr/R/xmR.R
#'Generate the XMR chart for XMR data #'@description Useful for diagnostics on xmr, and just visualizing the data. #' #'@param dataframe Output from xmR() #'@param time Time column #'@param measure Measure #'@param boundary_linetype Type of line for upper and lower boundary lines. Defaults to "dashed". #'@param central_linetype Type of line for central line. Defaults to "dotted". #'@param boundary_colour Colour of line for upper and lower boundary lines. Defaults to "#d02b27". #'@param point_colour Colour of points. Defaults to "#7ECBB5". #'@param point_size Size of points. Defaults to 2. #'@param line_width Width of lines. Defaults to 0.5. #'@param text_size Size of chart text. Defaults to 9. #'@import ggplot2 #'@import tidyr #'@export xmr_chart xmr_chart <- function(dataframe, time, measure, boundary_linetype = "dashed", central_linetype = "dotted", boundary_colour = "#d02b27", point_colour = "#7ECBB5", point_size = 2, line_width = 0.5, text_size = 9){ if("Upper Natural Process Limit" %in% names(dataframe)){ . <- "donotuse" `Order` <- . `Central Line` <- . `Average Moving Range` <- . `Lower Natural Process Limit` <- . `Upper Natural Process Limit` <- . if(missing(time)){time <- names(dataframe)[1]} if(missing(measure)){measure <- names(dataframe)[2]} plot <- ggplot2::ggplot(dataframe, aes(x = {{time}}), group = 1) + geom_line(aes(y = `Central Line`), size = line_width, linetype = central_linetype, na.rm = T) + geom_line(aes(y = `Lower Natural Process Limit`), color = boundary_colour, size = line_width, linetype = boundary_linetype, na.rm = T) + geom_line(aes(y = `Upper Natural Process Limit`), color = boundary_colour, size = line_width, linetype = boundary_linetype, na.rm = T) + geom_line(aes(y = {{measure}})) + geom_point(aes(y = {{measure}}), size = point_size, color = "#000000") + geom_point(aes(y = {{measure}}), size = point_size*.625, color = point_colour) + guides(colour=FALSE) + labs(x = time, y = measure) + theme_bw() + theme(strip.background = element_rect(fill = NA, linetype = 0), panel.border = element_rect(color = NA), panel.spacing.y = unit(4, "lines"), panel.spacing.x = unit(2, "lines"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.y = element_blank(), axis.title.y = element_blank(), axis.ticks.y = element_blank(), axis.ticks.x = element_blank(), text = element_text(family = "sans"), axis.text.x = element_text(colour = "#000000", size = text_size-2), axis.title.x = element_text(size = text_size, face = "bold")) return(plot) } else {warning("Data has not been analyzed using xmr().")} }
/scratch/gouwar.j/cran-all/cranData/xmrr/R/xmR_chart.R
#'Tidyeval Version of xmr() #'@description Used to calculate XMR data. Now works with more tidy workflows. #' #'@param dataframe The dataframe or tibble to calculate from. #'Data must be in a tidy format. #'At least one variable for time and one variable for measure. #'@param measure The column containing the measure. Must be in numeric format. #'@param ... Arguments to pipe to xmr #'@import dplyr #'@import ggplot2 #'@import tidyr #'@export xmr2 xmr2 = function(dataframe, measure, ...){ vc = deparse(substitute(measure)) dataframe %>% group_split() %>% purrr::map_df(xmr, measure = vc, ...) }
/scratch/gouwar.j/cran-all/cranData/xmrr/R/xmr2.R
#'Generate the XMR chart for XMR data. #'@description Useful for diagnostics on xmr, and just visualizing the data. Now works with more tidy workflows. #' #'@param dataframe Output from xmR() #'@param time Time column #'@param measure Measure #'@param ... Arguments to pipe to xmr_chart() #'@import dplyr #'@import ggplot2 #'@import tidyr #'@export xmr_chart2 xmr_chart2 = function(dataframe, time, measure, ...){ m = deparse(substitute(measure)) t = deparse(substitute(time)) dataframe %>% xmr_chart(t, m, ...) }
/scratch/gouwar.j/cran-all/cranData/xmrr/R/xmr_chart2.R
## ---- message=FALSE, echo = F------------------------------------------------- library(xmrr) library(tidyr) library(ggplot2) library(dplyr) library(tibble) set.seed(1) Measure <- round(runif(12, min = 0.50, max = 0.66)*100, 0) Measure <- c(Measure, round(runif(6, min = 0.70, max = .85)*100, 0)) Time <- c(2000:2017) example_data <- data.frame(Time, Measure) knitr::kable(example_data, format = "markdown", align = 'c') ## ---- message=FALSE, eval = F------------------------------------------------- # xmr_data <- xmr(df = example_data, measure = "Measure") ## ---- message=FALSE, eval = F------------------------------------------------- # xmr_data <- xmr(df = example_data, measure = "Measure", recalc = T) ## ---- echo=F, message=FALSE, warning = F, eval=F------------------------------ # xmr_data <- xmr(example_data, "Measure", # recalc = T) %>% # as_tibble() %>% # select(-Order) # knitr::kable(xmr_data, format = "markdown", align = 'c') ## ---- message = FALSE,eval=F-------------------------------------------------- # xmr_data <- xmr(example_data, "Measure", # recalc = T, # interval = 5, # shortrun = c(3,4), # longrun = c(5,8)) ## ---- message = FALSE, eval = F----------------------------------------------- # xmr_data <- xmr(df = example_data, # measure = "Measure", # recalc = T, # #change the rule like so:, # interval = 4, # shortrun = c(2,3)) ## ---- fig.height=5, fig.width=7, warning=F, eval = F-------------------------- # xmr_chart(xmr_data, # time = "Time", # measure = "Measure", # line_width = 0.75, text_size = 12, point_size = 2.5) ## ---- eval = F---------------------------------------------------------------- # example_data %>% # xmr("Measure", recalc = T) %>% # xmr_chart("Time", "Measure") ## ---- message=FALSE, echo = F------------------------------------------------- library(xmrr) library(dplyr) `Year` <- seq(2004, 2017, 1) Variable <- "A" FDA <- data.frame(`Year`, Variable, check.names = F) Variable <- "B" FDB <- data.frame(`Year`, Variable, check.names = F) MFD <- rbind(FDA, FDB) %>% as_tibble() MFD$Measure <- runif(nrow(MFD))*100 MFD$Measure <- round(MFD$Measure, 0) knitr::kable(MFD, format = "markdown", align = 'c') ## ---- eval = F---------------------------------------------------------------- # #this installs many useful packages # install.packages("tidyverse") # # #this just loads the ones we need # library(dplyr) # library(purrr) # library(ggplot2) ## ---- eval = F---------------------------------------------------------------- # MFD_xmr <- MFD %>% # group_split(Variable) %>% # map(xmr, measure = "Measure", recalc = T) %>% # map_df(as_tibble) ## ---- echo=FALSE, eval = F---------------------------------------------------- # knitr::kable(MFD_xmr, format = "markdown", align = 'c') ## ---- fig.height=5, fig.width=7, eval = F------------------------------------- # MFD_xmr %>% # xmr_chart("Year", "Measure", line_width = 0.75, text_size = 12) + # facet_wrap(~Variable) + # scale_x_discrete(breaks = seq(2004, 2017, 4))
/scratch/gouwar.j/cran-all/cranData/xmrr/inst/doc/xmR.R
--- title: "Using xmr() and xmr_chart()" output: rmarkdown::html_vignette vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Using xmr() and xmr_chart()} %\usepackage[UTF-8]{inputenc} --- # Introduction XMR control charts are useful when determining if there are significant trends in data. XMR charts have two key assumptions: one is that the measurements of value happen over time, and the other is that each measurement of time has exactly one measurement of value. Take careful thought about *what* you are trying to measure with XMR. Proportions work great, headcount is okay, costs over time don't work well. ------- # Arguments The arguments for `xmr()` are: - **df**: The dataframe containing the time-series data. - **measure**: The column containing the measure. This must be in a numeric format. - **interval**: The interval you'd like to use to calculate the averages. Defaults to 5. - **recalc**: Logical if you'd like it to recalculate bounds. Defaults to False for safety. - **reuse**: Logical: Should points be re-used in calculations? Defaults to False. - **longrun**: A vector of 2 to determine the rules for a long run. The first point is the 'n' of points used to calculate the new reference lines, and the second is to determine how many consecutive points are needed to define a longrun. Default is c(5,8) which uses the first 5 points of a run of 8 to recalculate the bounds. - **shortrun**: A vector of 2 to determine the rules for a short run. The first point is the minimum number of points within the set to qualify a shortrun, and the second is the length of a possible set. Default is c(3,4) which states that 3 of 4 consecutive points need to pass the test to be used in a calculation. The data required for XMR charts take a specific format, with at least two columns of data - one for the time variable and another for the measurement. Like so: ```{r, message=FALSE, echo = F} library(xmrr) library(tidyr) library(ggplot2) library(dplyr) library(tibble) set.seed(1) Measure <- round(runif(12, min = 0.50, max = 0.66)*100, 0) Measure <- c(Measure, round(runif(6, min = 0.70, max = .85)*100, 0)) Time <- c(2000:2017) example_data <- data.frame(Time, Measure) knitr::kable(example_data, format = "markdown", align = 'c') ``` If we wanted to use `xmr()` on this data would be written like this: ```{r, message=FALSE, eval = F} xmr_data <- xmr(df = example_data, measure = "Measure") ``` And if we wanted the bounds to recalculate, we'd use this. ```{r, message=FALSE, eval = F} xmr_data <- xmr(df = example_data, measure = "Measure", recalc = T) ``` Output data looks like this: ```{r, echo=F, message=FALSE, warning = F, eval=F} xmr_data <- xmr(example_data, "Measure", recalc = T) %>% as_tibble() %>% select(-Order) knitr::kable(xmr_data, format = "markdown", align = 'c') ``` The only mandatory arguments are **df**, because the function needs to operate on a dataframe, and **measure** because the function needs to be told which column contains the measurements. Everything else has been set to what I believe is a safe and sensible default. In our shop, we typically run the following rules. Since they are the default, there is no need to specify them directly: ```{r, message = FALSE,eval=F} xmr_data <- xmr(example_data, "Measure", recalc = T, interval = 5, shortrun = c(3,4), longrun = c(5,8)) ``` Feel free to play around with your own definitions of what a shortrun or longrun is. ```{r, message = FALSE, eval = F} xmr_data <- xmr(df = example_data, measure = "Measure", recalc = T, #change the rule like so:, interval = 4, shortrun = c(2,3)) ``` The statistical differences between rules are slight, but each user will have different needs and it's useful to be able to tune the function to those needs. It is important to use a consistent definition of what a long/short run are. It wouldn't be appropriate in one report to use one set of definitions for one dataset, and another set for a different dataset. ------- # Charts The `xmr()` function is handy for generating chart data as the output can be saved and used in other applications. But what about visualization within R? `xmr_chart()` takes the output from `xmr()` and generates a ggplot graphic. This works well for reporting, but it also works great for quick diagnostics of your data. The arguments for `xmr_chart()` are: - **dataframe**: Output from xmr() - **time**: The column containing the time variable for the x-axis. - **measure**: The column containing the measure for the y-axis. - **boundary_linetype**: Type of line for upper and lower boundary lines. Defaults to "dashed". - **central_linetype**: Type of line for central line. Defaults to "dotted". - **boundary_colour**: Colour of line for upper and lower boundary lines. Defaults to "#d02b27". - **point_colour**: Colour of points. Defaults to "#7ECBB5". - **point_size**: Size of points. Defaults to 2. - **line_width**: Width of lines. Defaults to 0.5. - **text_size**: Size of chart text. Defaults to 9. There are defaults set for most arguments, so all the user *needs* to supply are the column names for the Time and Measurement column unless they want some slight modification of the default chart. ```{r, fig.height=5, fig.width=7, warning=F, eval = F} xmr_chart(xmr_data, time = "Time", measure = "Measure", line_width = 0.75, text_size = 12, point_size = 2.5) ``` A work-flow that I use is to 'pipe' the output of `xmr()` directly into `xmr_chart()`: ```{r, eval = F} example_data %>% xmr("Measure", recalc = T) %>% xmr_chart("Time", "Measure") ``` ------- # Tidyverse - dplyr & ggplot2 Simple datasets like those illustrated above are common, but how could we work with large datasets that have multiple factors? Consider the following data. How would `xmr()` benefit the user in this case? ```{r, message=FALSE, echo = F} library(xmrr) library(dplyr) `Year` <- seq(2004, 2017, 1) Variable <- "A" FDA <- data.frame(`Year`, Variable, check.names = F) Variable <- "B" FDB <- data.frame(`Year`, Variable, check.names = F) MFD <- rbind(FDA, FDB) %>% as_tibble() MFD$Measure <- runif(nrow(MFD))*100 MFD$Measure <- round(MFD$Measure, 0) knitr::kable(MFD, format = "markdown", align = 'c') ``` The answer is by leveraging other R packages, namely the `tidyverse`. You can install and load the tidyverse with: ```{r, eval = F} #this installs many useful packages install.packages("tidyverse") #this just loads the ones we need library(dplyr) library(purrr) library(ggplot2) ``` With `dplyr`, we can make use of powerful data-wrangling verbs without writing them into `xmrr`'s functions specifically: - `select()`:- picks variables based on their names. - `filter()`:- picks cases based on their values. - `arrange()`:- changes the ordering of the rows. - `mutate()`:- adds new variables that are functions of existing variables. - `summarise()`:- reduces multiple values down to a single summary. - `group_by()`:- allows for group operations in the "split-apply-combine" concept Also loaded with `dplyr` is a powerful operator to chain functions together, called a pipe `%>%`. With `ggplot2`, we take a modern approach to visualizing data. An up-to-date reference list of functions can be found [here](http://ggplot2.tidyverse.org/reference/) This enables a number of verb-type functions for tidying, wrangling, and plotting data. This is how to use them alongside the `xmr()` and `xmr_chart()` functions. ------- # Grouping and Faceting Take our multiple factor data `MFD` - here is how to apply the `xmr()` function to certain groups within that data. ```{r, eval = F} MFD_xmr <- MFD %>% group_split(Variable) %>% map(xmr, measure = "Measure", recalc = T) %>% map_df(as_tibble) ``` To obtain the following: ```{r, echo=FALSE, eval = F} knitr::kable(MFD_xmr, format = "markdown", align = 'c') ``` And as you may be able to see in the data, the `xmr()` calculated on Measure **BY** Variable in one chained function instead of having to manually split the data and run the function multiple times. This is possible with an arbitrary number of factors, and leverages the speed of `dplyr` verbs. Similarly, `ggplot2` can be leveraged in plotting. Note that since `xmr_chart()` outputs a ggplot object, we can apply the regular ggplot2 functions to it and return a faceted chart rather than filtering the chart and making two. ```{r, fig.height=5, fig.width=7, eval = F} MFD_xmr %>% xmr_chart("Year", "Measure", line_width = 0.75, text_size = 12) + facet_wrap(~Variable) + scale_x_discrete(breaks = seq(2004, 2017, 4)) ```
/scratch/gouwar.j/cran-all/cranData/xmrr/inst/doc/xmR.Rmd
--- title: "Using xmr() and xmr_chart()" output: rmarkdown::html_vignette vignette: > %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{Using xmr() and xmr_chart()} %\usepackage[UTF-8]{inputenc} --- # Introduction XMR control charts are useful when determining if there are significant trends in data. XMR charts have two key assumptions: one is that the measurements of value happen over time, and the other is that each measurement of time has exactly one measurement of value. Take careful thought about *what* you are trying to measure with XMR. Proportions work great, headcount is okay, costs over time don't work well. ------- # Arguments The arguments for `xmr()` are: - **df**: The dataframe containing the time-series data. - **measure**: The column containing the measure. This must be in a numeric format. - **interval**: The interval you'd like to use to calculate the averages. Defaults to 5. - **recalc**: Logical if you'd like it to recalculate bounds. Defaults to False for safety. - **reuse**: Logical: Should points be re-used in calculations? Defaults to False. - **longrun**: A vector of 2 to determine the rules for a long run. The first point is the 'n' of points used to calculate the new reference lines, and the second is to determine how many consecutive points are needed to define a longrun. Default is c(5,8) which uses the first 5 points of a run of 8 to recalculate the bounds. - **shortrun**: A vector of 2 to determine the rules for a short run. The first point is the minimum number of points within the set to qualify a shortrun, and the second is the length of a possible set. Default is c(3,4) which states that 3 of 4 consecutive points need to pass the test to be used in a calculation. The data required for XMR charts take a specific format, with at least two columns of data - one for the time variable and another for the measurement. Like so: ```{r, message=FALSE, echo = F} library(xmrr) library(tidyr) library(ggplot2) library(dplyr) library(tibble) set.seed(1) Measure <- round(runif(12, min = 0.50, max = 0.66)*100, 0) Measure <- c(Measure, round(runif(6, min = 0.70, max = .85)*100, 0)) Time <- c(2000:2017) example_data <- data.frame(Time, Measure) knitr::kable(example_data, format = "markdown", align = 'c') ``` If we wanted to use `xmr()` on this data would be written like this: ```{r, message=FALSE, eval = F} xmr_data <- xmr(df = example_data, measure = "Measure") ``` And if we wanted the bounds to recalculate, we'd use this. ```{r, message=FALSE, eval = F} xmr_data <- xmr(df = example_data, measure = "Measure", recalc = T) ``` Output data looks like this: ```{r, echo=F, message=FALSE, warning = F, eval=F} xmr_data <- xmr(example_data, "Measure", recalc = T) %>% as_tibble() %>% select(-Order) knitr::kable(xmr_data, format = "markdown", align = 'c') ``` The only mandatory arguments are **df**, because the function needs to operate on a dataframe, and **measure** because the function needs to be told which column contains the measurements. Everything else has been set to what I believe is a safe and sensible default. In our shop, we typically run the following rules. Since they are the default, there is no need to specify them directly: ```{r, message = FALSE,eval=F} xmr_data <- xmr(example_data, "Measure", recalc = T, interval = 5, shortrun = c(3,4), longrun = c(5,8)) ``` Feel free to play around with your own definitions of what a shortrun or longrun is. ```{r, message = FALSE, eval = F} xmr_data <- xmr(df = example_data, measure = "Measure", recalc = T, #change the rule like so:, interval = 4, shortrun = c(2,3)) ``` The statistical differences between rules are slight, but each user will have different needs and it's useful to be able to tune the function to those needs. It is important to use a consistent definition of what a long/short run are. It wouldn't be appropriate in one report to use one set of definitions for one dataset, and another set for a different dataset. ------- # Charts The `xmr()` function is handy for generating chart data as the output can be saved and used in other applications. But what about visualization within R? `xmr_chart()` takes the output from `xmr()` and generates a ggplot graphic. This works well for reporting, but it also works great for quick diagnostics of your data. The arguments for `xmr_chart()` are: - **dataframe**: Output from xmr() - **time**: The column containing the time variable for the x-axis. - **measure**: The column containing the measure for the y-axis. - **boundary_linetype**: Type of line for upper and lower boundary lines. Defaults to "dashed". - **central_linetype**: Type of line for central line. Defaults to "dotted". - **boundary_colour**: Colour of line for upper and lower boundary lines. Defaults to "#d02b27". - **point_colour**: Colour of points. Defaults to "#7ECBB5". - **point_size**: Size of points. Defaults to 2. - **line_width**: Width of lines. Defaults to 0.5. - **text_size**: Size of chart text. Defaults to 9. There are defaults set for most arguments, so all the user *needs* to supply are the column names for the Time and Measurement column unless they want some slight modification of the default chart. ```{r, fig.height=5, fig.width=7, warning=F, eval = F} xmr_chart(xmr_data, time = "Time", measure = "Measure", line_width = 0.75, text_size = 12, point_size = 2.5) ``` A work-flow that I use is to 'pipe' the output of `xmr()` directly into `xmr_chart()`: ```{r, eval = F} example_data %>% xmr("Measure", recalc = T) %>% xmr_chart("Time", "Measure") ``` ------- # Tidyverse - dplyr & ggplot2 Simple datasets like those illustrated above are common, but how could we work with large datasets that have multiple factors? Consider the following data. How would `xmr()` benefit the user in this case? ```{r, message=FALSE, echo = F} library(xmrr) library(dplyr) `Year` <- seq(2004, 2017, 1) Variable <- "A" FDA <- data.frame(`Year`, Variable, check.names = F) Variable <- "B" FDB <- data.frame(`Year`, Variable, check.names = F) MFD <- rbind(FDA, FDB) %>% as_tibble() MFD$Measure <- runif(nrow(MFD))*100 MFD$Measure <- round(MFD$Measure, 0) knitr::kable(MFD, format = "markdown", align = 'c') ``` The answer is by leveraging other R packages, namely the `tidyverse`. You can install and load the tidyverse with: ```{r, eval = F} #this installs many useful packages install.packages("tidyverse") #this just loads the ones we need library(dplyr) library(purrr) library(ggplot2) ``` With `dplyr`, we can make use of powerful data-wrangling verbs without writing them into `xmrr`'s functions specifically: - `select()`:- picks variables based on their names. - `filter()`:- picks cases based on their values. - `arrange()`:- changes the ordering of the rows. - `mutate()`:- adds new variables that are functions of existing variables. - `summarise()`:- reduces multiple values down to a single summary. - `group_by()`:- allows for group operations in the "split-apply-combine" concept Also loaded with `dplyr` is a powerful operator to chain functions together, called a pipe `%>%`. With `ggplot2`, we take a modern approach to visualizing data. An up-to-date reference list of functions can be found [here](http://ggplot2.tidyverse.org/reference/) This enables a number of verb-type functions for tidying, wrangling, and plotting data. This is how to use them alongside the `xmr()` and `xmr_chart()` functions. ------- # Grouping and Faceting Take our multiple factor data `MFD` - here is how to apply the `xmr()` function to certain groups within that data. ```{r, eval = F} MFD_xmr <- MFD %>% group_split(Variable) %>% map(xmr, measure = "Measure", recalc = T) %>% map_df(as_tibble) ``` To obtain the following: ```{r, echo=FALSE, eval = F} knitr::kable(MFD_xmr, format = "markdown", align = 'c') ``` And as you may be able to see in the data, the `xmr()` calculated on Measure **BY** Variable in one chained function instead of having to manually split the data and run the function multiple times. This is possible with an arbitrary number of factors, and leverages the speed of `dplyr` verbs. Similarly, `ggplot2` can be leveraged in plotting. Note that since `xmr_chart()` outputs a ggplot object, we can apply the regular ggplot2 functions to it and return a faceted chart rather than filtering the chart and making two. ```{r, fig.height=5, fig.width=7, eval = F} MFD_xmr %>% xmr_chart("Year", "Measure", line_width = 0.75, text_size = 12) + facet_wrap(~Variable) + scale_x_discrete(breaks = seq(2004, 2017, 4)) ```
/scratch/gouwar.j/cran-all/cranData/xmrr/vignettes/xmR.Rmd
#' Class linearFilter #' #' The class represents the outcome of a linear filter, and is normally #' generated by the function \code{\link{linear_filter}} #' #' @slot y the original label matrix with responses. #' @slot alpha a numeric vector with the 4 alpha values of the model. #' @slot pred a matrix with the predictions #' @slot mean a numeric vector containing the global mean of \code{y} #' @slot colmeans a numeric vector containing the column means of \code{y} #' @slot rowmeans a numeric vector containing the row means of \code{y}. #' @slot na.rm a logical value indicating whether missing values were #' removed prior to the calculation of the means. #' @seealso \code{\link{linear_filter}} for creating a linear filter model, #' and \code{\link[=getters_linearFilter]{getter fuctions for linearFilter}}. #' #' @aliases linearFilter setClass("linearFilter", slots = c( y = "matrix", alpha = "numeric", pred = "matrix", mean = "numeric", colmeans = "numeric", rowmeans = "numeric", na.rm = "logical" )) validLinearFilter <- function(object){ if(length(object@mean) != 1) return("The mean should be exactly of length 1.") if(length(object@colmeans) != ncol(object@y)) return("The length of colmeans is incompatible with the number of columns in y.") if(length(object@rowmeans) != nrow(object@y)) return("The length of rowmeans is incompatible with the number of rows in y.") if(length([email protected]) != 1) return("na.rm needs to be a single logical value.") if(length(object@alpha) != 4) return("Alpha should contain exactly 4 numeric values.") else return(TRUE) } setValidity("linearFilter", validLinearFilter)
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_linearFilter.R
#' Class permtest #' #' This class represents the permutation test outcomes. See also #' the function \code{\link{permtest}}. #' #' @slot orig_loss a numeric value with the original loss of #' the model. #' @slot perm_losses a numeric vector with the losses of the #' different permutations. #' @slot n the number of permutations #' @slot loss_function the function used to calculate the losses. #' @slot exclusion a character value indicating the exclusion #' setting used for the test #' @slot replaceby0 a locigal value that indicates whether the #' exclusion was done by replacing with zero. See also #' \code{\link{loo}}. #' @slot permutation a character value that indicats in which #' kernel matrices were permuted. #' @slot pval a p value indicating how likely it is to find a #' smaller loss than the one of the model based on a normal #' approximation. #' @slot exact a logical value indicating whether the P value was #' calculated exactly or approximated by the normal distribution. #' #' @seealso #' * the function \code{\link{permtest}} for the actual test. #' * the function \code{\link{loo}} for the leave one out #' procedures #' * the function \code{\link{t.test}} for the actual test #' @md #' #' @include all_generics.R #' #' @rdname permtest-class #' @name permtest-class #' @exportClass permtest setClass("permtest", slots = c(orig_loss = "numeric", perm_losses = "numeric", n = "numeric", loss_function = "function", exclusion = "character", replaceby0 = "logical", permutation = "character", pval = "numeric", exact = "logical")) # Validity testing validPermtest <- function(object){ if(length(object@orig_loss) != 1) return("orig_loss should be a single value.") if(length(object@pval) != 1) return("pval should be a single value.") if(length(object@perm_losses) != object@n) return("perm_losses doesn't have a length of n.") if(length(object@exact)!= 1) return("exact should be a single value.") } setValidity("permtest", validPermtest) # internal .make_res_table <- function(perm_losses, orig_loss, pval){ avg <- mean(perm_losses) sd <- sd(perm_losses) # results res <- matrix( c(orig_loss, avg, sd, pval), nrow = 1, dimnames = list( " ", c("Loss", "Avg. loss", "St.dev", "Pr(X < loss)") ) ) } # Show method #' @param digits the number of digits shown in the output #' @rdname permtest #' @export print.permtest <- function(x, digits = max(3L, getOption("digits") - 3), ...){ if(identical(x@loss_function, loss_mse)) loss_name <- "Mean Squared Error (loss_mse)" else if(identical(x@loss_function, loss_auc)) loss_name <- "Area under curve (loss_auc)" else loss_name <- "custom function by user" excl <- x@exclusion if(x@replaceby0) excl <- paste(excl,"(values replaced by 0)") loss_name <- paste(" Loss function:",loss_name,"\n") excl <- paste(" Exclusion:", excl, "\n") perm <- paste0(" Permutations: ", x@n," (direction: ",x@permutation,")\n") res <- .make_res_table(x@perm_losses, x@orig_loss, x@pval) cat("\n") cat(strwrap("Permutation test for a tskrr model", prefix = "\t")) cat("\n") cat("Using:\n") cat(loss_name) cat(excl) cat(perm) cat("\n") printCoefmat(res, digits = digits) cat("\n") if(!x@exact) cat("P value is approximated based on a normal distribution.\n\n") invisible(res) } setMethod("show", "permtest", function(object){ print.permtest(object) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_permtest.R
#' Class tskrr #' #' The class tskrr represents a two step kernel ridge regression fitting #' object, and is normally generated by the function \code{\link{tskrr}}. #' This is a superclass so it should not be instantiated directly. #' #' @slot y the matrix with responses #' @slot k the eigen decomposition of the kernel matrix for the rows #' @slot lambda.k the lambda value used for k #' @slot pred the matrix with the predictions #' @slot has.hat a logical value indicating whether the kernel hat matrices #' are stored in the object. #' @slot Hk the kernel hat matrix for the rows. #' @slot labels a list with two character vectors, \code{k} and #' \code{g}, containing the labels for the rows resp. columns. See #' \code{\link{tskrrHomogeneous}} and #' \code{\link{tskrrHeterogeneous}} for more details. #' #' @seealso the classes \code{\link{tskrrHomogeneous}} and #' \code{\link{tskrrHeterogeneous}} for the actual classes. #' #' @importFrom utils str #' #' @rdname tskrr-class #' @name tskrr-class #' @exportClass tskrr setOldClass("eigen") setClass("tskrr", slots = c(y = "matrix", k = "eigen", lambda.k = "numeric", pred = "matrix", has.hat = "logical", Hk = "matrix", labels = "list"), prototype = list(y = matrix(0), k = structure(list(vectors = matrix(0), values = numeric(1)), class = "eigen" ), lambda.k = 1e-4, pred = matrix(0), has.hat = FALSE, Hk = matrix(0), labels = list(k = NA_character_, g = NA_character_))) validTskrr <- function(object){ if(!all(is.numeric(object@y), is.numeric(object@pred))) return("y and pred should be a numeric matrix.") else if(length([email protected]) != 1) return("lambda.k should be a single value.") else if(length(object@labels) != 2) return("labels should be a list with 2 elements") else if(any(names(object@labels) != c("k","g"))) return("The elements in labels should be called k and g") else if(!all(sapply(object@labels, is.character))) return("The elements in labels should be character vectors") else return(TRUE) } setValidity("tskrr", validTskrr) ################################################ # SHOW METHOD .show_tskrr <- function(object, homogeneous){ dims <- paste(dim(object@y), collapse = " x ") cat("Dimensions:", dims,"\n") cat("Lambda:\n") print(lambda(object)) labs <- labels(object) if(homogeneous) cat("\nLabels:") else cat("\nRow Labels:") str(labs$k, give.length = FALSE, give.head = FALSE, width = getOption("width") - 11) if(!homogeneous){ cat("Col Labels:") str(labs$g, give.length = FALSE, give.head = FALSE, width = getOption("width") - 11) } } setMethod("show", "tskrr", function(object){ ishomog <- is_homogeneous(object) type <- ifelse(ishomog,"Homogeneous","Heterogeneous") tl <- ifelse(ishomog,"----------","------------") cat(paste(type,"two-step kernel ridge regression"), paste(tl,"--------------------------------",sep="-"), sep = "\n") .show_tskrr(object, ishomog) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrr.R
#' Class tskrrHeterogeneous #' #' The class tskrrHeterogeneous is a subclass of the superclass #' \code{\link[xnet:tskrr-class]{tskrr}} specifically for #' heterogeneous networks. #' #' @slot y the matrix with responses #' @slot k the eigen decomposition of the kernel matrix for the rows #' @slot lambda.k the lambda value used for k #' @slot pred the matrix with the predictions #' @slot g the eigen decomposition of the kernel matrix for the columns #' @slot lambda.g the lambda value used for g #' @slot has.hat a logical value indicating whether the kernel hat matrices #' are stored in the object. #' @slot Hk the kernel hat matrix for the rows. #' @slot Hg the kernel hat matrix for the columns. #' @slot labels a list with elements \code{k} and \code{g} (see #' \code{\link{tskrr-class}}). #' If any element is \code{NA}, the labels used #' are integers indicating the row resp column number. #' #' @include Class_tskrr.R #' @rdname tskrrHeterogeneous-class #' @name tskrrHeterogeneous-class #' @aliases tskrrHeterogeneous #' @exportClass tskrrHeterogeneous setClass("tskrrHeterogeneous", contains = "tskrr", slots = c(g = "eigen", lambda.g = "numeric", Hg = "matrix"), prototype = list(lambda.g = 1e-4, g = structure(list(vectors = matrix(0), values = numeric(1)), class = "eigen"), Hg = matrix(0) ) ) validTskrrHeterogeneous <- function(object){ if(length([email protected]) != 1) return("lambda.g should be a single value") else if([email protected] && !valid_dimensions(object@y, object@Hk, object@Hg)) return("The dimensions of the original kernel matrices and the observations don't match.") else if( (length(object@labels$k) == 1 && !is.na(object@labels$k)) && (length(object@labels$k) != nrow(object@y)) ) return("The labels element k should either be NA or a character vector with the same number of values as there are rows in the Y matrix.") else if( (length(object@labels$g) == 1 && !is.na(object@labels$g)) && (length(object@labels$g) != ncol(object@y)) ) return("The labels element g should either be NA or a character vector with the same number of values as there are columns in the Y matrix.") else return(TRUE) } setValidity("tskrrHeterogeneous", validTskrrHeterogeneous)
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrHeterogeneous.R
#' Class tskrrHomogeneous #' #' The class tskrrHomogeneous is a subclass of the superclass #' \code{\link[xnet:tskrr-class]{tskrr}} specifically for #' homogeneous networks. #' #' @slot y the matrix with responses #' @slot k the eigen decomposition of the kernel matrix for the rows #' @slot lambda.k the lambda value used for k #' @slot pred the matrix with the predictions #' @slot symmetry a character value that can have the possible values #' \code{"symmetric"}, \code{"skewed"} or \code{"not"}. It indicates #' whether the \code{y} matrix is symmetric, skewed-symmetric or not #' symmetric. #' @slot has.hat a logical value indicating whether the kernel hat matrices #' are stored in the object. #' @slot Hk the kernel hat matrix for the rows. #' @slot labels a list with elements \code{k} and \code{g} (see #' \code{\link{tskrr-class}}). For homogeneous networks, \code{g} #' is always \code{NA}. If \code{k} is \code{NA}, the labels used #' are integers indicating the row resp column number. #' #' @include Class_tskrr.R #' @rdname tskrrHomogeneous-class #' @name tskrrHomogeneous-class #' @aliases tskrrHomogeneous #' @exportClass tskrrHomogeneous setClass("tskrrHomogeneous", contains = "tskrr", slots = c(symmetry = "character"), prototype = list(symmetry = "not") ) validTskrrHomogeneous <- function(object){ if(!object@symmetry %in% c("symmetric","skewed", "not")) return("symmetry should be one of: symmetric, skewed or not.") else if([email protected] && !valid_dimensions(object@y, object@Hk)) return("The dimensions of the original kernel matrices and the observations don't match.") else if(!length(object@labels$g) == 1 || !is.na(object@labels$g)) return("The element g of labels should be NA") else if( (length(object@labels$k) == 1 && !is.na(object@labels$k)) && (length(object@labels$k) != nrow(object@y)) ) return("The element k should either be NA or a character vector with the same number of values as there are rows in the Y matrix.") else return(TRUE) } setValidity("tskrrHomogeneous", validTskrrHomogeneous)
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrHomogeneous.R
#' Class tskrrImpute #' #' The class \code{tskrrImpute} is a virtual class that represents a #' \code{\link[xnet:tskrr-class]{tskrr}} model with imputed values in #' the label matrix Y. Apart from the model, it contains the #' following extra information on the imputed values. #' #' @slot imputeid a vector with integer values indicating which of #' the values in \code{y} are imputed #' @slot niter an integer value gving the number of iterations used #' @slot tol a numeric value with the tolerance used #' #' @rdname tskrrImpute-class #' @aliases tskrrImpute #' @exportClass tskrrImpute setClass("tskrrImpute", slots = c(imputeid = "integer", niter = "integer", tol = "numeric"), prototype = prototype( niter = 0L, tol = 0L ) ) validTskrrImpute <- function(object){ if(length(object@niter) != 1) return("niter should contain a single integer value") if(length(object@tol) != 1) return("tol should contain a single numeric value") } setValidity("tskrrImpute", validTskrrImpute) setMethod("show", "tskrrImpute", function(object){ ishomog <- is_homogeneous(object) type <- ifelse(ishomog,"Homogeneous","Heterogeneous") tl <- ifelse(ishomog,"----------","------------") cat(paste(type,"two-step kernel ridge regression with imputation"), paste(tl,"------------------------------------------------",sep="-"), sep = "\n") .show_tskrr(object, ishomog) cat("\nImputation information:\n") cat("-----------------------\n") cat("iterations:", object@niter,"\n") cat("tolerance:", signif(object@tol, 4),"\n") })
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrImpute.R
#' Class tskrrImputeHeterogeneous #' #' The class \code{tskrrImputeHeterogeneous} is a subclass of the #' class \code{\link[xnet:tskrrHeterogeneous-class]{tskrrHeterogeneous}} and #' \code{\link[xnet:tskrrImpute-class]{tskrrImpute}} #' specifically for heterogeneous networks with imputed values. It is #' the result of the function \code{\link{impute_tskrr}}. #' #' @slot y the matrix with responses #' @slot k the eigen decomposition of the kernel matrix for the rows #' @slot lambda.k the lambda value used for k #' @slot pred the matrix with the predictions #' @slot g the eigen decomposition of the kernel matrix for the columns #' @slot lambda.g the lambda value used for g #' @slot has.hat a logical value indicating whether the kernel hat matrices #' are stored in the object. #' @slot Hk the kernel hat matrix for the rows. #' @slot Hg the kernel hat matrix for the columns. #' @slot labels a list with elements \code{k} and \code{g} (see #' \code{\link{tskrr-class}}). #' If any element is \code{NA}, the labels used #' are integers indicating the row resp column number. #' @slot imputeid a vector with integer values indicating which of #' the values in \code{y} are imputed #' @slot niter an integer value gving the number of iterations used #' @slot tol a numeric value with the tolerance used #' #' @include Class_tskrrHeterogeneous.R Class_tskrrImpute.R #' @rdname tskrrImputeHeterogeneous-class #' @aliases tskrrImputeHeterogeneous #' @exportClass tskrrImputeHeterogeneous setClass("tskrrImputeHeterogeneous", contains = c("tskrrImpute", "tskrrHeterogeneous") )
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrImputeHeterogeneous.R
#' Class tskrrImputeHomogeneous #' #' The class \code{tskrrImputeHomogeneous} is a subclass of the #' class \code{\link[xnet:tskrrHomogeneous-class]{tskrrHomogeneous}} and #' \code{\link[xnet:tskrrImpute-class]{tskrrImpute}} #' specifically for homogeneous networks with imputed values. It is #' the result of the function \code{\link{impute_tskrr}} on a #' homogeneous network model. #' #' @slot y the matrix with responses #' @slot k the eigen decomposition of the kernel matrix for the rows #' @slot lambda.k the lambda value used for k #' @slot pred the matrix with the predictions #' @slot symmetry a character value that can have the possible values #' \code{"symmetric"}, \code{"skewed"} or \code{"not"}. It indicates #' whether the \code{y} matrix is symmetric, skewed-symmetric or not #' symmetric. #' @slot has.hat a logical value indicating whether the kernel hat matrices #' are stored in the object. #' @slot Hk the kernel hat matrix for the rows. #' @slot labels a list with elements \code{k} and \code{g} (see #' \code{\link{tskrr-class}}). For homogeneous networks, \code{g} #' is always \code{NA}. If \code{k} is \code{NA}, the labels used #' are integers indicating the row resp column number. #' @slot imputeid a vector with integer values indicating which of #' the values in \code{y} are imputed #' @slot niter an integer value gving the number of iterations used #' @slot tol a numeric value with the tolerance used #' #' @include Class_tskrrHomogeneous.R Class_tskrrImpute.R #' @rdname tskrrImputeHomogeneous-class #' @aliases tskrrImputeHomogeneous #' @exportClass tskrrImputeHomogeneous setClass("tskrrImputeHomogeneous", contains = c("tskrrImpute", "tskrrHomogeneous") )
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrImputeHomogeneous.R
#' Class tskrrTune #' #' The class tskrrTune represents a tuned \code{\link[xnet:tskrr-class]{tskrr}} #' model, and is the output of the function \code{\link{tune}}. Apart from #' the model, it contains extra information on the tuning procedure. This is #' a virtual class only. #' #' @slot lambda_grid a list object with the elements \code{k} and possibly #' \code{g} indicating the tested lambda values for the row kernel \code{K} #' and - if applicable - the column kernel \code{G}. Both elements have #' to be numeric. #' @slot best_loss a numeric value with the loss associated with the #' best lambdas #' @slot loss_values a matrix with the loss results from the searched grid. #' The rows form the X dimension (related to the first lambda), the columns #' form the Y dimension (related to the second lambda if applicable) #' @slot loss_function the used loss function #' @slot exclusion a character value describing the exclusion used #' @slot replaceby0 a logical value indicating whether or not the cross #' validation replaced the excluded values by zero #' @slot onedim a logical value indicating whether the grid search #' was done in one dimension. For homogeneous networks, this is #' true by default. #' #' @seealso #' * the function \code{tune} for the tuning itself #' * the class \code{\link{tskrrTuneHomogeneous}} and #' \code{tskrrTuneHeterogeneous} for the actual classes. #' @md #' #' @rdname tskrrTune-class #' @name tskrrTune-class #' @aliases tskrrTune #' @exportClass tskrrTune setClass("tskrrTune", slots = c(lambda_grid = "list", best_loss = "numeric", loss_values = "matrix", loss_function = "function", exclusion = "character", replaceby0 = "logical", onedim = "logical")) validTskrrTune <- function(object){ lossval <- object@loss_values lgrid <- object@lambda_grid excl <- object@exclusion # General tests if(!all(sapply(lgrid, is.numeric))) return("lambda_grid should have only numeric elements.") if(length(object@best_loss) != 1) return("best_loss should be a single value.") if(length(excl) != 1) return("exclusion should be a single character value.") if(length(object@onedim) != 1) return("onedim should be a single logical value.") else return(TRUE) } setValidity("tskrrTune", validTskrrTune) setMethod("show", "tskrrTune", function(object){ # HEADER ishomog <- is_homogeneous(object) type <- ifelse(ishomog,"homogeneous","heterogeneous") tl <- ifelse(ishomog,"----------","------------") cat(paste("Tuned",type,"two-step kernel ridge regression"), paste("-----",tl,"--------------------------------",sep="-"), sep = "\n") .show_tskrr(object, ishomog) # Information on tuning excl <- object@exclusion if(object@replaceby0) excl <- paste(excl,"(values replaced by 0)") if(identical(object@loss_function, loss_mse)) loss_name <- "Mean Squared Error (loss_mse)" else if(identical(object@loss_function, loss_auc)) loss_name <- "Area under curve (loss_auc)" else loss_name <- "custom function by user" cat("\nTuning information:\n") cat("-------------------\n") cat("exclusion setting:",object@exclusion,"\n") cat("loss value:", object@best_loss,"\n") cat("loss function:", loss_name,"\n") if(object@onedim && is_heterogeneous(object)) cat("Grid search done in one dimension.\n") })
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrTune.R
#' Class tskrrTuneHeterogeneous #' #' The class tskrrTuneHeterogeneous represents a tuned Heterogeneous #' \code{\link[xnet:tskrr-class]{tskrr}} model. It inherits from #' the classes \code{\link[xnet:tskrrHeterogeneous-class]{tskrrHeterogeneous}} #' and \code{\link[xnet:tskrrTune-class]{tskrrTune}}. #' #' @rdname tskrrTuneHeterogeneous-class #' @name tskrrTuneHeterogeneous-class #' @aliases tskrrTuneHeterogeneous #' @exportClass tskrrTuneHeterogeneous setClass("tskrrTuneHeterogeneous", contains = c("tskrrTune", "tskrrHeterogeneous")) validTskrrTuneHeterogeneous <- function(object){ lossval <- object@loss_values lgrid <- object@lambda_grid excl <- object@exclusion onedim <- object@onedim if(!onedim && any(names(lgrid) != c("k","g"))) return("lambda grid should be a list with two elements named k and g (in that order) for heterogeneous networks") else if(onedim && any(names(lgrid) != "k") && length(lgrid) > 1) return("in a one-dimensional search there should only be a single element named k in the lambda grid.") if(nrow(lossval) != length(lgrid$k)) return(paste("Loss values should have",length(lgrid$k),"rows to match the lambda grid.")) if(!onedim && ncol(lossval) != length(lgrid$g)) return(paste("Loss values should have",length(lgrid$g),"columns to match the lambda grid.")) else if(onedim && ncol(lossval) != 1) return(paste("Loss values should have one column in case of one-dimensional search.")) exclmatch <- match(excl, c("interaction","row","column","both"), nomatch = 0L) if(exclmatch == 0) return("exclusion should be one of 'interaction', 'row', 'column' or 'both'") if(object@replaceby0 && excl != "interaction") return("replaceby0 can only be used with interaction exclusion") else return(TRUE) } setValidity("tskrrTuneHeterogeneous", validTskrrTuneHeterogeneous)
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrTuneHeterogeneous.R
#' Class tskrrTuneHomogeneous #' #' The class tskrrTuneHomogeneous represents a tuned homogeneous #' \code{\link[xnet:tskrr-class]{tskrr}} model. It inherits from #' the classes \code{\link[xnet:tskrrHomogeneous-class]{tskrrHomogeneous}} #' and \code{\link[xnet:tskrrTune-class]{tskrrTune}}. #' #' @rdname tskrrTuneHomogeneous-class #' @name tskrrTuneHomogeneous-class #' @aliases tskrrTuneHomogeneous #' @exportClass tskrrTuneHomogeneous setClass("tskrrTuneHomogeneous", contains = c("tskrrTune", "tskrrHomogeneous")) validTskrrTuneHomogeneous <- function(object){ lossval <- object@loss_values lgrid <- object@lambda_grid excl <- object@exclusion if(names(lgrid) != "k") return("lambda_grid should be a list with one element named k for homogeneous networks.") if(ncol(lossval) != 1 || nrow(lossval) != length(lgrid$k)) return(paste("Loss values should have 1 row and",length(lgrid$k),"columns to match the lambda grid.")) exclmatch <- match(excl, c("edges","vertices"), nomatch = 0L) if(exclmatch == 0) return("exclusion should be either 'interaction' or 'both' for homogeneous networks.") else if(!object@onedim) return("grid search can only be done in one dimension for a homogeneous network.") if(object@replaceby0 && excl != "edges") return("replaceby0 can only be used with edges exclusion") else return(TRUE) } setValidity("tskrrTuneHomogeneous", validTskrrTuneHomogeneous)
/scratch/gouwar.j/cran-all/cranData/xnet/R/Class_tskrrTuneHomogeneous.R
# Classes needed for generics setOldClass("htest") # All Generics #' @rdname get_loo_fun #' @export setGeneric("get_loo_fun", function(x, ...) standardGeneric("get_loo_fun")) #' @rdname loo #' @export setGeneric("loo", function(x, ...) standardGeneric("loo")) ## For tskrr setGeneric("response", function(x, ...) standardGeneric("response")) setGeneric("lambda", function(x, ...) standardGeneric("lambda")) setGeneric("tune", function(x, ...) standardGeneric("tune")) #' @rdname permtest #' @export setGeneric("permtest", function(x, ...) standardGeneric("permtest")) #' @rdname update #' @export setGeneric("update") # For the hat matrices #' @rdname hat setGeneric("hat", function(x, ...) standardGeneric("hat")) setMethod("hat", "ANY", stats::hat) # For the labels setGeneric("labels") setGeneric("rownames") setGeneric("colnames") setGeneric("dimnames") # For the dimensions setGeneric("dim") # For the linearFilter setGeneric("mean") setGeneric("colMeans") setGeneric("rowMeans") #' @rdname getters_linearFilter #' @export setGeneric("alpha", function(x) standardGeneric("alpha")) #' @rdname getters_linearFilter #' @export setGeneric("na_removed", function(x) standardGeneric("na_removed")) # For the tune #' @rdname as_tuned setGeneric("as_tuned", function(x, ...) standardGeneric("as_tuned")) #' @rdname as_tuned setGeneric("as_tskrr", function(x, ...) standardGeneric("as_tskrr")) #' @rdname loss #' @export setGeneric("loss", function(x, ...) standardGeneric("loss")) #' @rdname residuals.tskrr #' @export setGeneric("residuals")
/scratch/gouwar.j/cran-all/cranData/xnet/R/all_generics.R
#' convert tskrr models #' #' These functions allow converting models that inherit from the #' \code{\link[xnet:tskrr-class]{tskrr}} and #' \code{\link[xnet:tskrrTune-class]{tskrrTune}} class into each other, #' keeping track of whether the model is homogeneous or heterogeneous. #' The dots argument allows specifying values for possible extra slots #' when converting from \code{tskrr} to \code{tskrrTune}. #' More information on these slots can be found #' on the help page of \code{\link[xnet:tskrrTune-class]{tskrrTune}}. #' **These functions are not exported.** #' #' @section \bold{Warning}: #' This functions do NOT tune a model. they are used internally to #' make the connection between both types in the methods. #' #' @seealso #' * \code{\link{tune}} for actually tuning a model. #' * \code{\link[xnet:tskrrTune-class]{tskrrTune}} for #' names and possible values of the slots passed through #' \dots #' @md #' #' @param x a model of class \code{\link[xnet:tskrr-class]{tskrr}} #' @param ... values for the extra slots defined by #' the class \code{\link[xnet:tskrrTune-class]{tskrrTune}} #' #' @return For \code{as_tuned}: #' a \code{\link[xnet:tskrrTune-class]{tskrrTune}} object of #' the proper class (homogeneous or heterogeneous) #' #' @include all_generics.R #' @rdname as_tuned #' @method as_tuned tskrrHomogeneous setMethod("as_tuned", "tskrrHomogeneous", function(x, ...){ x <- as(x, "tskrrTuneHomogeneous") initialize(x, ...) }) #' @rdname as_tuned #' @method as_tuned tskrrHeterogeneous setMethod("as_tuned", "tskrrHeterogeneous", function(x, ...){ x <- as(x, "tskrrTuneHeterogeneous") initialize(x, ...) }) #' @rdname as_tuned #' @return For \code{as_tskrr}: an object of class #' \code{\link[xnet:tskrrHomogeneous-class]{tskrrHomogeneous}} or #' \code{\link[xnet:tskrrHeterogeneous-class]{tskrrHeterogeneous}} depending #' on whether the original object was homogeneous or heterogeneous. #' #' @method as_tskrr tskrrTune setMethod("as_tskrr", "tskrrTune", function(x){ if(is_homogeneous(x)) as(x, "tskrrHomogeneous") else as(x, "tskrrHeterogeneous") }) #' @rdname as_tuned #' @method as_tskrr tskrrImpute setMethod("as_tskrr", "tskrrImpute", function(x){ if(is_homogeneous(x)) as(x, "tskrrHomogeneous") else as(x, "tskrrHeterogeneous") }) #' @rdname as_tuned #' @method as_tskrr tskrr setMethod("as_tskrr", "tskrr", function(x){ return(x) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/as_tuned.R
#' Create a grid of values for tuning tskrr #' #' This function creates a grid of values for #' tuning a \code{\link{tskrr}} model. The grid is equally spaced on #' a logarithmic scale. Normally it's not needed to call this method #' directly, it's usually called from \code{\link{tune}}. #' #' The \code{lim} argument sets the boundaries of the domain in which #' the lambdas are sought. The lambda values at which the function is #' evaluated, are calculated as: #' #' \code{exp(seq(log(1e-4), log(1e4), length.out = ngrid))} #' #' @param lim a numeric vector with 2 values giving the lower and upper limit #' for the grid. #' @param ngrid the number of values that have to be produced. If this #' number is not integer, it is truncated. The value should be 2 or #' larger. #' #' @return a numeric vector with values evenly spaced on a #' logarithmic scale. #' #' @seealso \code{\link{tune}} for tuning a tskrr model. #' #' @examples #' create_grid(lim = c(1e-4, 1), ngrid = 5) #' #' @export create_grid <- function(lim = c(1e-4, 1e4), ngrid = 10){ if(!length(lim) == 2 || !is.numeric(lim)) stop("The argument lim needs 2 numeric values.") if(!length(ngrid) == 1 || !is.numeric(ngrid)) stop("The argument ngrid should be a single numeric value.") #Optimized for speed llim <- log(lim) by <- (llim[2] - llim[1])/(ngrid - 1L) exp(c(llim[1], llim[1] + seq_len(ngrid - 2L) * by, llim[2])) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/create_grid.R
#' drug target interactions for neural receptors #' #' A dataset for examining the interaction between 54 drugs and 26 #' neural receptors. It consists of three different matrices. #' #' The dataset consists of the following objects : #' #' \itemize{ #' \item drugTargetInteraction: a matrix indicating whether or not a #' certain drug compound interacts with a certain neural receptor. #' \item targetSim: a similarity matrix for the neural receptors. #' \item drugSim: a similarity matrix for the drugs #' } #' #' The data originates from Yamanishi et al (2008) but was partly reworked #' to be suitable for two-step kernel ridge regression. This is explained #' in detail in the \href{../doc/Preparation_example_data.html}{Preparation of #' the example data} vignette. #' #' @format #' \itemize{ #' \item for drugTargetInteraction: a numeric matrix of 26 rows by #' 54 columns. #' \item For drugSim: a numeric square matrix with 54 rows/columns. #' \item For targetSim: a numeric square matrix with 26 rows/columns. #' } #' #' @references \href{https://doi.org/10.1093/bioinformatics/btn162}{Yamanishi et al, 2008} : Prediction of drug-target interaction networks from the #' integration of chemical and genomic spaces. #' #' @source \url{https://doi.org/10.1093/bioinformatics/btn162} #' @aliases drugtarget drugSim targetSim "drugTargetInteraction"
/scratch/gouwar.j/cran-all/cranData/xnet/R/data_drugtarget.R
#' Protein interaction for yeast #' #' A dataset for examining the interaction between proteins of #' yeast. The dataset consists of the following objects: #' #' \itemize{ #' \item proteinInteraction: the label matrix based on the protein #' network taken from the KEGG/PATHWAY database #' \item Kmat_y2h_sc: a kernel matrix indicating similarity of proteins. #' } #' #' The proteins in the dataset are a subset of the 769 proteins #' used in Yamanishi et al (2004). The kernel matrix used is the #' combination of 4 kernels: one based on expression data, one #' on protein interaction data, one on localization data and one #' on phylogenetic profile. These kernels and their combination are #' also explained in Yamanishi et al (2004). #' #' @format #' \itemize{ #' \item proteinInteraction: a numeric square matrix with 150 rows/columns #' \item Kmat_y2h_sc: a numeric square matrix with 150 rows/columns #' } #' #' @references \href{https://doi.org/10.1093/bioinformatics/bth910}{Yamanishi et al, 2004}: Protein network inference from multiple genomic data: a supervised approach. #' #' @source \url{https://doi.org/10.1093/bioinformatics/bth910} #' @aliases Kmat_y2h_sc "proteinInteraction"
/scratch/gouwar.j/cran-all/cranData/xnet/R/data_proteinInteraction.R
#' Get the dimensions of a tskrr object #' #' These functions allow you to extract the dimensions of a tskrr #' object. These dimensions are essentially the dimensions of the #' label matrix y. #' #' @param x a \code{\link[=tskrr-class]{tskrr}} object. #' #' @return a vector with two values indicating the number of rows #' and the number of columns. #' #' @examples #' data(drugtarget) #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' dim(mod) #' nrow(mod) #' ncol(mod) #' #' @aliases dim.tskrr #' @export setMethod("dim", "tskrr", function(x){ dim(x@y) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/dim.R
#' Calculate the hat matrix from an eigen decomposition #' #' These functions calculate either the hat matrix, the mapping matrix or #' the original (kernel) matrix for a two-step kernel ridge regression, #' based on the eigendecomposition of the kernel matrix. #' #' For the hat matrix, this boils down to: #' #' \deqn{U\Sigma(\Sigma + \lambda I)^{-1} U^{T}} #' #' For the map matrix, this is : #' #' \deqn{U(\Sigma + \lambda I)^{-1} U^{T}} #' #' with \eqn{U} the matrix with eigenvectors, \eqn{\Sigma} a diagonal matrix #' with the eigenvalues on the diagonal, \eqn{I} the identity matrix and #' \eqn{\lambda} the hyperparameter linked to this kernel. #' The internal calculation is optimized to avoid having to invert #' a matrix. This is done using the fact that \eqn{\Sigma} is a #' diagonal matrix. #' #' @param eigen a matrix with the eigenvectors. #' @param val an numeric vector with the eigenvalues. #' @param lambda a single numeric value for the hyperparameter lambda #' #' @return a numeric matrix representing either the hat matrix #' (\code{eigen2hat}), the map matrix (\code{eigen2map}) or #' the original matrix (\code{eigen2matrix}) #' #' @export eigen2hat <- function(eigen, val , lambda){ # Sigma is a diagonal matrix, so Sigma %*% Sigma + lambdaI can # be calculated based on the vals as val * 1/(val + lambda) # This can be calculated first due to associativity of the # matrix multiplication. mid <- val / (val + lambda) # Use recycling to calculate the right side first # thanks to associativity of the matrix multiplication. return(eigen %*% (mid * t(eigen))) } #' @rdname eigen2hat #' @export eigen2map <- function(eigen, val, lambda){ mid <- 1 / (val + lambda) # Use recycling to calculate the right side first # thanks to associativity of the matrix multiplication. return(eigen %*% (mid * t(eigen))) } #' @rdname eigen2hat #' @export eigen2matrix <- function(eigen, val){ return(eigen %*% (val * t(eigen)) ) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/eigen2hat.R
#' extract the predictions #' #' This functions extracts the fitted predictions from a #' \code{\link[xnet:tskrr-class]{tskrr}} object or an object #' inheriting from that class. The \code{xnet} #' package provides an S4 generic for the function #' \code{\link[=fitted]{fitted}} from the package \code{stats}, #' and a method for \code{\link[xnet:tskrr-class]{tskrr}} objects. #' #' @param object an object for which the extraction of model fitted values #' is meaningful. #' @param ... arguments passed to or from other methods. #' @param labels a logical value indicating whether the labels should #' be shown. Defaults to TRUE #' #' @return a numeric matrix with the predictions #' #' @examples #' #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' pred <- fitted(mod) #' #' @include all_generics.R #' #' #' @rdname fitted #' @method fitted tskrr #' @export fitted.tskrr <- function(object, labels = TRUE, ...){ out <- object@pred if(labels){ l <- labels(object) rownames(out) <- l$k colnames(out) <- l$g } out } #' @rdname fitted #' @method fitted linearFilter #' @export fitted.linearFilter <- function(object, ...){ object@pred } #' @rdname fitted #' @export setMethod("fitted", "tskrr", fitted.tskrr) #' @rdname fitted #' @export setMethod("fitted", "linearFilter", fitted.linearFilter)
/scratch/gouwar.j/cran-all/cranData/xnet/R/fitted.R
#' Retrieve a loo function #' #' This function returns the correct function needed to perform #' one of the leave-one-out cross-validations. It's primarily meant #' for internal use but can be useful when doing simulations. #' #' This function can be used to select the correct loo function in #' a simulation or tuning algorithm, based on the model object you #' created. Depending on its class, the returned functions will have #' different arguments, so you should only use this if you know #' what you're doing and after you checked the actual returned #' functions in \code{\link{loo_internal}}. #' #' Using \code{replaceby0} only makes sense if you only remove the interaction. #' In all other cases, this argument is ignored. #' #' For the class \code{tskrrHomogeneous}, it doesn't make sense to #' remove rows or columns. If you chose this option, the function will #' throw an error. Removing edges corresponds to the setting "edges" or #' "interaction". Removing vertices corresponds to the setting "vertices" or #' "both". These terms can be used interchangeably. #' #' For the class \code{linearFilter} it only makes sense to exclude the #' interaction (i.e., a single cell). Therefore you do not have an argument #' \code{exclusion} for that method. #' #' For the classes \code{tskrrTune} and \code{tskrrImpute}, #' not specifying \code{exclusion} or \code{replaceby0} returns the used #' loo function. If you specify either of them, #' it will use the method for the appropriate model and return #' a new loo function. #' #' @inheritParams loo #' @param x a character value with the class or a \code{\link{tskrr}} #' or \code{\link{linearFilter}} object. #' @param ... arguments passed to or from other methods. #' #' @return a function taking the arguments y, and possibly pred #' for calculating the leave-one-out cross-validation. For class #' \code{tskrrHeterogeneous}, the returned function also #' has an argument Hk and Hg, representing the hat matrix for the rows #' and the columns respectively. For class \code{tskrrHomogeneous}, #' only the extra argument Hk is available. For class \code{linearFilter}, #' the extra argument is called \code{alpha} and takes the alpha vector #' of that model. #' #' @seealso \code{\link{loo}} for carrying out a leave on out crossvalidation, #' and \code{\link{loo_internal}} for more information on the internal #' functions one retrieves with this one. #' #' @rdname get_loo_fun #' @export setMethod("get_loo_fun", "tskrrHeterogeneous", function(x, exclusion = c("interaction","row","column","both"), replaceby0 = FALSE ){ exclusion <- match.arg(exclusion) .getloo_heterogeneous(exclusion, replaceby0) }) #' @rdname get_loo_fun #' @export setMethod("get_loo_fun", "tskrrHomogeneous", function(x, exclusion = c("edges","vertices","interaction","both"), replaceby0 = FALSE ){ exclusion <- match.arg(exclusion) symmetry <- symmetry(x) .getloo_homogeneous(exclusion,replaceby0, symmetry) }) #' @rdname get_loo_fun #' @export setMethod("get_loo_fun", "linearFilter", function(x, replaceby0 = FALSE){ .getloo_linearfilter(replaceby0) }) #' @rdname get_loo_fun #' @export setMethod("get_loo_fun", "character", function(x = c("tskrrHeterogeneous","tskrrHomogeneous","linearFilter"), ...){ x <- match.arg(x) fun <- switch(x, tskrrHeterogeneous = .getloo_heterogeneous, tskrrHomogeneous = .getloo_homogeneous, linearFilter = .getloo_linearfilter) fun(...) }) #' @rdname get_loo_fun #' @export setMethod("get_loo_fun", "tskrrTune", function(x, ... ){ dots <- list(...) class <- if(is_homogeneous(x)) "tskrrHomogeneous" else "tskrrHeterogeneous" if(length(dots)) do.call(get_loo_fun, c(as(x, class), dots)) else get_loo_fun(as(x, class), exclusion = x@exclusion, replaceby0 = x@replaceby0) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/get_loo_fun.R
# Internal functions for get_loo_fun .getloo_heterogeneous <- function(exclusion, replaceby0){ if(exclusion == "interaction"){ if(replaceby0) loo.i0 else loo.i } else if(exclusion == "row"){ loo.r } else if(exclusion == "column"){ loo.c } else if(exclusion == "both"){ loo.b } else { stop("Exclusion should be one of interaction, row, column or both.") } } .getloo_homogeneous <- function(exclusion, replaceby0, symmetry){ # Translate edges and vertices if(exclusion %in% c("interaction","both")) exclusion <- switch(exclusion, interaction = "edges", both = "vertices") if(exclusion == "edges"){ if(symmetry == "symmetric"){ if(replaceby0) loo.e0.sym else loo.e.sym } else if(symmetry == "skewed"){ if(replaceby0) loo.e0.skew else loo.e.skew } else { stop("No loo optimization for homogeneous networks that aren't symmetric or skewed.") } } else if(exclusion == c("vertices")) { # exclusion is not interaction loo.v } else { stop("Exclusion should be one of edges or vertices") } } # dots catch other arguments to avoid errors when exclusion is passed .getloo_linearfilter <- function(replaceby0, ...){ if(replaceby0) loo.i0.lf else loo.i.lf }
/scratch/gouwar.j/cran-all/cranData/xnet/R/getlooInternal.R
#' Getters for linearFilter objects #' #' These functions allow you to extract slots from objects of the #' class \code{\link{linearFilter}}. #' #' @param x a \code{linearFilter} object #' @param ... arguments passed to or from other methods. #' #' @return for \code{mean}: the mean of the original matrix #' #' @examples #' data(drugtarget) #' lf <- linear_filter(drugTargetInteraction, alpha = 0.25) #' alpha(lf) #' mean(lf) #' colMeans(lf) #' na_removed(lf) #' #' @rdname getters_linearFilter #' @name getters_linearFilter #' #' @method mean linearFilter #' @export mean.linearFilter <- function(x,...){ x@mean } #' @rdname getters_linearFilter #' @export setMethod("mean", "linearFilter", mean.linearFilter) #' @rdname getters_linearFilter #' @return for \code{colMeans}: a numeric vector with the column means #' @export setMethod("colMeans", "linearFilter", function(x) x@colmeans) #' @rdname getters_linearFilter #' @return for \code{rowMeans}: a numeric vector with the row means #' @export setMethod("rowMeans", "linearFilter", function(x) x@rowmeans) #' @rdname getters_linearFilter #' @return for \code{alpha}: a numeric vector of length 4 with the alpha #' values. #' @export setMethod("alpha", "linearFilter", function(x) x@alpha) #' @rdname getters_linearFilter #' @return for \code{na_removed}: a logical value indicating whether #' missing values were removed prior to the fitting of the filter. #' @export setMethod("na_removed", "linearFilter", function(x) [email protected])
/scratch/gouwar.j/cran-all/cranData/xnet/R/getters_linearFilter.R
#' Getters for permtest objects #' #' The functions described here are convenience functions to get #' information out of a \code{\link[xnet:permtest-class]{permtest}} #' object. #' #' @param x a \code{\link[xnet:permtest-class]{permtest}} object #' @param i either a numeric vector, a logical vector or a character #' vector with the elements that need extraction. #' #' @return the requested values #' #' @seealso \code{\link{loss}} to extract the original loss value. #' #' @examples #' #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' ptest <- permtest(mod, fun = loss_auc) #' #' loss(ptest) #' ptest[c(2,3)] #' permutations(ptest) #' #' @rdname getters-permtest #' @aliases Extract-permtest permutations #' @export permutations <- function(x){ if(!inherits(x, "permtest")) stop("x has to be of class permtest") x@perm_losses } #' @rdname getters-permtest #' @export setMethod("[", c("permtest","ANY"), function(x,i){ res <- .make_res_table(x@perm_losses, x@orig_loss, x@pval) tryCatch(res[,i], error = function(e){ stop("Could not find requested element(s).", call. = FALSE) }) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/getters_permtest.R
#' Getters for tskrr objects #' #' The functions described here are convenience functions to get #' information out of a \code{\link[xnet:tskrr-class]{tskrr}} object. #' #' @section Warning: The function \code{get_kernel} is deprecated. #' Use \code{get_kernelmatrix} instead. #' #' @param x a \code{\link[xnet:tskrr-class]{tskrr}} object or an #' object inheriting from \code{tskrr}. #' @param ... arguments passed to other methods. #' #' @examples #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' is_homogeneous(mod) #' #' EigR <- get_eigen(mod) #' EigC <- get_eigen(mod, which = 'column') #' lambda(mod) #' #' @include all_generics.R #' @rdname getters-tskrr #' @aliases response #' @export #' @return For \code{response}: the original label matrix setMethod("response", "tskrr", function(x, ...){ x@y }) #' @rdname getters-tskrr #' @return For \code{lambda}: a named numeric vector with one resp both lambda #' values used in the model. The names are "k" and "g" respectively. #' @export setMethod("lambda", "tskrrHomogeneous", function(x){ c(k = [email protected]) }) #' @rdname getters-tskrr #' @aliases lambda #' @export setMethod("lambda", "tskrrHeterogeneous", function(x){ c(k = [email protected], g = [email protected]) }) #' @rdname getters-tskrr #' @aliases is_tskrr #' @return For \code{is_tskrr} a logical value indicating whether the #' object is a \code{tskrr} object is_tskrr <- function(x){ inherits(x, "tskrr") } #' @rdname getters-tskrr #' @aliases is_homogeneous #' @return For \code{is_homogeneous} a logical value indicating whether the #' tskrr model is a homogeneous one. #' @export is_homogeneous <- function(x){ if(!inherits(x, "tskrr")) stop("x should be a tskrr model.") inherits(x, "tskrrHomogeneous") } #' @rdname getters-tskrr #' @aliases is_heterogeneous #' @return For \code{is_heterogeneous} a logical value indicating whether the #' tskrr model is a heterogeneous one. #' @export is_heterogeneous <- function(x){ if(!inherits(x, "tskrr")) stop("x should be a tskrr model.") inherits(x, "tskrrHeterogeneous") } #' @rdname getters-tskrr #' @aliases symmetry #' @return For \code{symmetry} a character value indicating the symmetry #' for a \code{\link[xnet:tskrrHomogeneous-class]{homogeneous model}}. If #' the model is not homogeneous, \code{NA} is returned. #' @export symmetry <- function(x){ if(!is_homogeneous(x)) NA else x@symmetry } #' @rdname getters-tskrr #' @aliases get_eigen #' @param which a character value indicating whether the eigen decomposition #' for the row kernel matrix or the column kernel matrix should be returned. #' @return For \code{get_eigen} the eigen decomposition of the requested #' kernel matrix. #' @export get_eigen <- function(x, which = c('row', 'column')){ if(is_homogeneous(x)){ x@k } else { which <- match.arg(which) if(which == 'row') x@k else x@g } } #' @rdname getters-tskrr #' @aliases get_kernelmatrix #' @return For \code{get_kernelmatrix} the original kernel matrix #' for the rows or columns. #' @export get_kernelmatrix <- function(x, which = c('row','column')){ which <- match.arg(which) if(is_homogeneous(x) || which == 'row'){ eigen2matrix(x@k$vectors, x@k$values) } else{ eigen2matrix(x@g$vectors, x@g$values) } } #' @rdname getters-tskrr #' @aliases has_hat #' @return For \code{has_hat} a logical value indicating whether #' the tskrr model contains the kernel hat matrices. has_hat <- function(x){ if(!inherits(x, 'tskrr')) stop("x needs to be a tskrr model.") [email protected] } #' @rdname getters-tskrr #' @export get_kernel <- function(x, which = c('row','column')){ which <- match.arg(which) warning("This function is deprecated. Use get_kernelmatrix instead.") get_kernelmatrix(x, which) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/getters_tskrr.R
#' Getters for tskrrImpute objects #' #' The functions described here are convenience functions to get #' information out of a \code{\link[xnet:tskrrImpute-class]{tskrrImpute}} #' object. #' #' @param x a \code{\link[xnet:tskrrImpute-class]{tskrrImpute}} object or #' an object inheriting from \code{tskrrImpute}. #' #' @return For \code{has_imputed_values}: a logical value indicating whether #' the model has imputed values. If \code{x} is not some form of a #' \code{\link{tskrr}} model, the function will return an error. #' #' #' @examples #' #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' #' naid <- sample(length(drugTargetInteraction), 30) #' drugTargetInteraction[naid] <- NA #' #' impmod <- impute_tskrr(drugTargetInteraction, targetSim, drugSim) #' #' has_imputed_values(mod) #' has_imputed_values(impmod) #' #' # For illustration: extract imputed values #' id <- is_imputed(impmod) #' fitted(impmod)[id] #' #' @include all_generics.R #' @rdname getters-tskrrImpute #' @aliases has_imputed_values #' @export has_imputed_values <- function(x){ if(!inherits(x, "tskrr")) stop("x should be a tskrr model.") inherits(x, "tskrrImpute") } #' @rdname getters-tskrrImpute #' @return For \code{which_imputed}: a integer vector with the positions #' for which the values are imputed. #' @export which_imputed <- function(x){ if(!inherits(x, "tskrrImpute")) stop("x should be a tskrr model with imputed values.") x@imputeid } #' @rdname getters-tskrrImpute #' @return for \code{is_imputed}: a matrix of the same dimensions as the #' label matrix. It contains the value \code{FALSE} at positions that #' were not imputed, and \code{TRUE} at positions that were. #' @export is_imputed <- function(x){ if(!inherits(x, "tskrrImpute")) stop("x should be a tskrr model with imputed values.") dims <- dim(x@y) out <- matrix(FALSE, nrow = dims[1], ncol = dims[2]) out[x@imputeid] <- TRUE return(out) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/getters_tskrrImpute.R
#' Getters for tskrrTune objects #' #' The functions described here are convenience functions to get #' information out of a \code{\link[xnet:tskrrTune-class]{tskrrTune}} #' object. #' #' @param x a \code{\link[xnet:tskrrTune-class]{tskrrTune}} object or an #' object inheriting from \code{tskrrTune}. #' #' @return For \code{is_tuned}: a logical value indicating whether the #' model is tuned. #' #' @examples #' #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' tuned <- tune(mod, ngrid = 10) #' #' is_tuned(mod) #' is_tuned(tuned) #' #' # Basic visualization of the grid. #' #' gridvals <- get_grid(tuned) #' z <- get_loss_values(tuned) #' #' \dontrun{ #' image(gridvals$k,gridvals$g,log(z), log = 'xy', #' xlab = "lambda k", ylab = "lambda g") #' } #' #' @include all_generics.R #' @rdname getters-tskrrTune #' @aliases is_tuned #' @export is_tuned <- function(x){ if(!inherits(x, "tskrr")) stop("x should be a tskrr model.") inherits(x, "tskrrTune") } #' @return For \code{get_grid} a list with the elements \code{k} and #' possibly \code{g}, each containing the different lambdas tried in #' the tuning for the row and column kernel matrices respectively. #' @rdname getters-tskrrTune #' @aliases get_grid #' @export get_grid <- function(x){ if(!inherits(x, "tskrrTune")) stop("x should be a tuned model.") x@lambda_grid } #' @return For \code{get_loss_values} a matrix with the calculated #' loss values. Note that each row represents the result for one #' lambda value related to the row kernel matrix K. For heterogeneous #' models, every column represents the result for one lambda related #' to the column kernel matrix G. #' @rdname getters-tskrrTune #' @aliases get_loss_values #' @export get_loss_values <- function(x){ if(!inherits(x, "tskrrTune")) stop("x should be a tuned model.") x@loss_values } #' @return for \code{is_onedim} a single logical value telling whether the #' grid search in the object was onedimensional. #' @rdname getters-tskrrTune #' @aliases has_onedim has_onedim <- function(x){ if(!inherits(x, "tskrrTune")) stop("x should be a tuned model.") x@onedim }
/scratch/gouwar.j/cran-all/cranData/xnet/R/getters_tskrrTune.R
#' Return the hat matrix of a tskrr model #' #' This function returns the hat matrix or hat matrices of #' a tskrr model. \code{xnet} creates an S4 generic for \code{hat} #' and links the default method to the \code{\link[=influence.measures]{hat}} function #' of \code{stats} #' #' @param x a tskrr model #' @param which a character value with possible values "row" or #' "column" to indicate which should be returned. For homogeneous #' models, this parameter is ignored. #' @param ... arguments passed to other methods. #' #' @return the requested hat matrix of the model. #' @rdname hat #' @export setMethod("hat", "tskrrHeterogeneous", function(x, which = c('row','column')){ which <- match.arg(which) if(has_hat(x)){ if(which == "row") return(x@Hk) else return(x@Hg) } eig <- if(which == 'row') x@k else x@g l <- if(which == 'row') [email protected] else [email protected] eigen2hat(eig$vectors, eig$values, l) }) #' @rdname hat #' @export setMethod("hat", "tskrrHomogeneous", function(x, ...){ if(has_hat(x)){ return(x@Hk) } eig <- x@k l <- [email protected] eigen2hat(eig$vectors, eig$values, l) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/hat.R
#' Impute missing values in a label matrix #' #' This function implements an optimization algorithm that allows #' imputing missing values in the label matrix while fitting a #' \code{tskrr} model. #' #' @inheritParams tskrr #' @param niter an integer giving the maximum number of iterations #' @param tol a numeric value indicating the tolerance for convergence of #' the algorithm. It is the maximum sum of squared differences between #' to iteration steps. #' @param start a numeric value indicating the value with which NA's are #' replaced in the first step of the algorithm. Defaults to 0. #' @param verbose either a logical value, 1 or 2. \code{1} means "show the number #' of iterations and the final deviation", \code{2} means "show the deviation #' every 10 iterations". A value \code{TRUE} is read as \code{1}. #' #' @return A \code{tskrr} model of the class \code{\link{tskrrImputeHeterogeneous}} or \code{\link{tskrrImputeHomogeneous}} depending on whether or #' not \code{g} has a value. #' #' @examples #' #' data(drugtarget) #' #' naid <- sample(length(drugTargetInteraction), 30) #' drugTargetInteraction[naid] <- NA #' #' impute_tskrr(drugTargetInteraction, targetSim, drugSim) #' #' @rdname impute_tskrr #' @name impute_tskrr #' @aliases impute_tskrr #' @export impute_tskrr <- function(y, k, g = NULL, lambda = 1e-02, testdim = TRUE, testlabels = TRUE, symmetry = c("auto","symmetric","skewed"), keep = FALSE, niter = 1e4, tol = sqrt(.Machine$double.eps), start = mean(y, na.rm = TRUE), verbose = FALSE ){ iptest <- .test_input(y,k,g,lambda,testdim,testlabels, checkna = FALSE) homogeneous <- iptest$homogeneous lambda.k <- iptest$lambda.k lambda.g <- iptest$lambda.g # Rearrange matrices if necessary rk <- rownames(k) # not when there's no row/-colnames ck <- colnames(k) if(!is.null(rk)){ cg <- colnames(g) if(!all(rownames(y) == rk)) y <- match_labels(y,rk,cg) if(!all(rk == ck)) k <- match_labels(k,rk,rk) if(!homogeneous){ rg <- rownames(g) if(!all(cg == rg)) g <- match_labels(g,cg,cg) } } # CALCULATE EIGEN DECOMPOSITION k.eigen <- eigen(k, symmetric = TRUE) g.eigen <- if(!homogeneous) eigen(g, symmetric = TRUE) else NULL # CALCULATE HAT MATRICES Hk <- eigen2hat(k.eigen$vectors, k.eigen$values, lambda.k) Hg <- if(!homogeneous) eigen2hat(g.eigen$vectors, g.eigen$values, lambda.g) else Hk naid <- is.na(y) if(homogeneous){ # Test symmetry if required. symmetry <- match.arg(symmetry) if(symmetry == "auto"){ ynona <- y ynona[naid] <- 0 symmetry <- test_symmetry(ynona) if(symmetry == "none") stop(paste("The Y matrix is not symmetric or skewed symmetric.", "You need a kernel matrix for rows and columns.")) } } imp <- impute_tskrr.fit(y,Hk,Hg,naid,niter,tol, start, verbose) pred <- Hk %*% imp$y %*% Hg # Create labels rn <- rownames(y) cn <- colnames(y) if(is.null(rn)) rn <- NA_character_ if(is.null(cn)) cn <- NA_character_ # CREATE OUTPUT if(homogeneous){ out <- new("tskrrImputeHomogeneous", y = imp$y, k = k.eigen, lambda.k = lambda.k, pred = pred, symmetry = symmetry, has.hat = keep, Hk = if(keep) Hk else matrix(0), labels = list(k=rn, g = NA_character_), imputeid = which(naid), niter = as.integer(imp$niter), tol = tol ) } else { out <- new("tskrrImputeHeterogeneous", y = imp$y, k = k.eigen, g = g.eigen, lambda.k = lambda.k, lambda.g = lambda.g, pred = pred, has.hat = keep, Hk = if(keep) Hk else matrix(0), Hg = if(keep) Hg else matrix(0), labels = list(k=rn, g = cn), imputeid = which(naid), niter = as.integer(imp$niter), tol = tol ) } return(out) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/impute_tskrr.R
#' Impute values based on a two-step kernel ridge regression #' #' This function provides an interface for the imputation of values #' based on a \code{\link{tskrr}} model and is the internal function #' used by \code{\link{impute_tskrr}}. #' #' This function is mostly available for internal use. In most cases, #' it makes much more sense to use \code{\link{impute_tskrr}}, as that #' function returns an object one can work with. The function #' \code{impute_tskrr.fit} could be useful when doing simulations or #' creating fitting algorithms. #' #' @param y a label matrix #' @param Hk a hat matrix for the rows (see also \code{\link{eigen2hat}} #' on how to calculate them from an eigen decomposition) #' @param Hg a hat matrix for the columns. For homogeneous networks, this #' should be Hk again. #' @param naid an optional index with the values that have to be imputed, #' i.e. at which positions you find a \code{NA} value. It can be a vector #' with integers or a matrix with \code{TRUE}/\code{FALSE} values. #' @inheritParams impute_tskrr #' #' @return a list with two elements: #' * a matrix \code{y} with the imputed values filled in. #' * a numeric value \code{niter} with the amount of iterations #' #' @seealso #' * \code{\link{impute_tskrr}} for the user-level function, and #' * \code{\link{eigen2hat}} for conversion of a eigen decomposition to #' a hat matrix. #' @md #' #' @examples #' #' data(drugtarget) #' #' K <- eigen(targetSim) #' G <- eigen(drugSim) #' #' Hk <- eigen2hat(K$vectors, K$values, lambda = 0.01) #' Hg <- eigen2hat(G$vectors, G$values, lambda = 0.05) #' #' drugTargetInteraction[c(3,17,123)] <- NA #' #' res <- impute_tskrr.fit(drugTargetInteraction, Hk, Hg, #' niter = 1000, tol = 10e-10, #' start = 0, verbose = FALSE) #' #' @export impute_tskrr.fit <- function(y,Hk,Hg,naid = NULL, niter,tol, start, verbose){ if(is.null(naid)) naid <- is.na(y) if(!any(naid)){ warning("The matrix didn't contain missing values") return(list(y = y, niter = 0L)) } # Replace values y[naid] <- start prev <- y[naid] div <- TRUE # Loop iter <- 0 showsteps <- verbose > 1 showres <- verbose > 0 while(iter < niter && div > tol){ iter <- iter + 1 pred <- Hk %*% y %*% Hg y[naid] <- pred[naid] div <- sum((prev - y[naid])^2) if(showsteps){ if(iter %% 10 == 0) message("iteration: ",iter," - Deviation: ",div,"\n") } prev <- y[naid] } if(showres){ message("Nr. of iterations: ", iter, " - Deviation:",div,"\n") } return(list(y = y, niter = iter)) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/impute_tskrr.fit.R
# Internal functions ## Check whether something is a whole number is_whole_number <- function(x){ if(is.integer(x)){ TRUE } else if(is.numeric(x)){ if((x%%1) == 0 ){ TRUE } else { FALSE } } else { FALSE } } is_whole_positive <- function(x){ if(is_whole_number(x) && x >= 0) TRUE else FALSE }
/scratch/gouwar.j/cran-all/cranData/xnet/R/internal_helpers.R
#' Test symmetry of a matrix #' #' The function \code{\link[base]{isSymmetric}} tests for symmetry of a matrix but also #' takes row and column names into account. This function is a toned-down #' (and slightly faster) version that ignores row and column names. #' Currently, the function only works for real matrices, not complex ones. #' #' @param x a matrix to be tested. #' @param tol the tolerance for comparing the numbers. #' #' @return a logical value indicating whether or not the matrix is #' symmetric #' #' @examples #' x <- matrix(1:16,ncol = 4) #' is_symmetric(x) #' #' x <- x %*% t(x) #' is_symmetric(x) #' #' @export is_symmetric <- function(x, tol = 100 * .Machine$double.eps){ if(!is.numeric(x) || !is.matrix(x)) stop("x should be a numeric matrix") dims <- dim(x) if((n <- dims[1L]) != dims[2L]) return(FALSE) else if(n == 1L) return(TRUE) # fast first testing to check if the first column and row match if(any(abs(x[1,] - x[,1]) > tol)) return(FALSE) rd <- .row(dims - 1L) + 1 cd <- .col(dims - 1L) + 1 tohave <- rd > cd idr <- rd[tohave] idc <- cd[tohave] all(abs(x[cbind(idr,idc)] - x[cbind(idc,idr)]) < tol) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/is_symmetric.R
#' Extract labels from a tskrr object #' #' These functions allow you to extract the labels from a #' \code{\link{tskrr}} object. The function \code{labels} and the #' function \code{dimnames} are aliases and do the exact same #' thing. The functions \code{rownames} and \code{colnames} work like #' you would expect. Note that contrary to the latter two, \code{labels} #' will never return \code{NULL}. If no labels are found, it will construct #' labels using the prefixes defined in the argument \code{prefix}. #' #' @section Warning: #' If the original data didn't contain row- or column names for the #' label matrix, \code{rownames} and \code{colnames} will return #' \code{NULL}. Other functions will extract the automatically generated #' labels, so don't count on \code{rownames} and \code{colnames} if you #' want to predict output from other functions! #' #' @param x a \code{\link{tskrr}} object #' @param object a \code{\link{tskrr}} object #' @param do.NULL logical. If \code{FALSE} and labels are \code{NULL}, #' labels are created. If \code{TRUE}, the function returns \code{NULL} in #' the absence of labels. #' @param prefix a prefix used for construction of the labels in case #' none are available. For \code{label}, a character vector of length 1 for #' homogeneous networks or of length 2 for heterogeneous networks. #' In case two values are given, the first is used for the rows and the second #' for the columns. Otherwise the only value is used for both. In the case of #' \code{rownames} and \code{colnames}, a single value. #' See also \code{\link[=colnames]{row+colnames}} #' @param ... arguments passed to/from other methods. #' #' @return for \code{labels} and \code{dimnames}: a list with two elements \code{k} and #' \code{g} #' #' @rdname labels #' @method labels tskrr #' @export labels.tskrr <- function(object, prefix = if(is_homogeneous(object)) "row" else c("row","col"), ...){ labs <- object@labels homogeneous <- is_homogeneous(object) # Process the prefixes if(!is.character(prefix) || !is.vector(prefix)) stop("prefix should be a character vector with maximum 2 values.") nref <- length(prefix) if(nref == 1 && !homogeneous) stop("A heterogeneous network needs 2 values for prefix.") else if(nref > 2 || nref < 1) stop("prefix should contain 1 or 2 values. See also ?labels.") else if(nref == 2 && homogeneous) warning(paste("Two prefixes were given for a homogeneous model.", "The second value", prefix[2],"is ignored.")) # Generate the labels if no are available if(length(labs$k) == 1 && is.na(labs$k)){ labs$k <- paste0(prefix[1], seq_len(nrow(object@y))) } if(homogeneous) labs$g <- labs$k else if(length(labs$g) == 1 && is.na(labs$g)) labs$g <- paste0(prefix[2], seq_len(ncol(object@y))) return(labs) } #' @rdname labels #' @export setMethod("labels", "tskrr", labels.tskrr) #' @rdname labels #' @aliases dimnames.tskrr #' @export setMethod("dimnames", "tskrr", function(x) labels(x)) #' @rdname labels #' @export setMethod("rownames", "tskrr", function(x, do.NULL = TRUE, prefix = "row"){ rn <- x@labels$k nolabels <- length(rn) == 1 && is.na(rn) if(do.NULL && nolabels) return(NULL) else if(nolabels){ if(length(prefix) > 1 || !is.character(prefix)) stop("prefix should be a single character value.") rn <- paste0(prefix, seq_len(nrow(x@y))) } return(rn) }) #' @rdname labels #' @export setMethod("colnames", "tskrr", function(x, do.NULL = TRUE, prefix = "col"){ rn <- if(is_homogeneous(x)) x@labels$k else x@labels$g nolabels <- length(rn) == 1 && is.na(rn) if(do.NULL && nolabels) return(NULL) else if(nolabels){ if(length(prefix) > 1 || !is.character(prefix)) stop("prefix should be a single character value.") rn <- paste0(prefix, seq_len(ncol(x@y))) } return(rn) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/labels.R
#' Fit a linear filter over a label matrix #' #' This function fits a linear filter over a label matrix. It calculates #' the row, column and total means, and uses those to construct the linear #' filter. #' #' If there are missing values and they are removed before calculating the #' means, a warning is issued. If \code{na.rm = FALSE} and there are #' missing values present, the outcome is, by definition, a matrix filled #' with NA values. #' #' #' #' @param y a label matrix #' @param alpha a vector with 4 alpha values, or a single alpha value #' which then is used for all 4 alphas. #' @param na.rm a logical value indicating whether missing values should #' be removed before calculating the row-, column- and total means. #' #' @return an object of class \code{\link[=linearFilter-class]{linearFilter}} #' #' @examples #' data(drugtarget) #' linear_filter(drugTargetInteraction, alpha = 0.25) #' linear_filter(drugTargetInteraction, alpha = c(0.1,0.1,0.4,0.4)) #' #' @export linear_filter <- function(y, alpha=0.25, na.rm = FALSE){ stopifnot(is.matrix(y), is.numeric(alpha), is.atomic(alpha)) if(length(alpha) == 1) alpha <- rep(alpha,4) else if(length(alpha) !=4) stop("alpha should be a numeric vector with either 1 or 4 values.") # Needed to avoid floating point errors when long double disabled # Per check by BDR using R configured with --disable-long-double if(abs(sum(alpha) - 1) > .Machine$double.eps^0.5 || any(alpha > 1) || any(alpha < 0) ) stop("alpha values should be numbers between 0 and 1 and add up to 1.") cm <- colMeans(y, na.rm = na.rm) rm <- rowMeans(y, na.rm = na.rm) m <- mean(y, na.rm = na.rm) nc <- ncol(y) nr <- nrow(y) if(any(is.na(y))){ if(na.rm){ warning("NAs removed before fitting the linear filter.") } else { # Return the empty matrix for now. res <- new("linearFilter", y = y, alpha = alpha, pred = matrix(NA_real_, nrow = nrow(y),ncol = ncol(y)), mean = NA_real_, colmeans = cm, rowmeans = rm, na.rm = na.rm) } } pred <- .linear_filter(y,alpha,cm,rm,m,nr,nc) # simple matrix filter new("linearFilter", y = y, alpha = alpha, pred = pred, mean = m, colmeans = cm, rowmeans = rm, na.rm = na.rm) } # Function .linear_filter allows for optimization algorithms. # Input: cm is column mean, rm is row mean, m is global mean, nc is # number of columns .linear_filter <- function(y, alpha, cm, rm, m, nr, nc){ alpha[1]*y + rep(alpha[2]*cm, each = nr) + rep(alpha[3]*rm, times = nc) + alpha[4] * m }
/scratch/gouwar.j/cran-all/cranData/xnet/R/linear_filter.R
#' Leave-one-out cross-validation for tskrr #' #' Perform a leave-one-out cross-validation for two-step kernel #' ridge regression based on the shortcuts described in Stock et al, 2018. #' (\url{http://doi.org/10.1093/bib/bby095}). #' #' @details The parameter \code{exclusion} defines what is left out. #' The value "interaction" means that a single interaction is removed. #' In the case of a homogeneous model, this can be interpreted as the #' removal of the interaction between two edges. The values "row" and #' "column" mean that all interactions for a row edge resp. a column #' edge are removed. The value "both" removes all interactions for #' a row and a column edge. #' #' In the case of a homogeneous model, "row" and "column" don't make sense #' and will be replaced by "both" with a warning. This can be interpreted #' as removing vertices, i.e. all interactions between one edge and #' all other edges. Alternatively one can use "edges" to remove edges and #' "vertices" to remove vertices. In the case of a homogeneous model, #' the setting "edges" translates to "interaction", and "vertices" #' translates to "both". For more information, see Stock et al. (2018). #' #' Replacing by 0 only makes sense when \code{exclusion = "interaction"} and the #' label matrix contains only 0 and 1 values. The function checks whether #' the conditions are fulfilled and if not, returns an error. #' #' @param x an object of class \code{\link[xnet:tskrr-class]{tskrr}} or #' \code{\link{linearFilter}}. #' @param exclusion a character value with possible values "interaction", #' "row", "column", "both" for heterogeneous models, and "edges", "vertices", #' "interaction" or "both" for homogeneous models. #' Defaults to "interaction". See details. #' @param replaceby0 a logical value indicating whether the interaction #' should be simply removed (\code{FALSE}) or replaced by 0 (\code{TRUE}). #' @param ... arguments passed to methods. #' See Details. #' #' @return a numeric matrix with the leave-one-out predictions for #' the model. #' #' @examples #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim, #' lambda = c(0.01,0.01)) #' #' delta <- loo(mod, exclusion = 'both') - response(mod) #' delta0 <- loo(mod, replaceby0 = TRUE) - response(mod) #' #' @rdname loo #' @export setMethod("loo", "tskrrHeterogeneous", function(x, exclusion = c("interaction","row","column","both"), replaceby0 = FALSE){ exclusion <- match.arg(exclusion) if(replaceby0){ if(exclusion != "interaction") stop("replaceby0 only makes sense when exclusion is set to 'interaction'.") if(any(match(x@y, c(0,1), 0L ) == 0)) stop("replaceby0 only makes sense when the response has 0/1 values.") } Hk <- hat(x, "row") Hg <- hat(x, "column") if(exclusion == "interaction"){ out <- if(replaceby0) loo.i0(x@y, Hk, Hg, x@pred) else loo.i(x@y, Hk, Hg, x@pred) } else if(exclusion == "row"){ out <- loo.r(x@y, Hk, Hg) } else if(exclusion == "column"){ out <- loo.c(x@y, Hk, Hg) } else { out <- loo.b(x@y, Hk, Hg) } dimnames(out) <- unname(labels(x)) return(out) }) #' @rdname loo #' @export setMethod("loo", "tskrrHomogeneous", function(x, exclusion = c("edges","vertices","interaction","both"), replaceby0 = FALSE){ exclusion <- match.arg(exclusion) # Translate edges and vertices if(exclusion %in% c("interaction","both")) exclusion <- switch(exclusion, interaction = "edges", both = "vertices") symm <- symmetry(x) if(replaceby0){ if(exclusion != "edges") stop("replaceby0 only makes sense when exclusion is set to 'edges'.") if(symm == "symmetric" && any(match(x@y, c(0,1), 0L ) == 0)) stop("replaceby0 only makes sense when the response has 0/1 values.") else if(symm == "skewed" && any(match(x@y, c(-1,0,1), 0L ) == 0)) stop("replaceby0 only makes sense when the response has -1/0/1 values.") } Hk <- hat(x) if(exclusion == "edges"){ loofun <- .getloo_homogeneous("edges", replaceby0, symm) out <- loofun(x@y, Hk, x@pred) } else { out <- loo.v(x@y, Hk) } dimnames(out) <- unname(labels(x)) return(out) }) #' @rdname loo #' @export setMethod("loo", "linearFilter", function(x, replaceby0 = FALSE){ if(replaceby0 && any(match(x@y, c(0,1), 0L ) == 0)) stop("replaceby0 only makes sense when the response has 0/1 values.") if(replaceby0){ loo.i0.lf(x@y, x@alpha, x@pred) } else { loo.i.lf(x@y, x@alpha, x@pred) } })
/scratch/gouwar.j/cran-all/cranData/xnet/R/loo.R
#' Leave-one-out cross-validation for two-step kernel ridge regression #' #' These functions implement different cross-validation scenarios for #' two-step kernel ridge regression. It uses the shortcuts for #' leave-one-out cross-validation. #' #' These functions are primarily for internal use and hence not exported. #' Be careful when using them, as they do not perform any sanity check #' on the input. It is up to the user to make sure the input makes sense. #' #' @seealso \code{\link{loo}} for the user-level function. #' #' @param Y the matrix with responses #' @param Hk the hat matrix for the first kernel (rows of Y) #' @param Hg the hat matrix for the second kernel (columns of Y) #' @param alpha a vector of length 4 with the alpha values from a #' \code{\link{linearFilter}} model #' @param pred the predictions #' @param ... added to allow for specifying pred even when not needed. #' #' @return a matrix with the leave-one-out predictions #' @rdname looInternal #' @name loo_internal loo.i <- function(Y, Hk, Hg, pred){ L <- tcrossprod(diag(Hk), diag(Hg)) return((pred - Y * L) / (1 - L)) } #' @rdname looInternal loo.i0 <- function(Y, Hk, Hg, pred){ L <- tcrossprod(diag(Hk), diag(Hg)) return((pred - Y * L)) } #' @rdname looInternal loo.r <- function(Y, Hk, Hg, ...){ div <- 1 - diag(Hk) diag(Hk) <- 0 return( (Hk %*% Y %*% Hg) / div ) } #' @rdname looInternal loo.c <- function(Y, Hk, Hg, ...){ div <- 1 - diag(Hg) diag(Hg) <- 0 return( (Hk %*% Y %*% Hg) / rep(div, each = nrow(Y)) ) } #' @rdname looInternal loo.b <- function(Y, Hk, Hg, ...){ divk <- 1 - diag(Hk) divg <- 1 - diag(Hg) diag(Hk) <- 0 diag(Hg) <- 0 pred <- Hk %*% Y %*% Hg div <- tcrossprod(divk, divg) return(pred / div) } #################################### ## SHORTCUTS FOR HOMOGENOUS NETWORKS #' @rdname looInternal loo.e.sym <- function(Y, Hk, pred){ L <- tcrossprod(diag(Hk)) + Hk^2 return((pred - L * Y) / ( 1 - L)) } #' @rdname looInternal loo.e.skew <- function(Y, Hk, pred){ L <- tcrossprod(diag(Hk)) - Hk^2 return((pred - L * Y) / ( 1 - L)) } #' @rdname looInternal loo.e0.sym <- function(Y, Hk, pred){ L <- tcrossprod(diag(Hk)) + Hk^2 return( (pred - L * Y) ) } #' @rdname looInternal loo.e0.skew <- function(Y, Hk, pred){ L <- tcrossprod(diag(Hk)) - Hk^2 return( (pred - L * Y) ) } #' @rdname looInternal loo.v <- function(Y, Hk, ...){ Hk0 <- Hk diag(Hk0) <- 0 div <- 1 - diag(Hk) Floo <- Hk0 %*% Y / div FlooV <- Floo %*% Hk FlooV <- FlooV + Hk * ((diag(FlooV) - diag(Floo)) / div) return(FlooV) } #################################### ## SHORTCUTS FOR LINEAR FILTERS #' @rdname looInternal loo.i.lf <- function(Y, alpha, pred){ d <- dim(Y) n <- length(Y) lev <- alpha[1] + alpha[2] / d[1] + alpha[3] / d[2] + alpha[4] / n loolf <- (pred - Y*lev) / (1 - lev) return(loolf) } #' @rdname looInternal loo.i0.lf <- function(Y, alpha, pred){ d <- dim(Y) n <- length(Y) lev <- alpha[1] + alpha[2] / d[1] + alpha[3] / d[2] + alpha[4] / n loolf <- (pred - Y*lev) return(loolf) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/looInternal.R
#' Calculate or extract the loss of a tskrr model #' #' This function allows calculating the loss of a tskrr model using #' either one of the functions defined in \code{\link{loss_functions}} #' or a custom user function. If the model inherits from class #' \code{\link[xnet:tskrrTune-class]{tskrrTune}} and no additional arguments #' are given, the loss is returned for the settings used when tuning. #' The function can also be used to extract the original loss from a #' \code{\link[xnet:permtest-class]{permtest}} object. #' #' @param x a model that inherits from class #' \code{\link[xnet:tskrr-class]{tskrr}} #' @param fun a function to be used for calculating the loss. This #' can also be a character value giving the name of one of the loss #' functions provided in the package #' @param exclusion a character value with possible values "interaction", #' "row", "column" or "both". #' See also \code{\link{loo}} for more information. #' @param replaceby0 a logical value indicating whether the interaction #' should be simply removed (\code{FALSE}) or replaced by 0 (\code{TRUE}). #' @param predictions a logical value to indicate whether the #' predictions should be used instead of leave one out crossvalidation. #' If set to \code{TRUE}, the other arguments are ignored. #' @param ... extra arguments passed to the loss function in \code{fun}. #' #' @return a numeric value with the calculated loss #' #' @seealso #' * \code{\link{loss_functions}} for possible loss functions #' * \code{\link{tune}} for tuning a model based on loss functions #' @md #' #' @examples #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' #' loss(mod, fun = loss_auc) #' #' tuned <- tune(mod, fun = loss_auc) #' #' loss(tuned) #' loss(tuned, fun = loss_mse) #' #' @rdname loss #' @export setMethod("loss", "tskrr", function(x, fun = loss_mse, exclusion = c("interaction","row","column","both"), replaceby0 = FALSE, predictions = FALSE, ...){ fun <- match.fun(fun) exclusion <- match.arg(exclusion) # needed to make this work for homogeneous models! loo <- if(predictions){ fitted(x) } else { loo(x, exclusion, replaceby0) } fun(response(x), loo, ...) }) #' @rdname loss #' @export setMethod("loss", "tskrrTune", function(x, fun = loss_mse, exclusion = c("interaction","row","column","both"), replaceby0 = FALSE, predictions = FALSE, ...){ # When no arguments are given, return the loss from object if(missing(fun) && missing(predictions) && missing(exclusion) && missing(replaceby0)) return(x@best_loss) else callGeneric(as_tskrr(x), fun, exclusion, replaceby0, predictions, ...) }) #' @rdname loss #' @export setMethod("loss", "permtest", function(x, ...){ x@orig_loss })
/scratch/gouwar.j/cran-all/cranData/xnet/R/loss.R
#' loss functions #' #' These functions can be used as loss functions in \code{\link{tune}}. #' Currently, two functions are provided: a function calculating the #' classic mean squared error (\code{loss_mse}) and a function #' calculating 1 - AUC (\code{loss_auc}). #' #' The AUC is calculated by sorting the \code{Y} matrix based on #' the order of the values in the \code{LOO} matrix. The false and true #' positive rates are calculated solely based on that ordering, which #' allows for values in \code{LOO} outside the range [0,1]. It's #' a naive implementation which is good enough for tuning, but #' shouldn't be used as a correct value for 1 - auc in case the #' values in \code{LOO} are outside the range [0,1]. #' #' @section Note: #' The function \code{loss_auc} should only be used for a \code{Y} #' matrix that contains solely the values 0 and 1. #' #' @param Y the label matrix with observed responses #' @param LOO the leave-one-out crossvalidation (or predictions if you #' must). This one can be calculated by the function \code{loo}. #' @param na.rm a logical value #' #' @seealso \code{\link{tune}} for application of the loss function #' #' @examples #' #' x <- c(1,0,0,1,0,0,1,0,1) #' y <- c(0.8,-0.1,0.2,0.2,0.4,0.01,1.12,0.9,0.9) #' loss_mse(x,y) #' loss_auc(x,y) #' #' @rdname loss_functions #' @name loss_functions #' @aliases loss_mse loss_auc #' @export loss_mse <- function(Y, LOO, na.rm = FALSE){ mean((Y - LOO)^2, na.rm = na.rm) } #' @rdname loss_functions #' @export loss_auc <- function(Y, LOO){ id <- order(LOO) roc_y <- Y[id] # Calculate total number positives, negatives and y values np <- sum(roc_y) ny <- length(roc_y) nn <- ny - np # tpr and fpr fpr <- cumsum(roc_y)/np tpr <- cumsum(roc_y == 0) / nn dtpr <- diff(tpr) dfpr <- diff(fpr) auc <- sum( dfpr * tpr[2:ny] - (dfpr * dtpr)/2 ) return(1 - auc) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/loss_functions.R
#' Reorder the label matrix #' #' Reorders the label matrix based on the labels of the kernel matrices. #' In case there are no labels, the original label matrix is returned, #' but with the labels in \code{rows} and \code{cols} as rownames and #' column names respectively. #' #' @param y a matrix representing the label matrix. #' @param rows a character vector with the labels for the rows or a matrix #' with rownames that will be used as labels. #' @param cols a character vector with the labels for the cols or a matrix #' with colnames that will be used as labels. If \code{NULL}, \code{rows} will be #' used for both row and column labels. #' #' @return a matrix with the rows and columns reordered. #' #' @examples #' mat <- matrix(1:6, ncol = 2, #' dimnames = list(c("b", "a", "d"), #' c("ca", "cb")) #' ) #' #' match_labels(mat, c("a","b", "d"), c("ca","cb")) #' #' #Using matrices #' data(drugtarget) #' out <- match_labels(drugTargetInteraction, targetSim, drugSim) #' #' @rdname match_labels #' @name match_labels #' @export match_labels <- function(y,rows,cols = NULL){ if(!is.matrix(y)) stop("y has to be a matrix") if(is.matrix(rows)){ rows <- rownames(rows) if(is.null(rows)) stop("There are no rownames for rows.") } else if(!is.character(rows)) { stop("rows should be a matrix with rownames or a character vector.") } if(is.null(cols)){ cols <- rows } else if(is.matrix(cols)){ cols <- colnames(cols) if(is.null(cols)) stop("There are no colnames for cols.") } else if(!is.character(cols)){ stop("cols should be a matrix with colnames or a character vector.") } nr <- length(rows) nc <- length(cols) if(nrow(y) != nr) stop("row labels not of the correct length.") if(ncol(y) != nc) stop("col labels not of the correct length.") if(is.null(dn <- dimnames(y))){ dimnames(y) <- list(rows,cols) return(y) } rmatch <- match(rows, dn[[1]], 0L) if(any(rmatch == 0L )) stop("row labels not compatible with rownames y") cmatch <- match(cols, dn[[2]], 0L) if(any(cmatch == 0L)) stop("col labels not compatible with colnames y") return(y[rmatch,cmatch]) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/match_labels.R
#' Calculate the relative importance of the edges #' #' This function does a permutation-based evaluation of the impact of #' different edges on the final result. It does so by permuting the kernel #' matrices, refitting the model and calculating a loss function. #' #' The test involved uses a normal approximation. It assumes that under the #' null hypothesis, the loss values are approximately normally distributed. #' The cumulative probability of a loss as small or smaller than #' the one found in the original model, is calculated based on a normal #' distribution from which the mean and sd are calculated from the permutations. #' #' @section Warning: It should be noted that this normal approximation is an ad-hoc approach. #' There's no guarantee that the actual distribution of the loss under the #' null hypothesis is normal. Depending on the loss function, a significant #' deviation from the theoretic distribution can exist. Hence this functions should only #' be used as a rough guidance in model evaluation. #' #' @param x either a \code{\link{tskrr-class}} or a #' \code{\link{tskrrTune-class}} object #' @param permutation a character string that defines whether the row, #' column or both kernel matrices should be permuted. Ignored in case of #' a homogeneous network #' @param n the number of permutations for every kernel matrix #' @param exclusion the exclusion to be used in the \code{\link{loo}} function. See also \code{\link{get_loo_fun}} #' @param replaceby0 a logical value indicating whether \code{\link{loo}} #' removes a value in the leave-one-out procedure or replaces it by zero. #' See also \code{\link{get_loo_fun}}. #' @param fun a function (or a character string with the name of a #' function) that calculates the loss. See also \code{\link{tune}} and #' \code{\link{loss_functions}} #' @param exact a logical value that indicates whether or not an #' exact p-value should be calculated, or be approximated based on #' a normal distribution. #' @param ... arguments passed to other methods #' #' @return An object of the class permtest. #' #' @examples #' #' # Heterogeneous network #' #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' permtest(mod, fun = loss_auc) #' #' @importFrom stats pnorm printCoefmat sd #' @rdname permtest #' @aliases permtest #' @export setMethod("permtest","tskrrHeterogeneous", function(x, n = 100, permutation = c("both","row","column"), exclusion = c("interaction","row","column","both"), replaceby0 = FALSE, fun = loss_mse, exact = FALSE){ # Process arguments exclusion <- match.arg(exclusion) lossfun <- match.fun(fun) permutation <- match.arg(permutation) if(n <= 0 || !is_whole_positive(n)) stop("n should be a positive integer value.") # extract information k <- get_kernelmatrix(x, "row") g <- get_kernelmatrix(x, "column") y <- response(x) lambdas <- lambda(x) loofun <- get_loo_fun("tskrrHeterogeneous", exclusion = exclusion, replaceby0 = replaceby0) # Calculate the original loss function orig_loss <- lossfun(y,loofun(y, hat(x,"row"), hat(x,"column"), fitted(x))) # Do the permutation test perms <- .permtest_hetero(y,k,g,lambdas, n, permutation, lossfun, loofun) if(exact){ pval <- mean(orig_loss > perms) } else { pval <- pnorm(orig_loss, mean = mean(perms), sd = sd(perms)) } new("permtest", orig_loss = orig_loss, perm_losses = perms, n = n, loss_function = lossfun, exclusion = exclusion, replaceby0 = replaceby0, permutation = permutation, pval = pval, exact = exact) }) # END setMethod tskrrHeterogeneous #' @rdname permtest #' @export setMethod("permtest","tskrrHomogeneous", function(x, n = 100, permutation = c("both"), exclusion = c("interaction","both"), replaceby0 = FALSE, fun = loss_mse, exact = FALSE){ # Process arguments exclusion <- match.arg(exclusion) lossfun <- match.fun(fun) if(permutation != "both") stop("For a homogeneous model setting the permutation to anything else but 'both' doesn't make sense.") if(n <= 0 || !is_whole_positive(n)) stop("n should be a positive integer value.") # extract information k <- get_kernelmatrix(x, "row") y <- response(x) lambdas <- lambda(x) loofun <- get_loo_fun("tskrrHomogeneous", exclusion = exclusion, replaceby0 = replaceby0) # Calculate the original loss function orig_loss <- lossfun(y,loofun(y, hat(x,"row"), pred = fitted(x))) # Do the permutation test perms <- .permtest_homo(y,k,lambdas, n, lossfun, loofun) if(exact){ pval <- mean(orig_loss > perms) } else { pval <- pnorm(orig_loss, mean = mean(perms), sd = sd(perms)) } new("permtest", orig_loss = orig_loss, perm_losses = perms, n = n, loss_function = lossfun, exclusion = exclusion, replaceby0 = replaceby0, permutation = permutation, pval = pval, exact = exact) }) # END setMethod tskrrHomogeneous #' @rdname permtest #' @export setMethod("permtest", "tskrrTune", function(x, permutation = c("both","row","column"), n = 100){ permutation <- match.arg(permutation) hetero <- is_heterogeneous(x) # Extract info. No getters available! exclusion <- slot(x, "exclusion") replaceby0 <- slot(x, "replaceby0") lossfun <- slot(x, "loss_function") x <- as_tskrr(x) callGeneric(x = x, permutation = permutation, n = n, exclusion = exclusion, replaceby0 = replaceby0, fun = lossfun) }) # Internal permtest function. # y: the response matrix # k: the k kernel # g: the g kernel # lambda : the lambdas # n: number of permutations # permutation: which permutations need to happen # lossfun: the function for calculating the loss # loofun: the function for the loo .permtest_hetero <- function(y,k,g,lambda, n,permutation, lossfun, loofun){ pk <- permutation == "row" || permutation == "both" pg <- permutation == "column" || permutation == "both" nk <- dim(k)[1] ng <- dim(g)[1] lambda.k <- lambda[1] lambda.g <- lambda[2] if(pk && !pg ){ # This needs only to be calculated once g_eig <- eigen(g, symmetric = TRUE) gH <- eigen2hat(g_eig$vectors, g_eig$values, lambda.g) out <- replicate(n,{ id <- sample(nk) knew <- k[id,id] k_eig <- eigen(knew, symmetric = TRUE) kH <- eigen2hat(k_eig$vectors, k_eig$values, lambda.k) pred <- kH %*% y %*% gH loopred <- loofun(y,kH,gH,pred) lossfun(y, loopred) }) } else if (pg && !pk){ # This needs only to be calculated once k_eig <- eigen(k, symmetric = TRUE) kH <- eigen2hat(k_eig$vectors, k_eig$values, lambda.k) out <- replicate(n,{ id <- sample(ng) gnew <- g[id,id] g_eig <- eigen(gnew, symmetric = TRUE) gH <- eigen2hat(g_eig$vectors, g_eig$values, lambda.g) pred <- kH %*% y %*% gH loopred <- loofun(y,kH,gH,pred) lossfun(y, loopred) }) } else if (pk && pg){ # This needs only to be calculated once out <- replicate(n,{ id <- sample(nk) knew <- k[id,id] k_eig <- eigen(knew, symmetric = TRUE) kH <- eigen2hat(k_eig$vectors, k_eig$values, lambda.k) id2 <- sample(ng) gnew <- g[id2,id2] g_eig <- eigen(gnew, symmetric = TRUE) gH <- eigen2hat(g_eig$vectors, g_eig$values, lambda.g) pred <- kH %*% y %*% gH loopred <- loofun(y,kH,gH,pred) lossfun(y, loopred) }) } else { stop("No permutations done. Please contact the package maintainer.") } return(out) } # Internal permtest function for homogeneous networks. # y: the response matrix # k: the k kernel # lambda : the lambda # n: number of permutations # lossfun: the function for calculating the loss # loofun: the function for the loo .permtest_homo <- function(y,k,lambda, n, lossfun, loofun){ nk <- dim(k)[1] lambda.k <- lambda out <- replicate(n,{ id <- sample(nk) knew <- k[id,id] k_eig <- eigen(knew, symmetric = TRUE) kH <- eigen2hat(k_eig$vectors, k_eig$values, lambda.k) pred <- kH %*% y %*% kH loopred <- loofun(y,kH,pred = pred) lossfun(y, loopred) }) return(out) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/permtest.R
#' plot a heatmap of the predictions from a tskrr model #' #' This function plots a heatmap of the fitted values in a #' \code{\link{tskrr}} model. The function is loosely based on #' \code{\link{heatmap}}, but uses a different mechanism and adds #' a legend by default. #' #' The function can select a part of the model for plotting. Either you #' specify \code{rows} and \code{cols}, or you specify \code{nbest}. #' If \code{nbest} is specified, \code{rows} and \code{cols} are ignored. #' The n highest values are looked up in the plotted values, and only #' the rows and columns related to these values are shown then. This #' allows for a quick selection of the highest predictions. #' #' Dendrograms are created by converting the kernel matrices to #' a distance, using #' #' d(x,y) = K(x,x)^2 + K(y,y)^2 - 2*K(x,y) #' #' with K being the kernel function. The resulting distances are #' clustered using \code{\link{hclust}} and converted to a #' dendrogram using \code{\link{as.dendrogram}}. #' #' @param x a tskrr model #' @param dendro a character value indicating whether a dendrogram #' should be constructed. #' @param which a character value indicating whether the fitted values, #' the leave-one-out values, the original response values or the #' residuals should be plotted. #' @param exclusion if \code{which = "loo"}, this argument is passed to #' \code{\link{loo}} for the exclusion settings #' @param replaceby0 if \code{which = "loo"}, this argument is passed to #' \code{\link{loo}}. #' @param nbest a single integer value indicating the amount of best values #' that should be selected. If \code{0}, all data is shown. #' @param rows a numeric or character vector indicating which rows should be #' selected from the model. #' @param cols a numeric or character vector indicating which columns should be #' selected from the model. #' @param col a vector with colors to be used for plotting #' @param breaks a single value specifying the number of #' breaks (must be 1 more than number of colors), or a numeric #' vector with the breaks used for the color code. If \code{NULL}, #' the function tries to find evenly spaced breaks. #' @param legend a logical value indicating whether or not the legend should #' be added to the plot. #' @param main a character value with a title for the plot #' @param xlab a character label for the X axis #' @param ylab a character label for the Y axis #' @param labRow a character vector with labels to be used on the rows. #' Note that these labels are used as is (possibly reordered to match #' the dendrogram). They can replace the labels from the model. Set to #' \code{NA} to remove the row labels. #' @param labCol the same as \code{labRow} but then for the columns. #' @param margins a numeric vector with 2 values indicating the margins to #' be used for the row and column labels (cfr \code{par("mar")}) #' @param ... currently ignored #' #' @return an invisible list with the following elements: #' * \code{val}: the values plotted #' * \code{ddK}: if a row dendrogram was requested, the row dendrogram #' * \code{ddG}: if a column dendrogram was requested, #' the column dendrogram #' * \code{breaks}: the breaks used for the color codes #' * \code{col}: the colors used #' @md #' #' @seealso \code{\link{tskrr}}, \code{\link{tune}} and #' \code{link{impute_tskrr}} to construct tskrr models. #' #' @examples #' data(drugtarget) #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' #' plot(mod) #' plot(mod, dendro = "row", legend = FALSE) #' plot(mod, col = rainbow(20), dendro = "none", which = "residuals") #' plot(mod, labCol = NA, labRow = NA, margins = c(0.2,0.2)) #' #' @importFrom stats as.dendrogram as.dist hclust order.dendrogram #' @importFrom graphics par layout plot image axis mtext #' @importFrom grDevices dev.hold dev.flush #' @importFrom graphics frame title plot.new plot.window rect #' @rdname plot.tskrr #' @method plot tskrr #' @export plot.tskrr <- function(x, dendro = c("both","row","col","none"), which = c("fitted", "loo", "response","residuals"), exclusion = c("interaction", "row", "column", "both"), replaceby0 = FALSE, nbest = 0, rows, cols, col = rev(heat.colors(20)), breaks = NULL, legend = TRUE, main = NULL, xlab = NULL, ylab = NULL, labRow = NULL, labCol = NULL, margins = c(5,5), ...){ ## PROCESS INPUT AND PREPARE if(!is.logical(legend)) stop("legend should be a logical value") # process input dendro dendro <- match.arg(dendro) dendroK <- dendro %in% c("both", "row") dendroG <- dendro %in% c("both", "col") dendro <- dendroK || dendroG # process input which which <- match.arg(which) if(which != "loo"){ fun <- match.fun(which) val <- fun(x) } else { exclusion <- match.arg(exclusion) val <- loo(x, exclusion, replaceby0) } labs <- labels(x) rownames(val) <- labs$k colnames(val) <- labs$g # get kernel info if(dendroK){ K <- get_eigen(x, "row") K <- eigen2matrix(K$vectors, K$values) rownames(K) <- colnames(K) <- labs$k } if(dendroG){ G <- get_eigen(x, "column") G <- eigen2matrix(G$vectors, G$values) rownames(G) <- colnames(G) <- labs$g } ## PROCESS INPUT SELECTION if(nbest > 0){ # select the n best values to show bestpos <- find_best_pos(val, nbest) rows <- unique(bestpos[,1]) cols <- unique(bestpos[,2]) # Select values val <- val[rows, cols] if(dendroK) K <- K[rows, rows] if(dendroG) G <- G[cols, cols] } else if(!missing(rows) || !missing(cols)){ if(missing(rows)) rows <- seq_len(nrow(val)) if(missing(cols)) cols <- seq_len(ncol(val)) # process the rows and cols if(is.numeric(rows) && any((rows %% 1) != 0)) stop("rows contains non-integer values.") if(is.numeric(cols) && any((cols %% 1) != 0)) stop("cols contains non-integer values.") if(is.character(rows)){ rows <- match(rows, labs$k, nomatch = 0L) if(any(rows == 0)) stop("Not all row labels were found in the model.") } if(is.character(cols)){ cols <- match(cols, labs$g, nomatch = 0L) if(any(cols == 0)) stop("Not all column labels were found in the model.") } # Select values val <- val[rows, cols] if(dendroK) K <- K[rows, rows] if(dendroG) G <- G[cols, cols] } nr <- nrow(val) nc <- ncol(val) ## CONSTRUCT THE DENDROGRAMS IF NEEDED if(dendroK){ ddK <- .kernel2dendro(K) rowid <- order.dendrogram(ddK) val <- val[rowid,] } if(dendroG){ ddG <- .kernel2dendro(G) colid <- order.dendrogram(ddG) val <- val[, colid] } ## CREATE THE LABELS if(is.null(labRow)){ labRow <- rownames(val) } if(is.null(labCol)){ labCol <- colnames(val) } ## PROCESS THE COLORS nocol <- missing(col) ncolor <- length(col) if(is.null(breaks)){ minmax <- range(pretty(val, ncolor)) breaks <- seq(minmax[1], minmax[2], length.out = ncolor + 1) } else if(length(breaks) == 1 && is.numeric(breaks)){ if(breaks < 2) stop("You need at least 2 breaks.") if(nocol){ ncolor <- breaks - 1 col <- rev(heat.colors(ncolor)) } minmax <- range(pretty(val, ncolor)) if(ncolor < (breaks - 1)){ stop(paste("Not enough colors for",breaks,"breaks.")) } else if(ncolor > (breaks - 1)){ warning(paste("Too many colors for the number of breaks.", "The last",ncolor - breaks + 1,"colors", "are ignored.")) col <- col[seq_len(breaks - 1)] } breaks <- seq(minmax[1], minmax[2], length.out = breaks) } else if(is.numeric(breaks)){ if(nocol){ ncolor <- length(breaks) - 1 col <- rev(heat.colors(ncolor)) } if(length(breaks) != ncolor + 1) stop("breaks should be 1 value longer than colors.") } else { stop("breaks should be numeric.") } ## CREATE THE PLOT LAYOUT lmat <- matrix(c(0,2,3,1), ncol = 2) lwid <- if(dendroK) c(1,4) else c(0.05,4) lhei <- if(dendroG) c(1,4) else c(0.05,4) if(!is.null(main)) lhei[1] <- lhei[1] + 0.2 if(legend){ lmat <- rbind(lmat, c(4,4)) lhei <- c(lhei,0.8) } margmain <- if(is.null(main)) 0 else 1.5 ## PLOT THE DIFFERENT ELEMENTS dev.hold() on.exit(dev.flush()) op <- par(no.readonly = TRUE) on.exit(par(op), add = TRUE) layout(lmat, widths = lwid, heights = lhei) # Plot the heatmap par(mar = c(margins[1L],0,0,margins[2L])) image(1L:nc, 1L:nr, t(val), xlim = 0.5 + c(0,nc), ylim = 0.5 + c(0,nr), axes = FALSE, xlab = "", ylab = "", col = col, breaks = breaks) axis(1,1L:nc, labels = labCol, las = 2, line = -0.5, tick = 0) if (!is.null(xlab)) mtext(xlab, side = 1, line = margins[1L] - 1.25) axis(4, 1L:nr, labels = labRow, las = 2, line = -0.5, tick = 0) if (!is.null(ylab)) mtext(ylab, side = 4, line = margins[2L] - 1.25) box() # If needed, plot dendros par(mar = c(margins[1L],0,0,0)) if(dendroK){ plot(ddK, horiz = TRUE, axes = FALSE,yaxs = "i", leaflab = "none") } else { frame() } par(mar = c(0,0,margmain, margins[2L])) if(dendroG){ plot(ddG, axes = FALSE, xaxs = "i", leaflab = "none") } else { frame() } if (!is.null(main)) { par(xpd = NA) title(main) } if(legend){ nbreaks <- length(breaks) par(mar = c(3,2,0,2)) dev.hold() on.exit(dev.flush(), add = TRUE) plot.new() plot.window(ylim = c(0,1), xlim = range(breaks), xaxs = "i", yaxs = "i") ybottom <- rep(0,nbreaks-1) ytop <- rep(1,nbreaks-1) xleft <- breaks[-nbreaks] xright <- breaks[-1] rect(xleft, ybottom, xright,ytop,col = col, border = NA) axis(1, las = 1) box() } if(!dendroK) ddK <- NULL if(!dendroG) ddG <- NULL return(invisible( list(val = val, ddK = ddK, ddG = ddG, breaks = breaks, col = col) )) } # Helper function to create dendrograms .kernel2dendro <- function(x){ dists <- outer(diag(x)^2, diag(x)^2, `+`) - 2*x dists[dists < 0] <- 0 dists <- sqrt(dists) as.dendrogram(hclust(as.dist(dists))) } # Helper function to find the best positions find_best_pos <- function(x, n){ id <- order(x, decreasing = TRUE)[seq_len(n)] nr <- nrow(x) rowid <- id %% nr rowid[rowid == 0] <- nr colid <- id %/% nr + 1*(rowid != nr) return(cbind(rowid,colid)) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/plot.tskrr.R
#' Plot the grid of a tuned tskrr model #' #' With this function, you can visualize the grid search for optimal #' lambdas from a \code{\link[xnet:tskrrTune-class]{tskrrTune}} object. #' In the case of two-dimensional grid search, this function plots a #' contour plot on a grid, based on the functions \code{\link{image}} #' and \code{\link{contour}}. For one-dimensional grid search, the function #' creates a single line plot. #' #' @param x an object that inherits from #' \code{\link[xnet:tskrrTune-class]{tskrrTune}} #' @param addlambda a logical value indicating whether the #' lambda with the minimum loss should be added to the plot. #' In case of a one dimensional plot, this adds a colored #' vertical line. In the case of a two dimensional plot, this #' adds a colored point at the minimum. #' @param lambdapars a list with named \code{\link{par}} values #' passed to the function \code{\link{abline}} or #' \code{\link{points}} for plotting the best lambda value when #' \code{addmin = TRUE}. #' @param log a logical value indicating whether the lambdas should be #' plotted at a log scale (the default) or not. #' @param opts.contour options passed to the function #' \code{\link{contour}} for 2D grid plots. Ignored for 1D #' grid plots. #' @param ... arguments passed to other functions. For a one #' dimensional plot, this will be the function \code{\link{plot}} #' #' @return \code{NULL} invisibly #' #' @examples #' #' data(drugtarget) #' #' ## One dimensional tuning #' tuned1d <- tune(drugTargetInteraction, targetSim, drugSim, #' lim = c(1e-4,2), ngrid = 40, #' fun = loss_auc, onedim = TRUE) #' #' plot_grid(tuned1d) #' plot_grid(tuned1d, lambdapars = list(col = "green", #' lty = 1, lwd = 2), #' log = FALSE, las = 2, main = "1D tuning") #' #' ## Two dimensional tuning #' tuned2d <- tune(drugTargetInteraction, targetSim, drugSim, #' lim = c(1e-4,10), ngrid = 20, #' fun = loss_auc) #' #' plot_grid(tuned2d) #' #' @importFrom graphics plot abline axis contour par box #' @importFrom graphics image points #' @importFrom grDevices heat.colors #' @include Class_tskrrTune.R #' @rdname plot_grid #' @export plot_grid <- function(x, addlambda = TRUE, lambdapars = list( col = "red" ), log = TRUE, opts.contour = list( nlevels = 10 ), ...){ if(!inherits(x, "tskrrTune")) stop("x has to be a tskrrTune object") if(!is.logical(addlambda) || length(addlambda) != 1) stop("addlambda should be a single logical value.") if(addlambda && !is.list(lambdapars)) stop("lambdapars should be a named list.") if(has_onedim(x)) .plot_1d_grid(x, addlambda = addlambda, lambdapars = lambdapars, log = log, ...) else .plot_2d_grid(x, addlambda = addlambda, lambdapars = lambdapars, log = log, opts.contour = opts.contour, ...) return(invisible(NULL)) } # 1D plotting -------------------------------------------- .plot_1d_grid <- function(x, type = "l", xlab = "Lambda values", ylab = "loss", addlambda, lambdapars, log, opts.contour, ...){ xval <- get_grid(x)$k yval <- get_loss_values(x) dim(yval) <- NULL log <- if(log) "x" else "" plot(xval, yval, type = type, xlab = xlab, ylab = ylab, log = log, ...) if(addlambda){ l <- unname(lambda(x)[1]) if(! "lty" %in% names(lambdapars)) lambdapars <- c(lambdapars, lty = 2) do.call(abline, c(list(v=l), lambdapars)) } } # 2D plotting -------------------------------------------- .plot_2d_grid <- function(x, addlambda, lambdapars, log, opts.contour, col = rev(heat.colors(20)), xlab = "lambda k", ylab = "lambda g", las = par("las"), ... ){ gridvals <- get_grid(x) z <- get_loss_values(x) # extract x and y values if(log){ xval <- log10(gridvals$k) yval <- log10(gridvals$g) } else { xval <- gridvals$k yval <- gridvals$g } image(xval, yval, z, xlab = xlab, ylab = ylab, col = col, xaxt = "n", yaxt = "n", ...) # create axes xaxis <- pretty(xval) yaxis <- pretty(yval) xlabs <- if(log) 10^xaxis else xaxis ylabs <- if(log) 10^yaxis else yaxis axis(1, at = xaxis, labels = prettyNum(xlabs), las = las) axis(2, at = yaxis, labels = prettyNum(ylabs), las = las) # Add contours c.opts <- c(list(x = xval, y = yval, z = z), opts.contour) c.opts$add <- TRUE do.call(contour, c.opts) box() if(addlambda){ lambda <- lambda(x) if(log) lambda <- log10(lambda) p.opts <- c(list(x = lambda[1L], y = lambda[2L]), lambdapars) if(is.null(p.opts$pch)) p.opts$pch <- "+" do.call(points, p.opts) } }
/scratch/gouwar.j/cran-all/cranData/xnet/R/plot_grid.R
#' predict method for tskrr fits #' #' Obtains the predictions from a \code{\link{tskrr}} model for new data. #' To get the predictions on the training data, #' use the function \code{\link[xnet:fitted]{fitted}} #' or set both \code{k} and \code{g} to \code{NULL}. #' #' Predictions can be calculated between new vertices and the vertices #' used to train the model, between new sets of vertices, or both. Which #' predictions are given, depends on the kernel matrices passed to the #' function. #' #' In any case, both the K and G matrix need the kernel values for #' every combination of the new vertices and the vertices used to #' train the model. This is illustrated for both homogeneous and #' heterogeneous networks in the examples. #' #' To predict the links between a new set of vertices and the training #' vertices, you need to provide the kernel matrix for either the K #' or the G set of vertices. If you want to predict the mutual links #' between two new sets of vertices, you have to provide both the #' K and the G matrix. This is particularly important for homogeneous #' networks: if you only supply the \code{k} argument, you will get #' predictions for the links between the new vertices and the vertices #' on which the model is trained. So in order to get the #' mutual links between the new vertices, you need to provide the kernel #' matrix as the value for both the \code{k} and the \code{g} argument. #' #' @section Warning: #' This function is changed in version 0.1.9 so it's more consistent #' in how it expects the K and G matrices to be ordered. Up to version #' 0.1.8 the new vertices should be on the rows for the K matrix and on #' the columns for the G matrix. This lead to confusion. #' #' If you're using old code, you'll get an error pointing this out. #' You need to transpose the G matrix in the old code to make it work #' with the new version. #' #' @param object an object of class \code{\link[xnet:tskrr-class]{tskrr}}. #' @param k a new K matrix or \code{NULL}. if \code{NULL}, the fitted #' values on the training data are returned. #' @param g a new G matrix or \code{NULL}. If \code{NULL}, K is used #' for both. #' @param testdim a logical value indicating whether the dimensions should #' be checked prior to the calculation. You can set this to \code{FALSE} but #' you might get more obscure errors if dimensions don't match. #' @param ... arguments passed to or from other methods #' #' @return a matrix with predicted values. #' #' @seealso \code{\link{tskrr}} and \code{\link{tskrrTune}} for #' fitting the models. #' #' @examples #' #' ## Predictions for homogeneous networks #' #' data(proteinInteraction) #' #' idnew <- sample(nrow(Kmat_y2h_sc), 20) #' #' trainY <- proteinInteraction[-idnew,-idnew] #' trainK <- Kmat_y2h_sc[-idnew,-idnew] #' #' testK <- Kmat_y2h_sc[idnew, - idnew] #' #' mod <- tskrr(trainY, trainK, lambda = 0.1) #' # Predict interaction between test vertices #' predict(mod, testK, testK) #' #' # Predict interaction between test and train vertices #' predict(mod, testK) #' predict(mod, g = testK) #' #' ## Predictions for heterogeneous networks #' data("drugtarget") #' #' idnewK <- sample(nrow(targetSim), 10) #' idnewG <- sample(ncol(drugSim), 10) #' #' trainY <- drugTargetInteraction[-idnewK, -idnewG] #' trainK <- targetSim[-idnewK, -idnewK] #' trainG <- drugSim[-idnewG, -idnewG] #' #' testK <- targetSim[idnewK, -idnewK] #' testG <- drugSim[idnewG, -idnewG] #' #' mod <- tskrr(trainY, trainK, trainG, lambda = 0.01) #' #' # Predictions for new targets on drugs in model #' predict(mod, testK) #' # Predictions for new drugs on targets in model #' predict(mod, g = testG) #' # Predictions for new drugs and targets #' predict(mod, testK, testG) #' #' @include all_generics.R #' @rdname predict #' @method predict tskrr #' @export predict.tskrr <- function(object, k = NULL, g = NULL, testdim = TRUE, ...){ gnull <- is.null(g) knull <- is.null(k) if(testdim){ dims <- dim(object) if(!knull && ncol(k) != dims[1]){ stopmsg <- paste("The k matrix needs",dims[1], "columns. The new vertices should be on the rows.") if(nrow(k) == dims[1]) stopmsg <- paste(stopmsg, "/nYou might have transposed the K matrix.", "See also ?predict.tskrr.") stop(stopmsg, call. = FALSE) } if(!gnull && ncol(g) != dims[2]){ stopmsg <- paste("The g matrix needs",dims[2], "columns. The new vertices should be on the rows.") if(nrow(g) == dims[2]){ stopmsg <- paste(stopmsg, "\nYou might have transposed the G matrix or", "used old code that relied on versions <0.1.9.", "Please see the warning in ?predict.tskrr") } stop(stopmsg, call. = FALSE) } } if(knull && gnull) return(fitted(object)) if(gnull && is_homogeneous(object)){ Keig <- get_eigen(object) g <- eigen2matrix(Keig$vectors, Keig$values) } else if (gnull){ Geig <- get_eigen(object, which = "column") g <- eigen2matrix(Geig$vectors, Geig$values) } else if (knull){ Keig <- get_eigen(object) k <- eigen2matrix(Keig$vectors, Keig$values) } out <- k %*% tcrossprod(weights(object), g) if(knull){ rownames(out) <- labels(object)$k } if(gnull){ colnames(out) <- labels(object)$g } return(out) } #' @rdname predict #' @export setMethod("predict", "tskrr", predict.tskrr)
/scratch/gouwar.j/cran-all/cranData/xnet/R/predict.R
# Function to construct lambdas for the tuning # This functions prepare the lambdas for the function tune and # does some basic checks. Out comes a list with the lambdas # to be used in the tuning # Returns a list with lambdas that fits the tskrrTune slot .prepare_lambdas <- function(lim, ngrid, lambda = NULL, homogeneous, onedim = FALSE){ if(homogeneous || onedim){ # Processing for homogeneous networks if(is.null(lambda)){ lim <- .check_for_one(lim, "lim") ngrid <- .check_for_one(ngrid, "ngrid") lambda <- create_grid(lim, ngrid) } else { lambda <- .check_for_one(lambda, "lambda") } return(list(k = lambda)) } else { # Processing for heterogeneous networks if(is.null(lambda)){ lim <- .check_for_two(lim, "lim") ngrid <- .check_for_two(ngrid, "ngrid") lambdas <- mapply(create_grid, lim, ngrid, SIMPLIFY = FALSE) return(lambdas) } else { lambdas <- .check_for_two(lambda, "lambda") } } } .check_for_one <- function(x, arg = "argument"){ if(is.atomic(x) && is.numeric(x)){ return(x) } else { if(length(x) == 1 && is.numeric(x[[1]])) return(x[[1]]) else stop(paste(arg, "can have only a single series of numeric values for this model.")) } } .check_for_two <- function(x, arg = "argument"){ if(is.atomic(x) && is.numeric(x)){ return(list(k = x,g = x)) } else { if(length(x) == 2 && is.numeric(x[[1]]) && is.numeric(x[[2]]) ){ names(x) <- c("k","g") return(x) } else{ stop(paste(arg,"should either be a numeric vector or a list with two numeric elements for this model.")) } } }
/scratch/gouwar.j/cran-all/cranData/xnet/R/prepare_lambdas.R
#' calculate residuals from a tskrr model #' #' This function returns the residuals for #' an object inheriting from class \code{\link[xnet:tskrr-class]{tskrr}} #' #' @param object a tskrr model #' @param method a character value indicating whether the #' residuals should be based on the predictions or on a #' leave-one-out crossvalidation. #' @inheritParams loo #' @param ... arguments passed from/to other methods. #' #' @inherit loo details #' #' @return a matrix(!) with the requested residuals #' #' @examples #' #' data(drugtarget) #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim, #' lambda = c(0.01,0.01)) #' delta <- response(mod) - loo(mod, exclusion = "both") #' resid <- residuals(mod, method = "loo", exclusion = "both") #' all.equal(delta, resid) #' #' @rdname residuals.tskrr #' @method residuals tskrr #' @export residuals.tskrr <- function(object, method = c("predictions","loo"), exclusion = c("interaction","row", "column", "both"), replaceby0 = FALSE, ...){ method <- match.arg(method) exclusion <- match.arg(exclusion) obs <- response(object) preds <- if(method == "predictions"){ fitted(object) } else { loo(object, exclusion, replaceby0) } obs - preds } #' @rdname residuals.tskrr #' @export setMethod("residuals", "tskrr", residuals.tskrr)
/scratch/gouwar.j/cran-all/cranData/xnet/R/residuals.R
# Function to test inputs for tskrr etc. # This function tests the input for all fitting functions. # Put checkna = FALSE if NA values are allowed in y. # It returns a list with the following elements: # - lambda.k # - lambda.g # - homogeneous .test_input <- function(y,k,g, lambda = 1e-4, testdim = TRUE, testlabels = TRUE, checkna = TRUE){ # SET FLAGS homogeneous <- is.null(g) # TESTS INPUT if( !(is.matrix(y) && is.numeric(y)) ) stop("y should be a matrix.") if( !(is.matrix(k) && is.numeric(k)) ) stop("k should be a matrix.") if(!is.numeric(lambda)) stop("lambda should be numeric.") if(!homogeneous){ if( !(is.matrix(g) && is.numeric(g)) ) stop("g should be a matrix.") nl <- length(lambda) if(nl < 1 || nl > 2) stop("lambda should contain one or two values. See ?tskrr") } else { if(length(lambda) != 1) stop("lambda should be a single value. See ?tskrr") } if(checkna && any(is.na(y))) stop(paste("Missing values in the y matrix are not allowed. You can", "use the function impute_tskrr for imputations.")) # TEST KERNELS if(testdim){ if(!is_symmetric(k)) stop("k should be a symmetric matrix.") if(!homogeneous && !is_symmetric(g)) stop("g should be a symmetric matrix.") if(!valid_dimensions(y,k,g)) stop(paste("The dimensions of the matrices don't match.", "Did you maybe switch the k and g matrices?", sep = "\n")) } if(testlabels){ valid_labels(y,k,g) # Generates errors if something's wrong } # SET LAMBDAS lambda.k <- lambda[1] lambda.g <- if(!homogeneous){ if(nl == 1) lambda else lambda[2] } else NULL return(list( lambda.k = lambda.k, lambda.g = lambda.g, homogeneous = homogeneous )) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/test_input.R
#' test the symmetry of a matrix #' #' This function tells you whether a matrix is symmetric, #' skewed symmetric, or not symmetric. It's used by \code{\link{tskrr}} #' to determine which kind of homologous network is represented by #' the label matrix. #' #' @param x a matrix #' @param tol a single numeric value with the tolerance for comparison #' #' @return a character value with the possible values "symmetric", #' "skewed" or "none". #' #' @seealso \code{\link{tskrrHomogeneous}} for #' more information on the values for the slot \code{symmetry} #' #' @examples #' mat1 <- matrix(c(1,0,0,1),ncol = 2) #' test_symmetry(mat1) #' mat2 <- matrix(c(1,0,0,-1), ncol = 2) #' test_symmetry(mat2) #' mat3 <- matrix(1:4, ncol = 2) #' test_symmetry(mat3) #' #' @export test_symmetry <- function(x, tol = .Machine$double.eps){ if(!is.matrix(x)) stop("x should be a matrix") idl <- lower.tri(x) tx <- t(x) if(all(abs(x[idl] - tx[idl]) < tol )){ out <- "symmetric" } else if(all( abs(x[idl] + tx[idl]) < tol )){ out <- "skewed" } else { out <- "none" } return(out) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/test_symmetry.R
#' Fitting a two step kernel ridge regression #' #' \code{tskrr} is the primary function for fitting a two-step kernel #' ridge regression model. It can be used for both homogeneous and heterogeneous #' networks. #' #' @param y a label matrix #' @param k a kernel matrix for the rows #' @param g an optional kernel matrix for the columns #' @param lambda a numeric vector with one or two values for the #' hyperparameter lambda. If two values are given, the first one is #' used for the k matrix and the second for the g matrix. #' @param testdim a logical value indicating whether symmetry #' and the dimensions of the kernel(s) should be tested. #' Defaults to \code{TRUE}, but for large matrices #' putting this to \code{FALSE} will speed up the function. #' @param testlabels a logical value indicating wether the row- and column #' names of the matrices have to be checked for consistency. Defaults to #' \code{TRUE}, but for large matrices putting this to \code{FALSE} will #' speed up the function. #' @param symmetry a character value with the possibilities #' "auto", "symmetric" or "skewed". In case of a homogeneous fit, you #' can either specify whether the label matrix is symmetric or #' skewed, or you can let the function decide (option "auto"). #' @param keep a logical value indicating whether the kernel hat #' matrices should be stored in the model object. Doing so makes the #' model object quite larger, but can speed up predictions in #' some cases. Defaults to \code{FALSE}. #' #' @return a \code{\link[xnet:tskrr-class]{tskrr}} object #' #' @seealso \code{\link{response}}, \code{\link{fitted}}, #' \code{\link{get_eigen}}, \code{\link{eigen2hat}} #' @examples #' #' # Heterogeneous network #' #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' #' Y <- response(mod) #' pred <- fitted(mod) #' #' # Homogeneous network #' #' data(proteinInteraction) #' #' modh <- tskrr(proteinInteraction, Kmat_y2h_sc) #' #' Yh <- response(modh) #' pred <- fitted(modh) #' #' @export tskrr <- function(y,k,g = NULL, lambda = 1e-4, testdim = TRUE, testlabels = TRUE, symmetry = c("auto","symmetric","skewed"), keep = FALSE ){ iptest <- .test_input(y,k,g,lambda,testdim,testlabels) homogeneous <- iptest$homogeneous lambda.k <- iptest$lambda.k lambda.g <- iptest$lambda.g # Rearrange matrices if necessary rk <- rownames(k) # not when there's no row/-colnames if(!is.null(rk)){ if(homogeneous){ ck <- rownames(k) if(any(rownames(y) !=rk)) y <- match_labels(y,rk,ck) } else { cg <- colnames(g) if(any(rownames(y) != rk) || any(colnames(y) !=cg) ) y <- match_labels(y,rk,cg) } } # Test whether Y is symmetric if(homogeneous){ # Test symmetry if required. symmetry <- match.arg(symmetry) if(symmetry == "auto"){ symmetry <- test_symmetry(y) if(symmetry == "none") stop(paste("The Y matrix is not symmetric or skewed symmetric.", "You need a kernel matrix for rows and columns.")) } } # CALCULATE EIGEN DECOMPOSITION k.eigen <- eigen(k, symmetric = TRUE) g.eigen <- if(!homogeneous) eigen(g, symmetric = TRUE) else NULL res <- tskrr.fit(y, k.eigen, g.eigen, lambda.k, lambda.g) # Create labels rn <- rownames(y) cn <- colnames(y) if(is.null(rn)) rn <- NA_character_ if(is.null(cn)) cn <- NA_character_ # CREATE OUTPUT if(homogeneous){ out <- new("tskrrHomogeneous", y = y, k = k.eigen, lambda.k = lambda.k, pred = res$pred, symmetry = symmetry, has.hat = keep, Hk = if(keep) res$k else matrix(0), labels = list(k=rn, g = NA_character_)) } else { out <- new("tskrrHeterogeneous", y = y, k = k.eigen, g = g.eigen, lambda.k = lambda.k, lambda.g = lambda.g, pred = res$pred, has.hat = keep, Hk = if(keep) res$k else matrix(0), Hg = if(keep) res$g else matrix(0), labels = list(k=rn, g=cn)) } return(out) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/tskrr.R
#' Carry out a two-step kernel ridge regression #' #' This function provides an interface for two-step kernel ridge regression. #' To use this function, you need at least one kernel matrix and one #' label matrix. It's the internal engine used by the function #' \code{\link{tskrr}}. #' #' This function is mostly available for internal use. In most cases, it #' makes much more sense to use \code{\link{tskrr}}, as that function #' returns an object one can work with. The function #' \code{tskrr.fit} could be useful when doing simulations or #' fitting algorithms, as the information returned from this function #' is enough to use the functions returned by \code{\link{get_loo_fun}}. #' #' @param y a matrix representing the links between the nodes of both #' networks. #' @param k an object of class \code{\link{eigen}} containing the eigen #' decomposition of the first kernel matrix. #' @param g an optional object of class \code{\link{eigen}} containing #' the eigen decomposition of the second kernel matrix. If \code{NULL}, #' the network is considered to be homogeneous. #' @param lambda.k a numeric value for the lambda parameter tied #' to the first kernel. #' @param lambda.g a numeric value for the lambda parameter tied #' to the second kernel. If \code{NULL}, the model is fit using the same #' value for \code{lambda.k} and \code{lambda.g} #' @param ... arguments passed to other functions. Currently ignored. #' #' @return a list with three elements: #' \itemize{ #' \item k : the hat matrix for the rows #' \item g : the hat matrix for the columns (or \code{NULL}) #' for homogeneous networks. #' \item pred : the predictions #' } #' #' @examples #' #' data(drugtarget) #' #' K <- eigen(targetSim) #' G <- eigen(drugSim) #' #' res <- tskrr.fit(drugTargetInteraction,K,G, #' lambda.k = 0.01, lambda.g = 0.05) #' #' @export tskrr.fit <- function(y, k, g = NULL, lambda.k = NULL, lambda.g = NULL, ...){ # Set flags homogeneous <- is.null(g) # process input if(is.null(lambda.g)) lambda.g <- lambda.k # get hat matrics Hk <- eigen2hat(k$vectors, k$values, lambda.k) Hg <- if(!homogeneous) eigen2hat(g$vectors, g$values, lambda.g) else NULL # Create predictions pred <- if(!homogeneous) Hk %*% y %*% Hg else Hk %*% y %*% Hk return(list(k = Hk,g = Hg, pred = pred)) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/tskrr.fit.R
#' tune the lambda parameters for a tskrr #' #' This function lets you tune the lambda parameter(s) of a two-step #' kernel ridge regression model for optimal performance. You can either #' tune a previously fitted \code{\link{tskrr}} model, or pass the #' label matrix and kernel matrices to fit and tune a model in #' one go. #' #' This function currently only performs a simple grid search for all #' (combinations of) lambda values. If no specific lambda values are #' provided, then the function uses \code{\link{create_grid}} to #' create an evenly spaced (on a logarithmic scale) grid. #' #' In the case of a heterogeneous network, you can specify different values #' for the two parameters that need tuning. To do so, you need to #' provide a list with the settings for every parameter to the arguments #' \code{lim}, \code{ngrid} and/or \code{lambda}. If you #' try this for a homogeneous network, the function will return an error. #' #' Alternatively, you can speed up the grid search by searching in a #' single dimension. When \code{onedim = TRUE}, the search for a #' heterogeneous network will only consider cases where both lambda values #' are equal. #' #' The arguments \code{exclusion} and \code{replaceby0} are used by #' the function \code{\link{get_loo_fun}} to find the correct #' leave-one-out function. #' #' By default, the function uses standard mean squared error based on #' the cross-validation results as a measure for optimization. However, you #' can provide a custom function if needed, as long as it takes #' two matrices as input: \code{Y} being the observed interactions and #' \code{LOO} being the result of the chosen cross-validation. #' #' @param x a \code{\link{tskrr}} object representing a two step #' kernel ridge regression model. #' @param lim a vector with 2 values that give the boundaries for the domain #' in which lambda is searched, or possibly a list with 2 elements. See details #' @param ngrid a single numeric value giving the number of points #' in a single dimension of the grid, or possibly a list with 2 elements. #' See details. #' @param lambda a vector with the lambdas that need checking for #' homogeneous networks, or possibly a list with two elements for #' heterogeneous networks. See Details. Defaults to #' \code{NULL}, which means that the function constructs the search grid #' from the other arguments. #' @param fun a loss function that takes the label matrix Y and the #' result of the crossvalidation LOO as input. The function name can #' be passed as a character string as well. #' @param onedim a logical value indicating whether the search should be #' done in a single dimension. See details. #' @inheritParams get_loo_fun #' @inheritParams tskrr #' @param ... arguments to be passed to the loss function #' #' @return a model of class \code{\link[xnet:tskrrTune-class]{tskrrTune}} #' #' @seealso #' * \code{\link{loo}}, \code{\link{loo_internal}} and #' \code{\link{get_loo_fun}} for more information on how leave one out #' validation works. #' * \code{\link{tskrr}} for fitting a twostep kernel ridge regression. #' * \code{\link{loss_functions}} for different loss functions. #' @md #' #' @examples #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' tuned <- tune(mod, lim = c(0.1,1), ngrid = list(5,10), #' fun = loss_auc) #' #' \dontrun{ #' #' # This is just some visualization of the matrix #' # It can be run safely. #' gridvals <- get_grid(tuned) #' z <- get_loss_values(tuned) # loss values #' #' image(gridvals$k,gridvals$g,z, log = 'xy', #' xlab = "lambda k", ylab = "lambda g", #' col = rev(heat.colors(20))) #' #' } #' @rdname tune #' @name tune NULL #' @rdname tune #' @export setMethod("tune", "tskrrHomogeneous", function(x, lim = c(1e-4,1), ngrid = 10, lambda = NULL, fun = loss_mse, exclusion = 'edges', replaceby0 = FALSE, onedim = TRUE, ...){ # Translate edges and vertices if(exclusion %in% c("interaction","both")) exclusion <- switch(exclusion, interaction = "edges", both = "vertices") if(!onedim) warning("Only one-dimensional search is possible for homogeneous networks.") fun <- match.fun(fun) lambda <- .prepare_lambdas(lim, ngrid, lambda, homogeneous = TRUE) loofun <- .getloo_homogeneous(exclusion = exclusion, symmetry = symmetry(x), replaceby0 = replaceby0) decomp <- get_eigen(x) loss <- function(lambda){ Hr <- eigen2hat(decomp$vectors, decomp$values, lambda) pred <- Hr %*% x@y %*% Hr fun(x@y, loofun(x@y, Hr, pred), ...) } lval <- vapply(lambda$k,loss, numeric(1)) best <- which.min(lval) best_loss <- lval[best] best_lambda <- lambda$k[best] newx <- update(x, best_lambda) as_tuned(newx, lambda_grid = lambda, lambda.k = best_lambda, best_loss = best_loss, loss_values = matrix(lval, ncol = 1), loss_function = fun, exclusion = exclusion, replaceby0 = replaceby0, onedim = TRUE ) }) #' @rdname tune #' @export setMethod("tune", "tskrrHeterogeneous", function(x, lim = c(1e-4,1), ngrid = 10, lambda = NULL, fun = loss_mse, exclusion = 'interaction', replaceby0 = FALSE, onedim = FALSE, ...){ fun <- match.fun(fun) lambda <- .prepare_lambdas(lim, ngrid, lambda, homogeneous = FALSE, onedim = onedim) # Prepare objects decompr <- get_eigen(x, 'row') decompc <- get_eigen(x, 'column') loofun <- .getloo_heterogeneous(exclusion = exclusion, replaceby0 = replaceby0) loss <- function(l1, l2){ Hr <- eigen2hat(decompr$vectors, decompr$values, l1) Hc <- eigen2hat(decompc$vectors, decompc$values, l2) pred <- Hr %*% x@y %*% Hc fun(x@y, loofun(x@y, Hr, Hc, pred), ...) } if(onedim){ lval <- vapply(lambda$k, function(i) loss(i,i), numeric(1)) best <- which.min(lval) best_loss <- lval[best] best_lambda <- rep(lambda$k[best],2) # Add correct data for heterogeneous lval <- matrix(lval, ncol = 1) # must be a matrix } else { lval <- vapply(lambda$g, function(l2){ vapply(lambda$k, loss, numeric(1), l2) }, numeric(length(lambda$k))) best <- find_min_pos(lval) best_lambda <- c(lambda$k[best[1]], lambda$g[best[2]]) best_loss <- lval[best[1],best[2]] } newx <- update(x, best_lambda) as_tuned(newx, lambda_grid = lambda, lambda.k = best_lambda[1], lambda.g = best_lambda[2], best_loss = best_loss, loss_values = lval, loss_function = fun, exclusion = exclusion, replaceby0 = replaceby0, onedim = onedim ) }) #' @rdname tune #' @export setMethod("tune", "matrix", function(x, k, g = NULL, lim = c(1e-4,1), ngrid = 10, lambda = NULL, fun = loss_mse, exclusion = 'interaction', replaceby0 = FALSE, testdim = TRUE, testlabels = TRUE, symmetry = c("auto","symmetric","skewed"), keep = FALSE, onedim = is.null(g), ...){ homogeneous <- is.null(g) fun <- match.fun(fun) # get initial lambdas lambda <- .prepare_lambdas(lim, ngrid, lambda, homogeneous = homogeneous, onedim = onedim) if(homogeneous){ init_lambda <- lambda$k[1] } else { init_lambda <- c(lambda$k[1], lambda$g[1]) } # Fit initial model mod <- tskrr(x,k,g, lambda = init_lambda, testdim = testdim, testlabels = testlabels, symmetry = symmetry, keep = keep) # Carry out the tuning callGeneric(mod, lambda = lambda, fun = fun, exclusion = exclusion, replaceby0 = replaceby0, onedim = onedim, ...) }) # Helper function find_best_lambda find_min_pos <- function(x){ id <- which.min(x) nr <- nrow(x) rowid <- id %% nr if(rowid == 0) rowid <- nr colid <- id %/% nr + 1*(rowid != nr) return(c(rowid,colid)) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/tune.R
#' Update a tskrr object with a new lambda #' #' This function allows you to refit a \code{\link{tskrr}} with a #' new lambda. It can be used to do manual tuning/cross-validation. #' If the object has the hat matrices stored, these are updated #' as well. #' #' @param object a \code{\link[xnet:tskrr-class]{tskrr}} object #' @inheritParams tskrr #' @param ... arguments passed to methods #' #' @return an updated \code{\link[xnet:tskrr-class]{tskrr}} object #' fitted with the new lambdas. #' #' @examples #' data(drugtarget) #' #' mod <- tskrr(drugTargetInteraction, targetSim, drugSim) #' #' # Update with the same lambda #' mod2 <- update(mod, lambda = 1e-3) #' #' # Use different lambda for rows and columns #' mod3 <- update(mod, lambda = c(0.01,0.001)) #' #' # A model with the hat matrices stored #' lambda <- c(0.001,0.01) #' modkeep <- tskrr(drugTargetInteraction, targetSim, drugSim, keep = TRUE) #' Hk_1 <- hat(modkeep, which = "row") #' modkeep2 <- update(modkeep, lambda = lambda) #' Hk_2 <- hat(modkeep2, which = "row") #' #' # Calculate new hat matrix by hand: #' decomp <- get_eigen(modkeep, which = "row") #' Hk_byhand <- eigen2hat(decomp$vectors, #' decomp$values, #' lambda = lambda[1]) #' identical(Hk_2, Hk_byhand) #' #' @rdname update #' @export setMethod("update", "tskrrHomogeneous", function(object, lambda){ if(missing(lambda) || !is.numeric(lambda) || length(lambda) != 1){ stop(paste("lambda should be a single numeric value", "for homogeneous networks.")) } decomp <- get_eigen(object) Hk <- eigen2hat(decomp$vectors, decomp$values, lambda) [email protected] <- lambda object@pred <- Hk %*% object@y %*% Hk if(has_hat(object)) object@Hk <- Hk return(object) }) #' @rdname update #' @export setMethod("update", "tskrrHeterogeneous", function(object, lambda){ if(missing(lambda) || !is.numeric(lambda) || (ll<- length(lambda)) < 1 || ll > 2){ stop(paste("lambda should be a numeric vector", "with one or two values")) } if(ll == 1){ lambda.k <- lambda.g <- lambda } else { lambda.k <- lambda[1] lambda.g <- lambda[2] } decompk <- get_eigen(object, 'row') decompg <- get_eigen(object, 'column') Hk <- eigen2hat(decompk$vectors, decompk$values, lambda.k) Hg <- eigen2hat(decompg$vectors, decompg$values, lambda.g) [email protected] <- lambda.k [email protected] <- lambda.g object@pred <- Hk %*% object@y %*% Hg if(has_hat(object)){ object@Hk <- Hk object@Hg <- Hg } return(object) })
/scratch/gouwar.j/cran-all/cranData/xnet/R/update.R
#' Functions to check matrices #' #' These functions allow you to check whether the dimensions of the #' label matrix and the kernel matrix (matrices) are compatible. #' \code{valid_dimensions} checks whether both k and g are square matrices, #' whether y has as many rows as k and whether y has as many columns as g. #' \code{is_square} checks whether both dimensions are the same. #' #' @param y a label matrix #' @param k a kernel matrix #' @param g an optional second kernel matrix or \code{NULL} otherwise. #' #' @return a logical value indicating whether the dimensions of the #' matrices are compatible for a two step kernel ridge regression. #' #' @note The function \code{is_square} is not exported #' #' @rdname valid_dimensions #' @export valid_dimensions <- function(y, k, g = NULL){ ydim <- dim(y) out <- is_square(k) && ydim[1L] == dim(k)[2L] if(!is.null(g)){ out <- out && is_square(g) && ydim[2L] == dim(g)[1L] } else { out <- out && is_square(y) } return(out) } #' @param x any matrix #' @rdname valid_dimensions #' @aliases is_square is_square <- function(x){ dims <- dim(x) dims[2L] == dims[1L] }
/scratch/gouwar.j/cran-all/cranData/xnet/R/valid_dimensions.R
#' Test the correctness of the labels. #' #' This function checks whether the labels between the Y, K, and G #' matrices make sense. This means that all the labels found as #' rownames for \code{y} can be found as rownames \emph{and} column #' names of \code{k}, and all the colnames for \code{y} can be found #' as rownames \emph{and} colnames of \code{g} (if provided). #' #' Compatible labels mean that it is unequivocally clear which #' rows and columns can be linked throughout the model. In case none #' of the matrices have row- or colnames, the labels are considered #' compatible. In all other cases, all matrices should have both row #' and column names. They should fulfill the following conditions: #' #' \itemize{ #' \item the row- and column names of a kernel matrix must contain #' the same values in the same order. Otherwise, the matrix can't #' be symmetric. #' \item the rownames of \code{y} should correspond to the rownames #' of \code{k} #' \item the colnames of \code{y} should correspond to the colnames #' of \code{g} if it is supplied, or the colnames of \code{k} in #' case \code{g} is \code{NULL} #' } #' #' @param y the label matrix #' @param k the kernel matrix for the rows #' @param g the kernel matrix for the columns (optional). If not available, #' it takes the value \code{NULL} #' #' @note This is a non-exported convenience function. #' #' @return \code{TRUE} if all labels are compatible, an error otherwise. #' #' @rdname valid_labels valid_labels <- function(y, k, g = NULL){ if(!valid_dimensions(y, k, g)) stop("Dimensions are incompatible.") rny <- rownames(y) cny <- colnames(y) rnk <- rownames(k) cnk <- colnames(k) checkg <- !is.null(g) # Check for NULL rynull <- is.null(rny) rknull <- is.null(rnk) cynull <- is.null(cny) cknull <- is.null(cnk) if(checkg){ rng <- rownames(g) cng <- colnames(g) rgnull <- is.null(rng) cgnull <- is.null(cng) if(all(rynull,rknull,rgnull,cynull,cknull,cgnull)) return(TRUE) else if(any(rynull,rknull,rgnull,cynull,cknull,cgnull)) stop(paste("Not all row labels and col labels could be found.", "You need to have compatible row and column labels", "for all matrices. See also ?valid_labels.")) } else { if(all(rynull,rknull,cynull,cknull)) return(TRUE) else if(any(rynull,rknull,cynull,cknull)) stop(paste("Not all row labels and col labels could be found.", "You need to have compatible row and column labels", "for all matrices. See also ?valid_labels.")) } if(!all(rnk == cnk)) stop("Different row- and colnames found for k.") out <- all(match(rny,rnk,0L) > 0L) if(!out) stop(paste("rownames of y and k are not matching.", "See also ?valid_labels.")) if(checkg){ # When there is g, check against g cng <- colnames(g) rng <- rownames(g) if(!all(rng == cng)) stop("Different row- and colnames found for g.") out <- all(match(cny,cng,0L) > 0L) if(!out) stop(paste("colnames of y and g are not matching.", "See also ?valid_labels.")) } else { # No g, so check against k again out <- all(match(cny, cnk,0L) > 0L) if(!out) stop(paste("colnames of y and k are not matching.", "See also ?valid_labels.")) } return(out) }
/scratch/gouwar.j/cran-all/cranData/xnet/R/valid_labels.R
#' Extract weights from a tskrr model #' #' This function calculates the weight matrix for #' calculating the predictions of a tskrr model. #' #' The weight matrix is calculated from the map matrices through the #' function \code{\link{eigen2map}}. #' #' @note The package \code{xnet} adds a S4 generic function #' for \code{\link[stats]{weights}}. #' #' @param object a \code{\link{tskrr}} object for which the weights #' have to be calculated. #' #' #' @return a matrix with the weights for the tskrr model. #' #' @rdname weights #' @aliases weights #' @export setMethod("weights", "tskrrHeterogeneous", function(object){ eigK <- get_eigen(object, 'row') eigG <- get_eigen(object, 'column') l <- lambda(object) Mk <- eigen2map(eigK$vectors, eigK$values, l[1]) Mg <- eigen2map(eigG$vectors, eigG$values, l[2]) Mk %*% response(object) %*% Mg }) #' @rdname weights #' @export setMethod("weights", "tskrrHomogeneous", function(object){ eigK <- get_eigen(object) l <- lambda(object) Mk <- eigen2map(eigK$vectors, eigK$values, l) Mk %*% response(object) %*% Mk })
/scratch/gouwar.j/cran-all/cranData/xnet/R/weights.R
#' Two-step kernel ridge regression for network analysis #' #' This package implements the two-step kernel ridge regression model, a #' supervised network prediction method that can be used for all kinds of network #' analyses. Examples are protein-protein interaction, foodwebs, ... #' #' @seealso Send your bug reports to: #' #' \url{https://github.com/CenterForStatistics-UGent/xnet/issues} #' #' More background in the paper by Stock et al, 2018: #' #' \url{http://doi.org/10.1093/bib/bby095} #' #' @author Joris Meys and Michiel Stock #' #' @import methods "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/xnet/R/xnet-package.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----getFiles, eval = FALSE--------------------------------------------------- # adjAddress <- "http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/nr_admat_dgc.txt" # # targetAddress <- "http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/nr_simmat_dg.txt" # # drugTargetInteraction <- as.matrix( # read.table(adjAddress, header = TRUE, row.names = 1, sep = "\t") # ) # targetSim <- as.matrix( # read.table(targetAddress, header =TRUE, row.names = 1, sep = "\t") # ) ## ----importKEGG, eval = FALSE------------------------------------------------- # library(ChemmineR) # importKEGG <- function(ids){ # sdfset <- SDFset() # creates an empty SDF set # # # We use the link format for obtaining the data # urlp <- "http://www.genome.jp/dbget-bin/www_bget?-f+m+drug+" # # # Combine everything in an sdfset # for(i in ids){ # url <- paste0(urlp, i) # tmp <- as(read.SDFset(url), "SDFset") # cid(tmp) <- i # sdfset <- c(sdfset, tmp) # } # return(sdfset) # } # # Now read the SDF information for all compounds in the research # keggsdf <- importKEGG(colnames(drugTargetInteraction)) ## ----tanimoto, eval = FALSE--------------------------------------------------- # # Keep in mind this needs some time to run! # drugSim <- sapply(cid(keggsdf), # function(x){ # fmcsBatch(keggsdf[x], keggsdf, # au = 0, bu = 0)[,"Tanimoto_Coefficient"] # }) ## ----------------------------------------------------------------------------- data(drugtarget)
/scratch/gouwar.j/cran-all/cranData/xnet/inst/doc/Preparation_example_data.R
--- title: "Preparation of the example data" author: "Joris Meys" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Preparation of the example data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The example data used in this package was originally published by [Yamanishi et al, 2008](https://doi.org/10.1093/bioinformatics/btn162). They used [the KEGG data base](https://www.kegg.jp/) to get information drug-target interaction for different groups of enzymes. We used their supplementary material as a basis for the example data provided to the package. Their supplementary datasets can be downloaded from [here](http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/). ## Obtaining the original data The original adjacency matrix and similarity of the targets were downloaded from that website using the following code: ```{r getFiles, eval = FALSE} adjAddress <- "http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/nr_admat_dgc.txt" targetAddress <- "http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/nr_simmat_dg.txt" drugTargetInteraction <- as.matrix( read.table(adjAddress, header = TRUE, row.names = 1, sep = "\t") ) targetSim <- as.matrix( read.table(targetAddress, header =TRUE, row.names = 1, sep = "\t") ) ``` This data was used as is from the website. ## Processing the drug similarities In the original paper the authors relied on the SIMCOMP algorithm, but this method returns non-symmetric matrices and hence the original data cannot be used in a meaningful way for a two-step kernel ridge regression. Hence we decided to recreate the similarities between the different drugs, this time using the algorithms provided in the [fmcsR package v1.20.0](https://bioconductor.org/packages/release/bioc/html/fmcsR.html). The code used to obtain and process the drug similarities is heavily based on code kindly provided by Dr. Thomas Girke on the [BioConductor support forum](https://support.bioconductor.org/p/106712/#106744). ### Obtaining the data To read in the structural data for all compounds we create a function that constructs the actual link and retrieves the data from KEGG. This function is based on the tools provided in the [ChemmineR package v2.30.2](http://bioconductor.org/packages/ChemmineR/): ```{r importKEGG, eval = FALSE} library(ChemmineR) importKEGG <- function(ids){ sdfset <- SDFset() # creates an empty SDF set # We use the link format for obtaining the data urlp <- "http://www.genome.jp/dbget-bin/www_bget?-f+m+drug+" # Combine everything in an sdfset for(i in ids){ url <- paste0(urlp, i) tmp <- as(read.SDFset(url), "SDFset") cid(tmp) <- i sdfset <- c(sdfset, tmp) } return(sdfset) } # Now read the SDF information for all compounds in the research keggsdf <- importKEGG(colnames(drugTargetInteraction)) ``` ### Calculating the similarities The `fmcs` function in the `fmcsR` package allows to compute a similarity score between two compounds. It returns a few different similarity measures, including the Tanimoto coefficient. This coefficient turns out to be a valid kernel for chemical similarities ([Ralaivola et al, 2005](https://doi.org/10.1016/j.neunet.2005.07.009) , [Bajusz et al, 2015](https://doi.org/10.1186/s13321-015-0069-3)). So in this example we continue with the Tanimoto coefficients. ```{r tanimoto, eval = FALSE} # Keep in mind this needs some time to run! drugSim <- sapply(cid(keggsdf), function(x){ fmcsBatch(keggsdf[x], keggsdf, au = 0, bu = 0)[,"Tanimoto_Coefficient"] }) ``` All data is stored in the package and can be accessed using ```{r} data(drugtarget) ```
/scratch/gouwar.j/cran-all/cranData/xnet/inst/doc/Preparation_example_data.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(xnet) slotsToRmd <- function(class){ slots <- getSlots(class) txt <- paste0(" * `",names(slots), "` : object of type **", slots, "**") cat(txt, sep = "\n") } ## ----Create slots tskrrHomogeneous, results='asis', echo = FALSE-------------- slotsToRmd("tskrrHomogeneous") ## ----Create slots tskrrHeterogeneous, results='asis', echo = FALSE------------ slotsToRmd("tskrrHeterogeneous") ## ----Create slots tskrrTune, results='asis', echo = FALSE--------------------- slotsToRmd("tskrrTune") ## ----Create slots tskrrImpute, results='asis', echo = FALSE------------------- slotsToRmd("tskrrImpute")
/scratch/gouwar.j/cran-all/cranData/xnet/inst/doc/xnet_ClassStructure.R
--- title: "S4 class structure of the xnet package" author: "Meys Joris" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{xnet Class structure} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(xnet) slotsToRmd <- function(class){ slots <- getSlots(class) txt <- paste0(" * `",names(slots), "` : object of type **", slots, "**") cat(txt, sep = "\n") } ``` This document describes the S4 class structure used in the `xnet` package. It's mainly a reference for package developers. Users are advised to use the appropriate functions for extracting the information they need. ## Virtual classes The `xnet` package has three virtual classes that each define a number of slots necessary for that specific type of model: 1. the class `tskrr` for general two step kernel ridge regressions 2. the class `tskrrTune` for tuned two step kernel ridge regressions 3. the class `tskrrImpute` for two step kernel ridge regressions with imputed data. Each of these classes defines the necessary slots for that specific type of action. The actual classes returned by the functions `tskrr()`, `tune()` and `impute()` inherit from (a combination of) these virtual classes. ## Actual classes ### Inheritance from tskrr After using the function `tskrr()`, one of the following classes is returned: * `tskrrHomogeneous` : for homogeneous networks * `tskrrHeterogeneous` : for heterogeneous networks These classes have similar slots, but the homogeneous models don't need information on the column kernel matrix. The slots are listed below. In general the following design principles hold: * the slot `y` contains the adjacency matrix used to fit the model. This goes for all different classes, including the `tskrrTune` and `tskrrImpute` classes. * the object stores the eigendecompositions of the row kernel K and -if applicable- the column kernel G. * if `has.hat = TRUE`, the hat matrices Hk and possibly Hg are stored in the object as well. This can speed up calculations but comes at a memory cost. * the slot `pred` holds the predicted values. * the slots `lambda.k` and `lambda.g` store the tuning parameters. * the slot `labels` store the labels attached to the rows and the columns in a list with elements `k` and `g`. If no labels were present, the single element `k` will have one `NA` value. The function `labels()` will still construct default labels when required. ### Slots defined by tskrrHomogeneous ```{r Create slots tskrrHomogeneous, results='asis', echo = FALSE} slotsToRmd("tskrrHomogeneous") ``` ### Slots defined by tskrrHeterogeneous ```{r Create slots tskrrHeterogeneous, results='asis', echo = FALSE} slotsToRmd("tskrrHeterogeneous") ``` Both classes inherit directly from the class `tskrr`. But these classes also function as parent classes from which `tune()` related and `impute()` related classes inherit. ### Inheritance from tskrrTune When using the function `tune()`, you get one of the following classes: * `tskrrTuneHomogeneous` : for tuned homogeneous networks. Inherits also from `tskrrHomogeneous`. * `tskrrTuneHeterogeneous` : for tuned heterogeneous networks. Inherits also from `tskrrHeterogeneous`. Apart from the slots of the respective `tskrr` class, the inheritance from `tskrrTune` adds the following slots: ```{r Create slots tskrrTune, results='asis', echo = FALSE} slotsToRmd("tskrrTune") ``` These slots use the following design principles: * `lambda_grid` is a list with one or two elements named `k` and `g`, similar to the `labels` slot of the `tskrr` classes. These elements contain the lambda values tested for that dimension. If the grid search was one-dimensional (and `onedim` contains `TRUE`), there's only one element called `k`. * `loss_values` is always a matrix, but when `onedim = TRUE` it's a matrix with a single column. In that matrix, the values are arranged in such a way that the rows correspond with the lambdas for the row kernel, and the columns with the lambdas for the column kernel. * The slots `exclusion` and `replaceby0` follow the same rules as the arguments of the function `get_loo_fun()`. ### Inheritance from tskrrImpute When using the function `impute()`, you get one of the following classes: * `tskrrImputeHomogeneous` : for homogeneous networks with imputed data. * `tskrrImputeHeterogeneous` : for heterogeneous networks with imputed data. Apart from the slots of the respective `tskrr` class, the inheritance from `tskrrImpute` adds the following slots: ```{r Create slots tskrrImpute, results='asis', echo = FALSE} slotsToRmd("tskrrImpute") ``` The slot `imputeid` treats the Y matrix as a vector and stores the position of the imputed values as a integer vector. The other two slots just store the settings used during imputation.
/scratch/gouwar.j/cran-all/cranData/xnet/inst/doc/xnet_ClassStructure.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( fig.width = 6, fig.height = 4,out.width = '49%',fig.align = 'center', collapse = TRUE, comment = "#>" ) suppressMessages(library(xnet)) ## ----fit a heterogeneous model------------------------------------------------ data(drugtarget) drugmodel <- tskrr(y = drugTargetInteraction, k = targetSim, g = drugSim, lambda = c(0.01,0.1)) drugmodel ## ----fit a homogeneous model-------------------------------------------------- data(proteinInteraction) proteinmodel <- tskrr(proteinInteraction, k = Kmat_y2h_sc, lambda = 0.01) proteinmodel ## ----extract info from a model------------------------------------------------ lambda(drugmodel) # extract lambda values lambda(proteinmodel) dim(drugmodel) # extract the dimensions protlabels <- labels(proteinmodel) str(protlabels) ## ----calculate loo values----------------------------------------------------- loo_drugs_interaction <- loo(drugmodel, exclusion = "interaction", replaceby0 = TRUE) loo_protein_both <- loo(proteinmodel, exclusion = "both") ## ----calculate loo residuals-------------------------------------------------- loo_resid <- residuals(drugmodel, method = "loo", exclusion = "interaction", replaceby0 = TRUE) all.equal(loo_resid, response(drugmodel) - loo_drugs_interaction ) ## ----plot a model, fig.show = 'hold'------------------------------------------ plot(drugmodel, main = "Drug Target interaction") ## ----plot the loo values------------------------------------------------------ plot(proteinmodel, dendro = "none", main = "Protein interaction - LOO", which = "loo", exclusion = "both", rows = rownames(proteinmodel)[10:20], cols = colnames(proteinmodel)[30:35]) ## ----plot different color code------------------------------------------------ plot(drugmodel, which = "residuals", col = rainbow(20), breaks = seq(-1,1,by=0.1)) ## ----tune a homogeneous network----------------------------------------------- proteintuned <- tune(proteinmodel, lim = c(0.001,10), ngrid = 20, fun = loss_auc) proteintuned ## ----get the grid values------------------------------------------------------ get_grid(proteintuned) ## ----plot grid---------------------------------------------------------------- plot_grid(proteintuned) ## ----residuals tuned model---------------------------------------------------- plot(proteintuned, dendro = "none", main = "Protein interaction - LOO", which = "loo", exclusion = "both", rows = rownames(proteinmodel)[10:20], cols = colnames(proteinmodel)[30:35]) ## ----------------------------------------------------------------------------- drugtuned1d <- tune(drugmodel, lim = c(0.001,10), ngrid = 20, fun = loss_auc, onedim = TRUE) plot_grid(drugtuned1d, main = "1D search") ## ----tune 2d model------------------------------------------------------------ drugtuned2d <- tune(drugmodel, lim = list(k = c(0.001,10), g = c(0.0001,10)), ngrid = list(k = 20, g = 10), fun = loss_auc) ## ----plot grid 2d model------------------------------------------------------- plot_grid(drugtuned2d, main = "2D search") ## ----------------------------------------------------------------------------- lambda(drugtuned1d) lambda(drugtuned2d) ## ----------------------------------------------------------------------------- cbind( loss = get_loss_values(drugtuned1d)[,1], lambda = get_grid(drugtuned1d)$k )[10:15,] ## ----reorder the data--------------------------------------------------------- idk_test <- c(5,10,15,20,25) idg_test <- c(2,4,6,8,10) drugInteraction_train <- drugTargetInteraction[-idk_test, -idg_test] target_train <- targetSim[-idk_test, -idk_test] drug_train <- drugSim[-idg_test, -idg_test] target_test <- targetSim[idk_test, -idk_test] drug_test <- drugSim[idg_test, -idg_test] ## ----------------------------------------------------------------------------- rownames(target_test) colnames(drug_test) ## ----train the model---------------------------------------------------------- trained <- tune(drugInteraction_train, k = target_train, g = drug_train, ngrid = 30) ## ----------------------------------------------------------------------------- Newtargets <- predict(trained, k = target_test) Newtargets[, 1:5] ## ----------------------------------------------------------------------------- Newdrugs <- predict(trained, g = drug_test) Newdrugs[1:5, ] ## ----------------------------------------------------------------------------- Newdrugtarget <- predict(trained, k=target_test, g=drug_test) Newdrugtarget ## ----create missing values---------------------------------------------------- drugTargetMissing <- drugTargetInteraction idmissing <- c(10,20,30,40,50,60) drugTargetMissing[idmissing] <- NA ## ----------------------------------------------------------------------------- imputed <- impute_tskrr(drugTargetMissing, k = targetSim, g = drugSim, verbose = TRUE) plot(imputed, dendro = "none") ## ----------------------------------------------------------------------------- has_imputed_values(imputed) which_imputed(imputed) # Extract only the imputed values id <- is_imputed(imputed) predict(imputed)[id] ## ----------------------------------------------------------------------------- rowid <- rowSums(id) > 0 colid <- colSums(id) > 0 plot(imputed, rows = rowid, cols = colid)
/scratch/gouwar.j/cran-all/cranData/xnet/inst/doc/xnet_ShortIntroduction.R
--- title: "A short introduction to cross-network analysis with xnet" author: "Meys Joris" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{xnet} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( fig.width = 6, fig.height = 4,out.width = '49%',fig.align = 'center', collapse = TRUE, comment = "#>" ) suppressMessages(library(xnet)) ``` ## Concepts and terms used in the package. ### Notation and naming of networks in the package Networks exist in all forms and shapes. `xnet` is a simple, but powerful package to predict edges in networks in a supervised fashion. For example: * which proteins interact with eachother? * which goods are bought by which clients? * how many likes give Twitter users to each other's tweets? The two sets can contain the same types nodes (e.g. protein interaction networks) or different nodes (e.g. goods bought by clients in a recommender system). When the two sets are the same, we call this a *homogeneous* network. A network between two different sets of nodes is called a *heterogeneous* network. The interactions are presented in a *adjacency matrix*, noted **Y**. The rows of **Y** represent one set of nodes, the columns the second. Interactions can be measured on a continuous scale, indicating how strong each interaction is. Often the adjacency matrix only contains a few values: 1 for interaction, 0 for no interaction and possibly -1 for an inverse interaction. Two-step kernel ridge regression ( function `tskrr()` ) predicts the values in the adjacency matrix based on similarities within the node sets, calculated by using some form of a *kernel function*. This function takes two nodes as input, and outputs a measure of similarity with specific mathematical properties. The resulting *kernel matrix* has to be positive definite for the method to work. In the package, these matrices are noted **K** for the rows and - if applicable - **G** for the columns of **Y**. We refer to the [kernlab](https://cran.r-project.org/package=kernlab) for a collection of different kernel functions. ### Data in the package For the illustrations, we use two different datasets. #### Homogeneous networks The example dataset `proteinInteraction` originates from a publication by [Yamanishi et al (2004)](https://doi.org/10.1093/bioinformatics/bth910). It contains data on interaction between a subset of 769 proteins, and consists of two objects: * the adjacency matrix `proteinInteraction` where 1 indicates an interaction between proteins * the kernel matrix `Kmat_y2h_sc` describing the similarity between the proteins. #### Heterogeneous networks The dataset `drugtarget` serves as an example of a heterogeneous network and comes from a publication of [Yamanishi et al (2008)](https://doi.org/10.1093/bioinformatics/btn162). In order to get a correct kernel matrix, we recalculated the kernel matrices as explained in the vignette [Preparation of the example data](../doc/Preparation_example_data.html). The dataset exists of three objects * the adjacency matrix `drugTargetInteraction` * the kernel matrix for the targets `targetSim` * the kernel matrix for the drugs `drugSim` The adjacency matrix indicates which protein targets interact with which drugs, and the purpose is to predict new drug-target interactions. ## Fitting a two-step kernel ridge regression ### Heterogeneous network To fit a two-step kernel ridge regression, you use the function `tskrr()`. This function needs to get some tuning parameter(s) `lambda`. You can choose to set 1 lambda for tuning **K** and **G** using the same lambda value, or you can specify a different lambda for **K** and **G**. ```{r fit a heterogeneous model} data(drugtarget) drugmodel <- tskrr(y = drugTargetInteraction, k = targetSim, g = drugSim, lambda = c(0.01,0.1)) drugmodel ``` ### Homogeneous network For homogeneous networks you use the same function, but you don't specify the **G** matrix. You also need only a single lambda: ```{r fit a homogeneous model} data(proteinInteraction) proteinmodel <- tskrr(proteinInteraction, k = Kmat_y2h_sc, lambda = 0.01) proteinmodel ``` ### Extracting parameters from a trained model. The model output itself tells you only little, apart from the dimensions, the lambdas used and the labels found in the data. That information can be extracted using a number of convenient functions. ```{r extract info from a model} lambda(drugmodel) # extract lambda values lambda(proteinmodel) dim(drugmodel) # extract the dimensions protlabels <- labels(proteinmodel) str(protlabels) ``` * `lambda` returns a vector with the lambda values used. * `dim` returns the dimensions. * `labels` returns a list with two elements, `k` and `g`, containing the labels for the rows resp. the columns. You can also use the functions `rownames()` and `colnames()` to extract the labels. ### Information on the fit of the model The functions `fitted()` and `predict()` can be used to extract the fitted values. The latter also allows you to specify new kernel matrices to predict for new nodes in the network. To obtain the residuals, you can use the function `residuals()`. This is shown further in the document. ## Performing leave-one-out cross-validation ### Settings for LOO The most significant contribution of this package, are the various shortcuts for leave-one-out cross-validation (LOO-CV) described in [the paper by Stock et al, 2018](https://doi.org/10.1093/bib/bby095). Generally LOO-CV removes a value, refits the model and predicts the removed value based on this refit model. In this package you do this using the function `loo()`. The paper describes a number of different settings, which can be passed to the argument `exclusion`: * *interaction*: in this setting only the interaction between two nodes is removed from the adjacency matrix. * *row*: in this setting the entire row for that node is removed from the adjacency matrix. This boils down to removing a node from the set described by **K**. * *column*: in this setting the entire column for that node is removed from the adjacency matrix. This boils down to removing a node from the set decribed by **G**. * *both*: in this setting both rows and columns are removed, i.e. for every loo value the respective nodes are removed from both sets. For some networks, only information of interactions is available, so a 0 does not necessarily indicate "no interaction". It just indicates "no knowledge" for an interaction. In those cases it makes more sense to calculate the LOO values by replacing the interaction by 0 instead of removing it. This can be done by setting `replaceby0 = TRUE`. ```{r calculate loo values} loo_drugs_interaction <- loo(drugmodel, exclusion = "interaction", replaceby0 = TRUE) loo_protein_both <- loo(proteinmodel, exclusion = "both") ``` In both cases the result is a matrix with the LOO values. ### Use LOO in other functions There are several functions that allow to use the LOO values instead of predictions for model tuning and validation. For example, you can calculate residuals based on LOO values directly using the function `residuals()`: ```{r calculate loo residuals} loo_resid <- residuals(drugmodel, method = "loo", exclusion = "interaction", replaceby0 = TRUE) all.equal(loo_resid, response(drugmodel) - loo_drugs_interaction ) ``` Every other function that can use LOO values instead of predictions will have the same two arguments `exclusion` and `replaceby0`. ## Looking at model output The function provides a `plot()` function for looking at the model output. This function can show you the fitted values, LOO values or the residuals. It also lets you construct dendrograms based on distances computed using the **K** and **G** matrices, so you have both the predictions and the similarity information on the nodes in one plot. ```{r plot a model, fig.show = 'hold'} plot(drugmodel, main = "Drug Target interaction") ``` To plot LOO values, you set the argument `which`. As the protein model is pretty extensive, we can remove the dendrogram and select a number of proteins we want to inspect closer. ```{r plot the loo values} plot(proteinmodel, dendro = "none", main = "Protein interaction - LOO", which = "loo", exclusion = "both", rows = rownames(proteinmodel)[10:20], cols = colnames(proteinmodel)[30:35]) ``` If the colors don't suit you, you can set both the breaks used for the color code and the color code itself. ```{r plot different color code} plot(drugmodel, which = "residuals", col = rainbow(20), breaks = seq(-1,1,by=0.1)) ``` ## Tuning a model to find the best lambda. In most cases you don't know how to set the `lambda` values for optimal predictions. In order to find the best `lambda` values, the function `tune()` allows you to do a grid search. This grid search can be done in a number of ways: * by specifying actual values to be tested * by specifying the minimum and maximum lambda together with the number of values needed in every dimension. The function will create a grid that's even spaced on a log scale. Tuning minimizes a loss function. Two loss functions are provided, i.e. one based on mean squared error (`loss_mse`) and one based on the area under the curve (`loss_auc`). But you can provide your own loss function too, if needed. ### Homogeneous networks Homogeneous networks have a single lambda value, and should hence only search in a single dimension. The following code tests 20 lambda values between 0.001 and 10. ```{r tune a homogeneous network} proteintuned <- tune(proteinmodel, lim = c(0.001,10), ngrid = 20, fun = loss_auc) proteintuned ``` The returned object is a again a model object with the model fitted using the best lambda value. It also contains extra information on the settings of the tuning. You can extract the grid values as follows: ```{r get the grid values} get_grid(proteintuned) ``` This returns a list with one or two elements, each element containing the grid values for the respective kernel matrix. You can also create a plot to visually inspect the tuning: ```{r plot grid} plot_grid(proteintuned) ``` This object is also a tskrr model, so all the functions used above can be used here as well. For example, we can use the same code as before to inspect the LOO values of this tuned model: ```{r residuals tuned model} plot(proteintuned, dendro = "none", main = "Protein interaction - LOO", which = "loo", exclusion = "both", rows = rownames(proteinmodel)[10:20], cols = colnames(proteinmodel)[30:35]) ``` ### Heterogeneous networks For heterogeneous networks, the tuning works the same way. Standard, the function `tune()` performs a two-dimensional grid search. To do a one-dimensional grid search (i.e. use the same lambda for **K** and **G**), you set the argument `onedim = TRUE`. ```{r} drugtuned1d <- tune(drugmodel, lim = c(0.001,10), ngrid = 20, fun = loss_auc, onedim = TRUE) plot_grid(drugtuned1d, main = "1D search") ``` When performing a two-dimensional grid search, you can specify different limits and grid values or lambda values for both dimensions. You do this by passing a list with two elements for the respective arguments. ```{r tune 2d model} drugtuned2d <- tune(drugmodel, lim = list(k = c(0.001,10), g = c(0.0001,10)), ngrid = list(k = 20, g = 10), fun = loss_auc) ``` the `plot_grid()` function will give you a heatmap indicating where the optimal lambda values are found: ```{r plot grid 2d model} plot_grid(drugtuned2d, main = "2D search") ``` As before, you can use the function `lambda()` to get to the best lambda values. ```{r} lambda(drugtuned1d) lambda(drugtuned2d) ``` A one-dimensional grid search give might yield quite different optimal lambda values. To get more information on the loss values, the function `get_loss_values()` can be used. This allows you to examine the actual improvement for every lambda value. The output is always a matrix, and in the case of a 1D search it's a matrix with one column. Combining these values with the lambda grid, shows that the the difference between a lambda value of around 0.20 and around 0.34 is very small. This is also obvious from the grid plots shown above. ```{r} cbind( loss = get_loss_values(drugtuned1d)[,1], lambda = get_grid(drugtuned1d)$k )[10:15,] ``` ## Predicting new values In order to predict new values, you need information on the outcome of the kernel functions for the combination of the new values and those used to train the model. Depending on which information you have, you can do different predictions. To illustrate this, we split up the data for the drugsmodel. ```{r reorder the data} idk_test <- c(5,10,15,20,25) idg_test <- c(2,4,6,8,10) drugInteraction_train <- drugTargetInteraction[-idk_test, -idg_test] target_train <- targetSim[-idk_test, -idk_test] drug_train <- drugSim[-idg_test, -idg_test] target_test <- targetSim[idk_test, -idk_test] drug_test <- drugSim[idg_test, -idg_test] ``` So the following drugs and targets are removed from the training data and will be used for predictions later: ```{r} rownames(target_test) colnames(drug_test) ``` We can now train the data using `tune()` just like we would use `tskrr()` ```{r train the model} trained <- tune(drugInteraction_train, k = target_train, g = drug_train, ngrid = 30) ``` ### Predict for new K-nodes In order to predict the interaction between new targets and the drugs in the model, we need to pass the kernel values for the similarities between the new targets and the ones in the model. The `predict()` function will select the correct **G** matrix for calculating the predictions. ```{r} Newtargets <- predict(trained, k = target_test) Newtargets[, 1:5] ``` ### Predict for new G-nodes If you want to predict for new drugs, you need the kernel values for the similarities between new drugs and the drugs trained in the model. ```{r} Newdrugs <- predict(trained, g = drug_test) Newdrugs[1:5, ] ``` ### Predict for new K and G nodes You can combine both kernel matrices used above to get predictions about the interaction between new drugs and new targets: ```{r} Newdrugtarget <- predict(trained, k=target_test, g=drug_test) Newdrugtarget ``` ## Impute new values based on a tskrr model Sometimes you have missing values in a adjacency matrix. These missing values can be imputed based on a simple algorithm: 1. replace the missing values by a start value 2. fit a tskrr model with the added values 3. replace the missing values with the predictions of that model 4. repeat until the imputed values converge (i.e. the difference with the previous run falls below a tolerance value) Apart from the usual arguments of `tskrr`, you can give additional parameters to the function `impute_tskrr`. The most important ones are * `niter`: the maximum number of iterations * `tol`: the tolerance, i.e. the minimal sum of squared differences between iteration steps to keep the algorithm going * `verbose`: setting this to 1 or 2 gives additional info on the algorithm performance. So let's construct a dataset with missing values: ```{r create missing values} drugTargetMissing <- drugTargetInteraction idmissing <- c(10,20,30,40,50,60) drugTargetMissing[idmissing] <- NA ``` Now we can try to impute these values. The outcome is again a tskrr model. ```{r} imputed <- impute_tskrr(drugTargetMissing, k = targetSim, g = drugSim, verbose = TRUE) plot(imputed, dendro = "none") ``` To extract information on the imputation, you have a few convenience functions to your disposal: * `has_imputed_values()` tells you whether the model contains imputed values * `is_imputed()` returns a logical matrix where `TRUE` indicates an imputed value * `which_imputed()` returns an integer vector with the positions of the imputed values. Note that these positions are vector positions, i.e. they give the position in a single dimension (according to how a matrix is stored internally in R.) ```{r} has_imputed_values(imputed) which_imputed(imputed) # Extract only the imputed values id <- is_imputed(imputed) predict(imputed)[id] ``` You can use this information to plot the imputed values in context: ```{r} rowid <- rowSums(id) > 0 colid <- colSums(id) > 0 plot(imputed, rows = rowid, cols = colid) ```
/scratch/gouwar.j/cran-all/cranData/xnet/inst/doc/xnet_ShortIntroduction.Rmd
--- title: "Preparation of the example data" author: "Joris Meys" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Preparation of the example data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The example data used in this package was originally published by [Yamanishi et al, 2008](https://doi.org/10.1093/bioinformatics/btn162). They used [the KEGG data base](https://www.kegg.jp/) to get information drug-target interaction for different groups of enzymes. We used their supplementary material as a basis for the example data provided to the package. Their supplementary datasets can be downloaded from [here](http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/). ## Obtaining the original data The original adjacency matrix and similarity of the targets were downloaded from that website using the following code: ```{r getFiles, eval = FALSE} adjAddress <- "http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/nr_admat_dgc.txt" targetAddress <- "http://web.kuicr.kyoto-u.ac.jp/supp/yoshi/drugtarget/nr_simmat_dg.txt" drugTargetInteraction <- as.matrix( read.table(adjAddress, header = TRUE, row.names = 1, sep = "\t") ) targetSim <- as.matrix( read.table(targetAddress, header =TRUE, row.names = 1, sep = "\t") ) ``` This data was used as is from the website. ## Processing the drug similarities In the original paper the authors relied on the SIMCOMP algorithm, but this method returns non-symmetric matrices and hence the original data cannot be used in a meaningful way for a two-step kernel ridge regression. Hence we decided to recreate the similarities between the different drugs, this time using the algorithms provided in the [fmcsR package v1.20.0](https://bioconductor.org/packages/release/bioc/html/fmcsR.html). The code used to obtain and process the drug similarities is heavily based on code kindly provided by Dr. Thomas Girke on the [BioConductor support forum](https://support.bioconductor.org/p/106712/#106744). ### Obtaining the data To read in the structural data for all compounds we create a function that constructs the actual link and retrieves the data from KEGG. This function is based on the tools provided in the [ChemmineR package v2.30.2](http://bioconductor.org/packages/ChemmineR/): ```{r importKEGG, eval = FALSE} library(ChemmineR) importKEGG <- function(ids){ sdfset <- SDFset() # creates an empty SDF set # We use the link format for obtaining the data urlp <- "http://www.genome.jp/dbget-bin/www_bget?-f+m+drug+" # Combine everything in an sdfset for(i in ids){ url <- paste0(urlp, i) tmp <- as(read.SDFset(url), "SDFset") cid(tmp) <- i sdfset <- c(sdfset, tmp) } return(sdfset) } # Now read the SDF information for all compounds in the research keggsdf <- importKEGG(colnames(drugTargetInteraction)) ``` ### Calculating the similarities The `fmcs` function in the `fmcsR` package allows to compute a similarity score between two compounds. It returns a few different similarity measures, including the Tanimoto coefficient. This coefficient turns out to be a valid kernel for chemical similarities ([Ralaivola et al, 2005](https://doi.org/10.1016/j.neunet.2005.07.009) , [Bajusz et al, 2015](https://doi.org/10.1186/s13321-015-0069-3)). So in this example we continue with the Tanimoto coefficients. ```{r tanimoto, eval = FALSE} # Keep in mind this needs some time to run! drugSim <- sapply(cid(keggsdf), function(x){ fmcsBatch(keggsdf[x], keggsdf, au = 0, bu = 0)[,"Tanimoto_Coefficient"] }) ``` All data is stored in the package and can be accessed using ```{r} data(drugtarget) ```
/scratch/gouwar.j/cran-all/cranData/xnet/vignettes/Preparation_example_data.Rmd
--- title: "S4 class structure of the xnet package" author: "Meys Joris" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{xnet Class structure} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(xnet) slotsToRmd <- function(class){ slots <- getSlots(class) txt <- paste0(" * `",names(slots), "` : object of type **", slots, "**") cat(txt, sep = "\n") } ``` This document describes the S4 class structure used in the `xnet` package. It's mainly a reference for package developers. Users are advised to use the appropriate functions for extracting the information they need. ## Virtual classes The `xnet` package has three virtual classes that each define a number of slots necessary for that specific type of model: 1. the class `tskrr` for general two step kernel ridge regressions 2. the class `tskrrTune` for tuned two step kernel ridge regressions 3. the class `tskrrImpute` for two step kernel ridge regressions with imputed data. Each of these classes defines the necessary slots for that specific type of action. The actual classes returned by the functions `tskrr()`, `tune()` and `impute()` inherit from (a combination of) these virtual classes. ## Actual classes ### Inheritance from tskrr After using the function `tskrr()`, one of the following classes is returned: * `tskrrHomogeneous` : for homogeneous networks * `tskrrHeterogeneous` : for heterogeneous networks These classes have similar slots, but the homogeneous models don't need information on the column kernel matrix. The slots are listed below. In general the following design principles hold: * the slot `y` contains the adjacency matrix used to fit the model. This goes for all different classes, including the `tskrrTune` and `tskrrImpute` classes. * the object stores the eigendecompositions of the row kernel K and -if applicable- the column kernel G. * if `has.hat = TRUE`, the hat matrices Hk and possibly Hg are stored in the object as well. This can speed up calculations but comes at a memory cost. * the slot `pred` holds the predicted values. * the slots `lambda.k` and `lambda.g` store the tuning parameters. * the slot `labels` store the labels attached to the rows and the columns in a list with elements `k` and `g`. If no labels were present, the single element `k` will have one `NA` value. The function `labels()` will still construct default labels when required. ### Slots defined by tskrrHomogeneous ```{r Create slots tskrrHomogeneous, results='asis', echo = FALSE} slotsToRmd("tskrrHomogeneous") ``` ### Slots defined by tskrrHeterogeneous ```{r Create slots tskrrHeterogeneous, results='asis', echo = FALSE} slotsToRmd("tskrrHeterogeneous") ``` Both classes inherit directly from the class `tskrr`. But these classes also function as parent classes from which `tune()` related and `impute()` related classes inherit. ### Inheritance from tskrrTune When using the function `tune()`, you get one of the following classes: * `tskrrTuneHomogeneous` : for tuned homogeneous networks. Inherits also from `tskrrHomogeneous`. * `tskrrTuneHeterogeneous` : for tuned heterogeneous networks. Inherits also from `tskrrHeterogeneous`. Apart from the slots of the respective `tskrr` class, the inheritance from `tskrrTune` adds the following slots: ```{r Create slots tskrrTune, results='asis', echo = FALSE} slotsToRmd("tskrrTune") ``` These slots use the following design principles: * `lambda_grid` is a list with one or two elements named `k` and `g`, similar to the `labels` slot of the `tskrr` classes. These elements contain the lambda values tested for that dimension. If the grid search was one-dimensional (and `onedim` contains `TRUE`), there's only one element called `k`. * `loss_values` is always a matrix, but when `onedim = TRUE` it's a matrix with a single column. In that matrix, the values are arranged in such a way that the rows correspond with the lambdas for the row kernel, and the columns with the lambdas for the column kernel. * The slots `exclusion` and `replaceby0` follow the same rules as the arguments of the function `get_loo_fun()`. ### Inheritance from tskrrImpute When using the function `impute()`, you get one of the following classes: * `tskrrImputeHomogeneous` : for homogeneous networks with imputed data. * `tskrrImputeHeterogeneous` : for heterogeneous networks with imputed data. Apart from the slots of the respective `tskrr` class, the inheritance from `tskrrImpute` adds the following slots: ```{r Create slots tskrrImpute, results='asis', echo = FALSE} slotsToRmd("tskrrImpute") ``` The slot `imputeid` treats the Y matrix as a vector and stores the position of the imputed values as a integer vector. The other two slots just store the settings used during imputation.
/scratch/gouwar.j/cran-all/cranData/xnet/vignettes/xnet_ClassStructure.Rmd
--- title: "A short introduction to cross-network analysis with xnet" author: "Meys Joris" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{xnet} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( fig.width = 6, fig.height = 4,out.width = '49%',fig.align = 'center', collapse = TRUE, comment = "#>" ) suppressMessages(library(xnet)) ``` ## Concepts and terms used in the package. ### Notation and naming of networks in the package Networks exist in all forms and shapes. `xnet` is a simple, but powerful package to predict edges in networks in a supervised fashion. For example: * which proteins interact with eachother? * which goods are bought by which clients? * how many likes give Twitter users to each other's tweets? The two sets can contain the same types nodes (e.g. protein interaction networks) or different nodes (e.g. goods bought by clients in a recommender system). When the two sets are the same, we call this a *homogeneous* network. A network between two different sets of nodes is called a *heterogeneous* network. The interactions are presented in a *adjacency matrix*, noted **Y**. The rows of **Y** represent one set of nodes, the columns the second. Interactions can be measured on a continuous scale, indicating how strong each interaction is. Often the adjacency matrix only contains a few values: 1 for interaction, 0 for no interaction and possibly -1 for an inverse interaction. Two-step kernel ridge regression ( function `tskrr()` ) predicts the values in the adjacency matrix based on similarities within the node sets, calculated by using some form of a *kernel function*. This function takes two nodes as input, and outputs a measure of similarity with specific mathematical properties. The resulting *kernel matrix* has to be positive definite for the method to work. In the package, these matrices are noted **K** for the rows and - if applicable - **G** for the columns of **Y**. We refer to the [kernlab](https://cran.r-project.org/package=kernlab) for a collection of different kernel functions. ### Data in the package For the illustrations, we use two different datasets. #### Homogeneous networks The example dataset `proteinInteraction` originates from a publication by [Yamanishi et al (2004)](https://doi.org/10.1093/bioinformatics/bth910). It contains data on interaction between a subset of 769 proteins, and consists of two objects: * the adjacency matrix `proteinInteraction` where 1 indicates an interaction between proteins * the kernel matrix `Kmat_y2h_sc` describing the similarity between the proteins. #### Heterogeneous networks The dataset `drugtarget` serves as an example of a heterogeneous network and comes from a publication of [Yamanishi et al (2008)](https://doi.org/10.1093/bioinformatics/btn162). In order to get a correct kernel matrix, we recalculated the kernel matrices as explained in the vignette [Preparation of the example data](../doc/Preparation_example_data.html). The dataset exists of three objects * the adjacency matrix `drugTargetInteraction` * the kernel matrix for the targets `targetSim` * the kernel matrix for the drugs `drugSim` The adjacency matrix indicates which protein targets interact with which drugs, and the purpose is to predict new drug-target interactions. ## Fitting a two-step kernel ridge regression ### Heterogeneous network To fit a two-step kernel ridge regression, you use the function `tskrr()`. This function needs to get some tuning parameter(s) `lambda`. You can choose to set 1 lambda for tuning **K** and **G** using the same lambda value, or you can specify a different lambda for **K** and **G**. ```{r fit a heterogeneous model} data(drugtarget) drugmodel <- tskrr(y = drugTargetInteraction, k = targetSim, g = drugSim, lambda = c(0.01,0.1)) drugmodel ``` ### Homogeneous network For homogeneous networks you use the same function, but you don't specify the **G** matrix. You also need only a single lambda: ```{r fit a homogeneous model} data(proteinInteraction) proteinmodel <- tskrr(proteinInteraction, k = Kmat_y2h_sc, lambda = 0.01) proteinmodel ``` ### Extracting parameters from a trained model. The model output itself tells you only little, apart from the dimensions, the lambdas used and the labels found in the data. That information can be extracted using a number of convenient functions. ```{r extract info from a model} lambda(drugmodel) # extract lambda values lambda(proteinmodel) dim(drugmodel) # extract the dimensions protlabels <- labels(proteinmodel) str(protlabels) ``` * `lambda` returns a vector with the lambda values used. * `dim` returns the dimensions. * `labels` returns a list with two elements, `k` and `g`, containing the labels for the rows resp. the columns. You can also use the functions `rownames()` and `colnames()` to extract the labels. ### Information on the fit of the model The functions `fitted()` and `predict()` can be used to extract the fitted values. The latter also allows you to specify new kernel matrices to predict for new nodes in the network. To obtain the residuals, you can use the function `residuals()`. This is shown further in the document. ## Performing leave-one-out cross-validation ### Settings for LOO The most significant contribution of this package, are the various shortcuts for leave-one-out cross-validation (LOO-CV) described in [the paper by Stock et al, 2018](https://doi.org/10.1093/bib/bby095). Generally LOO-CV removes a value, refits the model and predicts the removed value based on this refit model. In this package you do this using the function `loo()`. The paper describes a number of different settings, which can be passed to the argument `exclusion`: * *interaction*: in this setting only the interaction between two nodes is removed from the adjacency matrix. * *row*: in this setting the entire row for that node is removed from the adjacency matrix. This boils down to removing a node from the set described by **K**. * *column*: in this setting the entire column for that node is removed from the adjacency matrix. This boils down to removing a node from the set decribed by **G**. * *both*: in this setting both rows and columns are removed, i.e. for every loo value the respective nodes are removed from both sets. For some networks, only information of interactions is available, so a 0 does not necessarily indicate "no interaction". It just indicates "no knowledge" for an interaction. In those cases it makes more sense to calculate the LOO values by replacing the interaction by 0 instead of removing it. This can be done by setting `replaceby0 = TRUE`. ```{r calculate loo values} loo_drugs_interaction <- loo(drugmodel, exclusion = "interaction", replaceby0 = TRUE) loo_protein_both <- loo(proteinmodel, exclusion = "both") ``` In both cases the result is a matrix with the LOO values. ### Use LOO in other functions There are several functions that allow to use the LOO values instead of predictions for model tuning and validation. For example, you can calculate residuals based on LOO values directly using the function `residuals()`: ```{r calculate loo residuals} loo_resid <- residuals(drugmodel, method = "loo", exclusion = "interaction", replaceby0 = TRUE) all.equal(loo_resid, response(drugmodel) - loo_drugs_interaction ) ``` Every other function that can use LOO values instead of predictions will have the same two arguments `exclusion` and `replaceby0`. ## Looking at model output The function provides a `plot()` function for looking at the model output. This function can show you the fitted values, LOO values or the residuals. It also lets you construct dendrograms based on distances computed using the **K** and **G** matrices, so you have both the predictions and the similarity information on the nodes in one plot. ```{r plot a model, fig.show = 'hold'} plot(drugmodel, main = "Drug Target interaction") ``` To plot LOO values, you set the argument `which`. As the protein model is pretty extensive, we can remove the dendrogram and select a number of proteins we want to inspect closer. ```{r plot the loo values} plot(proteinmodel, dendro = "none", main = "Protein interaction - LOO", which = "loo", exclusion = "both", rows = rownames(proteinmodel)[10:20], cols = colnames(proteinmodel)[30:35]) ``` If the colors don't suit you, you can set both the breaks used for the color code and the color code itself. ```{r plot different color code} plot(drugmodel, which = "residuals", col = rainbow(20), breaks = seq(-1,1,by=0.1)) ``` ## Tuning a model to find the best lambda. In most cases you don't know how to set the `lambda` values for optimal predictions. In order to find the best `lambda` values, the function `tune()` allows you to do a grid search. This grid search can be done in a number of ways: * by specifying actual values to be tested * by specifying the minimum and maximum lambda together with the number of values needed in every dimension. The function will create a grid that's even spaced on a log scale. Tuning minimizes a loss function. Two loss functions are provided, i.e. one based on mean squared error (`loss_mse`) and one based on the area under the curve (`loss_auc`). But you can provide your own loss function too, if needed. ### Homogeneous networks Homogeneous networks have a single lambda value, and should hence only search in a single dimension. The following code tests 20 lambda values between 0.001 and 10. ```{r tune a homogeneous network} proteintuned <- tune(proteinmodel, lim = c(0.001,10), ngrid = 20, fun = loss_auc) proteintuned ``` The returned object is a again a model object with the model fitted using the best lambda value. It also contains extra information on the settings of the tuning. You can extract the grid values as follows: ```{r get the grid values} get_grid(proteintuned) ``` This returns a list with one or two elements, each element containing the grid values for the respective kernel matrix. You can also create a plot to visually inspect the tuning: ```{r plot grid} plot_grid(proteintuned) ``` This object is also a tskrr model, so all the functions used above can be used here as well. For example, we can use the same code as before to inspect the LOO values of this tuned model: ```{r residuals tuned model} plot(proteintuned, dendro = "none", main = "Protein interaction - LOO", which = "loo", exclusion = "both", rows = rownames(proteinmodel)[10:20], cols = colnames(proteinmodel)[30:35]) ``` ### Heterogeneous networks For heterogeneous networks, the tuning works the same way. Standard, the function `tune()` performs a two-dimensional grid search. To do a one-dimensional grid search (i.e. use the same lambda for **K** and **G**), you set the argument `onedim = TRUE`. ```{r} drugtuned1d <- tune(drugmodel, lim = c(0.001,10), ngrid = 20, fun = loss_auc, onedim = TRUE) plot_grid(drugtuned1d, main = "1D search") ``` When performing a two-dimensional grid search, you can specify different limits and grid values or lambda values for both dimensions. You do this by passing a list with two elements for the respective arguments. ```{r tune 2d model} drugtuned2d <- tune(drugmodel, lim = list(k = c(0.001,10), g = c(0.0001,10)), ngrid = list(k = 20, g = 10), fun = loss_auc) ``` the `plot_grid()` function will give you a heatmap indicating where the optimal lambda values are found: ```{r plot grid 2d model} plot_grid(drugtuned2d, main = "2D search") ``` As before, you can use the function `lambda()` to get to the best lambda values. ```{r} lambda(drugtuned1d) lambda(drugtuned2d) ``` A one-dimensional grid search give might yield quite different optimal lambda values. To get more information on the loss values, the function `get_loss_values()` can be used. This allows you to examine the actual improvement for every lambda value. The output is always a matrix, and in the case of a 1D search it's a matrix with one column. Combining these values with the lambda grid, shows that the the difference between a lambda value of around 0.20 and around 0.34 is very small. This is also obvious from the grid plots shown above. ```{r} cbind( loss = get_loss_values(drugtuned1d)[,1], lambda = get_grid(drugtuned1d)$k )[10:15,] ``` ## Predicting new values In order to predict new values, you need information on the outcome of the kernel functions for the combination of the new values and those used to train the model. Depending on which information you have, you can do different predictions. To illustrate this, we split up the data for the drugsmodel. ```{r reorder the data} idk_test <- c(5,10,15,20,25) idg_test <- c(2,4,6,8,10) drugInteraction_train <- drugTargetInteraction[-idk_test, -idg_test] target_train <- targetSim[-idk_test, -idk_test] drug_train <- drugSim[-idg_test, -idg_test] target_test <- targetSim[idk_test, -idk_test] drug_test <- drugSim[idg_test, -idg_test] ``` So the following drugs and targets are removed from the training data and will be used for predictions later: ```{r} rownames(target_test) colnames(drug_test) ``` We can now train the data using `tune()` just like we would use `tskrr()` ```{r train the model} trained <- tune(drugInteraction_train, k = target_train, g = drug_train, ngrid = 30) ``` ### Predict for new K-nodes In order to predict the interaction between new targets and the drugs in the model, we need to pass the kernel values for the similarities between the new targets and the ones in the model. The `predict()` function will select the correct **G** matrix for calculating the predictions. ```{r} Newtargets <- predict(trained, k = target_test) Newtargets[, 1:5] ``` ### Predict for new G-nodes If you want to predict for new drugs, you need the kernel values for the similarities between new drugs and the drugs trained in the model. ```{r} Newdrugs <- predict(trained, g = drug_test) Newdrugs[1:5, ] ``` ### Predict for new K and G nodes You can combine both kernel matrices used above to get predictions about the interaction between new drugs and new targets: ```{r} Newdrugtarget <- predict(trained, k=target_test, g=drug_test) Newdrugtarget ``` ## Impute new values based on a tskrr model Sometimes you have missing values in a adjacency matrix. These missing values can be imputed based on a simple algorithm: 1. replace the missing values by a start value 2. fit a tskrr model with the added values 3. replace the missing values with the predictions of that model 4. repeat until the imputed values converge (i.e. the difference with the previous run falls below a tolerance value) Apart from the usual arguments of `tskrr`, you can give additional parameters to the function `impute_tskrr`. The most important ones are * `niter`: the maximum number of iterations * `tol`: the tolerance, i.e. the minimal sum of squared differences between iteration steps to keep the algorithm going * `verbose`: setting this to 1 or 2 gives additional info on the algorithm performance. So let's construct a dataset with missing values: ```{r create missing values} drugTargetMissing <- drugTargetInteraction idmissing <- c(10,20,30,40,50,60) drugTargetMissing[idmissing] <- NA ``` Now we can try to impute these values. The outcome is again a tskrr model. ```{r} imputed <- impute_tskrr(drugTargetMissing, k = targetSim, g = drugSim, verbose = TRUE) plot(imputed, dendro = "none") ``` To extract information on the imputation, you have a few convenience functions to your disposal: * `has_imputed_values()` tells you whether the model contains imputed values * `is_imputed()` returns a logical matrix where `TRUE` indicates an imputed value * `which_imputed()` returns an integer vector with the positions of the imputed values. Note that these positions are vector positions, i.e. they give the position in a single dimension (according to how a matrix is stored internally in R.) ```{r} has_imputed_values(imputed) which_imputed(imputed) # Extract only the imputed values id <- is_imputed(imputed) predict(imputed)[id] ``` You can use this information to plot the imputed values in context: ```{r} rowid <- rowSums(id) > 0 colid <- colSums(id) > 0 plot(imputed, rows = rowid, cols = colid) ```
/scratch/gouwar.j/cran-all/cranData/xnet/vignettes/xnet_ShortIntroduction.Rmd
## bssbsb-data.R #' @name bssbsb #' @title BSS/BSB backcross data #' #' @description Data from two densely genotyped backcrosses. #' #' @details #' There are 94 individuals from each of two interspecific backcross: (C57BL/6J #' \eqn{\times}{x} *M. spretus*) \eqn{\times}{x} C57BL/6J and (C57BL/6J #' \eqn{\times}{x} SPRET/Ei) \eqn{\times}{x} SPRET/Ei. They were typed on 1372 #' and 4913 genetic markers, respectively, with 904 markers in common. #' #' These data are from September, 2000. Updated data are available. #' #' @format An object of class `cross`. See [qtl::read.cross()] #' for details. #' @references Rowe, L. B., Nadeau, J. H., Turner, R., Frankel, W. N., Letts, #' V. A., Eppig, J. T., Ko, M. S., Thurston, S. J. and Birkenmeier, E. H. #' (1994) Maps from two interspecific backcross DNA panels available as a #' community genetic mapping resource. *Mamm. Genome* **5**, 253--274. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' @source Lucy Rowe, Jackson Laboratory #' @keywords datasets #' @examples #' #' data(bssbsb) #' summary(bssbsb) #' \dontrun{plot(bssbsb)} #' NULL
/scratch/gouwar.j/cran-all/cranData/xoi/R/bssbsb-data.R
## chiasma.R #' Estimate chiasma distribution from crossover counts #' #' Fit several models, with an assumption of no chromatid interference, to #' crossover count data to obtain fitted distributions of the number of #' chiasmata. #' #' @details #' See Broman and Weber (2000) for details of the method. #' #' We use R's [stats::integrate()] function for numerical integrals, #' [stats::optimize()] for optimizing the likelihood, and #' [stats::uniroot()] for identifying the endpoints of the likelihood #' support interval. #' #' @param xo Vector of non-negative integers; the number of crossovers in a set #' of meiotic products. #' @param max.chiasma Maximum number of chiasmata to allow. #' @param n.iter Maximum number of iterations in the EM algorithm. #' @param tol Tolerance for convergence of the EM algorithm. #' @param verbose If TRUE, print number of interations for each of the 4 models #' at the end. #' @return A list with three components. #' #' First, a matrix containing the observed distribution of the numbers of #' crossovers, followed by the fitted distributions under the Poisson model, #' the truncated Poisson model (assuming an obligate chiasma), the obligate #' chiasma model, and the freely varying model. In all cases we assume no #' chromatid interference. #' #' Second, a matrix containing the estimated distributions of the number of #' chiasmata on the four-strand bundle for the above four models. #' #' Third, the estimated average number of crossovers under the Poisson and #' truncated Poisson models. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [fitGamma()], [qtl::fitstahl()], #' [countxo()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' Yu, K. and Feinbold, E. (2001) Estimating the frequency distribution of #' crossovers during meiosis from recombination data. *Biometrics* #' **57**, 427--434. #' @keywords models #' @examples #' #' data(bssbsb) #' #' # estimated number of crossovers on chr 1 #' nxo <- countxo(bssbsb, chr=1) #' #' # estimate chiasma distribution #' \dontrun{chiasma(nxo)} #' \dontshow{chiasma(nxo, tol=0.001)} #' #' @useDynLib xoi, .registration=TRUE #' @export chiasma <- function(xo, max.chiasma=max(xo)*2+5, n.iter=10000, tol=1e-6, verbose=FALSE) { n.xo <- length(xo) res <- .C("chiasma", as.integer(xo), as.integer(n.xo), as.integer(max.chiasma), p.ch = as.double(rep(0,(max.chiasma+1)*4)), p.xo = as.double(rep(0,(max.chiasma+1)*4)), lambda = as.double(c(0,0)), as.double(rep(0,(max.chiasma+1)*n.xo+2+2*(max.chiasma+1))), n.iter = as.integer(c(n.iter,0,0,0,0)), as.double(tol), PACKAGE="xoi") if(verbose) cat("Done! number of iterations = ", paste(as.character(res$n.iter[-1]),collapse=" "), "\n") xo.table <- rbind(table(factor(xo,levels=0:max.chiasma))/length(xo), matrix(res$p.xo,nrow=4,byrow=TRUE)) ch.table <- matrix(res$p.ch,nrow=4,byrow=TRUE) colnames(ch.table) <- 0:(ncol(ch.table)-1) rownames(ch.table) <- c("truncPois","Pois","oblchi","free") rownames(xo.table) <- c("observed", "truncPois","Pois","oblchi","free") out <- list(xo.table=xo.table*n.xo,ch.table=ch.table, lambda = res$lambda) attr(out, "n.iter") <- res$n.iter[-1] out }
/scratch/gouwar.j/cran-all/cranData/xoi/R/chiasma.R
## coi_um.R #' Estimate the coincidence as a function of micron distance #' #' Estimate the coincidence as a function of micron distance, with #' data on XO locations in microns plus SC length in microns. #' #' The coincidence function is the probability of a recombination #' event in both of two intervals, divided by the product of the two #' intensity function for the two intervals. #' #' We estimate this as a function of the distance between the two #' intervals in microns, taking account of varying SC lengths,. #' #' @param xoloc list of crossover locations (in microns) for each of several oocytes or spermatocytes. #' @param sclength vector of SC lengths (in microns). #' @param centromeres vector of centromere locations (in microns). If NULL, taken to be `sclength/2`. #' @param group nominal vector of groups; the intensity function of #' the crossover process will be estimated separately for each group, #' but a joint coincidence function will be estimated. #' @param intwindow Window size used to smooth the estimated intensity #' function. #' @param coiwindow Window size used to smooth the estimated #' coincidence function. #' @param intloc Locations at which to estimate the intensity #' function, in the interval \[0,1\] #' @param coiloc Values at which the coincidence function is to be #' estimated, in microns, less than `max(sclength)` #' @return A list containing the estimated coincidence (as a matrix #' with two columns, micron distance and corresponding estimated #' coincidence) and the estimated intensity functions (as a matrix #' with `length(group)+1` columns (the locations at which the #' intensity functions were estimated followed by the group-specific estimates). #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [gammacoi()], [stahlcoi()], #' [kfunc()], [est.coi()] #' @keywords models #' @examples #' # simple example using data simulated with no crossover interference #' ncells <- 1000 #' L <- 2 # chr lengths in Morgans (constant here) #' nchi <- rpois(ncells, 2*L) # number of chiasmata #' xoloc <- lapply(nchi, function(a) runif(a, 0, L)) # chi locations #' coi <- est.coi.um(xoloc, rep(L, ncells)) #' #' # plot estimated coincidence and intensity #' # (intensity is after scaling chromosome to length 1) #' par(mfrow=c(2,1), las=1) #' plot(coi$coincidence, type="l", lwd=2, ylim=c(0, max(coi$coincidence[,2]))) #' plot(coi$intensity, type="l", lwd=2, ylim=c(0, max(coi$intensity[,2]))) #' #' @useDynLib xoi, .registration=TRUE #' @export est.coi.um <- function(xoloc, sclength, centromeres=NULL, group=NULL, intwindow=0.05, coiwindow=NULL, intloc=NULL, coiloc=NULL) { # check inputs stopifnot(length(xoloc) == length(sclength)) stopifnot(all(!is.na(unlist(xoloc)))) stopifnot(all(!is.na(sclength) & sclength >= 0)) for(i in seq(along=xoloc)) stopifnot(all(xoloc[[i]] >= 0 & xoloc[[i]] <= sclength[i])) if(is.null(centromeres)) { centromeres <- sclength/2 } else { stopifnot(length(centromeres) == length(xoloc)) stopifnot(all(!is.na(centromeres) & centromeres > 0 & centromeres < sclength)) } if(is.null(group)) { group <- rep(1, length(xoloc)) ugroup <- "intensity" } else { stopifnot(length(group) == length(xoloc)) ugroup <- unique(group) group <- match(group, ugroup) # turn into integers } if(min(table(group)) < 2) stop("At least one group with < 2 individuals") stopifnot(intwindow > 0 && intwindow < 1) if(is.null(coiwindow)) coiwindow <- min(sclength)/10 stopifnot(coiwindow > 0 && coiwindow < max(sclength)) if(is.null(intloc)) { intloc <- seq(0, 1, length=501) } else { intloc <- sort(intloc) stopifnot(length(intloc) > 0) stopifnot(all(!is.na(intloc) & intloc >= 0 & intloc <= 1)) } if(is.null(coiloc)) { coiloc <- seq(0, min(sclength)-coiwindow/2, length=501) } else { coiloc <- sort(coiloc) stopifnot(length(coiloc) > 0) stopifnot(all(!is.na(coiloc) & coiloc >= 0 & coiloc <= max(sclength))) } # end checks of inputs # do the estimation z <- .C("R_est_coi_um", as.integer(length(xoloc)), as.double(unlist(xoloc)), as.integer(sapply(xoloc, length)), as.double(sclength), as.double(centromeres), as.integer(group), as.integer(max(group)), as.double(intwindow), as.double(coiwindow), as.double(intloc), as.integer(length(intloc)), as.double(coiloc), as.integer(length(coiloc)), intensity=as.double(rep(0, length(intloc)*max(group))), coincidence=as.double(rep(0, length(coiloc))), PACKAGE="xoi") # reformat the results result <- list(coincidence = cbind(distance=coiloc, coincidence=z$coincidence), intensity = cbind(position=intloc, matrix(z$intensity, ncol=max(group)))) colnames(result$intensity)[-1] <- ugroup result }
/scratch/gouwar.j/cran-all/cranData/xoi/R/coi_um.R
## coincidence.R #' Estimate the coincidence function #' #' Estimate the coincidence function from backcross data. #' #' The coincidence function is the probability of a recombination event in both #' of two intervals, divided by the product of the two recombination fractions. #' We estimate this as a function of the distance between the two intervals. #' #' Note that we first call [qtl::fill.geno()] to impute any missing #' genotype data. #' #' @param cross Cross object; must be a backcross. See #' [qtl::read.cross()] for format details. #' @param chr Chromosome to consider (only one is allowed). If NULL, the #' first chromosome is considered. #' @param pos If provided, these are used as the marker positions. (This could #' be useful if you want to do things with respect to physical distance.) #' @param window Window size used to smooth the estimates. #' @param fill.method Method used to impute missing data. #' @param error.prob Genotyping error probability used in imputation of missing #' data. #' @param map.function Map function used in imputation of missing data. #' @return A data.frame containing the distance between intervals and the #' corresponding estimate of the coincidence. There are actually two columns #' of estimates of the coincidence. In the first estimate, we take a running #' mean of each of the numerator and denominator and then divide. In the #' second estimate, we first take a ratio and then take a running mean. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [gammacoi()], [stahlcoi()], [kfunc()] #' @references McPeek, M. S. and Speed, T. P. (1995) Modeling interference in #' genetic recombination. *Genetics* **139**, 1031--1044. #' @keywords models #' @examples #' #' map1 <- sim.map(103, n.mar=104, anchor=TRUE, include.x=FALSE, eq=TRUE) #' x <- sim.cross(map1, n.ind=2000, m=6, type="bc") #' #' out <- est.coi(x, window=5) #' plot(coi1 ~ d, data=out, type="l", lwd=2, col="blue") #' lines(coi2 ~ d, data=out, lwd=2, col="green") #' lines(gammacoi(7), lwd=2, col="red", lty=2) #' #' @useDynLib xoi, .registration=TRUE #' @export est.coi <- function(cross, chr=NULL, pos=NULL, window=0, fill.method=c("imp", "argmax"), error.prob=1e-10, map.function=c("haldane", "kosambi", "c-f", "morgan")) { if(!inherits(cross, "cross")) stop("This function is only prepared for backcrosses.") if(is.null(chr)) chr <- chrnames(cross)[1] if(length(chr) != 1) stop("You should specify just one chromosome.") cross <- subset(cross, chr=chr) dat <- cross$geno[[1]]$data if(any(is.na(dat))) { fill.method <- match.arg(fill.method) map.function <- match.arg(map.function) cross <- fill.geno(cross, method=fill.method, error.prob=error.prob, map.function=map.function) dat <- cross$geno[[1]]$data if(any(is.na(dat))) { warning("Some data still missing.") dat[is.na(dat)] <- 0 } } map <- cross$geno[[1]]$map if(!is.null(pos)) { if(length(pos) != length(map)) stop("pos must have length ", length(map)) map <- pos } ni <- nrow(dat) nm <- ncol(dat) if(nm < 3) stop("Need at least three markers.") npair <- choose(nm-1, 2) out <- .C("R_est_coi", as.integer(ni), as.integer(nm), as.integer(npair), as.double(map), as.integer(dat), d=as.double(rep(0, npair)), # distances coi1=as.double(rep(0, npair)), # smooth top and bottom and then ratio coi2=as.double(rep(0, npair)), # ratio then smooth n=as.integer(0), # no. distances to keep as.double(window), PACKAGE="xoi") n <- out$n data.frame(d=out$d[1:n], coi1=out$coi1[1:n], coi2=out$coi2[1:n]) }
/scratch/gouwar.j/cran-all/cranData/xoi/R/coincidence.R
## fitGamma.R #' Fit Gamma model #' #' Fit the gamma model for crossover interference to data on crossover #' locations. #' #' See Broman and Weber (2000) for details of the method. #' #' We use R's [stats::integrate()] function for numerical integrals, #' [stats::optimize()] for optimizing the likelihood, and #' [stats::uniroot()] for identifying the endpoints of the likelihood #' support interval. #' #' @param d A vector of inter-crossover distances in cM. This should include #' distances from start of chromosome to first crossover, last crossover to end #' of chromosome, and chromosome length, if there are no crossovers. #' #' Alternatively, this may be a matrix with the first column being the #' distances and second column being the censoring types (`censor`). #' @param censor A vector of the same length as `d`, indicating the #' censoring type for each distance. `0` = uncensored, `1` = #' right-censored, `2` = initial crossover on chromosome, `3` = whole #' chromosome. #' @param nu A vector of interference parameters (\eqn{\nu}{nu}) at which to #' calculate the log likelihood. If NULL, `lo` and `hi` must be #' specified. #' @param lo If `nu` is unspecified, `lo` indicates the lower value #' of the interval in which to search for the MLE. If `supint=TRUE`, this #' should be below the lower limit of the support interval. #' @param hi If `nu` is unspecified, `hi` indicates the upper value #' of the interval in which to search for the MLE. If `supint=TRUE`, this #' should be above the upper limit of the support interval. #' @param se If TRUE and `nu` was not specified, an estimated SE (based on #' the second derivative of the log likelihood) is estimated. #' @param supint If TRUE and `nu` was not specified, a likelihood support #' interval is calculated, with `drop` being the amount to drop in log #' (base 10). #' @param rescale If TRUE and `nu` was specified, re-scale the log #' likelihoods so that the maximum is at 0. #' @param drop If `supint` was specified, this indicates the amount to #' drop in log (base 10) for the likelihood support interval. #' @param tol Tolerance for converence to calculate the likelihood, SE, and #' likelihood support interval. #' @param maxit Maximum number of iterations in estimating the SE and #' likelihood support interval. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @param h Step used in estimating the second derivative of the log #' likelihood. #' @param hstep factor by which `h` is decreased in each iteration of the #' estimation of the second derivative of the log likelihood. #' @return If `nu` is specified, we return a data frame with two columns: #' `nu` and the corresponding log (base e) likelihood. If #' `rescale=TRUE`, the maximum log likelihood is subtracted off, so that #' its maximum is at 0. #' #' If `lo` and `hi` is specified, the output contains a single row #' with the MLE of \eqn{\nu}{nu} and the corresponding log likelihood. If #' `se=TRUE`, we also include the estimated SE. If `supint=TRUE`, we #' include two additional rows with the lower and upper limits of the #' likelihood support interval. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [qtl::fitstahl()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords models #' @examples #' #' data(bssbsb) #' \dontshow{bssbsb <- bssbsb[,1:50]} #' #' xodist <- convertxoloc(find.breaks(bssbsb, chr=1)) #' #' # plot a rough log likelihood curve #' \dontrun{out <- fitGamma(xodist, nu=seq(1, 19, by=2))} #' \dontshow{out <- fitGamma(xodist, nu=seq(1, 19, by=2), tol=0.001)} #' plot(out, type="l", lwd=2) #' #' # get MLE #' \dontrun{mle <- fitGamma(xodist, lo=8, hi=12)} #' \dontshow{mle <- fitGamma(xodist, lo=8, hi=12, tol=0.001)} #' mle #' #' abline(v=mle[1], h=mle[2], col="blue", lty=2) #' #' # get MLE and SE #' \dontrun{mle <- fitGamma(xodist, lo=9.5, hi=10.5, se=TRUE)} #' \dontshow{mle <- fitGamma(xodist, lo=9.5, hi=10.5, se=TRUE, tol=0.001)} #' mle #' #' # get MLE and 10^1.5 support interval #' \dontrun{int <- fitGamma(xodist, lo=1, hi=20, supint=TRUE)} #' \dontshow{int <- fitGamma(xodist, lo=1, hi=20, supint=TRUE, tol=0.001)} #' int #' abline(v=mle[2:3,1], h=mle[2:3,2], col="red", lty=2) #' #' @useDynLib xoi, .registration=TRUE #' @export fitGamma <- function(d, censor=NULL, nu=NULL, lo=NULL, hi=NULL, se=FALSE, supint=FALSE, rescale=FALSE, drop=1.5, tol=1e-5, maxit=1000, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10, h=0.1, hstep=1.5) { if(is.null(censor) && !is.null(d) && ncol(d)==2) { censor <- d[,2] d <- d[,1] } if(any(d <= 0 | is.na(d))) stop("d should be positive and not NA") if(any(is.na(censor) | (censor != 0 & censor != 1 & censor != 2 & censor != 3))) stop("censor should be 0, 1, 2 or 3 and not NA") if(length(d) != length(censor)) stop("d and censor should have the same length.") d <- d/100 if(!is.null(nu)) { if(!is.null(lo) || !is.null(hi)) warning("lo and hi ignored") if(se || supint) warning("se and support interval not calculated when nu is specified.") if(any(nu <= 0 | is.na(nu))) stop("nu should be positive and not NA") result <- .C("GammaS", as.integer(length(d)), as.double(d), as.integer(censor), as.integer(length(nu)), nu=as.double(nu), loglik=as.double(rep(0,length(nu))), as.integer(max.conv), as.integer(rescale), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") return(data.frame(nu=result$nu, loglik=result$loglik)) } else { if(is.null(lo) || is.null(hi)) stop("Need to specify nu or both lo and hi") if(lo < tol) lo <- tol if(hi < tol) hi <- tol if(lo < 0 || hi < 0 || lo >= hi) stop("Must have lo, hi positive and lo < hi") result <- .C("GammaMax", as.integer(length(d)), as.double(d), as.integer(censor), as.double(lo), as.double(hi), nu=as.double(0), loglik=as.double(0), as.integer(max.conv), as.double(tol), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") nu <- result$nu loglik <- result$loglik out <- data.frame(nu=nu, loglik=loglik) if(se) { seresult <- .C("GammaSE", as.integer(length(d)), as.double(d), as.integer(censor), as.double(nu), se=as.double(0), as.double(0), # sec deriv as.integer(max.conv), as.double(h), as.double(hstep), as.double(tol), as.integer(maxit), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") out <- cbind(out, se=seresult$se) } if(supint) { intresult <- .C("GammaInterval", as.integer(length(d)), as.double(d), as.integer(censor), as.double(lo), as.double(hi), as.double(nu), int=as.double(rep(0,2)), loglik=as.double(rep(0,2)), as.double(drop*log(10)), # drop in ln lik as.integer(max.conv), as.double(tol), as.integer(maxit), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") if(se) out <- rbind(out, data.frame(nu=intresult$int, loglik=intresult$loglik, se=rep(NA,2))) else out <- rbind(out, data.frame(nu=intresult$int, loglik=intresult$loglik)) rownames(out) <- c("est","low","high") } } out }
/scratch/gouwar.j/cran-all/cranData/xoi/R/fitGamma.R