content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
|---|---|
#' Manually delineate images
#'
#' Adjust the templates in a shiny interface. This will overwrite existing templates.
#'
#' @param stimuli list of stimuli
#'
#' @return list of stimuli with new templates
#' @export
#' @family tem
#'
#' @examples
#' if (interactive()) {
#' # adjust existing delineations
#' stimuli <- demo_stim() |> delin()
#'
#' # create new delineations from scratch
#' stimuli <- demo_stim() |> remove_tems() |> delin()
#' }
delin <- function(stimuli) {
# check for required packages in shiny app
req_packages <- c("shiny", "shinyjs", "shinydashboard", "shinyWidgets", "DT")
pkg_available <- sapply(req_packages, requireNamespace, quietly = TRUE)
if (!all(pkg_available)) {
pkg_txt <- pkg_available[pkg_available == FALSE] |> paste(collapse = ", ")
stop("You need to install the following packages to use the shiny delineator: ",
pkg_txt)
}
stimuli <- as_stimlist(stimuli)
# save images to temp dir
imgdir <- tempfile()
write_stim(stimuli, imgdir)
# start shiny app to delineate
message("Running shiny app...")
shiny::shinyOptions(imgdir = imgdir)
shiny::runApp(appDir = system.file("app", package = "webmorphR"))
# return contents of temp dir
read_stim(imgdir)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/delin.R
|
#' Demo Stimuli
#'
#' A convenience function to get demo stimuli. See the Details below for citation and license info.
#'
#' * [demo_stim()]: two composite faces with frl delineations; 500x500 pixels
#'
#' * [demo_tems()]: an image with 5 different delineations; 675x900 pixels
#'
#' * [demo_unstandard()]: a set of 10 composite faces with frl delineations; rotated, resized, and cropped so face position is not standard and each image is a different size (444 to 645 pixels)
#'
#' ### Citation
#'
#' The images from `demo_stim()` and `demo_unstandard()` are usable on a CC-BY license, citing:
#'
#' DeBruine, L. (2016).Young adult composite faces (Version1). figshare. \doi{https://doi.org/10.6084/m9.figshare.4055130.v1}
#'
#' The image from `demo_tems()` is Lisa DeBruine (the author of webmorphR) and available on a CC-O license (no attribution needed).
#'
#' @param pattern Vector of patterns to use to search for files, or a vector of image indices (e.g., 1:4 selects the first 4 images and their templates)
#'
#' @return list of stimuli
#' @export
#'
#' @examples
#' demo_stim() |> label()
#'
demo_stim <- function(pattern = NULL) {
path <- file.path("extdata", "test") |>
system.file(package = "webmorphR")
stimuli <- read_stim(path, pattern)
stimuli
}
#' @export
#' @rdname demo_stim
#'
#' @examples
#' \donttest{
#' # visualise templates
#' demo_tems() |>
#' draw_tem(pt.size = 10) |>
#' label() |>
#' plot(maxwidth = 1000)
#' }
demo_tems <- function(pattern = NULL) {
path <- file.path("extdata", "tem_examples") |>
system.file(package = "webmorphR")
stimuli <- read_stim(path, pattern)
stimuli
}
#' @export
#' @rdname demo_stim
#'
#' @examples
#' \donttest{
#' # visualise keeping relative sizes
#' demo_unstandard() |>
#' to_size(keep_rels = TRUE) |>
#' pad(80, 0, 0, 0) |>
#' label() |>
#' plot(nrow = 2, maxwidth = 1000)
#' }
demo_unstandard <- function(pattern = NULL) {
path <- file.path("extdata", "unstandard") |>
system.file(package = "webmorphR")
stimuli <- read_stim(path, pattern)
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/demo_stim.R
|
#' Draw template
#'
#' Visualise a template on an image.
#'
#' @details
#' Visualising the index of each point isn't great yet and will overlay
#'
#' @param stimuli list of stimuli
#' @param pt.color,line.color line or point color, see [color_conv()]
#' @param pt.alpha,line.alpha transparency (0-1), ignored if color is a hex value with transparency. Set alpha to 0 to omit lines or points.
#' @param pt.size,line.size size in pixels (scales to image size if NULL)
#' @param pt.shape the shape of the points ("circle", "cross", "index")
#' @param bg background color ("image" uses the original image)
#'
#' @return list of stimuli with template images
#' @export
#' @family tem
#' @family viz
#'
#' @examples
#' # get an image with 2 different templates
#' stimuli <- demo_tems("frl|fpp106")
#'
#' # default template
#' draw_tem(stimuli)
#'
#' \donttest{
#' # custom template
#' draw_tem(stimuli,
#' pt.shape = "cross",
#' pt.color = "red",
#' pt.alpha = 1,
#' pt.size = 15,
#' line.color = rgb(0, 0, 0),
#' line.alpha = 0.5,
#' line.size = 5)
#'
#' # indexed template
#' draw_tem(stimuli,
#' pt.shape = "index",
#' pt.size = 15,
#' pt.alpha = 1,
#' line.alpha = 0)
#' }
draw_tem <- function(stimuli, pt.color = wm_opts("pt.color"), pt.alpha = 0.75, pt.size = NULL, pt.shape = c("circle", "cross", "index"),
line.color = wm_opts("line.color"), line.alpha = 0.5, line.size = NULL,
bg = "image") {
stimuli <- require_tems(stimuli)
w <- width(stimuli) |> round()
h <- height(stimuli) |> round()
pt.shape <- match.arg(pt.shape)
# scale size to image if NULL
if (is.null(pt.size)) {
pt.size <- pmax(1, w/100) |> round(2)
}
if (is.null(line.size)) {
line.size <- pmax(0.5, w/250) |> round(2)
}
# allow for vectors
# pt and line color and alpha combined below
bg[bg != "image"] <- sapply(bg[bg != "image"], color_conv)
suppressWarnings({
l <- length(stimuli)
pt.color <- rep_len(pt.color, l)
pt.alpha <- rep_len(pt.alpha, l)
pt.size <- rep_len(pt.size %||% 0, l)
line.color <- rep_len(line.color, l)
line.alpha <- rep_len(line.alpha, l)
line.size <- rep_len(line.size %||% 0, l)
bg <- rep_len(bg, l)
})
for (i in seq_along(stimuli)) {
temPoints <- stimuli[[i]]$points
circle_radius <- max(0.1, pt.size[i]/2 - line.size[i]/2)
cross_arm <- pt.size[i]/2
# construct points ----
idx <- -1
points <- round(temPoints, 2) |>
apply(2, function(pts) {
x <- pts[1]
y <- pts[2]
if (pt.shape == "circle") {
sprintf("<circle cx=\"%.2f\" cy=\"%.2f\" r=\"%.2f\"/>",
x, y, circle_radius)
} else if (pt.shape == "cross") {
sprintf("<polygon points=\"%.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f\" />",
x, y, x, y-cross_arm, x, y, x+cross_arm, y,
x, y, x, y+cross_arm, x, y, x-cross_arm, y, x, y
)
# sprintf("<line x1=\"%.2f\" x2=\"%.2f\" y1=\"%.2f\" y2=\"%.2f\" />
# <line x1=\"%.2f\" x2=\"%.2f\" y1=\"%.2f\" y2=\"%.2f\" />",
# x, x, y-cross_arm, y+cross_arm,
# x-cross_arm, x+cross_arm, y, y)
} else if (pt.shape == "index") {
idx <<- idx + 1 # dumb but works
sprintf("<text x=\"%.2f\" y=\"%.2f\">%s</text>", x, y+(pt.size/2), idx)
}
}) |>
paste(collapse = "\n ")
# construct Bezier curves for lines ----
if (line.alpha[i] > 0) {
curves <- stimuli[[i]]$lines |>
lapply(function(m) {
v <- temPoints[, m+1]
svgBezier(v, 1)
}) |>
lapply(function(d) {
sprintf("<path d = \"%s\" />",
paste(d, collapse = "\n"))
}) |>
paste(collapse = "\n\n")
} else {
curves <- ""
}
# make SVG ----
svg <- sprintf("<svg width=\"%d\" height=\"%d\" xmlns=\"http://www.w3.org/2000/svg\">
<g id=\"lines\" stroke-width=\"%f\" stroke=\"%s\" fill=\"none\">
%s
</g>
<g id=\"points\" stroke-width=\"%f\" stroke=\"%s\" fill=\"%s\"
font-size=\"%f\" font-weight=\"100\"
font-family=\"FiraCode, Consolas, Courier, monospace\"
text-anchor=\"middle\">
%s
</g>
</svg>",
w[i], h[i], line.size[i],
color_conv(line.color[i], line.alpha[i]), curves,
line.size[i]/2, color_conv(pt.color[i], pt.alpha[i]),
color_conv(pt.color[i], pt.alpha[i]), pt.size[i], points)
temimg <- magick::image_read_svg(svg)
if (bg[i] == "image") {
img <- stimuli[[i]]$img
if (inherits(img, "magick-image")) {
stimuli[[i]]$img <- magick::image_composite(img, temimg)
} else {
stimuli[[i]]$img <- magick::image_background(temimg, wm_opts("fill"))
}
} else if (bg[i] == "none") {
stimuli[[i]]$img <- temimg
} else {
bgcolor <- color_conv(bg[i])
stimuli[[i]]$img <- magick::image_background(temimg, bgcolor)
}
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/draw_tem.R
|
#' Make eyes horizontal
#'
#' Rotate each stimulus so the eye points are horizontal.
#'
#' @param stimuli list of stimuli
#' @param left_eye The first point to align (defaults to 0)
#' @param right_eye The second point to align (defaults to 1)
#' @param fill background color to pass to rotate, see [color_conv()]
#'
#' @return list of stimuli with rotated tems and/or images
#' @export
#' @family manipulators
#'
#' @examples
#' stimuli <- demo_unstandard(1:3)
#' horiz_eyes(stimuli, fill = "red")
#'
horiz_eyes <- function(stimuli, left_eye = 0, right_eye = 1, fill = wm_opts("fill")) {
stimuli <- require_tems(stimuli)
degrees <- lapply(stimuli, `[[`, "points") |>
lapply(function(pt) {
x1 = pt[[1, left_eye+1]]
y1 = pt[[2, left_eye+1]]
x2 = pt[[1, right_eye+1]]
y2 = pt[[2, right_eye+1]]
rad <- atan2(y1 - y2, x1 - x2) %% (2*pi)
180 - (rad / (pi/180))
})
stimuli |>
rotate(degrees = degrees, fill = fill, keep_size = TRUE)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/horiz_eyes.R
|
#' Apply a magick function to each image
#'
#' This is a convenience function for applying {magick} functions that take an image as the first argument and return an image. It's fully vectorised, so you can set separate argument values for each image.
#'
#' @details
#' These functions only affect the image, not the template. If a function changes the morphology of the image (e.g., "implode"), the template will not alter in the same way.
#'
#' @param stimuli list of stimuli
#' @param func the function or a string with the short name of the magick function (see [image_func_types()])
#' @param ... arguments to pass to the function
#'
#' @return list of stimuli with new images
#' @export
#' @family manipulators
#'
#' @examples
#' stimuli <- demo_stim() |> resize(0.5)
#'
#' # make a photographic negative version
#' image_func(stimuli, "negate")
#'
#' # set different argument values for each image
#' image_func(stimuli, "implode", factor = c(0.2, -0.2))
#'
#' \donttest{
#' # other image functions
#' image_func(stimuli, "blur", 5, 3)
#' image_func(stimuli, "contrast", sharpen = 1)
#' image_func(stimuli, "oilpaint", radius = 5)
#' image_func(stimuli, "colorize", opacity = 50,
#' color = c("hotpink", "dodgerblue"))
#'
#' # load a logo image and superimpose it on each image
#' logo <- system.file("extdata/logo.png", package = "webmorphR") |>
#' magick::image_read() |>
#' magick::image_resize(70)
#'
#' image_func(stimuli, "composite", logo, offset = "+5+10")
#'
#' # use a self-defined function
#' testfunc <- function(image) {
#' rot <- magick::image_rotate(image, 180)
#' c(image, rot) |> magick::image_average()
#' }
#' image_func(stimuli, testfunc)
#' }
image_func <- function(stimuli, func, ...) {
stimuli <- as_stimlist(stimuli)
# make sure func is a function or a magick image function
if (is.character(func)) {
if (!func %in% image_func_types()) {
stop("That named function is not possible. See image_func_type() for a full list")
}
func <- parse(text = paste0("magick::image_", func)) |>
eval()
}
if (!is.function(func)) {
stop("func must be a function or the short name of an image function in the magick package (e.g., \"blur\" for the function `image_blur`")
}
# if an argument has the same length as the stimuli
# match argument to stimuli, otherwise pass to the function unaltered
n <- length(stimuli)
dots <- lapply(list(...), function(x) {
if (length(x) == n & is.vector(x)) {
rep_len(x, n)
} else {
rep_len(list(x), n)
}
})
for (i in seq_along(stimuli)) {
subdots <- lapply(dots, `[[`, i)
args <- c(list(stimuli[[i]]$img), subdots)
stimuli[[i]]$img <- do.call(func, args)
}
stimuli
}
#' Possible functions
#'
#' \code{\link{image_func}} can take a named function from the magick package, but only functions that return an image that is compatible with the current template (e.g., doesn't change size or shape).
#'
#' @return list of compatible function names
#' @export
#'
#' @examples
#' image_func_types()
image_func_types <- function() {
c("annotate", "apply", "average", "background", "blur",
"canny", "channel", "charcoal", "colorize", "combine",
"composite", "contrast", "convert", "convolve", "despeckle",
"edge", "emboss", "enhance", "equalize", "fill", "flatten",
"fuzzycmeans", "fx", "fx_sequence", "implode", "lat", "level",
"map", "median", "modulate", "morphology", "motion_blur",
"negate", "noise", "normalize", "oilpaint", "ordered_dither",
"page", "quantize", "reducenoise", "repage", "separate",
"set_defines", "shade", "strip", "threshold", "transparent")
}
#' Make images greyscale
#'
#' @param stimuli list of class stimuli
#'
#' @return stimlist with new images
#' @export
#' @family manipulators
#'
#' @examples
#' stimuli <- demo_stim()
#' grey_stim <- greyscale(stimuli)
#' plot(grey_stim)
greyscale <- function(stimuli) {
image_func(stimuli, "modulate", saturation = 0)
}
#' @rdname greyscale
#' @export
#' @family manipulators
grayscale <- greyscale
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/image_func.R
|
#' Add Information
#'
#' Add info with a data table that contains the info in either the same order as the stimulus list, or matching the stimuli item name with the column specified by `.by`.
#'
#' You can also add data as named vectors.
#'
#' @param stimuli list of stimuli
#' @param ... data table or named vectors of info to add
#' @param .by the column to use to match info to stimuli names; leave NULL if the data are to be matched by order
#'
#' @return list of stimuli with info added
#' @export
#' @family info
#'
#' @examples
#' stimuli <- demo_stim() |>
#' add_info(project = "XXX", gender = c("F", "M"))
#'
#' stimuli$f_multi$info |> str()
#'
add_info <- function(stimuli, ..., .by = NULL) {
stimuli <- as_stimlist(stimuli)
# handle table or vector formats
dots <- list(...)
if (length(dots) == 1 && is.data.frame(dots[[1]])) {
# data is in a table
info <- dots[[1]]
} else {
# dots are vectors
dots$..n.. <- seq_along(stimuli) # in case dots are single values
info <- as.data.frame(dots)
info$..n.. <- NULL
}
if (is.null(.by)) {
# match by index
for (i in seq_along(stimuli)) {
stimuli[[i]]$info <- lapply(info[i, , drop = FALSE], `[`)
}
} else {
# match by name
for (nm in names(stimuli)) {
row <- info[which(info[[.by]] == nm), , drop = FALSE]
row[[.by]] <- NULL
stimuli[[nm]]$info <- lapply(row, `[`)
}
}
stimuli
}
#' Get Information
#'
#' @param stimuli list of stimuli
#' @param ... column names to return
#' @param .rownames whether to return a table with no rownames (NULL), rownames from the list item names (NA), or as a new column (the column name as a string)
#'
#' @return a data frame or vector of the info
#' @export
#' @family info
#'
#' @examples
#' stimuli <- demo_stim() |>
#' add_info(project = "test", gender = c("F", "M"))
#'
#' get_info(stimuli)
#' get_info(stimuli, "gender")
get_info <- function(stimuli, ..., .rownames = "id") {
# get all info from stimuli
info <- lapply(stimuli, `[[`, "info") |>
list_to_tbl(rownames = .rownames)
info$width <- width(stimuli)
info$height <- height(stimuli)
info$tem <- lapply(stimuli, `[[`, "points") |>
sapply(ncol) |> sapply(`%||%`, NA)
# select specified columns
dots <- c(...)
if (length(dots) > 1 && is.character(.rownames)) { dots <- c(dots, .rownames) }
if (length(dots) > 0) {
info <- info[, dots, drop = FALSE]
# make vector if dots is 1 item
if (ncol(info) == 1) {
info <- info[[1]]
names(info) <- names(stimuli)
}
}
info
}
#' Image widths
#'
#' @param stimuli list of stimuli
#' @param type whether to return all widths, min, max, or only unique widths
#'
#' @return vector of widths
#' @export
#' @family info
#'
#' @examples
#'
#' demo_stim() |> width()
width <- function(stimuli, type = c("all", "min", "max", "unique")) {
stimuli <- as_stimlist(stimuli)
w <- sapply(stimuli, `[[`, "width")
switch(match.arg(type),
all = w,
min = min(w, na.rm = T),
max = max(w, na.rm = T),
unique = unique(w))
}
#' Image heights
#'
#' @param stimuli list of stimuli
#' @param type whether to return all heights, min, max, or only unique heights
#'
#' @return vector of heights
#' @export
#' @family info
#'
#' @examples
#'
#' demo_stim() |> height()
height <- function(stimuli, type = c("all", "min", "max", "unique")) {
stimuli <- as_stimlist(stimuli)
h <- sapply(stimuli, `[[`, "height")
switch(match.arg(type),
all = h,
min = min(h, na.rm = T),
max = max(h, na.rm = T),
unique = unique(h))
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/info.R
|
#' Label images
#'
#' Defaults to [mlabel()] unless you use arguments specific to [gglabel()]. All arguments are vectorised over the stimuli and values are recycled or truncated if there are fewer or more than stimuli.
#'
#' @param stimuli list of stimuli
#' @param ... arguments to pass on to [mlabel()] or [gglabel()]
#'
#' @return stimlist with labelled images
#' @export
#' @family viz
#'
#' @seealso [mlabel()], [gglabel()]
#'
#' @examples
#' stimuli <- demo_stim()
#'
#' # label with magick::image_annotate
#' label(stimuli,
#' text = c("CHINWE", "GEORGE"),
#' gravity = c("north", "south"),
#' color = "red")
#'
#' # label with ggplot2::annotate
#' label(stimuli,
#' label = c("CHINWE", "GEORGE"),
#' x = 0.5,
#' y = c(0.99, 0.02),
#' vjust = c(1, 0),
#' size = 18,
#' color = "red")
label <- function(stimuli, ...) {
args <- names(list(...))
# list unique args
magick_args <- c("text", "gravity", "location", "degrees",
"font", "style", "weight", "kerning",
"decoration", "strokecolor", "boxcolor")
gg_args <- c("label", "x", "y", "geom", "hjust", "vjust",
"xintercept", "yintercept", "xmax", "xmin", "ymax", "ymin",
"stat", "label.padding", "label.r", "label.size", "alpha",
"family", "fontface", "angle")
has_magic_args <- any(args %in% magick_args)
has_gg_args <- any(args %in% gg_args)
if (has_magic_args & has_gg_args) {
stop("You're using arguments for both mlabel() and gglabel(). Fix this or use one of those functions.")
} else if (has_magic_args) {
mlabel(stimuli, ...)
} else if (has_gg_args) {
gglabel(stimuli, ...)
} else { # default to mlabel
mlabel(stimuli, ...)
}
}
#' Label with magick annotations
#'
#' Label image using [magick::image_annotate]. All arguments are vectorised over the stimuli and values are recycled or truncated if there are fewer or more than stimuli. Setting a font, weight, style only works if your imagemagick is compiled with fontconfig support.
#'
#' @param stimuli list of stimuli
#' @param text a vector of the label text(s) or TRUE to use stimlist names
#' @param color a vector of the label colour(s)
#' @param gravity string with gravity value from \code{magick::gravity_types}.
#' @param location geometry string with location relative to gravity
#' @param degrees rotates text around center point
#' @param size font size in pixels or proportion of image width (if < 1.0)
#' @param font string with font family such as "sans", "mono", "serif", "Times", "Helvetica", "Trebuchet", "Georgia", "Palatino" or "Comic Sans".
#' @param style value of [magick::style_types()]: "Undefined", "Any", "Italic", "Normal", "Oblique"
#' @param weight thickness of th e font, 400 is normal and 700 is bold.
#' @param kerning increases or decreases whitespace between letters
#' @param decoration value of [magick::decoration_types()]: "LineThrough" "None", "Overline", "Underline"
#' @param strokecolor adds a stroke (border around the text)
#' @param boxcolor adds a background color
#'
#' @seealso [gglabel()] for a labeller using syntax like [ggplot2::annotate()]
#' @return stimlist with labelled images
#' @export
#' @family viz
#'
#' @examples
#' stimuli <- demo_stim()
#' mlabel(stimuli,
#' text = c("CHINWE", "GEORGE"),
#' gravity = c("north", "south"),
#' color = "red")
mlabel <- function(stimuli,
text = TRUE,
gravity = "north",
location = "+0+0",
degrees = 0,
size = 0.1,
font = "sans",
style = "normal",
weight = 400,
kerning = 0,
decoration = NULL,
color = "black",
strokecolor = NULL,
boxcolor = NULL) {
stimuli <- as_stimlist(stimuli)
if (isTRUE(text)) text <- names(stimuli)
tryCatch({
color <- sapply(color, color_conv)
}, error = function(e) {
stop("Invalid color: ", e$message, call. = FALSE)
})
if (!is.null(strokecolor)) {
tryCatch({
strokecolor <- sapply(strokecolor, color_conv)
}, error = function(e) {
stop("Invalid strokecolor: ", e$message, call. = FALSE)
})
}
if (!is.null(boxcolor)) {
tryCatch({
boxcolor <- sapply(boxcolor, color_conv)
}, error = function(e) {
stop("Invalid boxcolor: ", e$message, call. = FALSE)
})
}
# font size
if (!is.numeric(size)) {
stop("size must be a number")
} else if (any(size < 1.0)) {
# sizes are proportions of image width
size <- rep_len(size, length(stimuli)) * width(stimuli)
}
# allows for arguments to be vectors of any length
ith <- function(v, i) {
v[[(i-1)%%length(v)+1]]
}
for (i in seq_along(stimuli)) {
tryCatch({
stimuli[[i]]$img <- magick::image_annotate(
stimuli[[i]]$img,
ith(text, i),
gravity = ith(gravity, i),
location = ith(location, i),
degrees = ith(degrees, i),
size = ith(size, i),
font = ith(font, i),
style = ith(style, i),
weight = ith(weight, i),
kerning = ith(kerning, i),
decoration = ith(decoration, i),
color = ith(color, i),
strokecolor = ith(strokecolor, i),
boxcolor = ith(boxcolor, i)
)
}, error = function(e) {
stop("Error in label(): ", e$message, call. = FALSE)
})
}
stimuli
}
#' Label with ggplot annotations
#'
#' Label image using [ggplot2::annotate]. All arguments are vectorised over the stimuli and values are recycled or truncated if there are fewer or more than stimuli.
#'
#' @param stimuli list of stimuli
#' @param label a vector of the label text(s) or TRUE to use stimlist names
#' @param x x-coordinate for label anchor (left is 0); values <= 1 are interpreted as proportions of width
#' @param y y-coordinate for label anchor (bottom is 0); values <= 1 are interpreted as proportions of height
#' @param geom the geom to use
#' @param ... further arguments to pass to [ggplot2::annotate()]
#'
#' @return stimlist with labelled images
#' @seealso [label()] for a labeller using syntax like [magick::image_annotate]
#' @export
#' @family viz
#'
#' @examples
#' stimuli <- demo_stim()
#'
#' # label with image names
#' # the default text size in ggplot is tiny
#' gglabel(stimuli)
#' \donttest{
#' # add a watermark
#' gglabel(stimuli,
#' label = "watermark",
#' x = 0.5,
#' y = 0.5,
#' geom = "text",
#' size = 30,
#' color = "black",
#' angle = -30,
#' alpha = 0.5)
#' }
gglabel <- function(stimuli, label = TRUE, x = 0.5, y = 0.95, geom = "text", ...) {
stimuli <- as_stimlist(stimuli)
if (isTRUE(label)) label <- names(stimuli)
dots <- list(...)
dots$geom = geom
dots$label = label
dots$x = x
dots$y = y
# fix arguments in units
if (!is.null(dots$label.padding)) {
dots$label.padding <- list(dots$label.padding)
}
if (!is.null(dots$label.r)) {
dots$label.r <- list(dots$label.r)
}
suppressWarnings({
l <- length(stimuli)
dots <- lapply(dots, rep, length.out = l)
})
# convert x and y to pixels
w <- width(stimuli)
h <- height(stimuli)
dots$x <- ifelse(dots$x <= 1, dots$x*w, dots$x)
dots$y <- ifelse(dots$y <= 1, dots$y*h, dots$y)
for (i in seq_along(stimuli)) {
args <- lapply(dots, `[[`, i)
info <- magick::image_info(stimuli[[i]]$img)
res <- gsub("x.*$", "", info$density)
res <- as.integer(res)
# TODO: only suppress warnings that start with "Ignoring unknown"
suppressWarnings({
gg <- magick::image_ggplot(stimuli[[i]]$img) +
do.call(ggplot2::annotate, args)
})
img <- magick::image_graph(width = w[i],
height = h[i],
bg = "white",
res = res,
clip = FALSE, # TODO: check if this makes a difference
antialias = TRUE)
print(gg)
grDevices::dev.off()
stimuli[[i]]$img <- img
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/label.R
|
#' List format to table format
#'
#' @param list a list of lists
#' @param rownames whether to return a table with no rownames (NULL), rownames from the list item names (NA), or as a new column (the column name as a string)
#'
#' @return a data table
#' @keywords internal
list_to_tbl <- function(list, rownames = NULL) {
tbl_format <- list |>
# handle list() and NULL
lapply(function(x) {
if (length(x) == 0) { list(._. = NA) } else { x }
}) |>
# handle list(x = NULL)
lapply(lapply, function(x) {
if (length(x) == 0) { NA } else { x }
}) |>
dplyr::bind_rows()
tbl_format$._. <- NULL
if (is.null(rownames)) {
rownames(tbl_format) <- NULL
} else if (is.na(rownames)) {
# no rownames on a tibble :(
tbl_format <- as.data.frame(tbl_format)
rownames(tbl_format) <- names(list)
} else if (is.character(rownames)) {
tbl_format[[rownames[1]]] <- names(list)
tbl_format <- dplyr::relocate(tbl_format, !!rownames, .before = 1)
}
tbl_format
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/list_to_tbl.R
|
#' Loop
#'
#' Morph between each image in a list of stimuli, looping back to the start.
#'
#' @param stimuli list of stimuli to morph between
#' @param steps number of steps from one image to the next
#' @param ... arguments to pass to [trans()]
#'
#' @return list of stimuli containing each step of the loop
#' @export
#' @family webmorph
#'
#' @examples
#' \donttest{
#' if (webmorph_up()) {
#' # align and crop images
#' stimuli <- demo_unstandard(1:5) |>
#' align() |> crop_tem()
#'
#' loop <- loop(stimuli, 5)
#'
#' # create an animated gif
#' animate(loop, fps = 10)
#' }
#' }
loop <- function(stimuli, steps = 10, ...) {
stimuli <- require_tems(stimuli, TRUE)
if (length(stimuli) < 2) {
stop("You need at least 2 stimuli")
}
if (steps < 2) {
stop("You need at least 2 steps")
}
n_unique_names <- names(stimuli) |> unique() |> length()
if (n_unique_names < length(stimuli)) {
names(stimuli) <- paste0(seq_along(stimuli), "_", names(stimuli))
}
from_img <- stimuli
to_img <- c(stimuli[2:length(stimuli)], stimuli[1])
p <- seq(0, 1, length.out = steps+1)
p <- p[1:(length(p)-1)]
loop <- trans(from_img, from_img, to_img, p, p, p)
# get the right order
order <- paste0(names(from_img), "_", names(to_img)) |>
lapply(grepl, names(loop)) |>
lapply(which) |>
unlist()
loop[order]
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/loop.R
|
#' Mask Images with templates
#'
#' Use template points to define the borders of a mask to apply to the images. The image outside of the mask (or inside, if `reverse = TRUE`) is replaced by the fill color.
#'
#' @details
#' For FRL templates, the argument \code{mask} can be a vector with one or more of the following: oval, face, neck, ears (left_ear, right_ear), eyes (left_eye, right_eye), brows (left_brow, right_brow), mouth, teeth, nose.
#'
#' For Face++ templates (fpp83 or fpp106), the argument \code{mask} can be a vector with one or more of the following: face, eyes (left_eye, right_eye), brows (left_brow, right_brow), mouth, teeth, nose. Because these templates have no forehead points, "face" is usually disappointing.
#'
#' Set custom masks using the template points (0-based). View an image with labelled templates using \code{plot(stim, pt.plot = TRUE, pt.shape="index")}. Separate points along a line with commas, line segments with semicolons, and mask areas with colons. For example, this would be the custom mask for the eyes in the fpp83 template:
#'
#' \code{"44,4,56,51,79;79,58,11,25,44:61,67,38,34,40;40,41,17,47,61"}
#'
#' If you set expand = 0, there is sometimes a thin visible line where multiple components of the mask touch.
#'
#' @param stimuli list of stimuli
#' @param mask vector of masks or a custom list of template points
#' @param fill color to make the mask, see [color_conv()]
#' @param reverse logical; whether the mask covers the areas outside (FALSE) or inside (TRUE) the mask
#' @param expand how many pixels to expand the mask (negative numbers contract the mask)
#' @param tem_id template ID to pass on to [tem_def()] to get built-in mask definitions
#'
#' @return list of stimuli with masked images
#' @export
#' @family manipulators
#'
#' @examples
#' stimuli <- demo_stim()
#'
#' mask(stimuli,
#' mask = c("face", "neck", "ears"),
#' fill = "dodgerblue")
#'
#' mask(stimuli, "face", expand = 30)
#'
#' \donttest{
#' # reverse masking masks over the features
#' stimuli |>
#' mask("eyes", "#FFFF00", TRUE) |>
#' mask("brows", rgb(0.2, 0.5, 0.5), TRUE) |>
#' mask("mouth", "#FF000066", TRUE)
#'
#' # custom mask (list style)
#' fpp83_eyes <- list(
#' left_eye = list(
#' c(44,4,56,51,79),
#' c(79,58,11,25,44)
#' ),
#' right_eye = list(
#' c(61,67,38,34,40),
#' c(40,41,17,47,61)
#' )
#' )
#'
#' demo_tems("fpp83") |>
#' mask(fpp83_eyes, fill = color_conv("dodgerblue", alpha = 0.5))
#' }
#'
mask <- function(stimuli, mask = "face", fill = wm_opts("fill"),
reverse = FALSE, expand = 1, tem_id = "frl") {
stimuli <- require_tems(stimuli, TRUE)
# check masks
if (is.list(mask)) {
if (is.numeric(unlist(mask))) {
default_masks <- mask
names(default_masks) <- paste0("custom_", seq_along(default_masks))
mask <- names(default_masks)
} else {
default_masks <- mask
mask <- names(default_masks)
}
} else if (length(mask) == 1 && grepl("^([0-9]|,|;|:|\\s)+$", mask)) {
# parse mask
default_masks <- tryCatch({
strsplit(mask, "\\s*:\\s*")[[1]] |>
as.list() |>
lapply(strsplit, "\\s*;\\s*") |>
lapply(sapply, strsplit, "\\s*,\\s*") |>
lapply(sapply, as.integer, simplify = FALSE)
}, error = function(e) {
stop("There was a problem parsing the custom mask")
})
mask <- paste0("custom_", 1:length(default_masks))
names(default_masks) <- mask
} else if (is.character(mask)) {
tem <- tem_def(tem_id)
default_masks <- tem$masks
if ("eyes" %in% mask && !"eyes" %in% names(default_masks)) {
mask <- c(mask[which(mask != "eyes")], "left_eye", "right_eye")
}
if ("ears" %in% mask && !"ears" %in% names(default_masks)) {
mask <- c(mask[which(mask != "ears")], "left_ear", "right_ear")
}
if ("brows" %in% mask && !"brows" %in% names(default_masks)) {
mask <- c(mask[which(mask != "brows")], "left_brow", "right_brow")
}
missing_masks <- setdiff(mask, names(default_masks))
if (length(missing_masks) > 0) {
stop("The following masks were not found: ", paste(missing_masks, collapse = ", "))
}
} else {
stop("There was a problem with the mask.")
}
# allow for vectors of fill or expand
fill <- sapply(fill, color_conv)
suppressWarnings({
l <- length(stimuli)
fill <- rep_len(fill, l)
expand <- rep_len(expand, l)
})
w <- width(stimuli) |> round()
h <- height(stimuli) |> round()
for (i in seq_along(stimuli)) {
temPoints <- stimuli[[i]]$points
# construct sets of Bezier curves
curves <- default_masks[mask] |>
lapply(function(mm) {
mapply(function(m, idx) {
v <- temPoints[, m+1]
svgBezier(v, idx)
}, mm, seq_along(mm))
}) |>
lapply(function(d) {
sprintf("<path d = \"%s\" />",
paste(d, collapse = "\n"))
}) |>
paste(collapse = "\n\n")
# make SVG
if ((isTRUE(reverse) & fill[i] != "none") |
(!isTRUE(reverse) & fill[i] == "none")) {
strokecolor <- ifelse(expand[i] < 0, "black", "white")
svg_text <- "<svg
width=\"%d\" height=\"%d\"
xmlns=\"http://www.w3.org/2000/svg\">
<defs><mask id=\"image-mask\" fill=\"white\" stroke=\"%s\" stroke-width=\"%f\">
%s
</mask></defs>
<rect width=\"100%%\" height=\"100%%\" fill=\"%s\" mask=\"url(#image-mask)\"/>
</svg>"
} else {
strokecolor <- ifelse(expand[i] < 0, "white", "black")
svg_text <- "<svg
width=\"%d\" height=\"%d\"
xmlns=\"http://www.w3.org/2000/svg\">
<defs><mask id=\"image-mask\">
<rect fill=\"white\" width=\"100%%\" height=\"100%%\" fill-opacity=\"1\" />
<g stroke=\"%s\" stroke-width=\"%f\">
%s
</g>
</mask></defs>
<rect width=\"100%%\" height=\"100%%\" fill=\"%s\" mask=\"url(#image-mask)\"/>
</svg>"
}
if (fill[i] == "none") {
svg <- sprintf(svg_text, w[i], h[i], strokecolor,
abs(expand[i]), curves, "#000000ff")
maskimg <- magick::image_read_svg(svg)
stimuli[[i]]$img <- magick::image_composite(
image = stimuli[[i]]$img,
composite_image = maskimg,
operator = "CopyOpacity"
)
} else {
svg <- sprintf(svg_text, w[i], h[i], strokecolor,
abs(expand[i]), curves, fill[i])
maskimg <- magick::image_read_svg(svg)
stimuli[[i]]$img <- magick::image_composite(
image = stimuli[[i]]$img,
composite_image = maskimg,
operator = "Over") |>
magick::image_background("transparent")
}
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/mask.R
|
#' Apply an oval mask to images
#'
#' Superimpose an oval mask on a set of images.
#'
#' @details
#' If the images have templates and `bounds = NULL`, the maxiumum and minimum x and y coordinates for each image will be calculated (or the overall max and min if `each = FALSE`) and an oval with those dimensions and position will be placed over the face.
#'
#' If `bounds` are set to a list of top, right, bottom and left boundaries, these will be used instead of the boundaries derived from templates.
#'
#' @param stimuli list of stimuli
#' @param bounds bounds (t, r, b, l) of oval, calculated from templates if NULL
#' @param fill background color for mask, see [color_conv()]
#' @param each logical; whether to calculate a mask for each image (default) or just one
#'
#' @return list of stimuli with cropped tems and/or images
#' @export
#' @family manipulators
#'
#' @examples
#' # remove external template points and crop
#' stimuli <- demo_stim() |> subset_tem(features("face")) |> crop_tem(25)
#'
#' # three styles of mask
#' omask1 <- mask_oval(stimuli) |> label("default")
#' omask2 <- mask_oval(stimuli, each = FALSE) |> label("each = FALSE")
#' omask3 <- mask_oval(stimuli, bounds = list(t= 50, r = 30, b = 40, l = 30)) |>
#' label("manual bounds")
#'
#' # visualise masks
#' c(omask1, omask2, omask3) |> plot(nrow = 2, byrow = FALSE)
mask_oval <- function(stimuli, bounds = NULL, fill = wm_opts("fill"), each = TRUE) {
stimuli <- as_stimlist(stimuli)
w <- width(stimuli)
h <- height(stimuli)
# calculate oval coordinates
b <- list()
if (is.null(bounds)) {
stimuli <- require_tems(stimuli)
bounds <- bounds(stimuli, each)
b$top <- bounds$min_y
b$right <- w - bounds$max_x
b$bottom <- h - bounds$max_y
b$left <- bounds$min_x
} else {
bounds <- as.list(bounds)
}
borders <- list(
t = b$top %||% bounds$t %||% bounds[[1]],
r = b$right %||% bounds$r %||% bounds[[2]],
b = b$bottom %||% bounds$b %||% bounds[[3]],
l = b$left %||% bounds$l %||% bounds[[4]]
)
rx <- (w - borders$r - borders$l)/2
ry <- (h - borders$t - borders$b)/2
cx <- borders$l + rx
cy <- borders$t + ry
fill <- sapply(fill, color_conv)
suppressWarnings({
l <- length(stimuli)
fill <- rep_len(fill, l)
rx <- rep_len(rx, l)
ry <- rep_len(ry, l)
cx <- rep_len(cx, l)
cy <- rep_len(cy, l)
})
svg_text <- "<svg
width=\"%d\" height=\"%d\"
xmlns=\"http://www.w3.org/2000/svg\">
<defs><mask id=\"image-mask\">
<rect fill=\"white\" width=\"100%%\" height=\"100%%\" fill-opacity=\"1\" />
<ellipse cx='%.1f' cy='%.1f' rx='%.1f' ry='%.1f' />
</mask></defs>
<rect width=\"100%%\" height=\"100%%\" fill=\"%s\" mask=\"url(#image-mask)\"/>
</svg>"
for (i in seq_along(stimuli)) {
svg <- sprintf(svg_text, w[i], h[i],
cx[i], cy[i], rx[i], ry[i],
fill[i])
maskimg <- magick::image_read_svg(svg)
stimuli[[i]]$img <- magick::image_composite(stimuli[[i]]$img, maskimg)
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/mask_oval.R
|
#' Image shape metrics
#'
#' Get metrics defined by template points.
#'
#' Reference x and y coordinates by point number like `x[0]` or `y[188]`. Use any R functions to process the numbers, as well as `pow()` (same as `^()`, for consistency with webmorph.org). Remember that 0,0 is the top left for images; e.g., `min(y[0], y[1])` gives your the *higher* of the two pupil y-coordinates.
#'
#' @param stimuli list of stimuli with tems
#' @param formula a vector of two points to measure the distance apart, or a string of the formula for the metric
#'
#' @return named vector of the metric
#' @export
#' @family info
#'
#' @examples
#' stimuli <- demo_stim()
#'
#' metrics(stimuli, c(0, 1)) # eye-spacing
#'
#' # face width-to-height ratio
#' fwh <- "abs(max(x[113],x[112],x[114])-min(x[110],x[111],x[109]))/abs(y[90]-min(y[20],y[25]))"
#' metrics(stimuli, fwh)
#'
metrics <- function(stimuli, formula = c(0, 1)) {
stimuli <- require_tems(stimuli, TRUE)
if (all(is.numeric(formula)) && length(formula) == 2) {
# distance between two points
a <- formula[[1]]
b <- formula[[2]]
formula <- sprintf("sqrt(pow(x[%d]-x[%d], 2) + pow(y[%d]-y[%d],2))", a, b, a, b)
}
pow <- `^` # webmorph.org uses pow
rad2deg <- function(degrees) { degrees * (pi/180) }
lapply(stimuli, `[[`, "points") |>
sapply(function(pt) {
x <- pt["x", ]
y <- pt["y", ]
formula |>
(\(.) gsub("(x\\[\\d+)\\]", "\\1+1\\]", .))() |>
(\(.) gsub("(y\\[\\d+)\\]", "\\1+1\\]", .))() |>
(\(.) parse(text = .))() |>
eval()
})
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/metrics.R
|
#' Mirror templates and images
#'
#' Use tem_id to get the symmetry map for your template. If tem_id is omitted, images and templates will be fully reversed (e.g., if point 1 is the left eye in the original image, it will be the right eye in the mirrored image).
#'
#' @param stimuli list of stimuli
#' @param tem_id template ID to be passed to \code{tem_def} (usually "frl" or "fpp106") or NULL
#' @param axis vertical or horizontal axis of mirroring
#'
#' @return list of stimuli with mirrored images and templates
#' @export
#' @family manipulators
#'
#' @examples
#' # load an image and mirror it
#' o <- demo_tems("frl") |> resize(0.5)
#' m <- mirror(o, "frl")
#'
#' # visualise the face outline points
#' c(o, m) |>
#' subset_tem(features("face")) |>
#' draw_tem(pt.shape = "index", pt.size = 15) |>
#' label(c("original", "mirrored"))
#'
mirror <- function(stimuli, tem_id = NULL, axis = "vertical") {
stimuli <- as_stimlist(stimuli)
# get symmetry map
sym_map <- NULL
if (!is.null(tem_id)) {
tem <- tem_def(tem_id)
sym_map <- tem$points$sym
}
for (i in seq_along(stimuli)) {
cx <- (stimuli[[i]]$width-1)/2
cy <- (stimuli[[i]]$height-1)/2
p <- stimuli[[i]]$points
if (axis == "horizontal") {
stimuli[[i]]$img <- magick::image_flip(stimuli[[i]]$img)
# flip y points
if (!is.null(p)) {
stimuli[[i]]$points <- (p - c(0, cy)) * c(1, -1) +c(0, cy)
}
} else {
stimuli[[i]]$img <- magick::image_flop(stimuli[[i]]$img)
# flop x points
if (!is.null(p)) {
stimuli[[i]]$points <- (p - c(cx, 0)) * c(-1, 1) + c(cx, 0)
}
}
# mirror template points
if (!is.null(p) && axis == "vertical" && !is.null(sym_map)) {
n_pt <- ncol(p) - 1 # sym_map is 0-based
if (all(sym_map %in% 0:n_pt)) {
stimuli[[i]]$points <- stimuli[[i]]$points[, sym_map+1]
}
}
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/mirror.R
|
#' Patch colour
#'
#' Get the median (or mean or user-defined function) colour value of a specified patch of pixels on an image. This is useful for matching background colours.
#'
#' @details The colour values of each pixel in the patch are converted to CIE-Lab values before using the func to calculate the central tendency of the L (lightness), a (red-green axis) and b (blue-yellow axis); see [col2lab()] and [lab2rgb()] for more details.
#'
#' This excludes transparent pixels, and returns "transparent" if all pixels in the patch are transparent.
#'
#' @param stimuli list of stimuli
#' @param width,height dimensions of the patch in pixels, if <=1, interpreted as proportions of width or height
#' @param x_off,y_off offset in pixels or proportion (<1)
#' @param color The type of color to return (hex, rgb)
#' @param func The function to apply to an array of L*ab color values to determine the central colour (defaults to median, but mean, min, or max can also be useful)
#'
#' @return a vector of hex or rgba color values
#' @export
#'
#' @examples
#' stimuli <- demo_stim()
#'
#' # get colour from the upper left corder
#' patch(stimuli)
#'
#' # get median colour from centre .1 width pixels
#' patch(stimuli, width = .1, height = .1,
#' x_off = .45, y_off = .45)
#'
#' # get mean rgb colour from full image
#' patch(stimuli, width = 1, height = 1,
#' color = "rgb", func = mean)
#'
patch <- function(stimuli, width = 10, height = 10, x_off = 0, y_off = 0,
color = c("hex", "rgb"), func = stats::median) {
stimuli <- as_stimlist(stimuli)
color <- match.arg(color)
l <- length(stimuli)
w <- rep_len(width, l)
h <- rep_len(height, l)
x <- rep_len(x_off, l)
y <- rep_len(y_off, l)
# handle proportions
w <- ifelse(w <= 1, w * width(stimuli), w) |> round()
h <- ifelse(h <= 1, h * width(stimuli), h) |> round()
x <- ifelse(x < 1, x * height(stimuli), x) |> round()
y <- ifelse(y < 1, y * height(stimuli), y) |> round()
patches <- lapply(seq_along(stimuli), function(i) {
# crop image and get pixels
ga <- magick::geometry_area(w[i], h[i], x[i], y[i])
cropped <- magick::image_crop(stimuli[[i]]$img, ga, repage = TRUE)
pixels <- magick::image_raster(cropped)
# remove transparent pixels
pixels <- pixels[pixels$col != "transparent", ]
if (nrow(pixels) == 0) {
return("transparent")
}
# convert to Lab and get func
# prevent calling col2lab more than necessary
unique_col <- dplyr::count(pixels, col)
lab <- sapply(unique_col$col, col2lab)
mult <- apply(lab, 1, rep, times = unique_col$n,
simplify = FALSE)
avg_lab <- sapply(mult, func)
central_col <- lab2rgb(avg_lab)
central_col[['alpha']] <- paste0('0x', substr(pixels$col, 8, 9))|> strtoi() |> func()
if (color == "rgb") {
central_col
} else {
# get hex value
grDevices::rgb(
central_col[['red']],
central_col[['green']],
central_col[['blue']],
central_col[['alpha']],
maxColorValue = 255
)
}
})
names(patches) <- names(stimuli)
if (color == "hex") { patches <- unlist(patches) }
patches
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/patch.R
|
#' Plot stimuli
#'
#' @param x list of class stimlist
#' @param y omitted
#' @param ... Arguments to be passed to [plot_stim()]
#'
#' @return stimlist
#' @export
#' @family viz
#' @keywords internal
plot.stimlist <- function(x, y, ...) {
plot_stim(x, ...)
}
#' Plot stim
#'
#' @param x stim
#' @param y omitted
#' @param ... Arguments to be passed to [plot_stim()]
#'
#' @return stimlist
#' @export
#' @family viz
#' @keywords internal
plot.stim <- function(x, y, ...) {
stimlist <- as_stimlist(x)
plot(stimlist, ...)
}
#' Plot stimuli
#'
#' Show all the stimuli in a grid. You can use [plot()] as an alias.
#'
#' @param stimuli list of class stimlist
#' @param nrow number of rows
#' @param ncol number of columns
#' @param byrow fill grid by rows (first ncol images in the first row); if FALSE, fills by columns (first nrow images in the first column)
#' @param padding around each image in pixels
#' @param external_pad whether to include external padding
#' @param fill background color, see [color_conv()]
#' @param maxwidth,maxheight maximum width and height of grid in pixels
#'
#' @return stimlist with the plot image (no templates)
#' @export
#' @family viz
#'
#' @examples
#' stimuli <- demo_stim() |> resize(0.5)
#' plot_stim(stimuli)
#'
#' \donttest{
#' # default padding is 10px internal and external
#' plot(stimuli, fill = "dodgerblue")
#' plot(stimuli, external_pad = 0, fill = "dodgerblue")
#' plot(stimuli, padding = 0, fill = "dodgerblue")
#'
#' # make 8 numbered images
#' n <- blank(8, color = grDevices::cm.colors(8)) |>
#' label(1:8, gravity = "center", size = 50)
#'
#' # 2 rows, allocating by row
#' plot(n, nrow = 2)
#'
#' # 2 rows, allocating by column
#' plot(n, nrow = 2, byrow = FALSE)
#' }
plot_stim <- function(stimuli, nrow = NULL, ncol = NULL, byrow = TRUE,
padding = 10, external_pad = TRUE,
fill = wm_opts("fill"),
maxwidth = wm_opts("plot.maxwidth"),
maxheight = wm_opts("plot.maxheight")) {
stimuli <- as_stimlist(stimuli)
w <- width(stimuli)
h <- height(stimuli)
n <- length(stimuli)
fill <- color_conv(fill)
# calculate/validate nrow and ncol ----
if (is.null(nrow) && is.null(ncol)) {
if (n < 6) {
nrow <- 1
ncol <- n
} else {
nrow <- floor(sqrt(n))
ncol <- ceiling(n / nrow)
}
} else if (is.null(nrow)) {
nrow <- ceiling(n / ncol)
ncol <- ceiling(n / nrow) # reset in case nrow > n
} else {
# row takes precedence even if ncol is set
ncol <- ceiling(n / nrow)
nrow <- ceiling(n / ncol) # reset in case ncol > n
}
# shrink images to fit maxwidth and maxheight ----
npad <- ifelse(isTRUE(external_pad), 1, -1)
w_resize <- (maxwidth-padding*(ncol+npad)) / (ncol * max(w))
h_resize <- (maxheight-padding*(nrow+npad)) / (nrow * max(h))
if (w_resize < 1 || h_resize < 1) {
stimuli <- resize(stimuli, min(w_resize, h_resize))
}
stimuli <- pad(stimuli, padding/2, fill = fill)
# get vector of images in magick format
img <- get_imgs(stimuli)
# make rows ----
row_imgs <- list()
# make matrix of image layout
img_i <- matrix(1:(nrow*ncol), nrow = nrow, byrow = byrow)
for (r in 1:nrow) {
idx <- img_i[r, ] # get row indices
idx <- idx[idx <= length(img)] # for short rows
append_img <- magick::image_append(img[idx])
row_imgs[[r]] <- magick::image_flatten(append_img)
}
# make columns ----
for (i in seq_along(row_imgs)) {
if (i == 1) {
rows <- row_imgs[[i]]
} else {
rows <- c(rows, row_imgs[[i]])
}
}
# add or remove external padding ----
epad <- ifelse(isTRUE(external_pad), padding/2, -padding/2)
plot_img <- magick::image_append(rows, stack = TRUE)
plot_stim <- new_stim(plot_img, "plot")
padded_plot <- pad(plot_stim, epad, fill = fill)
padded_plot
}
#' Plot in rows
#'
#' @param ... stimlists (optionally named) and any arguments to pass on to \code{\link{label}}
#' @param top_label logical; whether to plot row labels above the row (TRUE) or inside (FALSE), if NULL, then TRUE if stimlists are named
#' @param maxwidth,maxheight maximum width and height of each row in pixels
#'
#' @return stimlist with plot
#' @export
#' @family viz
#'
#' @examples
#' s <- demo_unstandard()
#' plot_rows(
#' female = s[1:3],
#' male = s[6:8],
#' maxwidth = 600
#' )
plot_rows <- function(..., top_label = NULL,
maxwidth = wm_opts("plot.maxwidth"),
maxheight = wm_opts("plot.maxheight")) {
dots <- list(...)
is_stimlist <- sapply(dots, inherits, "stimlist")
rowlist <- dots[is_stimlist]
if (is.null(top_label)) {
top_label <- !is.null(names(rowlist))
}
rows <- lapply(rowlist, plot_stim,
nrow = 1,
external_pad = 0,
maxwidth = maxwidth,
maxheight = maxheight)|>
do.call(what = c)
rows <- resize(rows, width = min(width(rows)))
# add top padding
size <- dots$size %||% (sum(height(rows)) / 25)
if (isTRUE(top_label)) {
rows <- pad(rows, (size + 20), 0, 0, 0)
}
# label images
if (!is.null(names(rowlist))) {
label_args <- list(
stimuli = rows,
text = names(rowlist),
size = size,
gravity = "northwest",
location = ifelse(top_label, "+0+10", "+10+10")
)
label_args <- utils::modifyList(label_args, dots[!is_stimlist])
rows <- do.call(label, label_args)
}
plot_stim(rows, ncol = 1,
maxwidth = Inf,
maxheight = Inf)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/plot.R
|
#' Read stimuli
#'
#' Read images and templates from a directory.
#'
#' @param path Path to directory containing image and/or template files (or a single file path)
#' @param pattern Vector of patterns to use to search for files, or a vector of image indices (e.g., 1:4 selects the first 4 images and their templates if they exist)
#' @param breaks a vector of characters used to determine the stimulus names from the file names
#'
#' @return a list of stimuli
#' @export
#' @family stim
#'
#' @examples
#' path <- system.file("extdata/test", package = "webmorphR")
#'
#' # read in all images and templates in a directory
#' stimuli <- read_stim(path)
#'
#' # read in just images and templates with "m_"
#' m_stimuli <- read_stim(path, "m_")
#'
read_stim <- function (path, pattern = NULL, breaks = "/") {
imgext <- "\\.(jpg|jpeg|gif|png|bmp)$"
# get paths to temfiles ----
if (dir.exists(path) |> all()) {
if (is.numeric(pattern)) {
# get images by index and matching tems
imgpaths <- list.files(path, imgext, full.names = TRUE, ignore.case = TRUE)[pattern]
tempaths <- sub(imgext, "\\.tem", imgpaths)
tem_exists <- file.exists(tempaths)
files <- c(imgpaths, tempaths[tem_exists])
} else if (is.null(pattern)) {
files <- list.files(path, full.names = TRUE)
} else {
files <- lapply(pattern, list.files, path = path, full.names = TRUE) |> unlist()
}
} else if (sapply(path, file.exists) |> all()) {
files <- path
} else {
stop(path, " is neither a directory nor a file")
}
# load images ----
i <- grepl(imgext, files, ignore.case = TRUE)
imgfiles <- files[i]
imglist <- lapply(imgfiles, read_img)
# load tems ----
t <- grepl("\\.tem$", files, ignore.case = TRUE)
temfiles <- files[t]
temlist <- lapply(temfiles, read_tem)
# join image and tem lists ----
df_img <- data.frame(
img_i = seq_along(imgfiles),
path = tools::file_path_sans_ext(imgfiles)
)
df_tem <- data.frame(
tem_i = seq_along(temfiles),
path = tools::file_path_sans_ext(temfiles)
)
df_full <- dplyr::full_join(df_img, df_tem, by = "path")
stimuli <- mapply(function(img_i, tem_i) {
x <- c(imglist[[img_i]], temlist[[tem_i]])
class(x) <- c("stim", "list")
x
}, df_full$img_i, df_full$tem_i, SIMPLIFY = FALSE)
# assign unique names ----
names(stimuli) <- unique_names(df_full$path, breaks)
class(stimuli) <- c("stimlist", "list")
stimuli
}
#' Read image file
#'
#' @param imgfile
#'
#' @return list of image info
#' @export
#' @keywords internal
#' @family stim
#'
#' @examples
#' path <- system.file("extdata/test/f_multi.jpg",
#' package = "webmorphR")
#' img <- read_img(path)
read_img <- function(path) {
img <- list(
img = magick::image_read(path),
imgpath = path
)
# read attributes
attr <- magick::image_attributes(img$img)
wm_desc <- attr$value[attr$property == "exif:ImageDescription"]
if (length(wm_desc) > 0) {
img$desc <- tryCatch({
jsonlite::fromJSON(
wm_desc,
simplifyDataFrame = FALSE,
simplifyVector = TRUE)
}, error = function(e) { wm_desc })
}
# TODO: read embedded tem?
img$img <- magick::image_strip(img$img)
img_info <- magick::image_info(img$img)
img$width <- img_info$width
img$height <- img_info$height
img
}
#' Read tem file
#'
#' @param path path to template file
#'
#' @return list of template info
#' @export
#' @keywords internal
#' @family stim
#'
#' @examples
#' path <- system.file("extdata/test/f_multi.tem",
#' package = "webmorphR")
#' tem <- read_tem(path)
read_tem <- function(path) {
# read and clean ----
tem_txt <- readLines(path, skipNul = TRUE) |> trimws()
tem_txt <- tem_txt[tem_txt != ""] # get rid of blank lines
tem_txt <- tem_txt[substr(tem_txt, 1, 1) != "#"] # get rid of comments
# process points ----
npoints <- as.integer(tem_txt[[1]])
points <- tem_txt[2:(npoints+1)] |>
strsplit("\\s+") |>
sapply(as.numeric)
dimnames(points) <- list(c("x", "y"), NULL)
# process lines ----
nlines <- as.integer(tem_txt[[npoints+2]])
if (nlines > 0) {
x <- (npoints+3):(npoints+2+(nlines*3))
line_rows <- tem_txt[x] |>
matrix(nrow = 3)
lines <- line_rows[3, ] |>
strsplit("\\s+") |>
sapply(as.integer, simplify = FALSE)
# TODO: apply webmorph rules for open/closed lines
closed <- line_rows[1, ] |>
as.integer() |>
as.logical()
} else {
lines <- c()
closed <- c()
}
# create tem object ----
list(
tempath = path,
points = points,
lines = lines,
closed = closed
)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/read_stim.R
|
#' Check readline input
#'
#' @param prompt the prompt for readline
#' @param type what type of check to perform, one of c("numeric", "integer", "length", "grep")
#' @param min the minimum value
#' @param max the maximum value
#' @param warning an optional custom warning message
#' @param default the default option to return if the entry is blank, NULL allows no default, the default value will be displayed after the text in square brackets
#' @param ... other arguments to pass to grep
#'
#' @return the validated result of readline
#' @keywords internal
readline_check <- function(prompt, type = c("numeric", "integer", "length", "grep"),
min = -Inf, max = Inf, warning = NULL, default = NULL, ...) {
# get connection from options (hack to allow for unit testing)
con <- getOption("webmorph.connection", stdin())
if (!is.null(default)) prompt <- sprintf("%s [%s]", prompt, default)
cat(paste0(prompt, "\n"))
input <- readLines(con = con, n = 1)
if (!is.null(default) & input == "") {
return(default)
}
type <- match.arg(type)
if (type == "numeric") {
if (min != -Inf | max != Inf) {
warn_text <- paste0("The input must be a number between ", min, " and ", max, ":")
} else {
warn_text <- "The input must be a number:"
}
input <- suppressWarnings(as.numeric(input))
check <- !is.na(input)
check <- check & (input >= min) & (input <= max)
} else if (type == "integer") {
if (min != -Inf | max != Inf) {
warn_text <- paste0("The input must be an integer between ", min, " and ", max, ":")
} else {
warn_text <- "The input must be an integer:"
}
check <- grep("^\\d+$", input) |> length() > 0
input <- suppressWarnings(as.integer(input))
check <- check & (input >= min) & (input <= max)
} else if (type == "length") {
min <- max(min, 0) # min can't be smaller than 0 for text
warn_text <- paste0("The input must be between ", min, " and " , max, " characters long:")
check <- (nchar(input) >= min) & (nchar(input) <= max)
} else if (type == "grep") {
warn_text <- "The input is incorrect:"
check <- grep(x = input, ...) |> length() > 0
} else {
warn_text <- "The input is incorrect:"
check <- FALSE # default false if type is wrong?
}
# custom warning text
if (!is.null(warning)) {
warn_text = warning
}
# add red Error start
warn_text <- paste0("\033[31mError:\033[39m ", warn_text)
if (!check) {
Recall(warn_text, type, min, max, warning, ...)
} else {
input
}
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/readline_check.R
|
#' Set stimulus names in a stimlist
#'
#' @param stimuli A list of stimuli
#' @param new_names Vector of new names - must be the same length as the stimlist
#' @param prefix String to prefix to each name
#' @param suffix String to append to each name
#' @param pattern Pattern for gsub
#' @param replacement Replacement for gsub
#' @param ... Additional arguments to pass on to `base::gsub()`
#'
#' @return A list of stimuli with the new names
#' @export
#' @family info
#'
#' @examples
#' demo_stim() |>
#' rename_stim(prefix = "new_") |>
#' names()
rename_stim <- function(stimuli, new_names = NULL, prefix = "", suffix = "",
pattern = NULL, replacement = NULL, ...) {
stimuli <- as_stimlist(stimuli)
if (is.null(new_names)) {
new_names <- names(stimuli)
} else if (length(new_names) != length(stimuli)) {
stop("The length of new_names must be equal to the length of stimuli")
}
# search and replace strings
if (!is.null(pattern) && !is.null(replacement)) {
new_names <- gsub(pattern, replacement,
new_names, ...)
}
# add prefix and/or suffix
new_names <- paste0(prefix, new_names, suffix)
names(stimuli) <- new_names
for (i in seq_along(stimuli)) {
stimuli[[i]]$name <- new_names[i]
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/rename_stim.R
|
#' Resize stimuli
#'
#' Resize images and templates to the specified width and height.
#'
#' @param stimuli list of stimuli
#' @param width,height new dimensions (in pixels or percent if < 10)
#'
#' @return list of stimuli with resized tems and/or images
#' @export
#' @family manipulators
#'
#' @examples
#' stimuli <- demo_stim()
#'
#' # set width to proportion, height proportional
#' resize(stimuli, .5) |> draw_tem()
#'
#' # set width and height separately by pixels
#' resize(stimuli, 400, 250) |> draw_tem()
#'
resize <- function(stimuli, width = NULL, height = NULL) {
stimuli <- as_stimlist(stimuli)
if (is.null(width)) width <- 0
if (is.null(height)) height <- 0
if (all(width == 0) && all(height == 0)) {
return(stimuli)
} else if (any(width < 0)) {
stop("width must be a positive number")
} else if (any(height < 0)) {
stop("height must be a positive number")
}
n <- length(stimuli)
width <- rep_len(width, n)
height <- rep_len(height, n)
for (i in seq_along(stimuli)) {
# express height and/or width as % and fill empty value
if (width[i] == 0) {
# check height first
} else if (width[i] <= 10) { # percentage
w <- width[i]
} else if (!is.null(width[i])) { # pixels
w <- width[i]/stimuli[[i]]$width
}
if (height[i] == 0) {
h <- w
} else if (height[i] <= 10) { # percentage
h <- height[i]
} else { # pixels
h <- height[i]/stimuli[[i]]$height
}
if (width[i] == 0) w <- h
# resize template
if (!is.null(stimuli[[i]]$points)) {
stimuli[[i]]$points <- stimuli[[i]]$points * c(w, h)
}
# calculate new dimensions
stimuli[[i]]$width <- round(stimuli[[i]]$width*w)
stimuli[[i]]$height <- round(stimuli[[i]]$height*h)
if ("magick-image" %in% class(stimuli[[i]]$img)) {
# resize image
stimuli[[i]]$img <- magick::image_resize(
stimuli[[i]]$img,
#magick::geometry_size_percent(w*100, h*100)
magick::geometry_size_pixels(stimuli[[i]]$width,
stimuli[[i]]$height,
preserve_aspect = FALSE)
)
# make sure dimensions are consistent with image
info <- magick::image_info(stimuli[[i]]$img)
stimuli[[i]]$width <- info$width
stimuli[[i]]$height <- info$height
}
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/resize.R
|
#' Rotate templates and images
#'
#' @param stimuli list of stimuli
#' @param degrees degrees to rotate
#' @param fill background color, see [color_conv()]
#' @param keep_size whether to keep the original size or expand images to the new rotated size
#' @param origin The origin of the rotation. Options are:
#' `"image"` will rotate around the image center.
#'
#' `"tem"` will rotate around the average of all template coordinates.
#'
#' A vector of 1 or more point indices (0-based) will rotate around their average position.
#'
#' @return list of stimuli with rotated tems and/or images
#'
#' @export
#' @family manipulators
#'
#' @examples
#' stimuli <- demo_stim() |> resize(0.5)
#'
#' rotate(stimuli, 45, fill = "dodgerblue")
#' rotate(stimuli, 45, fill = "dodgerblue", keep_size = FALSE)
#'
#' \donttest{
#' # if images are not in the centre of the image,
#' # try setting the origin to tem or specific point(s)
#' offset <- stimuli[1] |>
#' draw_tem() |>
#' pad(0, 250, 0, 0, fill = "dodgerblue")
#'
#' rotate(offset, 45, origin = "image", fill = "pink")
#' rotate(offset, 45, origin = "tem", fill = "pink")
#'
#' # rotate around point 0 (left eye)
#' offset |> crop_tem() |> rep(8) |>
#' rotate(seq(0, 325, 45), origin = 0, fill = "pink") |>
#' animate(fps = 5)
#' }
#'
rotate <- function(stimuli, degrees = 0,
fill = wm_opts("fill"),
keep_size = TRUE,
origin = "image") {
stimuli <- as_stimlist(stimuli)
orig_w <- width(stimuli)
orig_h <- height(stimuli)
degrees <- degrees |>
rep(length.out = length(stimuli)) |>
sapply(`%%`, 360)
radians <- degrees * (pi/180)
fill <- sapply(fill, color_conv)
suppressWarnings({
l <- length(stimuli)
fill <- rep_len(fill, l)
})
for (i in seq_along(stimuli)) {
w <- stimuli[[i]]$width
h <- stimuli[[i]]$height
# calculate xm1, ym1 ----
if ((keep_size && origin == "tem") ||
is.null(w) || is.null(h)) {
ct <- centroid(stimuli[[i]])
xm1 <- ct[1, 'x']
ym1 <- ct[1, 'y']
} else if (!keep_size || origin == "image") {
xm1 <- w/2
ym1 <- h/2
} else if (is.numeric(origin)) {
ct <- centroid(stimuli[[i]], points = origin)
xm1 <- ct[1, 'x']
ym1 <- ct[1, 'y']
}
# calculate rotsize ----
if (keep_size) {
rotsize <- list(width = w, height = h)
xm2 <- xm1
ym2 <- ym1
} else {
w <- w %||% (2*xm1)
h <- h %||% (2*ym1)
rotsize <- rotated_size(w, h, degrees[i]) |> lapply(ceiling)
xm2 <- rotsize$width/2
ym2 <- rotsize$height/2
}
# rotate image ----
if ("magick-image" %in% class(stimuli[[i]]$img)) {
# centre image on xm1, ym1
if ((xm1 != w/2 || ym1 != h/2) && keep_size) {
new_w <- ceiling(max(xm1, w-xm1) * 2)
new_h <- ceiling(max(ym1, h-ym1) * 2)
x_off <- ifelse(xm1 < w-xm1, w - new_w, 0) |> round()
y_off <- ifelse(ym1 < h-ym1, h - new_h, 0) |> round()
centred_img <- crop(stimuli[[i]],
new_w, new_h,
x_off, y_off,
fill = fill[i])
} else {
centred_img <- stimuli[i]
}
# rotate on center
rotimg <- centred_img[[1]]$img |>
magick::image_background(color = "none") |>
magick::image_rotate(degrees[i])
stimuli[[i]]$img <- magick::image_repage(rotimg)
# crop back to right size
# get center of new img to xm2,ym2 at rotsize
info <- magick::image_info(stimuli[[i]]$img)
stimuli[[i]]$width <- info$width
stimuli[[i]]$height <- info$height
if (!keep_size) {
x_off <- NULL
y_off <- NULL
} else {
rot_xm <- info$width/2
rot_ym <- info$height/2
x_off <- round(rot_xm - xm2)
y_off <- round(rot_ym - ym2)
}
uncropimg <- crop(stimuli[[i]],
rotsize$width,
rotsize$height,
x_off, y_off,
fill = fill[i])
stimuli[[i]]$img <- uncropimg[[1]]$img
stimuli[[i]]$width = rotsize$width
stimuli[[i]]$height = rotsize$height
}
# rotate points ----
if (!is.null(stimuli[[i]]$points)) {
pt <- stimuli[[i]]$points
offset <- pt - c(xm1, ym1)
crad <- cos(radians[i]) * offset
srad <- sin(radians[i]) * offset
xr <- crad[1,] - srad[2,] + xm2
yr <- srad[1,] + crad[2,] + ym2
stimuli[[i]]$points <- matrix(c(xr, yr), 2,
byrow = TRUE,
dimnames = dimnames(pt))
}
}
# if (keep_size) {
# stimuli <- crop(stimuli, orig_w, orig_h, fill = fill)
# }
stimuli
}
#' Image size after rotation
#'
#' @param width Width of the original image
#' @param height Height of the original image
#' @param degrees Rotation in degreed
#'
#' @return list of rotated width and height
#' @keywords internal
rotated_size <- function(width, height, degrees) {
degrees <- degrees %% 180
if (degrees < 0) {
degrees <- 180 + degrees
}
if (degrees >= 90) {
tmpw <- width
width <- height
height <- tmpw
degrees <- degrees - 90
}
radians <- degrees * pi / 180;
w <- (width * cos(radians)) + (height * sin(radians))
h <- (width * sin(radians)) + (height * cos(radians))
list(
width = w,
height = h
)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/rotate.R
|
#' Social Media Image Sizes
#'
#' A convenience function for getting recommended dimensions for images on social media sites.
#'
#' Twitter:
#'
#' link: Image from a Tweet with shared link
#' one: Tweet sharing a single image (default)
#' two: Tweet sharing two images
#' three_left: Tweet sharing three images, Left image
#' three_tight Tweet sharing three images, Right images
#' four: Tweet sharing four images
#'
#' Instagram:
#'
#' feed_large: (default)
#' feed_small:
#' stories_large:
#' stories_small:
#'
#' @param platform currently only "twitter"
#' @param type which type of image
#'
#' @return named vector of width and height in pixels
#' @export
#'
#' @examples
#' social_media_size("twitter", "link")
#' social_media_size("twitter", "one")
#' social_media_size("twitter", "two")
#'
social_media_size <- function(platform = c("twitter", "instagram"),
type = "default") {
# https://sproutsocial.com/insights/social-media-image-sizes-guide/
if (match.arg(platform) == "twitter") {
size <- switch(type,
# Image from a Tweet with shared link:
link = c(1200, 628),
# Tweet sharing a single image:
one = c(1200, 675),
# Tweet sharing two images:
two = c(700, 800),
# Tweet sharing three images:
# Left image:
three_left = c(700, 800),
# Right images:
three_right = c(1200, 686),
# Tweet sharing four images:
four = c(1200, 600),
c(1200, 675)
)
} else if (match.arg(platform) == "instagram") {
size <- switch(type,
feed_large = c(1080, 1080),
feed_small = c(612, 612),
stories_large = c(1080, 1920),
stories_small = c(600, 1067),
c(1080, 1080)
)
}
names(size) <- c("width", "height")
size
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/social_media_size.R
|
#' Squash Template Points
#'
#' Move template points that are outside the image boundaries (e.g., negative values or larger than image width or height) to the borders of the image.
#'
#' @param stimuli list of stimuli
#'
#' @return list of stimuli
#' @export
#' @family tem
#'
#' @examples
#' nosquash <- demo_stim(1) |>
#' crop(0.4, 0.5)
#'
#' squash <- demo_stim(1) |>
#' crop(0.4, 0.5) |>
#' squash_tem()
#'
#' # add padding and visualise templates
#' c(nosquash, squash) |>
#' pad(50) |>
#' draw_tem(pt.size = 5)
squash_tem <- function(stimuli) {
stimuli <- as_stimlist(stimuli)
for (i in seq_along(stimuli)) {
if (!is.null(stimuli[[i]]$points)) {
w <- stimuli[[i]]$width
h <- stimuli[[i]]$height
stimuli[[i]]$points <- apply(stimuli[[i]]$points, 2, function(pt) {
# move points into image boundaries
pt |>
pmax(c(0, 0)) |>
pmin(c(w-1, h-1)) # subtract 1 for 0-vs 1-based origin
})
}
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/squash_tem.R
|
#' Make a new stimlist
#'
#' @param ... Lists with class "stim"
#' @param .names Names for each stimulus
#'
#' @return A stimlist
#' @export
#' @keywords internal
#' @family stim
new_stimlist <- function(..., .names = NULL) {
stimuli <- list(...)
check_stim <- lapply(stimuli, class) |>
sapply(`%in%`, x = "stim") |> all()
if (!check_stim) {
stop("All arguments need to have the class 'stim'", call. = FALSE)
} else {
class(stimuli) <- c("stimlist", "list")
}
if (!is.null(.names)) names(stimuli) <- .names
stimuli
}
#' Make a new stim
#'
#' @param img Image made by magick
#' @param path Path to image file (or name)
#' @param ... Additional items for stim
#'
#' @return list with class stim
#' @export
#' @keywords internal
#' @family stim
new_stim <- function(img, path = "", ...) {
info <- magick::image_info(img)
stim_i <- list(
img = img,
imgpath = path,
width = info$width,
height = info$height
)
stim <- c(stim_i, list(...))
class(stim) <- c("stim", "list")
stim
}
#' Convert list to stimlist
#'
#' Checks if an object is a stimulus or list of stimuli and repairs common problems.
#'
#' @details
#' Some webmorphR functions, like [plot()] and [print()] require objects to have a "stimlist" class. If you've processed a list of stimuli with iterator functions like [lapply()] or [purrr::map()] and the resulting object prints or plots oddly, it is probably unclassed, and this function will fix that.
#'
#' @param x The object
#'
#' @return A stimlist
#' @export
#' @family stim
#'
#' @examples
#' stimuli <- demo_stim() |>
#' lapply(function(stim) {
#' # remove template lines
#' stim$lines <- NULL
#' return(stim)
#' })
#'
#' class(stimuli)
#'
#' \dontrun{
#' plot(stimuli) # error
#' }
#'
#' s <- as_stimlist(stimuli)
#' class(s)
#' plot(s)
#'
as_stimlist <- function(x) {
# handle list without stim or stimlist classes
if (is.list(x) &&
!"stimlist" %in% class(x) &&
!"stim" %in% class(x)) {
# does x or the items in x have names consistent with a stim?
is_stim <- c("points", "lines") %in% names(x) |> all() ||
c("img", "width", "height") %in% names(x) |> all()
is_stimlist <- sapply(x, function(xi) {
c("points", "lines") %in% names(xi) |> all() ||
c("img", "width", "height") %in% names(xi) |> all()
}) |> all()
if (is_stimlist) {
class(x) <- c("stimlist", "list")
} else if (is_stim) {
class(x) <- c("stim", "list")
}
}
# convert stim to stimlist
if ("stim" %in% class(x)) {
# convert to stimlist
stimuli <- list(x)
class(stimuli) <- c("stimlist", "list")
} else if ("stimlist" %in% class(x)) {
stimuli <- x
} else {
arg <- match.call()$x
stop(arg, " needs to be a stimlist")
}
# add names
if (is.null(names(stimuli))) {
i <- sapply(stimuli, `[[`, "imgpath")
t <- sapply(stimuli, `[[`, "tempath")
nm <- mapply(function(i, t) { i %||% t }, i, t)
names(stimuli) <- unique_names(nm)
}
# check if images are available and reload if not
# TODO: add _magick_magick_image_dead via RCpp
# for (i in seq_along(stimuli)) {
# # TODO: decide if this should warn the user
# is_dead <- .Call('_magick_magick_image_dead', PACKAGE = 'magick', stimuli[[i]]$img)
# if (is_dead) stimuli[[i]]$img <- magick::image_read(stimuli[[i]]$imgpath)
# }
# check if stim have width and height and get from img or tem if not
w <- lapply(stimuli, `[[`, "width")
h <- lapply(stimuli, `[[`, "height")
has_dim <- !(sapply(w, is.null) | sapply(h, is.null))
if (any(!has_dim)) {
imgs <- lapply(stimuli, `[[`, "img")
has_img <- !sapply(imgs, is.null)
pts <- lapply(stimuli, `[[`, "points")
has_tem <- !sapply(pts, is.null)
for (i in which(!has_dim)) {
if (has_img[i]) {
info <- magick::image_info(imgs[[i]])
ww <- info$width
hh <- info$height
} else if (has_tem[i]) {
ww <- range(pts[[i]][1, ]) |> sum() |> ceiling()
hh <- range(pts[[i]][2, ]) |> sum() |> ceiling()
if (wm_opts("verbose")) {
sprintf("Stimulus dimensions guessed from template for %s (w = %d, h = %d)",
names(stimuli)[i], ww, hh) |>
warning(call. = FALSE)
}
}
stimuli[[i]]$width <- ww
stimuli[[i]]$height <- hh
}
}
stimuli
}
#' Require templates
#'
#' Checks a list of stimuli for templates and omits images without a template. If all_same = TRUE, checks that all the templates are the same type. Errors if no images have a template or not all templates are the same (when all_same == TRUE).
#'
#' @param stimuli list of stimuli
#' @param all_same logical; whether all images should have the same template
#'
#' @return list of stimuli with tems
#' @export
#' @family tem
#'
#' @examples
#' stimuli <- demo_stim()
#' have_tems <- require_tems(stimuli)
#'
#' \dontrun{
#' # produces an error because no tems
#' no_tems <- stimuli |> remove_tem()
#' require_tems(no_tems)
#'
#' # warns that some images were removed
#' mix_tems <- c(stimuli, no_tems)
#' have_tems <- require_tems(mix_tems)
#'
#' # produces an error because tems are different
#' demo_tems() |> require_tems(all_same = TRUE)
#' }
require_tems <- function(stimuli, all_same = FALSE) {
stimuli <- as_stimlist(stimuli)
no_tems <- lapply(stimuli, `[[`, "points") |> sapply(is.null)
if (all(no_tems)) {
stop("No images had templates", call. = FALSE)
} else if (any(no_tems)) {
if (wm_opts("verbose")) {
warning("Images without templates were removed: ",
paste(names(stimuli)[no_tems], collapse = ", "),
call. = FALSE)
}
stimuli <- stimuli[!no_tems]
}
if (all_same) {
if (!same_tems(stimuli)) {
stop("Not all of the images have the same template")
}
}
stimuli
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/stimlist.R
|
#' SVG Path Move
#'
#' @param x,y coordinates
#' @param digits number of digits to round to
#'
#' @return string with M path component
#' @keywords internal
svgMoveTo <- function(x, y, digits = 2) {
paste0("M %.", digits, "f %.", digits, "f") |>
sprintf(round(x, digits), round(y, digits))
}
#' SVG Path Line
#'
#' @param x,y coordinates
#' @param digits number of digits to round to
#'
#' @return string with L path component
#' @keywords internal
svgLineTo <- function(x, y, digits = 2) {
paste0("L %.", digits, "f %.", digits, "f") |>
sprintf(round(x, digits), round(y, digits))
}
#' SVG Path Quadratic Curve
#'
#' @param x1,y1 coordinates of control point
#' @param x,y coordinates of main point
#' @param digits number of digits to round to
#'
#' @return string with Q path component
#' @keywords internal
svgQuadraticTo <- function(x1, y1, x, y, digits = 2) {
paste0("Q %.", digits, "f %.", digits, "f, %.",
digits, "f %.", digits, "f") |>
sprintf(round(x1, digits), round(y1, digits),
round(x, digits), round(y, digits))
}
#' SVG Path Quadratic Curve
#'
#' @param x1,y1,x2,y2 coordinates of control points
#' @param x,y coordinates of main point
#' @param digits number of digits to round to
#'
#' @return string with Q path component
#' @keywords internal
svgCubicTo <- function(x1, y1, x2, y2, x, y, digits = 2) {
paste0("C %.", digits, "f %.", digits, "f, %.",
digits, "f %.", digits, "f, %.",
digits, "f %.", digits, "f") |>
sprintf(round(x1, digits), round(y1, digits),
round(x2, digits), round(y2, digits),
round(x , digits), round(y , digits))
}
#' Get Control Points
#'
#' @param x0,y0 coordinates of previous point
#' @param x1,y1 coordinates of main point
#' @param x2,y2 coordinates of next point
#' @param t curving factor (0-1)
#'
#' @return x- and y-coordinates of control points (x1, y1, x2, y2)
#' @keywords internal
svgControlPoints <- function(x0, y0, x1, y1, x2, y2, t = 0.3) {
d01 <- sqrt(`^`(x1-x0,2) + `^`(y1-y0,2))
d12 <- sqrt(`^`(x2-x1,2) + `^`(y2-y1,2))
fa <- t*d01/(d01+d12) # scaling factor for triangle Ta
fb <- t*d12/(d01+d12) # ditto for Tb, simplifies to fb=t-fa
p1x <- x1-fa*(x2-x0) # x2-x0 is the width of triangle T
p1y <- y1-fa*(y2-y0) # y2-y0 is the height of T
p2x <- x1+fb*(x2-x0)
p2y <- y1+fb*(y2-y0)
c(p1x, p1y, p2x, p2y)
}
#' Construct Bezier Curves from Template Points
#'
#' @param v matrix of template points with x and y as rows and point as columns
#' @param idx index of line segment within the path
#'
#' @return string with path component
#' @keywords internal
svgBezier <- function(v, idx = 1) {
path <- list()
if (ncol(v) == 2) {
# connect with straight line
if (idx == 1) path[length(path) + 1] = svgMoveTo(v[1, 1], v[2, 1])
path[length(path) + 1] = svgLineTo(v[1, 2], v[2, 2])
return(paste(path, collapse = "\n"))
}
# connect with bezier curve
pts <- as.vector(v)
cp <- c() # control points
n <- length(pts)
if (pts[1] == pts[n - 1] && pts[2] == pts[n]) {
# Draw a closed curve, connected at the ends
# remove duplicate points and adjust n
n <- n - 2
pts <- pts[1:n]
# Append and prepend knots and control points to close the curve
pts <- c(pts[(n-1):n], pts, pts[1:4])
for (j in seq(1, n, 2) ) {
newPts <- do.call(svgControlPoints, as.list(pts[j:(j+5)]))
cp <- c(cp, newPts)
}
cp <- c(cp, cp[1:2])
# omit moves in all but first segment in path
if (idx == 1) path[length(path) + 1] = svgMoveTo(pts[3], pts[4])
# cubic curves
for (j in seq(2, n+1, 2)) {
path[length(path) + 1] = svgCubicTo(
cp[2 * j - 1], cp[2 * j],
cp[2 * j + 1], cp[2 * j + 2],
pts[j + 3], pts[j + 4])
}
} else {
# Draw an open curve, not connected at the ends
for (j in seq(1, n-4, 2)) {
newPts <- do.call(svgControlPoints, as.list(pts[j:(j+5)]))
cp <- c(cp, newPts)
}
# omit moves in all but first segment in path
if (idx == 1) path[length(path) + 1] = svgMoveTo(pts[1], pts[2])
# first arc
path[length(path) + 1] = svgQuadraticTo(cp[1], cp[2], pts[3], pts[4])
# cubic curves
if (n > 6) {
for (j in seq(2, n-5, 2)) {
path[length(path) + 1] = svgCubicTo(
cp[2 * j - 1], cp[2 * j],
cp[2 * j + 1], cp[2 * j + 2],
pts[j + 3], pts[j + 4])
}
}
# last arc
path[length(path) + 1] = svgQuadraticTo(
cp[2 * n - 9], cp[2 * n - 8],
pts[n - 1], pts[n])
}
paste(path, collapse = "\n")
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/svg.R
|
#' Symmetrize Images
#'
#' Use webmorph.org to make faces symmetric in shape and/or colour.
#'
#' @param stimuli list of stimuli
#' @param shape,color amount of symmetry (0 for none, 1.0 for perfect)
#' @param tem_id template ID to be passed to [tem_def()] (usually "frl" or "fpp106")
#' @param ... Additional arguments to pass to [trans()]
#'
#' @return list of stimuli with symmetrised images and templates
#' @export
#' @family webmorph
#' @aliases symmetrise
#'
#' @examples
#' \donttest{
#' if (webmorph_up()) {
#' stimuli <- demo_stim(1)
#'
#' sym_both <- symmetrize(stimuli)
#' sym_shape <- symmetrize(stimuli, color = 0)
#' sym_color <- symmetrize(stimuli, shape = 0)
#' sym_anti <- symmetrize(stimuli, shape = -1.0, color = 0)
#' }
#' }
symmetrize <- function(stimuli, shape = 1.0, color = 1.0, tem_id = "frl", ...) {
stimuli <- require_tems(stimuli, TRUE)
mirror <- mirror(stimuli, tem_id) |>
rename_stim(prefix = "mirror_")
sym <- trans(trans_img = stimuli, from_img = stimuli, to_img = mirror,
shape = shape[[1]]/2, color = color[[1]]/2, texture = color[[1]]/2,
outname = names(stimuli), ...)
sym
}
#' @rdname symmetrize
#' @export
symmetrise <- symmetrize
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/symmetrise.R
|
#' Get template definition
#'
#' Template definitions are lists that contain information about templates that are needed to do things like symmetrising and masking images. This function is mostly used internally.
#'
#' @details
#' If you have defined a custom template on webmorph.org, you can get its function definition by ID. You can see the ID numbers next to the templates available to you under the *Template > Current Template* menu.
#'
#' @param tem_id the name of a built-in template (frl, fpp106, fpp83, dlib70, or dlib7) or a numeric ID of a template to retrieve from webmorph.org
#' @param path path of local tem definition file
#'
#' @return list with template definition
#' @export
#' @family tem
#'
#' @examples
#' fpp106 <- tem_def("fpp106")
#' fpp106$lines |> str()
#'
#' \donttest{
#' fpp83 <- tem_def("fpp83")
#' fpp83$mask |> str()
#'
#' frl <- tem_def("frl")
#' frl$points[1:10, ]
#' viz_tem_def(frl, pt.size = 10, line.size = 5)
#' }
tem_def <- function(tem_id = "frl", path = NULL) {
# read file or url ----
if (!is.null(path)) {
if (!file.exists(path)) {
stop(sprintf("The file at %s does not exist", path))
}
tem_def <- tryCatch({
jsonlite::read_json(path, simplifyVector = TRUE,
simplifyMatrix = FALSE)
}, error = function(e) {
stop("The file couldn't be read")
})
} else if (is.numeric(tem_id)) {
url <- sprintf("https://webmorph.org/scripts/temDownloadJSON?tem_id=%d",
tem_id)
tem_def <- tryCatch({
jsonlite::read_json(url, simplifyVector = TRUE,
simplifyMatrix = FALSE)
}, error = function(e) {
stop("You might not have an internet connection")
})
} else if (is.character(tem_id)) {
temdir <- system.file("extdata/tem_defs", package = "webmorphR")
temdefs <- list.files(temdir, "\\.json$", full.names = TRUE)
match <- grepl(tolower(tem_id),
tolower(temdefs),
fixed = TRUE)
if (all(match == FALSE)) {
stop(tem_id, " is not a built-in template")
}
tem_def <- jsonlite::read_json(temdefs[match][[1]],
simplifyVector = TRUE,
simplifyMatrix = FALSE)
} else {
stop("You must supply a numeric tem_id or a valid path to a template definition file.")
}
tem_def
}
#' Visualise a template definition
#'
#' @param tem_def the template definition; usually from [tem_def()]
#' @param ... further arguments to pass to [draw_tem()]; pt.size and line.size often need to be adjusted
#'
#' @return a stimlist with a blank image and the template drawn on it
#' @export
#' @family tem
#'
#' @examples
#' dlib70 <- tem_def("dlib70")
#' viz_tem_def(dlib70, pt.size = 5, line.size = 3)
viz_tem_def <- function(tem_def, ...) {
# make a blank image the size of the template
width <- tem_def$width %||% mean(tem_def$points$x) * 2
height <- tem_def$height %||% max(tem_def$points$y) + 20
x <- blank(1, width, height)
# add the default template points and line to the blank image
points <- tem_def$points[c("x", "y")] |>
as.matrix() |> t()
colnames(points) <- tem_def$points$name
x[[1]]$points <- points
x[[1]]$lines <- tem_def$lines
x[[1]]$closed <- tem_def$closed
draw_tem(x, ...)
}
#' Change template lines
#'
#' Alter, add or remove lines in a template
#'
#' @param stimuli list of stimuli
#' @param line_id index of the line to change
#' @param pts vector of points to change the line_idx to (deletes line if NULL)
#'
#' @return stimlist with altered templates
#' @export
#' @family tem
#'
#' @examples
#' # get image with dlib70 template and view lines
#' s <- demo_tems("dlib70")
#' s[[1]]$lines
#'
#' # remove all lines
#' s2 <- change_lines(s, line_id = 1:13, pts = NULL)
#' s2[[1]]$lines
#'
#' # visualise point indices
#' draw_tem(s2, pt.shape = "index", pt.size = 15)
#'
#' # add a new line
#' s3 <- change_lines(s2, line_id = "face_outline",
#' pts = c(2:18, 28:19, 2))
#' s3[[1]]$lines
#' draw_tem(s3)
change_lines <- function(stimuli, line_id = 1, pts = NULL) {
for (i in seq_along(stimuli)) {
oldlines <- stimuli[[i]]$lines
if (is.null(pts)) {
oldlines[line_id] <- NULL
} else {
oldlines[[line_id]] <- pts
}
stimuli[[i]]$lines <- oldlines
}
stimuli
}
#' Subset template points
#'
#' Keep or delete specified template points. Points will be renumbered and line definitions will be updated. If all points in a line are deleted, the line will be removed. POint indexing is 0-based, so the first two points (usually the pupils) are 0 and 1.
#'
#' @param stimuli list of stimuli
#' @param ... vectors of points to keep or delete
#' @param keep logical; whether to keep or delete the points
#'
#' @return stimlist with altered templates
#' @export
#' @family tem
#'
#' @examples
#' # keep just the first two points
#' demo_stim(1) |>
#' subset_tem(0:1) |>
#' draw_tem(pt.size = 10)
#'
#' # remove the last 10 points
#' # (produces the 179-point Perception Lab template)
#' demo_stim(1) |>
#' subset_tem(179:188, keep = FALSE) |>
#' draw_tem()
#'
#' # use features() to keep only points from a pre-defined set
#' # "gmm" is points used for geometric morphometrics
#' demo_stim(1) |>
#' subset_tem(features("gmm")) |>
#' draw_tem()
#'
subset_tem <- function(stimuli, ..., keep = TRUE) {
stimuli <- require_tems(stimuli, TRUE)
points <- list(...) |> unlist() |> unique() |> sort()
for (i in seq_along(stimuli)) {
oldpts <- stimuli[[i]]$points
oldlines <- stimuli[[i]]$lines
oldclosed <- stimuli[[i]]$closed
full_idx <- 1:dim(oldpts)[[2]]
# remove points, webmorph points are 0-indexed so +1
if (keep) {
keep_idx <- points + 1
} else {
keep_idx <- setdiff(full_idx, points+1)
}
# check for bad points
if (setdiff(keep_idx, full_idx) |> length() > 0) {
stop("Some points are not in the template")
}
newpoints <- oldpts[, keep_idx]
# translate
trans <- sapply(full_idx, function(x) {
ifelse(x %in% keep_idx, match(x, keep_idx), NA)
})
# remove points from lines and renumber
newlines <- lapply(oldlines, function(x) {
# translate tem idx to r idx
l <- trans[(x + 1)] |>
stats::na.omit() |>
as.vector()
if (length(l) > 1) {
# only return if >1 points remain
return(l - 1) # translate r idx to tem idx
}
})
removed_lines <- sapply(newlines, is.null)
newlines <- newlines[!removed_lines]
newclosed <- oldclosed[!removed_lines]
stimuli[[i]]$points <- newpoints
stimuli[[i]]$lines <- newlines
stimuli[[i]]$closed <- newclosed
}
stimuli
}
#' Feature Points
#'
#' Get point indices for features, usually for use with \code{\link{subset_tem}}.
#'
#' Available features for the frl template are: "gmm", "oval", "face", "mouth", "nose", "eyes", "brows", "left_eye", "right_eye", "left_brow", "right_brow", "ears", "undereyes", "teeth", "smile_lines", "cheekbones", "philtrum", "chin", "neck", "halo".
#'
#' Available features for the dlib70 template are: "teeth", "left_eye", "right_eye", "left_brow", "right_brow", "nose", "mouth", "face".
#'
#' @param ... a vector of feature names (see Details)
#' @param tem_id template ID (currently only works for frl and dlib70)
#'
#' @return vector of corresponding template indices
#' @export
#' @family tem
#'
#' @examples
#' features("mouth")
#' features("gmm")
#' features("nose", tem_id = "dlib70")
#'
features <- function(..., tem_id = c("frl", "dlib70")) {
# 0-based for compatibility with webmorph
tem_id <- match.arg(tem_id)
named_features <- list(...) |> unlist()
if (tem_id == "frl") {
features <- list(
# imprecise
undereyes = c(44:49),
ears = c(115:124),
halo = c(146:156),
teeth = c(99:103),
smile_lines = c(158:163),
cheekbones = c(164:169),
philtrum = c(170:173),
chin = c(174:178),
neck = c(183:184, 145, 157),
# features
left_eye = c(0, 2:9, 18:22, 28:30, 34:38),
right_eye = c(1, 10:17, 23:27, 31:33, 39:43),
left_brow = c(71:76, 83:84),
right_brow = c(77:82, 85:86),
nose = c(50:70, 170, 172, 179:182),
mouth = c(87:108),
face = c(109:114, 125:144, 185:188)
)
features$oval <- c(features$halo, features$neck)
} else if (tem_id == "dlib70") {
features <- list(
# imprecise
teeth = c(62:69),
# features
left_eye = c(0, 38:43),
right_eye = c(1, 44:49),
left_brow = c(19:23),
right_brow = c(24:28),
nose = c(29:37),
mouth = c(50:69),
face = c(2:18)
)
}
# combo features
features$eyes <- c(features$left_eye, features$right_eye)
features$brows <- c(features$left_brow, features$right_brow)
features$gmm <- c(features$face, features$eyes, features$brows,
features$nose, features$mouth)
features$all <- 0:max(unlist(features))
# unavailable and duplicate features are ignored
features[named_features] |>
unlist() |> unname() |>
unique() |> sort()
}
#' Remove templates
#'
#' @param stimuli list of stimuli
#'
#' @return list of stimuli
#' @export
#' @family tem
#'
#' @examples
#' demo_stim() |> remove_tem()
remove_tem <- function(stimuli) {
stimuli <- as_stimlist(stimuli)
for (i in seq_along(stimuli)) {
stimuli[[i]]$tempath <- NULL
stimuli[[i]]$points <- NULL
stimuli[[i]]$lines <- NULL
stimuli[[i]]$closed <- NULL
}
stimuli
}
#' Check All Templates are the Same
#'
#' @param stimuli list of stimuli
#'
#' @return logical
#' @export
#' @family tem
#'
#' @examples
#' stim <- demo_stim()
#' stim2 <- subset_tem(stim, features("gmm"))
#'
#' same_tems(stim)
#'
#' c(stim, stim2) |> same_tems()
same_tems <- function(stimuli) {
stimuli <- as_stimlist(stimuli)
pts <- lapply(stimuli, `[[`, "points") |>
sapply(ncol) |>
unique()
lines <- lapply(stimuli, `[[`, "lines") |>
unique()
if (length(pts) == 1 && length(lines) == 1) {
TRUE
} else {
FALSE
}
}
#' Get Point Coordinates
#'
#' Get a data frame of the x and y coordinates of a template point
#'
#' @param stimuli list of stimuli with templates
#' @param pt point(s) to return
#'
#' @return data frame of x and y coordinates of the specified point(s) for each stimulus
#' @export
#' @family tem
#' @family info
#'
#' @examples
#' demo_stim() |> get_point(0:1)
get_point <- function(stimuli, pt = 0) {
stimuli <- require_tems(stimuli)
all_pts <- tems_to_array(stimuli)
# this function reverses y-coordinates
data.frame(
image = rep(names(stimuli), each = length(pt)),
point = rep(pt, times = length(stimuli)),
x = all_pts[pt+1, "X", ] |> matrix(ncol = 1),
y = all_pts[pt+1, "Y", ] |> matrix(ncol = 1) * -1
)
}
#' Get center coordinates
#'
#' @param stimuli list of stimuli
#' @param points which points to include (0-based); if NULL, all points will be used
#'
#' @return named matrix of centroid x and y coordinates
#' @export
#' @family tem
#'
#' @examples
#' demo_stim() |> centroid()
#'
#' # get the centre of the eye points
#' demo_stim() |> centroid(0:1)
centroid <- function(stimuli, points = NULL) {
stimuli <- require_tems(stimuli)
pts <- lapply(stimuli, `[[`, "points")
if (!is.null(points)) {
pts <- lapply(pts, `[`, , points+1, drop = FALSE)
}
sapply(pts, apply, 1, mean) |> t()
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/tem.R
|
#' Resize and crop/pad images to a specified size
#'
#' @param stimuli list of stimuli
#' @param width the target width (if null, the maximum stimulus width is used)
#' @param height the target height (if null, the maximum stimulus height is used)
#' @param fill background color if cropping goes outside the original image, see [color_conv()]
#' @param crop whether to crop or pad images to make them the specified size
#' @param keep_rels whether to keep the size relationships between images in the set, or make all the maximum size
#'
#' @return list of stimuli with cropped tems and/or images
#' @export
#' @family manipulators
#'
#' @examples
#'
#' # images with different aspect ratios and sizes
#' stimuli <- demo_unstandard(c(1:4, 6:9))
#'
#' to_size(stimuli, 200, 200, fill = "dodgerblue")
#'
to_size <- function(stimuli, width = NULL, height = NULL,
fill = wm_opts("fill"),
crop = FALSE, keep_rels = FALSE) {
stimuli <- as_stimlist(stimuli)
# process width and height
# set to maximum width and height in set
if (is.null(width)) width <- width(stimuli, "max")
if (is.null(height)) height <- height(stimuli, "max")
if (!is.numeric(width) || !is.numeric(height)) {
stop("width and height must be numeric")
} else if (any(width < 1) || any(height < 1)) {
stop("width and height must be positive numbers")
}
w <- width(stimuli)
h <- height(stimuli)
if (keep_rels) {
# resize all the same %
if (isTRUE(crop)) {
w_pcnt <- width / min(w)
h_pcnt <- height / min(h)
pcnt <- max(c(w_pcnt, h_pcnt))
} else {
w_pcnt <- width / max(w)
h_pcnt <- height / max(h)
pcnt <- min(c(w_pcnt, h_pcnt))
}
} else {
# resize each to fit
w_pcnt <- width / w
h_pcnt <- height / h
if (isTRUE(crop)) {
pcnt <- mapply(max, w_pcnt, h_pcnt)
} else {
pcnt <- mapply(min, w_pcnt, h_pcnt)
}
}
resized <- resize(stimuli, pcnt)
crop(resized, width, height, fill = fill)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/to_size.R
|
#' Transform Images
#'
#' Transform a base image in shape, color, and/or texture by the differences between two images.
#'
#' @details
#'
#' ### Normalisation options
#'
#' * none: averages will have all coordinates as the mathematical average of the coordinates in the component templates
#' * twopoint: all images are first aligned to the 2 alignment points designated in `normpoint`. Their position is set to their position in the first image in stimuli
#' * rigid: procrustes aligns all images to the position of the first image in stimuli
#'
#' ### Sample contours
#'
#' This interpolates more control points along the lines. This can improve the accuracy of averages and transforms. If you see a “feathery” appearance along lines that have many, close-together points, try turning this off.
#'
#' ### Warp types
#'
#' * multiscale: Implements multi-scale affine interpolation for image warping. This is the default, with a good balance between speed and accuracy
#' * linear: Implements triangulated linear interpolation for image warping. Linear warping is least accurate, often resulting in image artifacts, but is very fast.
#' * multiscalerb: Implements multi-scale rigid body interpolation for image warping. This decreases image artifacts in some circumstances, but is much slower.
#'
#' @param trans_img list of stimuli to transform
#' @param from_img negative transform dimension endpoint (0% image)
#' @param to_img positive transform dimension endpoint (100% image)
#' @param shape,color,texture amount to change along the vector defined by from_img and to_img (can range from -3 to +3)
#' @param outname name to save each image as
#' @param norm how to normalise the images; see Details
#' @param normpoint points for twopoint normalisation
#' @param sample_contours whether to sample contours or just points
#' @param warp warp type
#'
#' @return list of stimuli with transformed images and templates
#' @export
#' @family webmorph
#'
#' @examples
#' \donttest{
#' if (webmorph_up()) {
#' stimuli <- demo_stim()
#' sexdim <- trans(stimuli, stimuli$f_multi, stimuli$m_multi,
#' shape = c(fem = -0.5, masc = 0.5))
#'
#' sexdim |> draw_tem() |> label()
#' }
#' }
#'
trans <- function(trans_img = NULL, from_img = NULL, to_img = NULL,
shape = 0,
color = 0,
texture = 0,
outname = NULL,
norm = c("none", "twopoint", "rigid"),
normpoint = 0:1,
sample_contours = TRUE,
warp = c("multiscale", "linear", "multiscalerb")) {
if (!webmorph_up()) {
stop("Webmorph.org can't be reached. Check if you are connected to the internet.")
}
trans_img <- require_tems(trans_img)
from_img <- require_tems(from_img)
to_img <- require_tems(to_img)
norm <- match.arg(norm)
warp <- match.arg(warp)
format <- "jpg" # match.arg(format)
sample_contours <- ifelse(isTRUE(as.logical(sample_contours)), "true", "false")
# find identical stimuli to avoid duplicate upload
to_upload <- c(trans_img, from_img, to_img)
n <- length(to_upload)
pairs <- expand.grid(a = 1:n, b = 1:n)
upairs <- pairs[pairs$a < pairs$b, ]
idpairs <- mapply(identical, to_upload[upairs$a], to_upload[upairs$b])
dupes <- upairs[which(idpairs == TRUE), ]
nondupes <- setdiff(1:n, dupes$b)
# take care of duplicate names
dupenames <- duplicated(names(to_upload)[nondupes]) |> which()
while(length(dupenames) > 0) {
dnames <- nondupes[dupenames]
names(to_upload)[dnames] <- paste0(
names(to_upload[dnames]), "_")
dupenames <- duplicated(names(to_upload)[nondupes]) |> which()
}
from_start <- length(trans_img)+1
to_start <- length(trans_img)+length(from_img) +1
names(trans_img) <- names(to_upload)[1:(from_start-1)]
names(from_img) <- names(to_upload)[from_start:(to_start-1)]
names(to_img) <- names(to_upload)[to_start:length(to_upload)]
# save images locally
tdir <- tempfile()
files <- write_stim(to_upload[nondupes], tdir, format = "jpg") |> unlist()
if (length(files) > 200) {
stop("Sorry! We can't upload more than 100 images at a time. You will need to break your transform into smaller chunks.")
}
upload <- lapply(files, httr::upload_file)
names(upload) <- sprintf("upload[%d]", 0:(length(upload)-1))
# get all to the same length
filenames <- list(trans = names(trans_img),
from = names(from_img),
to = names(to_img))
n_img <- sapply(filenames, length) |> max()
filenames <- lapply(filenames, rep_len, n_img) |> as.data.frame()
filenames$trans <- factor(filenames$trans, unique(filenames$trans))
filenames$from <- factor(filenames$from, unique(filenames$from))
filenames$to <- factor(filenames$to, unique(filenames$to))
n_param <- list(shape, color, texture) |>
sapply(length) |> max()
# use indices, not values, so crossing doesn't mangle order
param <- data.frame(
shape = rep_len(seq_along(shape), n_param),
color = rep_len(seq_along(color), n_param),
texture = rep_len(seq_along(texture), n_param)
)
#batch <- tidyr::crossing(param, filenames)
n <- nrow(filenames)
batch <- data.frame(
shape = rep(param$shape, each = n),
color = rep(param$color, each = n),
texture = rep(param$texture, each = n),
trans = rep(filenames$trans, times = n_param),
from = rep(filenames$from, times = n_param),
to = rep(filenames$to, times = n_param)
)
# translate back to characters or numbers
batch$trans <- as.character(batch$trans)
batch$from <- as.character(batch$from)
batch$to <- as.character(batch$to)
batch$shape <- shape[batch$shape]
batch$color <- color[batch$color]
batch$texture <- texture[batch$texture]
# clean params
for (x in c("shape", "color", "texture")) {
is_pcnt <- grepl("%", batch[[x]])
if (is.character(batch[[x]]))
batch[x] <- gsub("%", "", batch[[x]]) |> as.numeric()
# percents are definitely percents
batch[[x]][is_pcnt] <- batch[[x]][is_pcnt] / 100
# numbers bigger than 3 are probably percents
prob_pcnts <- abs(batch[[x]]) > 3
batch[[x]][prob_pcnts] <- batch[[x]][prob_pcnts] / 100
}
# outnames
if (!is.null(outname)) {
n <- nrow(batch)
outname <- gsub("\\.(jpg|gif|png)$", "", outname)
if (length(outname) < n) {
outname <- rep_len(outname, n) |>
paste0("_", 1:n)
}
batch$outname <- outname[1:n]
} else {
# construct outnames
trans_names <- names(trans_img)
from_names <- names(from_img)
to_names <- names(to_img)
if (all(from_names == trans_names)) from_names = ""
if (all(from_names == to_names)) to_names = ""
if (all(to_names == trans_names)) to_names = ""
imgnames <- list(trans = trans_names,
from = from_names,
to = to_names) |>
lapply(function(x) if (length(x)==1) "" else x) |>
lapply(rep_len, n_img) |>
as.data.frame()
# factorise to keep order
if (!all(imgnames$trans == "")) {
imgnames$trans <- factor(imgnames$trans, unique(trans_names))
}
if (!all(imgnames$from == "")) {
imgnames$from <- factor(imgnames$from, unique(from_names))
}
if (!all(imgnames$to == "")) {
imgnames$to <- factor(imgnames$to, unique(to_names))
}
paramnames <- data.frame(
shape = rep_len(names(shape) %||% "", n_param),
color = rep_len(names(color) %||% "", n_param),
texture = rep_len(names(texture) %||% "", n_param)
)
# fix if no names and multiple params
if (nrow(paramnames) > 1 &&
is.null(names(shape)) &&
is.null(names(color)) &&
is.null(names(texture))) {
char_n <- nrow(paramnames) |> as.character() |> nchar()
paramnames$shape <- paste0("%0", char_n, "d") |>
sprintf(1:nrow(paramnames))
}
if (!all(paramnames$shape == "") && !is.null(names(shape))) {
paramnames$shape <- factor(paramnames$shape, names(shape))
}
if (!all(paramnames$color == "") && !is.null(names(color))) {
paramnames$color <- factor(paramnames$color, names(color))
}
if (!all(paramnames$texture == "") && !is.null(names(texture))) {
paramnames$texture <- factor(paramnames$texture, names(texture))
}
# remove exact duplicates
if (all(paramnames$shape == paramnames$color))
paramnames$color <- ""
if (all(paramnames$shape == paramnames$texture))
paramnames$texture <- ""
if (all(paramnames$color == paramnames$texture))
paramnames$texture <- ""
pn <- nrow(paramnames)
imgn <- nrow(imgnames)
batch$outname <- paste(sep = "_",
rep(imgnames$trans, times = pn),
rep(imgnames$from, times = pn),
rep(imgnames$to, times = pn),
rep(paramnames$shape, each = imgn),
rep(paramnames$color, each = imgn),
rep(paramnames$texture, each = imgn)
) |>
gsub(pattern = "_{2,}", replacement = "_") |>
gsub(pattern = "^_", replacement = "") |>
gsub(pattern = "_$", replacement = "")
}
# fix missing or duplicate outnames
if (all(batch$outname == "") ||
unique(batch$outname) |> length() == 1) {
batch$outname <- paste0("trans", seq_along(batch$outname))
}
# remove image suffixes and make local if starts with /
batch$outname <- gsub("\\.(jpg|gif|png)$", "", batch$outname)
batch$outname <- gsub("^/", "./", batch$outname)
settings <- list(
count = nrow(batch)
)
for (i in seq_along(batch$outname)) {
settings[paste0('transimage', i-1)] = batch$trans[[i]]
settings[paste0('fromimage', i-1)] = batch$from[[i]]
settings[paste0('toimage', i-1)] = batch$to[[i]]
settings[paste0('shape', i-1)] = batch$shape[[i]]
settings[paste0('color', i-1)] = batch$color[[i]]
settings[paste0('texture', i-1)] = batch$texture[[i]]
settings[paste0('sampleContours', i-1)] = sample_contours
settings[paste0('norm', i-1)] = norm
settings[paste0('warp', i-1)] = warp
settings[paste0('normPoint0_', i-1)] = normpoint[[1]]
settings[paste0('normPoint1_', i-1)] = normpoint[[2]]
settings[paste0('format', i-1)] = format
settings[paste0('outname', i-1)] = batch$outname[[i]]
}
# send request to webmorph and handle zip file
ziptmp <- paste0(tdir, "/trans.zip")
httr::timeout(30 + 10*nrow(batch))
httr::set_config( httr::config( ssl_verifypeer = 0L ) )
url <- paste0(wm_opts("server"), "/scripts/webmorphR_trans")
r <- httr::POST(url, body = c(upload, settings) ,
httr::write_disk(ziptmp, TRUE))
utils::unzip(ziptmp, exdir = file.path(tdir, "trans"))
# check return zip
nfiles <- file.path(tdir, "trans") |> list.files() |> length()
if (nfiles == 0) {
resp <- httr::content(r)
stop(resp$errorText, call. = FALSE)
}
trans <- file.path(tdir, "trans") |>
read_stim()
unlink(tdir, recursive = TRUE) # clean up temp directory
trans[batch$outname]
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/trans.R
|
#' Get unique names
#'
#' @param full_names a list of full names
#' @param breaks regex for breaking up the names into parts. If "", then each character will be assessed.
#' @param remove_ext whether to remove the extension before comparing
#'
#' @return a list or vector of names with the common beginnings removed
#' @keywords internal
unique_names <- function(full_names,
breaks = "/",
remove_ext = TRUE) {
# check is a 1D list or vector
if (!is.list(full_names) &&
!is.atomic(full_names)) {
stop("full_names must be a list or vector")
} else if (!(sapply(full_names, is.character) |> all())) {
stop("full_names must contain only character strings")
}
# remove extension ----
fnames <- full_names
if (remove_ext) {
fnames <- gsub("\\..{1,4}$", "", full_names)
}
# handle blanks
fnames[fnames == ""] <- "stim"
# handle NULL breaks ----
if (is.null(breaks)) {
names(fnames) <- full_names
return(fnames)
}
# handle single item ----
if (length(fnames) == 1) {
if (breaks == "") {
unames <- fnames[[1]]
} else {
# break and take last section
unames <- fnames[[1]] |>
strsplit(breaks) |> # break
.subset2(1)
unames <- unames[length(unames)] # get last item
}
names(unames) <- full_names[[1]]
return(unames)
}
# compare multiple items ----
split_names <- fnames |> strsplit(breaks)
m <- sapply(split_names, length) |> min()
# check first m sections for overlap ----
drop_start <- sapply(1:m, function(i) {
sapply(split_names, `[[`, i) |>
unique() |>
length() == 1
}) |>
dplyr::cumall() |> # set TRUE until first FALSE
sum()
# reverse & check last m sections for overlap ----
drop_end <- sapply(1:m, function(i) {
sapply(split_names, function(x) {
j <- length(x) + 1 - i
x[[j]]
}) |>
unique() |>
length() == 1
}) |>
dplyr::cumall() |>
sum()
# trim unvarying characters from each name ----
is_regex <- grepl("(\\(|\\|)", breaks) # CHECK
glue <- ifelse(is_regex, "/", breaks)
unames <- sapply(split_names, function(x) {
start <- drop_start+1
stop <- length(x)-drop_end
x[start:stop] |> paste(collapse = glue)
})
names(unames) <- full_names
unames
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/unique_names.R
|
#' Piped OR
#'
#' LHS if not \code{NULL}, otherwise RHS
#'
#' @param l LHS.
#' @param r RHS.
#' @return LHS if not \code{NULL}, otherwise RHS.
#' @name OR
#'
#' @keywords internal
#'
`%||%` <- function(l, r) {
if (is.null(l)) r else l
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/utils-pipe.R
|
#' Print stim
#'
#' @param x a list of class stim
#' @param ... arguments passed to or from other methods
#'
#' @return prints summary info and returns x
#' @export
#' @keywords internal
#'
print.stim <- function(x, ...) {
as_stimlist(x) |> print()
}
# print.stim <- function(x, ...) {
# # uses magick:::print.magick-image
# print(x$img, FALSE)
# }
#' Print stimlist
#'
#' @param x list of stimuli
#' @param ... arguments passed to or from other methods
#'
#' @return prints summary info and returns x
#' @export
#' @keywords internal
#'
print.stimlist <- function(x, ...) {
if (!length(x)) return(invisible(x))
if (length(x) == 1) {
if (length(x[[1]]$img) > 1) {
# animated gif
print(x[[1]]$img, info = FALSE)
return(invisible(x))
}
} else {
x <- plot(x)
}
grid::grid.newpage()
grid::grid.raster(x[[1]]$img)
# width = x[[1]]$width,
# height = x[[1]]$height,
# default.units = "points")
invisible(x)
}
# This is registered as an S3 method in .onLoad()
knit_print.stimlist <- function(x, ...) {
if (!length(x)) return(invisible())
if (length(x) == 1) {
print(x[[1]]$img, info = FALSE)
} else {
plot(x) |> get_imgs() |> print(info = FALSE)
}
}
# print.stimlist <- function(x, ...) {
# img <- get_imgs(x)
#
# # print image inline if option set and not knitting
# # TODO: only run this if in an Rmd chunk
# #rmd_inline <- rstudioapi::readRStudioPreference("rmd_chunk_output_inline", NA)
# if (length(img) == 1 &&
# interactive() &&
# wm_opts("plot") == "inline" &&
# #rmd_inline &&
# !isTRUE(getOption("knitr.in.progress"))) {
# tmp <- tempfile(fileext = ".png")
# magick::image_write(img, tmp)
# suppressWarnings({
# # suppress warning about absolute paths
# knitr::include_graphics(tmp) |> print()
# })
# }
#
# # prints in the viewer using magick:::print.magick-image
# # if multiple images or not in an Rmd document
# suppressWarnings({
# # suppress warning about absolute paths
# print(img, FALSE)
# })
# }
#' Subset Stimulus Lists
#'
#' Returns a subset of the stimulus list meeting the condition.
#'
#' @param x list of stimuli
#' @param subset a character string to use as a pattern for searching stimulus IDs, or a logical expression indicating elements or rows to keep: missing values are taken as false.
#' @param ... further arguments to be passed to or from other methods.
#'
#' @return list of stimuli
#' @export
#' @keywords internal
subset.stimlist <- function (x, subset, ...) {
e <- substitute(subset)
info <- get_info(x)
r <- eval(e, info, parent.frame())
if (is.logical(r)) {
selected <- r & !is.na(r)
} else if (is.numeric(subset)) {
selected <- subset
} else {
selected <- grepl(subset, names(x))
}
x[selected]
}
#' Repeat stim in a list
#'
#' @param x A list of class stim
#' @param ... Additional arguments to pass on to `base::rep()`
#'
#' @return A stimlist
#' @export
#' @keywords internal
rep.stim <- function (x, ...) {
# turn into a list and handle below
x <- as_stimlist(x)
rep.stimlist(x, ...)
}
#' Repeat stim in a list
#'
#' @param x A stimlist
#' @param ... Additional arguments to pass on to `base::rep()`
#'
#' @return A stimlist
#' @export
#' @keywords internal
rep.stimlist <- function(x, ...) {
nm <- names(x)
newnm <- rep(nm, ...)
newx <- x[newnm]
class(newx) <- c("stimlist", "list")
newx
}
#' Combine stim
#'
#' @param ... stim to be concatenated
#'
#' @return stimlist
#' @export
#' @keywords internal
#'
c.stim <- function(...) {
# turn into a stimlist and handle below
list(...) |>
lapply(as_stimlist) |>
do.call(what = c.stimlist)
}
#' Combine stimlists
#'
#' @param ... stimlists to be concatenated
#'
#' @return stimlist
#' @export
#' @keywords internal
#'
c.stimlist <- function(...) {
dots <- lapply(list(...), as_stimlist) |>
lapply(unclass) # prevent infinite recursion
x <- do.call(c, dots)
class(x) <- c("stimlist", "list")
x
}
#' Extract stimlist elements
#'
#' @param x stimlist from which to extract elements
#' @param i indices to be selected
#'
#' @return stimlist
#' @export
#' @keywords internal
#'
`[.stimlist` <- function(x, i) {
x <- NextMethod()
class(x) <- c("stimlist", "list")
x
}
#' Replace stimlist element
#'
#' @param x stimlist from which to extract elements
#' @param i index to be replaced
#' @param value stim element to replace with
#'
#' @return stimlist
#' @export
#' @keywords internal
#'
`[[<-.stimlist` <- function(x, i, value) {
stopifnot("stim" %in% class(value))
NextMethod()
}
#' WebmorphR Message
#'
#' @param ... arguments to pass to base::message()
#'
#' @return NULL
#' @keywords internal
message <- function(...) {
if (isTRUE(wm_opts("verbose"))) {
base::message(...)
}
}
#' Format file size
#'
#' @param x the file size in bytes
#'
#' @return human-readable file size
#' @keywords internal
format_size <- function (x) {
digits = 1L
base <- 1024
units_map <- c("b", "Kb", "Mb", "Gb", "Tb", "Pb")
power <- if (x <= 0) 0L else min(as.integer(log(x, base = base)), length(units_map) - 1L)
unit <- units_map[power + 1L]
if (power == 0) unit <- "bytes"
paste(round(x/base^power, digits = digits), unit)
}
#' Get Images into List
#'
#' @param stimuli list of stimuli
#'
#' @return list of magick images
#' @keywords internal
get_imgs <- function(stimuli) {
args <- as_stimlist(stimuli) |>
lapply(`[[`, "img")
do.call(c, args)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/utils.R
|
#' webmorphR: Reproducible Face Stimuli
#'
#' Create reproducible image stimuli, specialised for images with webmorph.org templates.
#'
#' @docType package
#' @name webmorphR
#' @keywords internal
#'
#' @importFrom stats cor sd
#' @importFrom dplyr .data
#' @importFrom rsvg rsvg_raw
#'
"_PACKAGE"
.onLoad <- function(libname, pkgname) {
## set default options for wm_opts:
op <- options()
op.webmorph <- list(
webmorph.overwrite = "ask",
webmorph.connection = stdin(),
webmorph.verbose = TRUE,
webmorph.line.color = "blue",
webmorph.pt.color = "green",
webmorph.fill = "white",
webmorph.server = "https://webmorph.org",
webmorph.plot = "inline",
webmorph.plot.maxwidth = 2400,
webmorph.plot.maxheight = 2400
)
toset <- !(names(op.webmorph) %in% names(op))
if(any(toset)) options(op.webmorph[toset])
register_s3_method("knitr", "knit_print", "stimlist")
invisible()
}
register_s3_method <- function(pkg, generic, class, fun = NULL) {
stopifnot(is.character(pkg), length(pkg) == 1)
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
if (is.null(fun)) {
fun <- get(paste0(generic, ".", class), envir = parent.frame())
} else {
stopifnot(is.function(fun))
}
if (pkg %in% loadedNamespaces()) {
registerS3method(generic, class, fun, envir = asNamespace(pkg))
}
# Always register hook in case package is later unloaded & reloaded
setHook(
packageEvent(pkg, "onLoad"),
function(...) {
registerS3method(generic, class, fun, envir = asNamespace(pkg))
}
)
}
.onAttach <- function(libname, pkgname) {
paste(
"\n************",
"Welcome to webmorphR. For support and examples visit:",
"https://debruine.github.io/webmorphR/",
# "If this package is useful, please cite it:",
# paste0("http://doi.org/", utils::citation("webmorphR")$doi),
"************\n",
sep = "\n"
) |> packageStartupMessage()
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/webmorphR-package.R
|
#' Set/get global webmorph options
#'
#' See [wm_opts_defaults()] for explanations of the default options.
#'
#' @param ... One of four: (1) nothing, then returns all options as a list; (2) a name of an option element, then returns its value; (3) a name-value pair which sets the corresponding option to the new value (and returns nothing), (4) a list with option-value pairs which sets all the corresponding arguments.
#'
#' @return a list of options, values of an option, or nothing
#' @export
#'
#' @seealso [wm_opts_defaults()]
#'
#' @examples
#'
#' wm_opts() # see all options
#'
#' wm_opts("verbose") # see value of webmorph.verbose
#'
#' \dontrun{
#' # set value of webmorph.verbose
#' wm_opts(verbose = FALSE)
#'
#' # set multiple options
#' opts <- list(fill = "black",
#' pt.color = "white",
#' line.color = "red")
#' wm_opts(opts)
#' }
#'
wm_opts <- function (...) {
# code from afex::afex_options
dots <- list(...)
if (length(dots) == 0) {
# get all webmorph options
op <- options()
webmorph_op <- op[grepl("^webmorph.", names(op))]
names(webmorph_op) <- sub("^webmorph.", "", names(webmorph_op))
return(webmorph_op)
} else if (is.list(dots[[1]])) {
# first item is a list, set from list if named
newop <- dots[[1]]
if (is.null(names(newop)))
stop("Format lists with names like list(verbose = FALSE)")
names(newop) <- paste0("webmorph.", names(newop))
options(newop)
} else if (!is.null(names(dots))) {
# dots have names, so set webmorph options
newop <- dots
names(newop) <- paste0("webmorph.", names(newop))
options(newop)
} else if (is.null(names(dots))) {
# dots don't have names, so get webmorph options
opnames <- paste0("webmorph.", unlist(dots))
getop <- lapply(opnames, getOption)
if (length(opnames) == 1) {
getop <- getop[[1]]
} else {
names(getop) <- unlist(dots)
}
return(getop)
} else {
warning("Unsupported command to wm_opts(), nothing done.",
call. = FALSE)
}
}
#' WebmorphR default options
#'
#' @description
#' Options set on load (unless they were already set by .Renviron)
#'
#' * overwrite ("ask"): Whether to overwrite images saved with [write_stim()] when in interactive mode; possible values are "ask" (ask if filenames exist), TRUE (always overwrite), and FALSE (never overwrite)
#' * fill ("white"): the colour to use to fill image backgrounds
#' * pt.color ("green") : the colour to use for points in [draw_tem()]
#' * line.color ("blue"): the colour to use for lines in [draw_tem()]
#' * plot ("inline"): whether to plot images inline in R markdown documents (set to any other value to just view them in the viewer)
#' * plot.maxwidth (2400): The maximum width of images created by [plot()]
#' * plot.maxheight (2400): The maximum height of images created by [plot()]
#' * verbose (TRUE): Whether to produce verbose output and progress bars for long functions like [auto_delin()], [avg()] or [trans()]
#' * server ("https://webmorph.org"): The server to use for webmorph functions like [avg()] and [trans()]; do not change unless you've set up a local server
#' * connection (stdin()): use internally for testing interactive functions; do not change
#'
#' @return a list of default options
#' @export
#'
#' @seealso [wm_opts()]
#'
#' @examples
#' wm_opts_defaults() |> str() # view defaults
#'
#' \dontrun{
#' # reset all options to default
#' wm_opts_defaults() |> wm_opts()
#' }
wm_opts_defaults <- function() {
list(
connection = stdin(),
fill = "white",
line.color = "blue",
overwrite = "ask",
plot = "inline",
plot.maxheight = 2400,
plot.maxwidth = 2400,
pt.color = "green",
server = "https://webmorph.org",
verbose = TRUE
)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/wm_opts.R
|
#' Write images and templates to files
#'
#' @param stimuli list of stimuli
#' @param dir Directory to save to
#' @param names A vector of stimulus names or NULL to use names from the stimuli list
#' @param format output format such as "png", "jpeg", "gif"; is overridden if names end in .png, .jpg, or .gif
#' @param ... other arguments to pass to [magick::image_write], such as quality (for jpegs)
#' @param overwrite whether to overwrite existing files (TRUE/FALSE) or "ask" (only in interactive mode)
#'
#' @return list of saved paths
#' @export
#' @family stim
#'
#' @examples
#' \dontrun{
#' # write demo stim as jpegs to directory ./test_faces
#' demo_stim() |>
#' write_stim("test_faces", format = "jpg")
#' }
write_stim <- function(stimuli, dir = ".",
names = NULL, format = "png", ...,
overwrite = wm_opts("overwrite")) {
stimuli <- as_stimlist(stimuli)
if (!is.null(names)) {
n <- length(stimuli)
if (length(names) > n) {
names <- names[1:n]
} else if (length(names) < n) {
idx <- as.character(n) |> nchar() |>
formatC(x = 1:n, digits = 0, flag = "0")
names <- rep_len(names, n) |> paste0("_", idx)
}
stimuli <- rename_stim(stimuli, names)
}
# make dir if it doesn't exist
if (!dir.exists(dir)) {
dir.create(dir, recursive = TRUE)
}
# set image format and extension
format <- gsub("\\.", "", format) |>
tolower() |>
switch(png = "png",
jpg = "jpeg",
jpeg = "jpeg",
gif = "gif",
"png") # default to png
# iterate over stimuli and names to save
# TODO: make this less clunky
paths <- mapply(function(stim, name) {
imgsaved <- NULL
temsaved <- NULL
# save images
if (!is.null(stim$img)) {
# get image format from name, if available
img_format <- format
has_ext <- grepl("\\.(png|gif|jpg|jpeg)$", tolower(name))
if (has_ext) {
img_format <- gsub("^.+\\.", "", tolower(name)) |>
switch(png = "png",
jpg = "jpeg",
jpeg = "jpeg",
gif = "gif")
# remove ext from name for tem
name <- gsub("\\.(png|gif|jpg|jpeg)$", "",
name, ignore.case = TRUE)
}
ext <- switch(img_format,
png = ".png",
jpeg = ".jpg",
gif = ".gif")
imgpath <- file.path(dir, paste0(name, ext))
# check if file exists
if (interactive() && overwrite == "ask" && file.exists(imgpath)) {
txt <- paste0("The file ", imgpath, " already exists; do you want to: \n1: Skip\n2: Save over\n3: Skip all\n4: Save over all")
ow <- readline_check(txt,
type = "numeric",
min = 1, max = 4)
if (ow == 3) { overwrite <<- FALSE }
if (ow == 4) { overwrite <<- TRUE }
if (ow == 2 || ow == 4) {
imgsaved <- magick::image_write(
stim$img, path = imgpath, format = img_format, ...)
}
} else if (isTRUE(overwrite) || !file.exists(imgpath)) {
imgsaved <- magick::image_write(
stim$img, path = imgpath, format = img_format, ...)
}
}
# save templates
if (!is.null(stim$points)) {
tem_txt <- tem_text(stim)
tempath <- file.path(dir, paste0(name, ".tem"))
# check if file exists
if (interactive() && overwrite == "ask" && file.exists(tempath)) {
txt <- paste0("The file ", tempath, " already exists; do you want to: \n1: Skip\n2: Save over\n3: Skip all\n4: Save over all")
ow <- readline_check(txt,
type = "numeric",
min = 1, max = 4)
if (ow == 3) { overwrite <<- FALSE }
if (ow == 4) { overwrite <<- TRUE }
if (ow == 2 || ow == 4) {
write(tem_txt, tempath)
temsaved <- tempath
}
} else if (isTRUE(overwrite) || !file.exists(tempath)) {
write(tem_txt, tempath)
temsaved <- tempath
}
}
# return save paths or FALSE if not saved
list(tem = temsaved,
img = imgsaved)
}, stimuli, names(stimuli) %||% seq_along(stimuli))
invisible(paths)
}
#' Make text version of a template
#'
#' @param stim A list of class stim (one item in a stimlist)
#'
#' @return The text for a .tem file
#' @export
#' @keywords internal
#'
#' @examples
#' stimuli <- demo_stim()
#' f_tem_text <- tem_text(stimuli$f_multi)
tem_text <- function(stim) {
txt <- list()
# add points
txt <- c(txt, dim(stim$points)[[2]])
pts <- apply(stim$points, 2, paste, collapse = "\t")
txt <- c(txt, pts)
# add lines
if (!is.null(stim$lines)) {
txt <- c(txt, length(stim$lines))
for (i in seq_along(stim$lines)) {
txt <- c(txt, list(
as.integer(stim$closed[[i]]),
length(stim$lines[[i]]),
paste(stim$lines[[i]], collapse = " ")
))
}
} else {
txt <- c(txt, "0")
}
txt <- paste(txt, collapse = "\n")
txt
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/write_stim.R
|
#' Create a TPS file from a stimlist
#'
#' @param stimuli list of stimuli
#' @param path_to_tps optional filename to save TPS file
#'
#' @return text of tps file
#' @export
#'
#' @examples
#' # set path_to_tps to save to a file
#' tps <- demo_stim() |>
#' write_tps()
#'
write_tps <- function(stimuli, path_to_tps = NULL) {
stimuli <- as_stimlist(stimuli)
tps <- mapply(function(stim, name) {
pt <- {stim$points * c(1, -1)} |>
t() |> as.data.frame()
pt_list <- paste(pt[[1]], pt[[2]], sep = "\t") |>
paste(collapse = "\n")
sprintf("LM=%i\n%s\nID=%s",
ncol(stim$points),
pt_list,
name)
}, stimuli, names(stimuli) %||% seq_along(stimuli)) |>
paste(collapse = "\n")
if (is.null(path_to_tps)) {
return(tps)
} else {
write(tps, path_to_tps)
stimuli
}
}
#' Convert stimuli to array for geomorph
#'
#' @param stimuli list of stimuli
#'
#' @return 3D array
#' @export
#'
#' @examples
#' data <- demo_stim() |> tems_to_array()
#' dim(data)
#'
tems_to_array <- function(stimuli) {
stimuli <- require_tems(stimuli, TRUE)
# check number of points
n_pts <- lapply(stimuli, `[[`, "points") |>
sapply(ncol) |>
unique()
if (is.null(n_pts[[1]])) {
stop("No image had templates")
} else if (length(n_pts) > 1) {
stop("Each tem must have the same length")
}
sapply(stimuli, function(tem) {
t(tem$points * c(1, -1))
}) |>
array(dim = c(n_pts, 2, length(stimuli)),
dimnames = list(NULL, c("X", "Y"), names(stimuli)))
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/R/write_tps.R
|
# display debugging messages in R if local,
# or in the console log if remote
debug_msg <- function(...) {
is_local <- Sys.getenv('SHINY_PORT') == ""
txt <- paste(...)
if (is_local) {
message(txt)
} else {
shinyjs::logjs(txt)
}
}
## datatable constants ----
dt_options <- function() {
list(
info = FALSE,
lengthChange = FALSE,
paging = FALSE,
ordering = FALSE,
searching = FALSE,
pageLength = 500,
keys = TRUE
)
}
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/inst/app/R/funcs.R
|
suppressPackageStartupMessages({
library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinyWidgets)
library(DT)
library(dplyr)
library(webmorphR)
})
imgdir <- getShinyOption("imgdir")
# tabs ----
## main_tab ----
main_tab <- tabItem(
tabName = "main_tab",
textOutput("quickhelp"),
#fluidRow(
#column(width = 6,
#actionButton("delin_clear", "Clear Points"),
actionButton("delin_reload", NULL, icon = icon("redo")),
actionButton("prev_img", NULL, icon = icon("step-backward")),
actionButton("delin_save", "Save", icon = icon("save")),
actionButton("next_img", NULL, icon = icon("step-forward")),
#),
#column(width = 6,
sliderTextInput("img_size", NULL,
selected = 100,
grid = FALSE,
post = "%",
choices = c(seq(10,100, 10), seq(200, 1000, 100))),
#)
#),
tags$div(id = "delin_box_box",
tags$div(id = "delin_box", imageOutput("delin_img", ))
)
)
# UI ----
ui <- dashboardPage(
skin = "blue",
dashboardHeader(title = "WebmorphR"),
dashboardSidebar(
sidebarMenu(
id = "tabs",
#menuItem("QuickDelin", tabName = "main_tab"),
hidden(downloadButton("tem_dl", "Templates")),
actionButton("delin_finish", "Save and Back to R"),
actionButton("delin_cancel", "Cancel without Saving"),
fileInput("finder_load", "Load Files", multiple = TRUE,
width = "100%", accept = c("image/*", ".tem")),
DTOutput("finder_table")
)
),
dashboardBody(
useShinyjs(),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "custom.css"),
tags$script(src= "https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"),
tags$script(src = "keycodes.js"),
tags$script(src = "custom.js")
),
#tabItems(
main_tab
#)
)
)
# server ----
server <- function(input, output, session) {
v <- reactiveValues()
if (!is.null(imgdir)) {
output$quickhelp <- renderText("Loading stimuli from webmorphR")
runjs("delin_clear();")
v$stimuli <- read_stim(imgdir)
v$delin_current <- 1
output$quickhelp <- renderText({
sprintf("%d images loaded", length(v$stimuli))
})
# hide desktop use functions
hide("finder_load")
hide("tem_dl")
}
## finder_load ----
observeEvent(input$finder_load, { debug_msg("finder_load")
# rename files to original names in tempdir
tdir <- dirname(input$finder_load$datapath[[1]])
file.rename(input$finder_load$datapath,
file.path(tdir, input$finder_load$name))
# load as stimlist
runjs("delin_clear();")
v$stimuli <- webmorphR::read_stim(tdir)
v$delin_current <- 1
show("tem_dl")
}, ignoreNULL = TRUE)
## finder_table ----
output$finder_table <- renderDT({
req(v$stimuli)
df <- data.frame(
file = names(v$stimuli)
)
# my_col <- rep('black', nrow(df))
# my_col[v$delin_current] <- 'white'
# my_bg <- rep('white', nrow(df))
# my_bg[v$delin_current] <- '#204969'
datatable(df, escape = TRUE,
rownames = FALSE,
selection = 'single',
options = dt_options()) #|>
# formatStyle(1, target = 'row',
# color = styleEqual(df$file, my_col),
# backgroundColor = styleEqual(df$file, my_bg))
})
## finder_table_rows_selected ----
observeEvent(input$finder_table_rows_selected, {
debug_msg("finder_table_rows_selected")
idx <- input$finder_table_rows_selected
if (length(idx) == 0) { return() }
v$delin_current <- idx
updateTabItems(session, "tabs", selected = "delin_tab")
})
## img_size ----
observeEvent(input$img_size, {
sprintf("resize = %f; delin_resize();",
input$img_size) |>
runjs()
})
# update save button on template change ----
observeEvent(input$pts, { debug_msg("pts change")
req(v$stimuli)
img <- v$stimuli[[v$delin_current]]
# check if same as delin
needs_saved <- TRUE
if (!is.null(img$points)) {
saved_pts <- apply(img$points, 2, c) |> c() |> round(1)
needs_saved <- !all(round(input$pts, 1) == saved_pts)
# debug_msg("input: ", str(input$pts))
# debug_msg("saved: ", str(saved_pts))
}
shinyjs::toggleClass("delin_save", "btn-danger", needs_saved)
})
## delin_img ----
output$delin_img <- renderImage({ debug_msg("delin_img")
req(v$stimuli)
img <- v$stimuli[[v$delin_current]]
# update size
w <- img$width * input$img_size/100
h <- img$height * input$img_size/100
js <- sprintf("$('#delin_img, #delin_box').css('width', %d).css('height', %d)", w, h)
runjs(js)
list(src = img$imgpath,
alt = "Image failed to render",
draggable = "false",
width = w,
height = h)
}, deleteFile = FALSE)
# draw tem points -----
observeEvent(v$delin_current, {
req(v$stimuli)
img <- v$stimuli[[v$delin_current]]
runjs("delin_clear();")
if (is.null(img$points)) {
output$quickhelp <- renderText("Hold down cmd/ctrl and shift to add points")
} else {
# add points with js
apply(img$points, 2, function(pt) {
sprintf("new_pt({originalEvent: {layerX: %f, layerY: %f}});",
pt[["x"]] * input$img_size / 100,
pt[["y"]] * input$img_size / 100) |>
runjs()
})
}
})
## delin_reload ----
observeEvent(input$delin_reload, {
req(v$stimuli)
img <- v$stimuli[[v$delin_current]]
runjs("delin_clear();")
# add points with js
if (!is.null(img$points)) {
apply(img$points, 2, function(pt) {
sprintf("new_pt({originalEvent: {layerX: %f, layerY: %f}});",
pt[["x"]] * input$img_size / 100,
pt[["y"]] * input$img_size / 100) |>
runjs()
})
}
})
## delin_clear ----
observeEvent(input$delin_clear, {
runjs("delin_clear();")
})
# next_img ----
next_img <- function() {
# increment image
if (v$delin_current >= length(v$stimuli)) {
v$delin_current <- 1
} else {
v$delin_current <- v$delin_current + 1
}
}
observeEvent(input$next_img, { next_img() })
# prev_img ----
observeEvent(input$prev_img, {
if (v$delin_current == 1) {
v$delin_current <- length(v$stimuli)
} else {
v$delin_current <- v$delin_current - 1
}
})
# delin_save ----
observeEvent(input$delin_save, {
# add delin to v$stimuli
v$stimuli[[v$delin_current]]$points <-
matrix(input$pts, 2, dimnames = list(c("x", "y")))
next_img()
})
## tem_dl ----
output$tem_dl <- downloadHandler(
filename = function() {
debug_msg("tem_dl")
"tems.zip"
},
content = function(file) {
tryCatch({
# change wd to tempdir for zipping
oldwd <- getwd()
on.exit(setwd(oldwd))
tdir <- tempfile()
write_stim(v$stimuli, tdir, overwrite = TRUE)
setwd(tdir)
utils::zip(file, list.files(pattern = "\\.tem$"))
}, error = function(e) {
alert(e)
})
},
contentType = "application/zip"
)
# delin_finish ----
observeEvent(input$delin_finish, {
if (!is.null(imgdir)) {
debug_msg("writing stimuli to ", imgdir)
write_stim(v$stimuli, imgdir, overwrite = TRUE)
}
# clean up and signal done
hide("delin_img")
runjs("delin_clear();")
showModal(modalDialog(title = "Images saved and returning to R",
"You can close this app now."))
stopApp()
})
# delin_cancel ----
modal_quit_confirm <- modalDialog(
"This will not save any changes you made to the delineations.",
title = "Cancel without Saving",
footer = tagList(
actionButton("quit_cancel", "Return to Delineator"),
actionButton("quit_ok", "Cancel without Saving", class = "btn btn-danger")
)
)
observeEvent(input$delin_cancel, { showModal(modal_quit_confirm) })
observeEvent(input$quit_cancel, removeModal())
observeEvent(input$quit_ok, {
removeModal()
stopApp()
})
} # end server()
shinyApp(ui, server)
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/inst/app/app.R
|
list(
rd_family_title = list(manipulators = "Stimulus manipulation functions",
webmorph = "WebMorph.org functions",
tem = "Template functions",
viz = "Visualisation functions",
stim = "Stimulus creating functions")
)
|
/scratch/gouwar.j/cran-all/cranData/webmorphR/man/roxygen/meta.R
|
#' Webp image format
#'
#' Read and write webp images into a bitmap array. The bitmap array uses the same
#' conventions as the \code{png} and \code{jpeg} package.
#'
#' @export
#' @useDynLib webp R_webp_decode
#' @rdname read_webp
#' @aliases webp
#' @param source raw vector or path to webp file
#' @param numeric convert the image to 0-1 real numbers to be compatible with
#' images from the jpeg or png package.
#' @examples # Convert to webp
#' library(png)
#' img <- readPNG(system.file("img", "Rlogo.png", package="png"))
#' out <- file.path(tempdir(), "rlogo.webp")
#' write_webp(img, out)
#' # browseURL(out)
#'
#' # Convert from webp
#' library(jpeg)
#' img <- read_webp(out)
#' jpeg <- file.path(tempdir(), "rlogo.jpeg")
#' writeJPEG(img, jpeg)
#' # browseURL(jpeg)
read_webp <- function(source, numeric = TRUE) {
if(is.character(source))
source <- readBin(source[1], raw(), file.info(source)$size)
stopifnot(is.raw(source))
out <- .Call(R_webp_decode, source)
if(isTRUE(numeric)){
out <- structure(as.numeric(out)/255, dim = dim(out))
out <- aperm(out)
} else {
class(out) <- c("rawimg", class(out))
}
out
}
#' @export
#' @rdname read_webp
#' @useDynLib webp R_webp_encode
#' @param image array of 3 dimensions (width * height * channel) with real numbers
#' between 0 and 1.
#' @param target path to a file or \code{NULL} to return the image as a raw vector
#' @param quality value between 0 and 100 for lossy compression, or \code{NA} for
#' lossless compression.
write_webp <- function(image, target = NULL, quality = 80) {
if(is.numeric(image)){
image <- structure(as.raw(image * 255), dim = dim(image))
image <- aperm(image)
}
channels = dim(image)[1]
quality <- as.integer(quality)
if(!is.na(quality))
stopifnot("quality must be between 0 and 100" = quality > -1 && quality < 101)
stopifnot(channels == 3 || channels == 4)
buf <- .Call(R_webp_encode, image, quality)
if(is.character(target))
writeBin(buf, target)
else
structure(buf, class = "webp")
}
#' @useDynLib webp R_webp_get_info
webp_dims <- function(buf) {
stopifnot(is.raw(buf))
.Call(R_webp_get_info, buf)
}
#' @export
print.rawimg <- function(x, ...){
dims <- dim(x)
cat(sprintf("raw image (%d x %d) with %d channels\n", dims[2], dims[3], dims[1]))
invisible()
}
#' @export
print.webp <- function(x, ...){
dims <- webp_dims(x)
cat(sprintf("webp buffer (%d x %d)\n", dims[1], dims[2]))
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/webp/R/webp.R
|
if(!file.exists("../windows/libwebp/include/webp/decode.h")){
unlink("../windows", recursive = TRUE)
url <- if(grepl("aarch", R.version$platform)){
"https://github.com/r-windows/bundles/releases/download/libwebp-1.3.2/libwebp-1.3.2-clang-aarch64.tar.xz"
} else if(grepl("clang", Sys.getenv('R_COMPILED_BY'))){
"https://github.com/r-windows/bundles/releases/download/libwebp-1.3.2/libwebp-1.3.2-clang-x86_64.tar.xz"
} else if(getRversion() >= "4.2") {
"https://github.com/r-windows/bundles/releases/download/libwebp-1.3.2/libwebp-1.3.2-ucrt-x86_64.tar.xz"
} else {
"https://github.com/rwinlib/webp/archive/v1.3.2.tar.gz"
}
download.file(url, basename(url), quiet = TRUE)
dir.create("../windows", showWarnings = FALSE)
untar(basename(url), exdir = "../windows", tar = 'internal')
unlink(basename(url))
setwd("../windows")
file.rename(list.files(), 'libwebp')
}
|
/scratch/gouwar.j/cran-all/cranData/webp/tools/winlibs.R
|
#' Make transparent theme
#' @param size border size. default value is 0
#' @importFrom ggplot2 theme element_rect element_blank
#' @export
transparent=function(size=0){
temp=theme(rect= element_rect(fill = 'transparent',size=size),
panel.background=element_rect(fill = 'transparent'),
panel.border=element_rect(size=size),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank())
temp
}
#' Make default palette
#' @param n number of colors
#' @importFrom grDevices hcl
#' @export
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
#' Make subcolors with main colors
#' @param main character. main colors
#' @param no number of subcolors
#' @importFrom ztable gradientColor
#' @export
makeSubColor=function(main,no=3){
result=c()
for(i in 1:length(main)){
temp=ztable::gradientColor(main[i],n=no+2)[2:(no+1)]
result=c(result,temp)
}
result
}
#'Draw a PieDonut plot
#'@param data A data.frame
#'@param mapping Set of aesthetic mappings created by aes or aes_.
#'@param start offset of starting point from 12 o'clock in radians
#'@param addPieLabel A logical value. If TRUE, labels are added to the Pies
#'@param addDonutLabel A logical value. If TRUE, labels are added to the Donuts
#'@param showRatioDonut A logical value. If TRUE, ratios are added to the DonutLabels
#'@param showRatioPie A logical value. If TRUE, ratios are added to the PieLabels
#'@param ratioByGroup A logical value. If TRUE, ratios ara calculated per group
#'@param showRatioThreshold An integer. Threshold to show label as a ratio of total. default value is 0.02.
#'@param labelposition A number indicating the label position
#'@param labelpositionThreshold label position threshold. Default value is 0.1.
#'@param r0 Integer. start point of pie
#'@param r1 Integer. end point of pie
#'@param r2 Integer. end point of donut
#'@param explode pies to explode
#'@param selected donuts to explode
#'@param explodePos explode position
#'@param color color
#'@param pieAlpha transparency of pie
#'@param donutAlpha transparency of pie
#'@param maxx maximum position of plot
#'@param showPieName logical. Whether or not show Pie Name
#'@param showDonutName logical. Whether or not show Pie Name
#'@param title title of plot
#'@param pieLabelSize integer. Pie label size
#'@param donutLabelSize integer. Donut label size
#'@param titlesize integer. Title size
#'@param explodePie Logical. Whether or not explode pies
#'@param explodeDonut Logical. Whether or not explode donuts
#'@param use.label Logical. Whether or not use column label in case of labelled data
#'@param use.labels Logical. Whether or not use value labels in case of labelled data
#'@param family font family
#'@importFrom ggplot2 aes geom_segment coord_fixed scale_fill_manual xlim ylim annotate geom_text guides
#'@importFrom grid grid.newpage viewport
#'@importFrom ggforce geom_arc_bar theme_no_axes
#'@importFrom rlang .data
#'@importFrom dplyr arrange group_by summarize lag
#'@importFrom tidyr spread complete
#'@importFrom scales percent
#'@importFrom moonBook addLabelDf getMapping
#'@export
#'@examples
#'require(moonBook)
#'require(ggplot2)
#'browser=c("MSIE","Firefox","Chrome","Safari","Opera")
#'share=c(50,21.9,10.8,6.5,1.8)
#'df=data.frame(browser,share)
#'PieDonut(df,aes(browser,count=share),r0=0.7,start=3*pi/2,labelpositionThreshold=0.1)
#' \donttest{
#'PieDonut(df,aes(browser,count=share),r0=0.7,explode=5,start=3*pi/2)
#'PieDonut(mtcars,aes(gear,carb),start=3*pi/2,explode=3,explodeDonut=TRUE,maxx=1.7)
#'PieDonut(mtcars,aes(carb,gear),r0=0)
#'PieDonut(acs,aes(smoking,Dx),title="Distribution of smoking status by diagnosis")
#'PieDonut(acs,aes(Dx,smoking),ratioByGroup=FALSE,r0=0)
#'PieDonut(acs,aes(Dx,smoking),selected=c(1,3,5,7),explodeDonut=TRUE)
#'PieDonut(acs,aes(Dx,smoking),explode=1,selected=c(2,4,6,8),labelposition=0,explodeDonut=TRUE)
#'PieDonut(acs,aes(Dx,smoking),explode=1)
#'PieDonut(acs,aes(Dx,smoking),explode=1,explodeDonut=TRUE,labelposition=0)
#'PieDonut(acs,aes(Dx,smoking),explode=1,explodePie=FALSE,explodeDonut=TRUE,labelposition=0)
#'PieDonut(acs,aes(Dx,smoking),selected=c(2,5,8), explodeDonut=TRUE,start=pi/2,labelposition=0)
#'PieDonut(acs,aes(Dx,smoking),r0=0.2,r1=0.9,r2=1.3,explode=1,start=pi/2,explodeDonut=TRUE)
#'PieDonut(acs,aes(Dx,smoking),r0=0.2,r1=0.9,r2=1.3,explode=1,start=pi/2,labelposition=0)
#'PieDonut(acs,aes(Dx,smoking),explode=1,start=pi,explodeDonut=TRUE,labelposition=0)
#'require(dplyr)
#'df=mtcars %>% group_by(gear,carb) %>% summarize(n=n())
#'PieDonut(df,aes(pies=gear,donuts=carb,count=n),ratioByGroup=FALSE)
#'}
PieDonut=function(data,mapping,
start=getOption("PieDonut.start",0),
addPieLabel=TRUE,addDonutLabel=TRUE,
showRatioDonut=TRUE,showRatioPie=TRUE,
ratioByGroup=TRUE,
showRatioThreshold=getOption("PieDonut.showRatioThreshold",0.02),
labelposition=getOption("PieDonut.labelposition",2),
labelpositionThreshold=0.1,
r0=getOption("PieDonut.r0",0.3),
r1=getOption("PieDonut.r1",1.0),
r2=getOption("PieDonut.r2",1.2),
explode=NULL,
selected=NULL,
explodePos=0.1,
color="white",
pieAlpha=0.8,
donutAlpha=1.0,
maxx=NULL,
showPieName=TRUE,
showDonutName=FALSE,
title=NULL,
pieLabelSize=4,
donutLabelSize=3,
titlesize=5,
explodePie=TRUE,explodeDonut=FALSE,
use.label=TRUE,use.labels=TRUE,
family=getOption("PieDonut.family","")){
(cols=colnames(data))
if(use.labels) data=addLabelDf(data,mapping)
count<-NULL
if("count" %in% names(mapping)) count<-getMapping(mapping,"count")
count
pies<-donuts<-NULL
(pies=getMapping(mapping,"pies"))
if(is.null(pies)) (pies=getMapping(mapping,"pie"))
if(is.null(pies)) (pies=getMapping(mapping,"x"))
(donuts=getMapping(mapping,"donuts"))
if(is.null(donuts)) (donuts=getMapping(mapping,"donut"))
if(is.null(donuts)) (donuts=getMapping(mapping,"y"))
if(!is.null(count)){
df<-data %>% group_by(.data[[pies]]) %>%dplyr::summarize(Freq=sum(.data[[count]]))
df
} else{
df=data.frame(table(data[[pies]]))
}
colnames(df)[1]=pies
df$end=cumsum(df$Freq)
df$start=dplyr::lag(df$end)
df$start[1]=0
total=sum(df$Freq)
df$start1=df$start*2*pi/total
df$end1=df$end*2*pi/total
df$start1=df$start1+start
df$end1=df$end1+start
df$focus=0
if(explodePie) df$focus[explode]=explodePos
df$mid=(df$start1+df$end1)/2
df$x=ifelse(df$focus==0,0,df$focus*sin(df$mid))
df$y=ifelse(df$focus==0,0,df$focus*cos(df$mid))
df$label=df[[pies]]
df$ratio=df$Freq/sum(df$Freq)
if(showRatioPie) {
df$label=ifelse(df$ratio>=showRatioThreshold,
paste0(df$label,"\n(",scales::percent(df$ratio),")"),
as.character(df$label))
}
df$labelx=(r0+r1)/2*sin(df$mid)+df$x
df$labely=(r0+r1)/2*cos(df$mid)+df$y
if(!is.factor(df[[pies]])) df[[pies]]<-factor(df[[pies]])
df
mainCol=gg_color_hue(nrow(df))
df$radius=r1
df$radius[df$focus!=0]=df$radius[df$focus!=0]+df$focus[df$focus!=0]
df$hjust=ifelse((df$mid %% (2*pi))>pi,1,0)
df$vjust=ifelse(((df$mid %% (2*pi)) <(pi/2))|(df$mid %% (2*pi) >(pi*3/2)),0,1)
df$segx=df$radius*sin(df$mid)
df$segy=df$radius*cos(df$mid)
df$segxend=(df$radius+0.05)*sin(df$mid)
df$segyend=(df$radius+0.05)*cos(df$mid)
df
if(!is.null(donuts)){
subColor=makeSubColor(mainCol,no=length(unique(data[[donuts]])))
subColor
data
if(!is.null(count)){
df3 <- as.data.frame(data[c(donuts,pies,count)])
colnames(df3)=c("donut","pie","Freq")
df3
df3<-eval(parse(text="complete(df3,donut,pie)"))
# df3<-df3 %>% complete(donut,pie)
df3$Freq[is.na(df3$Freq)]=0
if(!is.factor(df3[[1]])) df3[[1]]=factor(df3[[1]])
if(!is.factor(df3[[2]])) df3[[2]]=factor(df3[[2]])
df3<-df3 %>% arrange(.data$pie,.data$donut)
a<-df3 %>% spread(.data$pie,value=.data$Freq)
# a<-df3 %>% spread(pie,value=Freq)
a=as.data.frame(a)
a
rownames(a)=a[[1]]
a=a[-1]
a
colnames(df3)[1:2]=c(donuts,pies)
} else{
df3=data.frame(table(data[[donuts]],data[[pies]]),stringsAsFactors = FALSE)
colnames(df3)[1:2]=c(donuts,pies)
a=table(data[[donuts]],data[[pies]])
a
}
a
df3
df3$group=rep(colSums(a),each=nrow(a))
df3$pie=rep(1:ncol(a),each=nrow(a))
total=sum(df3$Freq)
total
df3$ratio1=df3$Freq/total
df3
if(ratioByGroup) {
df3$ratio=scales::percent(df3$Freq/df3$group)
} else {
df3$ratio<-scales::percent(df3$ratio1)
}
df3$end=cumsum(df3$Freq)
df3
df3$start=dplyr::lag(df3$end)
df3$start[1]=0
df3$start1=df3$start*2*pi/total
df3$end1=df3$end*2*pi/total
df3$start1=df3$start1+start
df3$end1=df3$end1+start
df3$mid=(df3$start1+df3$end1)/2
df3$focus=0
if(!is.null(selected)){
df3$focus[selected]=explodePos
} else if(!is.null(explode)) {
selected=c()
for(i in 1:length(explode)){
start=1+nrow(a)*(explode[i]-1)
selected=c(selected,start:(start+nrow(a)-1))
}
selected
df3$focus[selected]=explodePos
}
df3
df3$x=0
df3$y=0
df
if(!is.null(explode)){
explode
for(i in 1:length(explode)){
xpos=df$focus[explode[i]]*sin(df$mid[explode[i]])
ypos=df$focus[explode[i]]*cos(df$mid[explode[i]])
df3$x[df3$pie==explode[i]]=xpos
df3$y[df3$pie==explode[i]]=ypos
}
}
df3$no=1:nrow(df3)
df3$label=df3[[donuts]]
if(showRatioDonut) {
if(max(nchar(levels(df3$label)))<=2) df3$label=paste0(df3$label,"(",df3$ratio,")")
else df3$label=paste0(df3$label,"\n(",df3$ratio,")")
}
df3$label[df3$ratio1==0]=""
# if(labelposition==0)
df3$label[df3$ratio1<showRatioThreshold]=""
df3$hjust=ifelse((df3$mid %% (2*pi))>pi,1,0)
df3$vjust=ifelse(((df3$mid %% (2*pi)) <(pi/2))|(df3$mid %% (2*pi) >(pi*3/2)),0,1)
df3$no=factor(df3$no)
df3
# str(df3)
labelposition
if(labelposition>0){
df3$radius=r2
if(explodeDonut) df3$radius[df3$focus!=0]=df3$radius[df3$focus!=0]+df3$focus[df3$focus!=0]
df3$segx=df3$radius*sin(df3$mid)+df3$x
df3$segy=df3$radius*cos(df3$mid)+df3$y
df3$segxend=(df3$radius+0.05)*sin(df3$mid)+df3$x
df3$segyend=(df3$radius+0.05)*cos(df3$mid)+df3$y
if(labelposition==2) df3$radius=(r1+r2)/2
df3$labelx= (df3$radius)*sin(df3$mid)+df3$x
df3$labely= (df3$radius)*cos(df3$mid)+df3$y
} else{
df3$radius=(r1+r2)/2
if(explodeDonut) df3$radius[df3$focus!=0]=df3$radius[df3$focus!=0]+df3$focus[df3$focus!=0]
df3$labelx=df3$radius*sin(df3$mid)+df3$x
df3$labely=df3$radius*cos(df3$mid)+df3$y
}
df3$segx[df3$ratio1==0]=0
df3$segxend[df3$ratio1==0]=0
df3$segy[df3$ratio1==0]=0
df3$segyend[df3$ratio1==0]=0
if(labelposition==0){
df3$segx[df3$ratio1<showRatioThreshold]=0
df3$segxend[df3$ratio1<showRatioThreshold]=0
df3$segy[df3$ratio1<showRatioThreshold]=0
df3$segyend[df3$ratio1<showRatioThreshold]=0
}
df3
del=which(df3$Freq==0)
del
if(length(del)>0) subColor<-subColor[-del]
subColor
}
p <- ggplot() + theme_no_axes() + coord_fixed()
if(is.null(maxx)) {
r3=r2+0.3
} else{
r3=maxx
}
p1<-p + geom_arc_bar(aes_string(x0 = "x", y0 = "y",
r0 = as.character(r0), r = as.character(r1),
start="start1",end="end1",
fill = pies),alpha=pieAlpha,color=color,
data = df)+transparent()+
scale_fill_manual(values=mainCol)+
xlim(r3*c(-1,1))+ylim(r3*c(-1,1))+guides(fill=FALSE)
if((labelposition==1)&(is.null(donuts))){
p1<-p1+ geom_segment(aes_string(x="segx",y="segy",
xend="segxend",yend="segyend"),data=df)+
geom_text(aes_string(x="segxend",y="segyend",label="label",hjust="hjust",vjust="vjust"),size=pieLabelSize,data=df,family=family)
} else if((labelposition==2)&(is.null(donuts))){
p1<-p1+ geom_segment(aes_string(x="segx",y="segy",
xend="segxend",yend="segyend"),data=df[df$ratio<labelpositionThreshold,])+
geom_text(aes_string(x="segxend",y="segyend",label="label",hjust="hjust",vjust="vjust"),size=pieLabelSize,data=df[df$ratio<labelpositionThreshold,],family=family)+
geom_text(aes_string(x="labelx",y="labely",label="label"),size=pieLabelSize,data=df[df$ratio>=labelpositionThreshold,],family=family)
} else{
p1 <-p1+geom_text(aes_string(x="labelx",y="labely",label="label"),size=pieLabelSize,data=df,family=family)
}
if(showPieName) p1<-p1+annotate("text",x=0,y=0,label=pies,size=titlesize,family=family)
p1<-p1+theme(text=element_text(family=family))
if(!is.null(donuts)){
# donutAlpha=1.0;color="white"
# explodeDonut=FALSE
if(explodeDonut) {
p3<-p+geom_arc_bar(aes_string(x0 = "x", y0 = "y", r0 = as.character(r1),
r = as.character(r2), start="start1",end="end1",
fill = "no",explode="focus"),alpha=donutAlpha,color=color,
data = df3)
} else{
p3<-p+geom_arc_bar(aes_string(x0 = "x", y0 = "y", r0 = as.character(r1),
r = as.character(r2), start="start1",end="end1",
fill = "no"),alpha=donutAlpha,color=color,
data = df3)
}
p3<-p3+transparent()+
scale_fill_manual(values=subColor)+
xlim(r3*c(-1,1))+ylim(r3*c(-1,1))+guides(fill=FALSE)
p3
if(labelposition==1){
p3<-p3+ geom_segment(aes_string(x="segx",y="segy",
xend="segxend",yend="segyend"),data=df3)+
geom_text(aes_string(x="segxend",y="segyend",
label="label",hjust="hjust",vjust="vjust"),size=donutLabelSize,data=df3,family=family)
} else if(labelposition==0){
p3<-p3+geom_text(aes_string(x="labelx",y="labely",
label="label"),size=donutLabelSize,data=df3,family=family)
} else{
p3<-p3+ geom_segment(aes_string(x="segx",y="segy",
xend="segxend",yend="segyend"),data=df3[df3$ratio1<labelpositionThreshold,])+
geom_text(aes_string(x="segxend",y="segyend",
label="label",hjust="hjust",vjust="vjust"),size=donutLabelSize,data=df3[df3$ratio1<labelpositionThreshold,],family=family)+
geom_text(aes_string(x="labelx",y="labely",
label="label"),size=donutLabelSize,data=df3[df3$ratio1>=labelpositionThreshold,],family=family)
}
if(!is.null(title)) p3<-p3+annotate("text",x=0,y=r3,label=title,size=titlesize,family=family)
else if(showDonutName) p3<-p3+annotate("text",x=(-1)*r3,y=r3,label=donuts,hjust=0,size=titlesize,family=family)
p3<-p3+theme(text=element_text(family=family))
grid.newpage()
print(p1,vp=viewport(height=1,width=1))
print(p3,vp=viewport(height=1,width=1))
}
else{
p1
}
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/PieDonut.R
|
#' Extract categorical variables
#' @param df a data.frame
#' @param max.ylev maximal length of unique values of catergorical variables
#' @export
GroupVar=function(df,max.ylev=20){
result=c()
for(i in 1:ncol(df)){
if(length(unique(df[[i]]))<=max.ylev) result=c(result,colnames(df)[i])
}
result
}
#' Extract continuous variables
#' @param df a data.frame
#' @export
ContinuousVar=function(df){
result=c()
for(i in 1:ncol(df)){
if(is.numeric(df[[i]])) result=c(result,colnames(df)[i])
}
result
}
#' Extract bivariate variables
#' @param df a data.frame
#' @export
BiVar=function(df){
result=c()
for(i in 1:ncol(df)){
if(length(unique(df[[i]]))==2) result=c(result,colnames(df)[i])
}
result
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/cleaning.R
|
#' Cox-Stuart test for trend analysis
#' The Cox-Stuart test is defined as a little powerful test (power equal to 0.78), but very robust for the trend analysis.
#' It is therefore applicable to a wide variety of situations, to get an idea of the evolution of values obtained.
#' The proposed method is based on the binomial distribution.
#' This function was written by Tommaso Martino<todoslogos@@gmail.com> (See 'References')
#'
#' @param x A numeric vector
#' @return A list with class "htest"
#' @references Original code: \url{http://statistic-on-air.blogspot.kr/2009/08/trend-analysis-with-cox-stuart-test-in.html}
#' @examples
#' customers = c(5, 9, 12, 18, 17, 16, 19, 20, 4, 3, 18, 16, 17, 15, 14)
#' cox.stuart.test(customers)
#' @importFrom stats pbinom
#' @export
cox.stuart.test = function(x) {
method = "Cox-Stuart test for trend analysis"
leng = length(x)
apross = round(leng)%%2
if (apross == 1) {
delete = (length(x) + 1)/2
x = x[-delete]
}
half = length(x)/2
x1 = x[1:half]
x2 = x[(half + 1):(length(x))]
difference = x1 - x2
signs = sign(difference)
signcorr = signs[signs != 0]
pos = signs[signs > 0]
neg = signs[signs < 0]
if (length(pos) < length(neg)) {
prop = pbinom(length(pos), length(signcorr), 0.5)
names(prop) = "Increasing trend, p-value"
rval <- list(method = method, statistic = prop)
class(rval) = "htest"
return(rval)
} else {
prop = pbinom(length(neg), length(signcorr), 0.5)
names(prop) = "Decreasing trend, p-value"
rval <- list(method = method, statistic = prop)
class(rval) = "htest"
return(rval)
}
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/cox.stuart.test.R
|
#' Make table summarizing frequency
#' @param x A vector
#' @param digits integer indicating the number of decimal places
#' @param lang Language. choices are one of c("en","kor")
#' @export
#' @importFrom sjlabelled get_labels
#' @importFrom stats addmargins
#' @examples
#' require(moonBook)
#' freqSummary(acs$Dx)
#' #freqSummary(acs$smoking,lang="kor")
freqSummary=function(x,digits=1,lang="en"){
if(sum(is.na(x))==0){
# (x=to_label(x))
(res=table(x))
(labels=get_labels(x,attr.only=TRUE))
if(!is.null(labels)) {
#str(labels)
if(length(rownames(res))==length(labels)) {
if(!all(rownames(res) %in% labels)){
rownames(res)=labels
}
} else{
for(i in 1:length(rownames(res))){
rownames(res)[i]=labels[as.numeric(rownames(res)[i])]
}
}
}
res
(res1=prop.table(res)*100)
(result=cbind(res,res1,res1))
(result=addmargins(result,1))
res2=cumsum(res1)
res2=c(res2,NA)
(result=cbind(result,res2))
result2=result[,1]
for(i in (2:4)) {
format=paste0("%0.",digits,"f")
temp=sprintf(format,result[,i])
result2=cbind(result2,temp)
}
result2[result2=="NA"]=""
} else {
res=table(x)
res
# if(!is.null(names(attr(x,"labels")))) rownames(res)=names(attr(x,"labels"))
# if(!is.null(names(attr(x,"value.labels")))) rownames(res)=names(attr(x,"value.labels"))
(labels=get_labels(x,attr.only=TRUE))
if(!is.null(labels)) {
rownames(res)
#str(labels)
if(length(rownames(res))==length(labels)) {
rownames(res)=labels
} else{
for(i in 1:length(rownames(res))){
rownames(res)[i]=labels[as.numeric(rownames(res)[i])]
}
}
}
res
res1=c(res,sum(is.na(x)))
res1
names(res1)[length(res1)]=langchoice1(1,lang)
res2=prop.table(res1)*100
result=cbind(res1,res2)
result=addmargins(result,1)
res3=prop.table(table(x))*100
res3=c(res3,NA,sum(res3))
res4=cumsum(res3)
result=cbind(result,res3,res4)
result2=result[,1]
for(i in (2:4)) {
format=paste0("%0.",digits,"f")
temp=sprintf(format,result[,i])
result2=cbind(result2,temp)
}
result2[result2=="NA"]=""
rownames(result2)[nrow(result2)-1]<-langchoice1(1,lang)
result2
}
colnames(result2)=langchoice1(2:5,lang=lang)
rownames(result2)[nrow(result2)]=langchoice1(6,lang=lang)
result2
}
#' Make flextable summarizing frequency
#' @param x A vector
#' @param digits integer indicating the number of decimal places
#' @param lang Language. choices are one of c("en","kor")
#' @param vanilla Logical. Whether make vanilla table or not
#' @param ... Further arguments to paseed to the df2flextable function
#' @return An object of clss flextable
#' @export
#' @importFrom rrtable df2flextable
#' @importFrom flextable color autofit
#' @importFrom magrittr '%>%'
#' @examples
#' require(moonBook)
#' freqTable(acs$Dx)
#' #freqTable(acs$smoking,lang="kor",vanilla=TRUE,fontsize=12)
freqTable=function(x,digits=1,lang=getOption("freqTable.lang","en"),vanilla=FALSE,...){
res=freqSummary(x,digits=digits,lang=lang)
tempname=colnames(res)
res=data.frame(res,stringsAsFactors=FALSE)
colnames(res)=tempname
result<-rrtable::df2flextable(res,add.rownames=TRUE,vanilla=vanilla,...) %>% autofit()
if(vanilla) {
result<- result %>% color(i=1,j=1,color="white",part="header")
} else {
result<- result %>% color(i=1,j=1,color="#007FA6",part="header")
}
result
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/freqTable.R
|
#' Numerical Summary
#' @param x A numeric vector or a data.frame or a grouped_df
#' @param digits integer indicating the number of decimal places
#' @param lang Language. choices are one of c("en","kor")
#' @param ... further arguments to be passed
#' @export
#' @examples
#' require(moonBook)
#' require(magrittr)
#' require(dplyr)
#' require(rrtable)
#' require(webr)
#' require(tibble)
#' numSummary(acs)
#' numSummary(acs$age)
#' numSummary(acs,age,EF)
#' acs %>% group_by(sex) %>% numSummary(age,BMI)
#' acs %>% group_by(sex) %>% select(age) %>% numSummary
#' acs %>% group_by(sex) %>% select(age,EF) %>% numSummary
#' acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummary
#' acs %>% group_by(sex,Dx) %>% select(age) %>% numSummary
#' #acs %>% group_by(sex,Dx) %>% numSummary(age,EF,lang="kor")
numSummary <- function(x,...,digits=2,lang="en") {
if("grouped_df" %in% class(x)) {
numSummary2(x,...,digits=digits,lang=lang)
} else{
numSummary1(x,...,digits=digits,lang=lang)
}
}
#'@describeIn numSummary Numerical Summary of a data.frame or a vector
#'@importFrom psych describe
#'@importFrom tibble as_tibble
#'@importFrom dplyr enexprs
numSummary1 <- function(x,...,digits=2,lang="en"){
if('data.frame' %in% class(x)) {
vars=enexprs(...)
if(length(vars)>0) x<-x %>% select(...)
select=sapply(x,is.numeric)
x=x[select]
if(ncol(x)==1) x=x[[1]]
}
result=psych::describe(x)
if('data.frame' %in% class(x)) {
result$vars=rownames(result)
} else{
result$vars=NULL
}
if(digits!=2) result=print(result,digits=digits)
if(lang=="kor"){
if('data.frame' %in% class(x)) {
colnames(result)=c(langchoice1(21,lang=lang),"n",langchoice1(7:17,lang=lang))
} else{
colnames(result)=c("n",langchoice1(7:17,lang=lang))
}
}
as_tibble(result)
}
#' @describeIn numSummary Numerical Summary of a grouped_df
#' @importFrom rlang quos
#' @importFrom tidyr nest unnest
#' @importFrom purrr map
#' @importFrom dplyr mutate select
numSummary2 <- function(x,...,digits=2,lang="en") {
temp="mutate(x,summary=map(data,numSummary1,...,digits=digits,lang=lang))"
x<-x %>% nest()
eval(parse(text=temp)) %>%
select(-c('data')) %>%
unnest()
}
#' Make a table showing numerical summary
#' @param x A grouped_df or a data.frame or a vector
#' @param ... further argument to be passed
#' @param lang Language. choices are one of c("en","kor")
#' @param vanilla Logical. Whether make vanilla table or not
#' @param add.rownames Logical. Whether or not add rownames
#' @export
#' @examples
#' require(moonBook)
#' require(dplyr)
#' numSummaryTable(acs)
#' numSummaryTable(acs$age)
#' acs %>% group_by(sex) %>% select(age) %>% numSummaryTable
#' acs %>% group_by(sex) %>% select(age,EF) %>% numSummaryTable
#' acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummaryTable(vanilla=FALSE)
#' acs %>% group_by(sex,Dx) %>% numSummaryTable(age,EF,add.rownames=FALSE)
numSummaryTable <- function(x,...,lang=getOption("numSummaryTable.lang","en"),vanilla=FALSE,add.rownames=NULL){
result=numSummary(x,lang=lang,...)
if(is.null(add.rownames)){
add.rownames=FALSE
if("data.frame" %in% class(x)) add.rownames=TRUE
if("tibble" %in% class(x)) add.rownames=TRUE
if("grouped_df" %in% class(x)) add.rownames=FALSE
}
df2flextable(result,add.rownames=add.rownames,vanilla=vanilla)
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/numSummary.R
|
require(ggplot2)
#' Plotting distribution of statistic for object "htest"
#'
#' @param x object of class "htest"
#' @param ... further arguments to ggplot
#' @importFrom ggplot2 ggplot geom_point geom_line theme_bw annotate aes aes_string geom_area labs theme element_text
#' @importFrom stringr str_pad str_c
#' @export
#' @return a ggplot or NULL
#'
#' @examples
#'
#' require(moonBook)
#' require(webr)
#' ## chi-square test
#' x=chisq.test(table(mtcars$am,mtcars$cyl))
#' plot(x)
#'
#' #Welch Two Sample t-test
#' x=t.test(mpg~am,data=mtcars)
#' plot(x)
#'\donttest{
#' x=t.test(BMI~sex,data=acs)
#' plot(x)
#'
#' # F test to compare two variances
#' x=var.test(age~sex,data=acs,alternative="less")
#' plot(x)
#'
#' # Paired t-test
#' x=t.test(iris$Sepal.Length,iris$Sepal.Width,paired=TRUE)
#' plot(x)
#'
#' # One sample t-test
#' plot(t.test(acs$age,mu=63))
#'
#' # Two sample t-test
#' x=t.test(age~sex, data=acs,conf.level=0.99,alternative="greater",var.equal=TRUE)
#' plot(x)
#' }
plot.htest=function(x,...){
tests=c("Welch Two Sample t-test","Pearson's Chi-squared test"," Two Sample t-test","Pearson's Chi-squared test with Yates' continuity correction",
"One Sample t-test","F test to compare two variances","Paired t-test")
if(!(x$method %in% tests)) {
cat("Currently, ",x$method," is not supported")
return(invisible(0))
}
(degf=x[[2]])
statName=tolower(attr(x$statistic,"names"))
statName
if(statName=="x-squared") {
statName<-"chisq"
alternative<-"greater"
alpha<-0.05
} else{
if(statName=="w") {
statName<-"wilcox"
alpha=0.05
} else{
alpha=1-attr(x$conf.int,"conf.level")
}
alternative<-x$alternative
}
(newalpha=alpha)
if(alternative=="two.sided") newalpha=alpha/2
qF=function(...){
eval(parse(text=paste0("q",statName,"(...)")))
}
dF=function(...){
eval(parse(text=paste0("d",statName,"(...)")))
}
if(statName=="chisq"){
x0 <- seq(0,qF(p=0.999,df=degf),length=100)
y0=dF(x0,df=degf)
x1=seq(qF(p=1-newalpha,df=degf),qF(p=0.999,df=degf),length=50)
y1=dF(x1,df=degf)
} else if(statName %in% c("f","wilcox")){
x0 <- seq(qF(p=0.0001,degf[1],degf[2]),qF(p=0.9999,degf[1],degf[2]),length=100)
y0=dF(x0,degf[1],degf[2])
x2=seq(qF(p=0.0001,degf[1],degf[2]),qF(p=newalpha,degf[1],degf[2]),length=50)
y2=dF(x2,degf[1],degf[2])
x1=seq(qF(p=1-newalpha,degf[1],degf[2]),qF(p=0.9999,degf[1],degf[2]),length=50)
y1=dF(x1,degf[1],degf[2])
} else{
x0 <- seq(-4,4,length=100)
if(x[[1]]>4) {
x0=c(x0,x[[1]])
} else if(x[[1]] < -4) {
x0=c(x[[1]],x0)
}
x0
y0=dF(x0,df=degf)
y0
x1=seq(qF(p=1-newalpha,df=degf),4,length=50)
y1=dF(x1,df=degf)
x2=seq(-4,qF(p=newalpha,df=degf),length=50)
y2=dF(x2,df=degf)
}
data=data.frame(x=x0,y=y0)
data
data1=data.frame(x=x1,y1=y1)
if(statName!="chisq") data2=data.frame(x=x2,y1=y2)
x
label=paste0(sprintf("%9s",attr(x$statistic,"names"))," = ",
sprintf("%.03f",x$statistic))
if(length(degf)==2) {
label=c(label,paste0("num df=",degf[1],", denom df=",degf[2]))
} else {
label=c(label,paste0(sprintf("%9s","df")," = ",sprintf("%.2f",degf)))
}
if(x[[3]]>=0.00001) {
label=c(label,paste0(sprintf("%9s","p")," = ",sprintf("%.5f",x[[3]])))
} else {
label=c(label,paste0(sprintf("%9s","p")," < 0.00001"))
}
label=stringr::str_pad(label,19,side="right")
label=stringr::str_c(label,collapse="\n")
label
p2<-ggplot(data,aes_string(x="x",y="y"))+geom_line()+theme_bw()
if(alternative!="less") p2<-p2+geom_area(data=data1,aes(x1,y1),fill="red",alpha=0.5)
if(alternative!="greater") p2<-p2+ geom_area(data=data2,aes(x2,y2),fill="red",alpha=0.5)
p2
if(abs(x$statistic)>4) {
hjust=1
} else if(x$statistic>0) {
hjust=-0.1
} else hjust=0.1
if(statName %in% c("f","wilcox")) {
ypoint=dF(x$statistic,degf[1],degf[2])
xpoint=qF(p=1-newalpha,degf[1],degf[2])
xpoint2=qF(p=newalpha,degf[1],degf[2])
} else {
ypoint=dF(x$statistic,df=degf)
ypoint
xpoint=qF(p=1-newalpha,df=degf)
xpoint2=qF(p=newalpha,df=degf)
}
p2<-p2+geom_point(x=x[[1]],y=ypoint,color="blue")
p2<-p2+ annotate(geom="label",x=Inf,y=Inf,label=label,vjust=1.1,hjust=1.1)
# geom_text(x=xpoint2,y=0.38,label=label)+
#
p2 <-p2+ annotate(geom="text",x=ifelse(alternative=="less",xpoint2,xpoint),y=0,
label=paste0("p < ",alpha),vjust=1.5,color="red")
p2<-p2+labs(title=x$method,x=paste0(statName," statistic"),y="Probability Density")+theme(plot.title=element_text(hjust=0.5))
sub=makeSub(x)
if(sub!="") p2<-p2+labs(subtitle=sub)
p2
}
#' Make subtitle
#'
#' @param x An object of class "htest"
#'
makeSub=function(x){
sub=""
if (!is.null(x$alternative)) {
sub="alternative hypothesis: "
if (!is.null(x$null.value)) {
if (length(x$null.value) == 1L) {
alt.char <- switch(x$alternative, two.sided = "not equal to",
less = "less than", greater = "greater than")
sub=paste(sub,"true ", names(x$null.value), " is ", alt.char,
" ", x$null.value, sep = "")
}
else {
sub=paste(sub,x$alternative, "\nnull values:\n", sep = "")
sub=paste0(sub,x$null.value)
}
}
}
sub
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/plot.htest.R
|
#' Renew dictionary
renew_dic=function(){
#' Renew dictionary
# dicTable=rio::import("./R/sysdata.rda")
# result=editData::editData(dicTable)
# result
# dicTable<-result
#
# devtools::use_data(dicTable,internal=TRUE,overwrite=TRUE)
}
#' Select word
#' @param id data id
#' @param lang language. Possible choices are c("en","kor")
#' @export
langchoice1=function(id,lang="en"){
temp=dicTable[as.numeric(dicTable$id) %in% id,]
if(lang=="en"){
result=temp$en
} else{
result=temp$kor
}
result
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/renew_dic.R
|
#' Runs test for randomness
#' @param y A vector
#' @param plot.it A logical. whether or not draw a plot
#' @param alternative a character string specifying the alternative hypothesis, must be one of "two.sided" (default), "greater" or "less".
#' @return A list with class "htest" containing the following components: statistic,p-value,method and data.name
#' @importFrom stats median na.omit pnorm
#' @importFrom graphics abline plot points
#' @export
#' @examples
#' y=c(1,2,2,1,1,2,1,2)
#' runs.test(y)
#' y=c("A","B","B","A","A","B","A","B")
#' runs.test(y,alternative="p")
runs.test=function (y, plot.it = FALSE, alternative = c("two.sided", "positive.correlated",
"negative.correlated"))
{
if(!is.numeric(y)){
if(is.factor(y)) y=as.numeric(y)
else y=as.numeric(factor(y))
}
alternative <- match.arg(alternative)
DNAME = deparse(substitute(y))
y <- na.omit(y)
med <- median(y, na.rm = TRUE)
for (k in 2:length(y)) {
if ((y[k] == med) & (y[k - 1] < med)) {
y[k] = y[k - 1]
}
else if ((y[k] == med) & (y[k - 1] > med)) {
y[k] = y[k - 1]
}
}
q <- rep(0.05, length(y))
p <- rep(-0.05, length(y))
d <- y
q[I(d < med) | I(d == med)] <- NA
p[I(d >= med)] <- NA
if (plot.it) {
plot(q, type = "p", pch = "A", col = "red", ylim = c(-0.5,
0.5), xlim = c(1, length(y)), xlab = "", ylab = "")
points(p, pch = "B", col = "blue")
abline(h = 0)
}
m <- length(na.omit(q))
n <- length(na.omit(p))
R <- 1
s <- sign(y - med)
for (k in 1:(length(y) - 1)) {
if (s[k] != s[k + 1]) {
R <- R + 1
}
}
E <- 1 + 2 * n * m/(n + m)
s2 <- (2 * n * m * (2 * n * m - n - m))/((n + m)^2 * (n +
m - 1))
statistic <- (R - E)/sqrt(s2)
if (alternative == "positive.correlated") {
p.value = pnorm(statistic)
METHOD = "Runs Test - Positive Correlated"
}
else if (alternative == "negative.correlated") {
p.value = 1 - pnorm(statistic)
METHOD = "Runs Test - Negative Correlated"
}
else {
p.value = 2 * min(pnorm(statistic), 1 - pnorm(statistic))
alternative = "two.sided"
METHOD = "Runs Test - Two sided"
}
STATISTIC = statistic
names(STATISTIC) = "Standardized Runs Statistic"
structure(list(statistic = STATISTIC, p.value = p.value,
method = METHOD, data.name = DNAME), class = "htest")
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/runs.test.R
|
#' My chisquare test
#' @param x a table
#' @importFrom stats chisq.test fisher.test
mychisq.test=function(x){
result=tryCatch(chisq.test(x),warning=function(w) return("warnings present"))
if(class(result)!="htest"){
result1=tryCatch(fisher.test(x),
error=function(e) return("error present"),
warning=function(w) return("warning present"),
message = function(c) "message")
if(class(result1)=="htest") result<-result1
}
result
}
#' Extract labels
#' @param x a vector
extractLabels=function(x){
result=NULL
if(!is.null(names(attr(x,"labels")))) result=names(attr(x,"labels"))
if(!is.null(names(attr(x,"value.labels")))) result=names(attr(x,"value.labels"))
#if(is.null(result)) result=as.character(unique(x))
result
}
#' Extract x2 statistical result
#' @param x a table
#' @importFrom vcd assocstats
x2result=function(x){
warning=0
(result=mychisq.test(x))
(result1=chisq.test(x))
if(class(result)!="htest") {
result=result1
warning=1
}
cramer=vcd::assocstats(x)$cramer
statresult=paste0("Chi-squared=",round(result1$statistic,3),", df=",result1$parameter)
statresult=paste0(statresult,", Cramer\'s V=",round(cramer,3))
if(substr(result$method,1,6)=="Fisher") {
statresult=paste0(statresult,", Fisher's p")
} else {
statresult=paste0(statresult,", Chi-squared p")
}
pvalue=ifelse(result$p.value>=0.001,paste0("=",round(result$p.value,4)),"< 0.001")
statresult=paste0(statresult,pvalue)
if(warning==1) statresult=paste0(statresult,"; approximation may be incorrect")
statresult
}
#' Summarize chisquare result
#' @param data A data.frame
#' @param x a column name
#' @param y a column name
#' @param a a vector
#' @param b a vector
#' @param margin numeric If 1 row percent, if 2 col percent
#' @param show.percent logical
#' @param show.label logical
#' @export
#' @examples
#' require(moonBook)
#' x2summary(acs,sex,DM)
x2summary=function(data=NULL,x=NULL,y=NULL,a,b,margin=1,show.percent=TRUE,show.label=TRUE){
# data=acs;x=sex;y=DM
# margin=1;show.percent=TRUE;show.label=TRUE
if(!is.null(data)){
x=substitute(x)
y=as.character(substitute(y))
a=data[[x]]
b=data[[y]]
}
x=table(a,b)
# str(x)
# (labela=attr(a,"label"))
# (labelb=attr(b,"label"))
labela=sjlabelled::get_label(a)
labelb=sjlabelled::get_label(b)
ncolb=ncol(x)
x=addmargins(x,margin)
x
x1=scales::percent(round(t(apply(x,margin,function(a) a/sum(a))),3))
if(margin==2) x1=matrix(x1,nrow=nrow(x),byrow=TRUE)
if(show.percent) {
x3=paste0(x,"\n(",x1,")")
} else{
x3<-x
}
if(margin==1){
x2=matrix(x3,ncol=ncol(x))
rowcol=rowSums(x)
if(show.percent) rowcol=paste0(rowcol,"\n(100 %)")
x2=cbind(x2,Total=rowcol)
} else{
x2=matrix(x3,nrow=nrow(x))
colrow=colSums(x)
if(show.percent) colrow=paste0(colrow,"\n(100 %)")
x2=rbind(x2,Total=colrow)
}
x2
x
colnames(x)
labels=extractLabels(b)
labels
if(!is.null(labels)) {
colnames(x)
#str(labels)
if(length(colnames(x))==length(labels)+1) {
colnames(x)=c(labels,"total")
} else{
if(margin==2){
for(i in 1:(length(colnames(x))-1)){
colnames(x)[i]=labels[as.numeric(colnames(x)[i])]
}
} else{
for(i in 1:(length(colnames(x)))){
colnames(x)[i]=labels[as.numeric(colnames(x)[i])]
}
}
}
}
if(is.null(labels)) {
if(margin==1) {
colnames(x2)=c(colnames(x),"Total")
} else{
colnames(x2)=c(colnames(x)[1:(ncol(x)-1)],"Total")
}
} else if(ncol(x2)==length(labels)+1){
colnames(x2)=c(labels,"Total")
} else{
if(margin==1) {
colnames(x2)=c(colnames(x),"Total")
} else{
colnames(x2)=c(colnames(x)[1:(ncol(x)-1)],"Total")
}
}
x2
labels=extractLabels(a)
rownames(x2)
nrow(x2)
rownames(x)
if(!is.null(labels)) {
colnames(x)
#str(labels)
if(length(rownames(x))==length(labels)+1) {
rownames(x)=c(labels,"total")
} else{
if(margin==1){
for(i in 1:(length(rownames(x))-1)){
rownames(x)[i]=labels[as.numeric(rownames(x)[i])]
}
} else{
for(i in 1:(length(colnames(x)))){
rownames(x)[i]=labels[as.numeric(rownames(x)[i])]
}
}
}
}
if(is.null(labels)) {
if(margin==2){
rownames(x2)=c(rownames(x),"Total")
} else{
rownames(x2)=c(rownames(x)[1:(nrow(x)-1)],"Total")
}
} else if(nrow(x2)==length(labels)+1){
rownames(x2)=c(labels,"Total")
} else{
if(margin==2) {
rownames(x2)=c(rownames(x),"Total")
} else{
rownames(x2)=c(rownames(x)[1:(nrow(x)-1)],"Total")
}
}
# else {
# rownames(x2)=c(temp,"Total")
# }
x2
as.data.frame(x2)
}
#' Make a chisquare result table
#' @param data A data.frame
#' @param x a column name
#' @param y a column name
#' @param margin numeric If 1 row percent, if 2 col percent
#' @param show.percent logical
#' @param show.label logical
#' @param show.stat logical
#' @param vanilla logical whether or not make vanilla table
#' @param fontsize A numeric
#' @param ... Further arguments to be passed to df2flextable()
#' @importFrom rrtable df2flextable
#' @importFrom flextable align add_footer merge_at italic autofit
#' @export
#' @examples
#' require(moonBook)
#' x2Table(acs,sex,DM)
x2Table=function(data,x,y,margin=1,show.percent=TRUE,show.label=TRUE,
show.stat=TRUE,vanilla=FALSE,fontsize=12,...){
# data=acs;x=sex;y=DM;margin=1;show.percent=TRUE;show.label=TRUE;
# show.stat=TRUE;vanilla=FALSE;fontsize=12
x=substitute(x)
y=as.character(substitute(y))
a=data[[x]]
b=data[[y]]
x2=x2summary(a=a,b=b,margin=margin,show.percent=show.percent,show.label=show.label)
MyTable=rrtable::df2flextable(x2,add.rownames = TRUE,vanilla=vanilla,fontsize=fontsize,digits=0,...) %>%
flextable::align(j=1,align='center',part='body') %>%
flextable::align(i=1,align='center',part='header')
if(show.stat){
x=table(a,b)
statresult=x2result(x)
MyTable<- MyTable %>%
flextable::add_footer(rowname=statresult) %>%
flextable::merge_at(j=1:(ncol(x2)+1),part="footer") %>%
flextable::italic(j=1:(ncol(x2)+1),part="footer") %>%
flextable::align(align='right',part='footer') %>%
flextable::autofit()
}
color=ifelse(vanilla,"white","#5B7778")
MyTable<- MyTable %>% flextable::color(color=color,i=1,j=1,part='header')
MyTable$header$dataset[1]<-y
MyTable
}
|
/scratch/gouwar.j/cran-all/cranData/webr/R/x2Table.R
|
---
title: "Pie Chart Revisited"
author: "Keon-Woong Moon"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Vignette Title}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE,comment = NA,warning=FALSE,fig.width=6,fig.height = 6, fig.align='center',out.width="70%")
```
A pie chart (or a circle chart) is a circular statistical graphic which is divided into slices to illustrate numerical proportion. In a pie chart, the arc length of each slice (and consequently its central angle and area), is proportional to the quantity it represents. While it is named for its resemblance to a pie which has been sliced, there are variations on the way it can be presented. A doughnut chart (also spelled donut) is a variant of the pie chart, with a blank center allowing for additional information about the data as a whole to be included. I recently developed a function named "PieDonut" to combine pie and donut chart.
## Installation of packages
You have to install the latest versions of "webr" and "moonBook" packages from github. The CRAN version does not have PieDonut() function.
```{r,eval=FALSE}
if(!require(devtools)) install.packages("devtools")
devtools::install_github("cardiomoon/moonBook")
devtools::install_github("cardiomoon/webr")
```
## Load packages
```{r,message=FALSE}
require(ggplot2)
require(moonBook)
require(webr)
```
## Basic Use
The acs data included in package moonBook is demographic and laboratory data of 857 patients with acute coronary syndrome(ACS). If you want to show the distribution of smoking status according to diagnosis, make the PieDonut Plot with the following code.
```{r}
PieDonut(acs,aes(pies=Dx,donuts=smoking))
```
## Label position
By default, the labelposition argument is 2 - labels for doughnuts are located outside if the percentage of total is less than 10 % (labelpositionThreshold=0.1 by default).
```{r}
PieDonut(acs,aes(Dx,smoking),ratioByGroup=FALSE)
```
If you want to place the labels for donuts inside, set the labelposition argument 0. To place all labels outside, set the labelposition argument 1.
```{r,fig.show='hold',out.width='45%',fig.align='default'}
PieDonut(acs,aes(Dx,smoking),selected=1,labelposition=0,title="labelposition=0")
PieDonut(acs,aes(Dx,smoking),selected=1,labelposition=1,title="labelposition=1")
```
## Explode Pie
```{r}
PieDonut(acs,aes(Dx,smoking),explode=1)
```
## Explode Pie and Donuts
```{r}
PieDonut(acs,aes(Dx,smoking),explode=1,explodeDonut=TRUE)
```
## Explode Pie and Donuts independently
```{r}
PieDonut(acs,aes(Dx,smoking),explode=1,selected=c(3,6,9),explodeDonut=TRUE)
```
## Customize start angle
```{r}
PieDonut(acs,aes(Dx,smoking),start=3*pi/2,explode=1,selected=c(3,6,9),explodeDonut=TRUE)
```
## Add title
```{r}
PieDonut(acs,aes(Dx,smoking),start=3*pi/2,explode=1,selected=c(3,6,9),explodeDonut=TRUE,title="Distribution of Smoking Status by Diagnosis")
```
## Adjust the radius
You can adjust the radius of pie and donut plot with r0, r1 and r2 arguments. If you want to show exact pie(withoue a center hole), set the r0 argument '0' and showPieName FALSE.
```{r}
PieDonut(acs,aes(Dx,smoking),r0=0,showPieName=FALSE)
```
You can adjust the radius of pie(r1, default value 1) and radius doughnut(r2, default value 1.2). You can make smaller pies and larger doughnuts with the following codes.
```{r}
PieDonut(acs,aes(Dx,smoking),r0=0.2,r1=0.8,r2=1.4,explode=1,start=pi/2,explodeDonut=TRUE)
```
## Show Ratio by group
By Default, the ratio of donuts are percentage by group. If you want to show percentage of total, set the ratioByGroup argument FALSE.
```{r}
PieDonut(acs,aes(Dx,smoking),ratioByGroup=FALSE)
```
## Doughnut plot
If you want to show donut plot(without pie), please use the followng code.
```{r,fig.show='hold',out.width='45%',fig.align='default'}
browser=c("MSIE","Firefox","Chrome","Safari","Opera")
share=c(50,21.9,10.8,6.5,1.8)
df=data.frame(browser,share)
PieDonut(df,aes(browser,count=share),r0=0.7,start=3*pi/2,labelpositionThreshold=0.1)
PieDonut(df,aes(browser,count=share),r0=0.7,explode=c(1,4),start=3*pi/2)
```
## Summarized Data
If you have summarized data, please map the count variable to count.
```{r,message=FALSE}
require(dplyr)
df=mtcars %>% group_by(gear,carb) %>% summarize(n=n())
df
```
```{r}
PieDonut(df,aes(gear,carb,count=n),explode=3,r1=0.9,explodeDonut=TRUE,title="Distribution of carburetors by gears",star=3*pi/2,labelposition=0)
```
This plot is identical with the following plot.
```{r}
PieDonut(mtcars,aes(gear,carb),explode=3,r1=0.9,explodeDonut=TRUE,title="Distribution of carburetors by gears",star=3*pi/2,labelposition=0)
```
|
/scratch/gouwar.j/cran-all/cranData/webr/inst/PieDonut/PieDonut.Rmd
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(echo = TRUE,comment = NA,message=FALSE,warning=FALSE,fig.width=6,fig.height = 6, fig.align='center',out.width="70%")
## ----eval=FALSE---------------------------------------------------------------
# if(!require(devtools)) install.packages("devtools")
# devtools::install_github("cardiomoon/webr")
# devtools::install_github("cardiomoon/moonBook") # For examples
# devtools::install_github("cardiomoon/rrtable") # For reproducible research
## ----message=FALSE------------------------------------------------------------
require(webr)
require(moonBook) # For data acs
## -----------------------------------------------------------------------------
freqSummary(acs$Dx)
freqTable(acs$Dx)
## -----------------------------------------------------------------------------
result=freqTable(acs$Dx)
class(result)
## -----------------------------------------------------------------------------
freqTable(mtcars$mpg)
## -----------------------------------------------------------------------------
x2Table(acs,Dx,sex)
## -----------------------------------------------------------------------------
x2Table(acs,Dx,sex,margin=2)
## -----------------------------------------------------------------------------
x2Table(acs,Dx,sex,show.percent=FALSE)
## ----message=FALSE------------------------------------------------------------
require(dplyr)
numSummary(acs$age)
numSummaryTable(acs$age)
## -----------------------------------------------------------------------------
numSummary(acs)
numSummaryTable(acs)
## -----------------------------------------------------------------------------
acs %>% select(age,EF) %>% numSummary
acs %>% select(age,EF) %>% numSummaryTable
## -----------------------------------------------------------------------------
acs %>% group_by(sex) %>% select(age,EF) %>% numSummary
acs %>% group_by(sex) %>% select(age,EF) %>% numSummaryTable
## -----------------------------------------------------------------------------
acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummary
acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummaryTable
## -----------------------------------------------------------------------------
require(rrtable)
type=c("table","table")
title=c("Frequency Table","Numerical Summary")
code=c("freqTable(acs$Dx)","acs %>% group_by(sex) %>% select(EF,age) %>% numSummaryTable")
data=data.frame(type,title,code,stringsAsFactors = FALSE)
data2pptx(data)
data2docx(data)
|
/scratch/gouwar.j/cran-all/cranData/webr/inst/doc/descStatictics.R
|
---
title: "Functions for descriptive statistics"
author: "Keon-Woong Moon"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{descStatistics}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE,comment = NA,message=FALSE,warning=FALSE,fig.width=6,fig.height = 6, fig.align='center',out.width="70%")
```
You can make tables summarizing descriptive statistics easily with webr package.
## Installation of packages
You have to install the latest versions of "webr" and "moonBook" packages from github.
```{r,eval=FALSE}
if(!require(devtools)) install.packages("devtools")
devtools::install_github("cardiomoon/webr")
devtools::install_github("cardiomoon/moonBook") # For examples
devtools::install_github("cardiomoon/rrtable") # For reproducible research
```
## Load packages
```{r,message=FALSE}
require(webr)
require(moonBook) # For data acs
```
## Summarizing Frequencies
You can summmarize the frequencies easily with freqSummary() function. Also you can make a table summarizng frequencies with freqTable() function.
```{r}
freqSummary(acs$Dx)
freqTable(acs$Dx)
```
### Ready for reproducible research
The freqTable() function returns an object of class "flextable". With this object, you can make html, pdf, docx, pptx file easily.
```{r}
result=freqTable(acs$Dx)
class(result)
```
### Frequency table for a continuous variable
You can make the frequency table for a continuous variable. In this time, you can get a long table.
```{r}
freqTable(mtcars$mpg)
```
## Frequency table for two categorical variables
You can make a table summarizing the independency of two categorical variables.
```{r}
x2Table(acs,Dx,sex)
```
You can make a table with columnwise percentages.
```{r}
x2Table(acs,Dx,sex,margin=2)
```
You can hide pecentages.
```{r}
x2Table(acs,Dx,sex,show.percent=FALSE)
```
## Numerical summary
### Numerical summary of a vector
You can make a numerical summary table with numSummary() function. If you use the numSummary() function to a continuous vector, you can get the following summary. This function uses psych::describe function
```{r,message=FALSE}
require(dplyr)
numSummary(acs$age)
numSummaryTable(acs$age)
```
### Numerical summary of a data.frame or a tibble
You can make a numerical summary of a data.frame. The numSummary function uses is.numeric function to select numeric columns and make a numeric summary.
```{r}
numSummary(acs)
numSummaryTable(acs)
```
### Use of dplyr::group_by() and dplyr::select() function to summarize
You can use dplyr::select() function to select variables to summarize.
```{r}
acs %>% select(age,EF) %>% numSummary
acs %>% select(age,EF) %>% numSummaryTable
```
You can use dplyr::group_by() and dplyr::select() function to select variables to summarize by group.
```{r}
acs %>% group_by(sex) %>% select(age,EF) %>% numSummary
acs %>% group_by(sex) %>% select(age,EF) %>% numSummaryTable
```
You can summarize by multiple groups.
```{r}
acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummary
acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummaryTable
```
## For reproducible research
You can use package `rrtable` for reproducible research.
```{r}
require(rrtable)
type=c("table","table")
title=c("Frequency Table","Numerical Summary")
code=c("freqTable(acs$Dx)","acs %>% group_by(sex) %>% select(EF,age) %>% numSummaryTable")
data=data.frame(type,title,code,stringsAsFactors = FALSE)
data2pptx(data)
data2docx(data)
```
|
/scratch/gouwar.j/cran-all/cranData/webr/inst/doc/descStatictics.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE,comment = NA,fig.width=6,fig.height = 5, fig.align='center',out.width="90%")
## ----eval=FALSE---------------------------------------------------------------
# #install.packages("devtools")
# devtools::install_github("cardiomoon/webr")
## ----message=FALSE------------------------------------------------------------
require(moonBook)
require(webr)
# chi-squared test
x=chisq.test(table(acs$sex,acs$DM))
x
plot(x)
## -----------------------------------------------------------------------------
t.test(acs$age,mu=63)
plot(t.test(acs$age,mu=63))
## -----------------------------------------------------------------------------
x=var.test(age~DM,data=acs)
x
plot(x)
## -----------------------------------------------------------------------------
x=t.test(age~DM,data=acs)
x
plot(x)
## -----------------------------------------------------------------------------
var.test(BMI~sex,data=acs)
plot(var.test(BMI~sex,data=acs))
## -----------------------------------------------------------------------------
x=t.test(BMI~sex,data=acs,var.equal=TRUE)
x
plot(x)
## -----------------------------------------------------------------------------
x=t.test(iris$Sepal.Width,iris$Petal.Width,paired=TRUE)
plot(x)
## -----------------------------------------------------------------------------
x=t.test(BMI~sex, data=acs,conf.level=0.99,alternative="greater",var.equal=TRUE)
plot(x)
|
/scratch/gouwar.j/cran-all/cranData/webr/inst/doc/plot-htest.R
|
---
title: "Plot for distribution of common statistics and p-value"
author: "Keon-Woong Moon"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{plot.htest}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,comment = NA,fig.width=6,fig.height = 5, fig.align='center',out.width="90%")
```
To understand the concept of p value is very important. To teach the the distribution of common statistic( $\chi^2$ for chisq.test() , t for Student's t-test , F for F-test) and concept of the p-value, plot.htest() function can be used.
## Package Installation
You can install this package form the github. Currently, package `webr` is under construction and consists of only one function - plot.htest().
```{r,eval=FALSE}
#install.packages("devtools")
devtools::install_github("cardiomoon/webr")
```
## Coverage of plot.htest()
The plot.htest() function is a S3 method for class "htest". Currently, this function covers Welch Two Sample t-test, Pearson's Chi-squared test, Two Sample t-test, One Sample t-test, Paired t-test and F test to compare two variances.
## For Chi-squared Test
You can show the distribution of chi-squre statistic and p-value.
```{r,message=FALSE}
require(moonBook)
require(webr)
# chi-squared test
x=chisq.test(table(acs$sex,acs$DM))
x
plot(x)
```
## For one sample t-test
You can show the distribution of t-statistic and p-value in one sample t-test.
```{r}
t.test(acs$age,mu=63)
plot(t.test(acs$age,mu=63))
```
## Student t-test to compare means for two independent samples
Before performing a t-test, you have to compare two variances.
### F test to compare two variances
```{r}
x=var.test(age~DM,data=acs)
x
plot(x)
```
### Use for Two Sample t-test for independence samples
Based on the result of var.test(), you can perform t.test with default option(var.equal=FALSE).
```{r}
x=t.test(age~DM,data=acs)
x
plot(x)
```
## Student t-test using pooled variance
To compare means of body-mass index between male and female patients, perform F test first.
```{r}
var.test(BMI~sex,data=acs)
plot(var.test(BMI~sex,data=acs))
```
Based on the result of F test, you can perform t-test using pooled variance.
```{r}
x=t.test(BMI~sex,data=acs,var.equal=TRUE)
x
plot(x)
```
## Paired t-test
You can show the distribution of t-statistic and p-value in paired t-test.
```{r}
x=t.test(iris$Sepal.Width,iris$Petal.Width,paired=TRUE)
plot(x)
```
## Options for t-test
You can change the options of t.test.
```{r}
x=t.test(BMI~sex, data=acs,conf.level=0.99,alternative="greater",var.equal=TRUE)
plot(x)
```
|
/scratch/gouwar.j/cran-all/cranData/webr/inst/doc/plot-htest.Rmd
|
---
title: "Functions for descriptive statistics"
author: "Keon-Woong Moon"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{descStatistics}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE,comment = NA,message=FALSE,warning=FALSE,fig.width=6,fig.height = 6, fig.align='center',out.width="70%")
```
You can make tables summarizing descriptive statistics easily with webr package.
## Installation of packages
You have to install the latest versions of "webr" and "moonBook" packages from github.
```{r,eval=FALSE}
if(!require(devtools)) install.packages("devtools")
devtools::install_github("cardiomoon/webr")
devtools::install_github("cardiomoon/moonBook") # For examples
devtools::install_github("cardiomoon/rrtable") # For reproducible research
```
## Load packages
```{r,message=FALSE}
require(webr)
require(moonBook) # For data acs
```
## Summarizing Frequencies
You can summmarize the frequencies easily with freqSummary() function. Also you can make a table summarizng frequencies with freqTable() function.
```{r}
freqSummary(acs$Dx)
freqTable(acs$Dx)
```
### Ready for reproducible research
The freqTable() function returns an object of class "flextable". With this object, you can make html, pdf, docx, pptx file easily.
```{r}
result=freqTable(acs$Dx)
class(result)
```
### Frequency table for a continuous variable
You can make the frequency table for a continuous variable. In this time, you can get a long table.
```{r}
freqTable(mtcars$mpg)
```
## Frequency table for two categorical variables
You can make a table summarizing the independency of two categorical variables.
```{r}
x2Table(acs,Dx,sex)
```
You can make a table with columnwise percentages.
```{r}
x2Table(acs,Dx,sex,margin=2)
```
You can hide pecentages.
```{r}
x2Table(acs,Dx,sex,show.percent=FALSE)
```
## Numerical summary
### Numerical summary of a vector
You can make a numerical summary table with numSummary() function. If you use the numSummary() function to a continuous vector, you can get the following summary. This function uses psych::describe function
```{r,message=FALSE}
require(dplyr)
numSummary(acs$age)
numSummaryTable(acs$age)
```
### Numerical summary of a data.frame or a tibble
You can make a numerical summary of a data.frame. The numSummary function uses is.numeric function to select numeric columns and make a numeric summary.
```{r}
numSummary(acs)
numSummaryTable(acs)
```
### Use of dplyr::group_by() and dplyr::select() function to summarize
You can use dplyr::select() function to select variables to summarize.
```{r}
acs %>% select(age,EF) %>% numSummary
acs %>% select(age,EF) %>% numSummaryTable
```
You can use dplyr::group_by() and dplyr::select() function to select variables to summarize by group.
```{r}
acs %>% group_by(sex) %>% select(age,EF) %>% numSummary
acs %>% group_by(sex) %>% select(age,EF) %>% numSummaryTable
```
You can summarize by multiple groups.
```{r}
acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummary
acs %>% group_by(sex,Dx) %>% select(age,EF) %>% numSummaryTable
```
## For reproducible research
You can use package `rrtable` for reproducible research.
```{r}
require(rrtable)
type=c("table","table")
title=c("Frequency Table","Numerical Summary")
code=c("freqTable(acs$Dx)","acs %>% group_by(sex) %>% select(EF,age) %>% numSummaryTable")
data=data.frame(type,title,code,stringsAsFactors = FALSE)
data2pptx(data)
data2docx(data)
```
|
/scratch/gouwar.j/cran-all/cranData/webr/vignettes/descStatictics.Rmd
|
---
title: "Plot for distribution of common statistics and p-value"
author: "Keon-Woong Moon"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{plot.htest}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,comment = NA,fig.width=6,fig.height = 5, fig.align='center',out.width="90%")
```
To understand the concept of p value is very important. To teach the the distribution of common statistic( $\chi^2$ for chisq.test() , t for Student's t-test , F for F-test) and concept of the p-value, plot.htest() function can be used.
## Package Installation
You can install this package form the github. Currently, package `webr` is under construction and consists of only one function - plot.htest().
```{r,eval=FALSE}
#install.packages("devtools")
devtools::install_github("cardiomoon/webr")
```
## Coverage of plot.htest()
The plot.htest() function is a S3 method for class "htest". Currently, this function covers Welch Two Sample t-test, Pearson's Chi-squared test, Two Sample t-test, One Sample t-test, Paired t-test and F test to compare two variances.
## For Chi-squared Test
You can show the distribution of chi-squre statistic and p-value.
```{r,message=FALSE}
require(moonBook)
require(webr)
# chi-squared test
x=chisq.test(table(acs$sex,acs$DM))
x
plot(x)
```
## For one sample t-test
You can show the distribution of t-statistic and p-value in one sample t-test.
```{r}
t.test(acs$age,mu=63)
plot(t.test(acs$age,mu=63))
```
## Student t-test to compare means for two independent samples
Before performing a t-test, you have to compare two variances.
### F test to compare two variances
```{r}
x=var.test(age~DM,data=acs)
x
plot(x)
```
### Use for Two Sample t-test for independence samples
Based on the result of var.test(), you can perform t.test with default option(var.equal=FALSE).
```{r}
x=t.test(age~DM,data=acs)
x
plot(x)
```
## Student t-test using pooled variance
To compare means of body-mass index between male and female patients, perform F test first.
```{r}
var.test(BMI~sex,data=acs)
plot(var.test(BMI~sex,data=acs))
```
Based on the result of F test, you can perform t-test using pooled variance.
```{r}
x=t.test(BMI~sex,data=acs,var.equal=TRUE)
x
plot(x)
```
## Paired t-test
You can show the distribution of t-statistic and p-value in paired t-test.
```{r}
x=t.test(iris$Sepal.Width,iris$Petal.Width,paired=TRUE)
plot(x)
```
## Options for t-test
You can change the options of t.test.
```{r}
x=t.test(BMI~sex, data=acs,conf.level=0.99,alternative="greater",var.equal=TRUE)
plot(x)
```
|
/scratch/gouwar.j/cran-all/cranData/webr/vignettes/plot-htest.Rmd
|
# This file was generated by Rcpp::compileAttributes
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
internal_split_clf <- function(requests) {
.Call('webreadr_internal_split_clf', PACKAGE = 'webreadr', requests)
}
internal_split_squid <- function(requests) {
.Call('webreadr_internal_split_squid', PACKAGE = 'webreadr', requests)
}
|
/scratch/gouwar.j/cran-all/cranData/webreadr/R/RcppExports.R
|
# Read in file metadata
get_bro_metadata <- function(file){
# Read the data in, check it and name it
metadata <- strsplit(x = readr::read_lines(file, n_max = 7), split = "\\t")
if(!all(grepl(x = metadata, pattern = "#"))){
stop("This file does not contain properly formatted comments and cannot be read in.")
}
names(metadata) <- c("separator", "set_separator", "empty_field", "unset_field",
"log_type", "start_timestamp", "fields")
# Extract the components
metadata$separator <- unlist(strsplit(metadata$separator, " ", fixed = TRUE))[2]
metadata$separator <- ifelse(metadata$separator == "\\x09", "\t", metadata$separator)
metadata$set_separator <- metadata$set_separator[2]
metadata$empty_field <- metadata$empty_field[2]
metadata$unset_field <- metadata$unset_field[2]
metadata$log_type <- metadata$log_type[2]
metadata$start_timestamp <- metadata$start_timestamp[2]
metadata$fields <- metadata$fields[2:length(metadata$fields)]
# Return
return(metadata)
}
# Select which fields are in the file, since some bro files at least have
# optional fields
select_fields <- function(metadata, old_names, new_names){
which_in <- which(old_names %in% metadata$fields)
metadata$types <- paste(names(new_names)[which_in], collapse = "")
metadata$names <- unname(new_names[which_in])
return(metadata)
}
# Base reader
read_bro_base <- function(file, metadata){
# Generate NA values
na_vals <- c("", "NA", metadata$empty_field, metadata$unset_field)
return(readr::read_delim(file, delim = metadata$separator, col_types = metadata$types,
col_names = metadata$names, na = na_vals, comment = "#"))
}
# App stats files
read_bro_app_stats <- function(file, metadata){
# Set names
col_names <- c("timestamp", "interval", "app", "unique_hosts", "hits", "total_bytes")
names(col_names) <- c("n", "n", "c", "i", "i", "i")
old_names <- c("ts", "ts_delta", "app", "uniq_hosts", "hits", "bytes")
# Get additional metadata
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps and return
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
return(data)
}
# Conn files
read_bro_conn <- function(file, metadata){
# Specify colum names and types
col_names <- c("timestamp", "uid", "origin_host", "origin_port", "response_host",
"response_port", "protocol", "service", "duration", "origin_bytes",
"response_bytes", "conn_state", "origin_local", "response_local",
"missed_bytes", "history", "origin_packets", "origin_bytes",
"response_packets", "response_bytes")
names(col_names) <- c("n", "c", "c", "n", "c", "n", "c", "c", "n", "n", "n", "c",
"n", "n", "c", "i", "i", "i", "i", "c")
old_names <- c("ts", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p",
"proto", "service", "duration", "orig_bytes", "resp_bytes", "conn_state",
"local_orig", "missed_bytes", "history", "orig_pkts", "orig_ip_bytes",
"resp_pkts", "resp_ip_bytes", "tunnel_parents")
# Update metadata with required fields
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps and return
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
return(data)
}
# DHCP files
read_bro_dhcp <- function(file, metadata){
# Retrieve metadata
metadata <- get_bro_metadata(file)
# Specify colum names and types
col_names <- c("timestamp", "uid", "origin_host", "origin_port", "response_host",
"response_port", "mac_address", "assigned_ip", "lease_time",
"transaction_id")
names(col_names) <- c("n", "c", "c", "n", "c", "n", "c", "c", "d", "n")
old_names <- c("ts", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p",
"mac", "assigned_ip", "lease_time", "trans_id")
# Update metadata with required fields
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
#Return!
return(data)
}
# DNS files
read_bro_dns <- function(file, metadata){
# Specify colum names and types
col_names <- c("timestamp", "uid", "origin_host", "origin_port", "response_host",
"response_port", "protocol", "transaction_id", "query",
"query_class", "class_name", "query_type", "type_name",
"response_code", "response_name", "auth_answer", "truncation",
"recursion_desired", "recursion_available", "Z", "answers",
"caching_intervals", "rejected", "total_answers", "total_replies",
"saw_query", "saw_reply", "auth_response", "additional")
names(col_names) <- c("n", "c", "c", "i", "c", "i", "c",
"i", "c", "i", "c", "i", "c", "i", "c", "l",
"l", "l", "l", "i", "c", "n", "l", "n", "n",
"l", "l", "c", "c")
old_names <- c("ts", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p",
"proto", "trans_id", "query", "qclass", "qclass_name", "qtype",
"qtype_name", "rcode", "rcode_name", "AA", "TC", "RD", "RA",
"Z", "answers", "TTLs", "rejected", "total_answers", "total_replies",
"saw_query", "saw_reply", "auth", "addl")
# Update metadata with required fields
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
# Return!
return(data)
}
read_bro_ftp <- function(file, metadata){
col_names <- c("timestamp", "uid", "origin_host", "origin_port", "response_host",
"response_port", "user", "password", "command",
"argument", "mime_type", "file_size", "reply_code",
"reply_message", "passive_chan","chan_origin_host", "chan_response_host",
"chan_response_port", "working_dir", "command_timestamp", "command_cmd",
"command_arg", "command_seq", "pending_timestamp", "pending_command", "pending_arg",
"pending_seq", "is_passive", "capture_password", "file_uid", "last_auth")
names(col_names) <- c("n", "c", "c", "i", "c", "i", "c",
"c", "c", "c", "c", "n", "i", "c", "l",
"c", "c", "i", "c", "n", "c", "c", "i",
"n", "c", "c", "i", "l", "l", "c", "c")
old_names <- c("ts", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p",
"user", "password", "command", "arg", "mime_type", "file_size",
"reply_code", "reply_msg", "data_channel.passive", "data_channel.orig_h",
"data_channel.resp_h", "data_channel.resp_p", "cwd","cmdarg.ts", "cmdarg.cmd",
"cmdarg.arg", "cmdarg.seq", "pending_commands.ts", "pending_commands.cmd",
"pending_commands.arg", "pending_commands.seq", "passive", "capture_password",
"fuid", "last_auth_requested")
# Update metadata with required fields
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
if("pending_timestamp" %in% metadata$names){
data$pending_timestamp <- unix_to_posix(data$pending_timestamp)
}
if("command_timestamp" %in% metadata$names){
data$command_timestamp <- unix_to_posix(data$command_timestamp)
}
# Return!
return(data)
}
read_bro_files <- function(file, metadata){
col_names <- c("timestamp", "fuid", "origin_host", "destination_host", "conn_uids",
"source", "depth", "analysers", "mime_type",
"filename", "duration", "local_origin", "is_origin",
"bytes_seen", "total_bytes", "missing_bytes", "overflow_bytes",
"timedout", "parent_fuid", "md5", "sha1", "sha256", "x509_timestamp",
"x509_id", "x509_certificate_version", "x509_certificate_serial",
"x509_certificate_subject", "x509_certificate_issuer", "x509_certificate_name",
"x509_certificate_invalid_before", "x509_certificate_invalid_after",
"x509_certificate_key_algorithm", "x509_certificate_sig_algorithm",
"x509_certificate_key_type", "x509_certificate_key_length", "x509_certificate_exponent",
"x509_certificate_curve", "x509_handle", "x509_extensions",
"x509_san_dns", "x509_san_uri", "x509_san_email", "x509_san_ip", "x509_san_other",
"x509_constraints_ca", "x509_constraints_path_length", "x509_logcert",
"extracted")
names(col_names) <- c("d", "c", "c", "c", "c", "c", "i", "c", "c", "c", "d", "l",
"l", "d", "d", "d", "d", "l", "c", "c", "c", "c", "n",
"c", "n", "c", "c", "c", "c", "c", "c", "c", "c", "c",
"i", "c", "c", "c", "c", "c", "c", "c", "c", "l", "l",
"i", "l", "c")
old_names <- c("ts", "fuid", "tx_hosts", "rx_hosts", "conn_uids", "source",
"depth", "analyzers", "mime_type", "filename", "duration", "local_orig",
"is_orig", "seen_bytes", "total_bytes", "missing_bytes", "overflow_bytes",
"timedout", "parent_fuid", "md5", "sha1", "sha256", "x509.ts", "x509.id",
"x509.certificate.version","x509.certificate.serial","x509.certificate.subject",
"x509.certificate.issuer", "x509.certificate.cn", "x509.certificate.not_valid_before",
"x509.certificate.not_valid_after", "x509.certificate.key_alg", "x509.certificate.sig_alg",
"x509.certificate.key_type", "x509.certificate.key_length", "x509.certificate.exponent",
"x509.certificate.curve", "x509.handle", "x509.extensions", "x509.san.dns", "x509.san.url",
"x509.san.email", "x509.san.ip", "x509.san.other_fields", "x509.basic_constraints.ca",
"x509.basic_constraints.path_len", "x509.logcert", "extracted")
# Update metadata with required fields
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
if("x509_timestamp" %in% metadata$names){
data$x509_timestamp <- unix_to_posix(data$x509_timestamp)
}
# Return!
return(data)
}
read_bro_http <- function(file, metadata){
col_names <- c("timestamp", "uid", "origin_host", "origin_port", "response_host",
"response_port", "transaction_depth", "method", "host", "uri",
"referrer", "user_agent", "request_body_length", "response_body_length",
"status_code", "status_message", "info_code", "info_message", "filename",
"tags", "username", "password", "capture_password", "proxied", "range_request",
"origin_fuids", "origin_mime_types", "response_fuids", "response_mime_types",
"current_entity", "origin_mime_depth", "response_mime_depth", "client_header_names",
"server_header_names", "omniture", "cookie_variables", "uri_variables")
names(col_names) <- c("n", "c", "c", "i", "c", "i", "i", "c", "c", "c", "c", "c", "i",
"i", "i", "c", "i", "c", "c", "c", "c", "c", "l", "c", "l", "c",
"c", "c", "c", "c", "i", "i", "c", "c", "l", "c", "c")
old_names <- c("ts", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p", "trans_depth",
"method", "host", "uri", "referrer", "user_agent", "request_body_len",
"response_body_len", "status_code", "status_msg", "info_code", "info_msg",
"filename", "tags", "username", "password", "capture_password", "proxied",
"range_request", "orig_fuids", "orig_mime_types", "resp_fuids", "resp_mime_types",
"current_entity", "orig_mime_depth", "resp_mime_depth", "client_header_names",
"server_header_names", "omniture", "cookie_vars", "uri_vars")
# Update metadata with required fields
metadata <- select_fields(metadata, old_names, col_names)
# Read the data in, format the timestamps
data <- read_bro_base(file, metadata)
data$timestamp <- unix_to_posix(data$timestamp)
# Return!
return(data)
}
read_bro <- function(file){
# Read the metadata to check what kind of file we have.
metadata <- get_bro_metadata(file)
# Switch through file types
if(metadata$log_type == "app_stats"){
return(read_bro_app_stats(file, metadata))
}
if(metadata$log_type == "conn"){
return(read_bro_conn(file, metadata))
}
if(metadata$log_type == "dhcp"){
return(read_bro_dhcp(file, metadata))
}
if(metadata$log_type == "dns"){
return(read_bro_dns(file, metadata))
}
if(metadata$log_type == "ftp"){
return(read_bro_ftp(file, metadata))
}
if(metadata$log_type == "files"){
return(read_bro_files(file, metadata))
}
if(metadata$log_type == "http"){
return(read_bro_http(file, metadata))
}
stop("File type not recognised/supported")
}
|
/scratch/gouwar.j/cran-all/cranData/webreadr/R/bro.R
|
#'@title read CLF-formatted logs
#'@description Read a file of request logs stored in the
#'\href{https://en.wikipedia.org/wiki/Common_Log_Format}{Common Log Format}.
#'
#'@details the CLF is a standardised format for web request logs. It consists of the fields:
#'
#'\itemize{
#' \item{ip_address:} {the IP address of the remote host that made the request. The CLF
#' does not (by default) include the de-facto standard X-Forwarded-For header}
#' \item{remote_user_ident:} {the \href{https://tools.ietf.org/html/rfc1413}{RFC 1413} remote
#' user identifier.}
#' \item{local_user_ident:} {the identifier the user has authenticated with locally.}
#' \item{timestamp:} {the timestamp associated with the request, stored as
#' "[08/Apr/2001:17:39:04 -0800]", where "-0800" represents the time offset (minus
#' eight hours) of the timestamp from UTC.}
#' \item{request:} {the actual user request, containing the HTTP method used, the
#' asset requested, and the HTTP Protocol version used.}
#' \item{status_code:} {the HTTP status code returned.}
#' \item{bytes_sent:} {the number of bytes sent}
#'}
#'
#'While outdated as a standard, systems using the CLF are still around; the Squid caching
#'system, for example, uses the CLF as one of its default log formats (the other,
#'the squid "native" format, can be read with \code{\link{read_squid}}).
#'
#'@param file the full path to the CLF-formatted file you want to read.
#'
#'@param has_header whether or not the file has a header row. Set to FALSE by
#'default.
#'
#'@return a data.frame consisting of seven fields, as discussed above, with normalised
#'timestamps.
#'
#'@seealso \code{\link{read_combined}} for the /Combined/ Log Format, and
#'\code{\link{split_clf}} for splitting out the "requests" field.
#'@examples
#'#Read in an example CLF-formatted file provided with the webreadr package.
#'data <- read_clf(system.file("extdata/log.clf", package = "webreadr"))
#'@export
read_clf <- function(file, has_header = FALSE){
names <- c("ip_address", "remote_user_ident", "local_user_ident", "timestamp"
,"request", "status_code","bytes_sent")
col_types <- list(col_character(),
col_character(),
col_character(),
col_datetime(format = "%d/%b/%Y:%H:%M:%S %z"),
col_character(),
col_integer(),
col_integer())
data <- read_log(file = file, col_names = names, col_types = col_types, skip = ifelse(has_header, 1, 0))
return(data)
}
#'@title read Combined Log Format files
#'@description read requests logs following the Combined Log Format.
#'
#'@details the Combined Log Format (CLF) is the same as the Common Log Format (CLF, because
#'software engineers and naming go together like chalk and cheese), which
#'is documented at \code{\link{read_clf}}. In addition to the fields described there,
#'the Combined Log Format also includes:
#'
#'\itemize{
#' \item{referer:} {the referer associated with the request.}
#' \item{user_agent:} {the user agent of the user that made the request.}
#'}
#'
#'\code{read_combined} handles these fields, as well as the CLF-standard ones. This is (amongst
#'other things) the default logging format for \href{http://nginx.org/}{nginx} servers
#'
#'@param file the full path to the CLF-formatted file you want to read.
#'
#'@param has_header whether or not the file has a header row. Set to FALSE by
#'default.
#'
#'@seealso \code{\link{read_clf}} for the /Common/ Log Format, and
#'\code{\link{split_clf}} for splitting out the "requests" field.
#'
#'@examples
#'#Read in an example Combined-formatted file provided with the webreadr package.
#'data <- read_combined(system.file("extdata/combined_log.clf", package = "webreadr"))
#'@export
read_combined <- function(file, has_header = FALSE){
names <- c("ip_address", "remote_user_ident", "local_user_ident", "timestamp",
"request", "status_code","bytes_sent","referer","user_agent")
col_types <- list(col_character(),
col_character(),
col_character(),
col_datetime("%d/%b/%Y:%H:%M:%S %z"),
col_character(),
col_integer(),
col_integer(),
col_character(),
col_character())
data <- read_log(file = file, col_names = names, col_types = col_types, skip = ifelse(has_header, 1, 0))
return(data)
}
#'@title read Squid files
#'@description the Squid default log formats are either the CLF - for which, use
#'\code{\link{read_clf}} - or the "native" Squid format, which is described in more detail
#'below. \code{read_squid} allows you to read the latter.
#'
#'@details
#'
#'The log format for Squid servers can be custom-set, but by default follows one of two
#'patterns; it's either the Common Log Format (CLF), which you can read in with
#'\code{\link{read_clf}}, or the "native log format", a Squid-specific format handled
#'by this function. It consists of the fields:
#'
#'\itemize{
#' \item{timestamp:} {the timestamp identifying when the request was received. This is
#' stored (from the file's point of view) as a count of seconds, in UNIX time:
#' \code{read_squid} turns them into POSIXlt timestamps, assuming UTC as an
#' origin timezone.}
#' \item{time_elapsed:} the amount of time (in milliseconds) that the connection and fulfilment
#' of the request lasted for.
#' \item{ip_address:} {the IP address of the remote host making the request.}
#' \item{status_code:} {the status code and Squid response code associated with that request,
#' stored as a single field. This can be split into two distinct fields with \code{\link{split_squid}}}
#' \item{bytes_sent:} {the number of bytes sent}
#' \item{http_method:} {the HTTP method (POST, GET, etc) used.}
#' \item{url: }{the URL of the requested asset.}
#' \item{remote_user_ident:} {the \href{https://tools.ietf.org/html/rfc1413}{RFC 1413} remote
#' user identifier.}
#' \item{peer_info:} {the status of how forwarding to a peer server was handled and, if the
#' request was forwarded, the server it was sent to.}
#'}
#'
#'@param file the full path to the CLF-formatted file you want to read.
#'
#'@param has_header whether or not the file has a header row. Set to FALSE by
#'default.
#'
#'@seealso \code{\link{read_clf}} for the Common Log Format (also used by Squids), and
#'\code{\link{split_squid}} for splitting the "status_code" field into its component parts.
#'
#'@examples
#'#Read in an example Squid file provided with the webreadr package.
#'data <- read_squid(system.file("extdata/log.squid", package = "webreadr"))
#'@export
read_squid <- function(file, has_header = FALSE){
names <- c("timestamp", "time_elapsed", "ip_address", "status_code",
"bytes_sent","http_method", "url","remote_user_ident","peer_info")
col_types <- list(col_number(),
col_integer(),
col_character(),
col_character(),
col_integer(),
col_character(),
col_character(),
col_character(),
col_character())
data <- read_log(file = file, col_names = names, col_types = col_types, skip = ifelse(has_header, 1, 0))
data$timestamp <- as.POSIXct(data$timestamp, origin = "1970-01-01", tz = "UTC")
return(data)
}
#'@title read Amazon CloudFront access logs
#'@description Amazon CloudFront uses access logs with a standard format described
#'\href{http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html}{
#'on their website}. \code{read_aws} reads these files in; due to the Amazon treatment of header lines,
#'it is capable of organically detecting whether files lack common fields, and compensating for that. See
#'"Details"
#'
#'@param file the full path to the AWS file you want to read.
#'
#'@details
#'Amazon CloudFront uses tab-separated files with
#'\href{http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html}{
#'Amazon-specific fields}. This can be changed by individual CloudFront users, however, to exclude particular fields,
#'and historically has contained fewer fields than it now does. Luckily, Amazon's insistence on standardisation in field
#'names means that we can organically detect if fields are missing, and compensate for that before reading in the file.
#'
#'If no fields are missing, the fields returned will be:
#'
#'\itemize{
#' \item{date:} {the date and time when the request was \emph{completed}}
#' \item{time_elapsed:} {the amount of time (in milliseconds) that the connection and fulfilment
#' of the request lasted for.}
#' \item{edge_location:} {the Amazon edge location that served the request, identified by a three-letter
#' code. See the Amazon documentation for more details.}
#' \item{bytes_sent:} {a count of the number of bytes sent by the server to the client, including headers,
#' to fulfil the request.}
#' \item{ip_address:} {the IP address of the client making the request.}
#' \item{http_method:} {the HTTP method (POST, GET, etc) used.}
#' \item{host:} {the CloudFront host name.}
#' \item{path:} {the path to the requested asset.}
#' \item{status_code:} {the HTTP status code associated with the request.}
#' \item{referer:} {the referer associated with the request.}
#' \item{user_agent:} {the user agent of the client that made the request.}
#' \item{query:} {the query string associated with the request; if there is no query string,
#' this will be a dash.}
#' \item{cookie:} {the cookie header from the request, stored as name-value pairs. When no
#' cookie header is provided, or it is empty, this will be a dash.}
#' \item{result_type:} {the result of the request. This is similar to Squid response codes (
#' see \code{\link{read_squid}}) but Amazon-specific; their documentation contains details on
#' what each code means.}
#' \item{request_id:} {A hashed unique identifier for each request.}
#' \item{host_header: }{the host header of the requested asset. While \code{host} will always
#' be the CloudFront host name, \code{host_header} contains alternate domain names (or 'CNAMES')
#' when the CloudFront distribution is using them}.
#' \item{protocol: } {the protocol used in the request (http/https).}
#' \item{bytes_received: }{client-to-server bytes, including headers.}
#' \item{time_elapsed:} {the time elapsed, in seconds, between the time the request was received and
#' the time the server completed responding to it.}
#'}
#'
#'@seealso \code{\link{read_s3}}, for Amazon S3 files,
#'\code{\link{read_clf}} for the Common Log Format, \code{\link{read_squid}} and
#'\code{\link{read_combined}}.
#'
#'@examples
#'#Read in an example CloudFront file provided with the webreadr package.
#'data <- read_aws(system.file("extdata/log.aws", package = "webreadr"))
#'@export
read_aws <- function(file){
header_fields <- unlist(strsplit(read_lines(file, n_max = 2)[2], " "))[-1]
formatters <- aws_header_select(header_fields)
data <- read_delim(file = file, delim = "\t", escape_backslash = FALSE, col_names = formatters[[1]],
col_types = formatters[[2]], skip = 2)
if(all(c("date","time") %in% names(data))){
data$date <- as.POSIXct(paste(data$date, data$time), tz = "UTC")
return(data[,!names(data) == "time"])
}
return(data)
}
#'@title Read Amazon S3 Access Logs
#'@description \code{read_s3} provides a reader for Amazon's S3 service's access logs, described
#'\href{http://docs.aws.amazon.com/AmazonS3/latest/dev/LogFormat.html}{here}.
#'
#'@param file the full path to the S3 file you want to read.
#'
#'@details S3 access logs contain information about requests to S3 buckets, and follow
#'a standard format described
#'\href{http://docs.aws.amazon.com/AmazonS3/latest/dev/LogFormat.html}{here}.
#'
#'The fields for S3 files are:
#'
#'\itemize{
#' \item{owner:} {the owner of the S3 bucket; a hashed user ID}
#' \item{bucket:} {the bucket that processed the request.}
#' \item{request_time:} {the time that a request was received. Formatted as POSIXct
#' timestamps.}
#' \item{remote_ip:} {the IP address that made the request.}
#' \item{requester:} {the user ID of the person making the request; \code{Anonymous}
#' if the request was not authenticated.}
#' \item{operation:} {the actual operation performed with the request.}
#' \item{key:} {the request's key, normally an encoded URL fragment or NA if
#' the operation did not contain a key.}
#' \item{uri:} {the full URI for the request, as well as the HTTP method and
#' version. \code{\link{split_clf}} works to split this into a data.frame of 3
#' columns.}
#' \item{status:} {the HTTP status code associated with the request.}
#' \item{error:} {the error code, if an error occurred; NA otherwise. See
#' \href{http://docs.aws.amazon.com/AmazonS3/latest/dev/ErrorCode.html}{here} for
#' more information about S3 error codes.}
#' \item{sent:} {the number of bytes returned in response to the request.}
#' \item{size:} {the total size of the returned object.}
#' \item{time:} {the number of milliseconds between the request being sent and
#' the response being sent, from the server's perspective.}
#' \item{turn_around:} {the number of milliseconds the S3 bucket spent processing
#' the request.}
#' \item{referer:} {the referer associated with the request.}
#' \item{user_agent:} {the user agent associated with the request.}
#' \item{version_id:} {the version ID of the request; NA if the requested operation
#' does not involve a version ID.}
#'}
#'
#'@seealso \code{\link{read_aws}} for reading Amazon Web Services (AWS) access log files,
#'and \code{\link{split_clf}}, which works well on the \code{uri} field from S3 files.
#'
#'@examples
#'# Using the inbuilt testing dataset
#'s3_data <- read_s3(system.file("extdata/s3.log", package = "webreadr"))
#'
#'@export
read_s3 <- function(file){
names <- c("owner", "bucket", "request_time", "remote_ip", "requester", "request_id", "operation",
"key", "uri", "status", "error", "sent", "size", "time", "turn_around", "referer",
"user_agent", "version_id")
types <- "cccccccccicnniiccc"
data <- readr::read_log(file = file, col_types = types, col_names = names)
data$request_time <- readr::parse_datetime(data$request_time, format = "%d/%b/%Y:%H:%M:%S %z")
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/webreadr/R/readers.R
|
#'@title split requests from a CLF-formatted file
#'@description CLF (Combined/Common Log Format) files store the HTTP method, protocol
#'and asset requested in the same field. \code{split_clf} takes this field as a vector
#'and returns a data.frame containing these elements in distinct columns. The function
#'also works nicely with the \code{uri} field from Amazon S3 files (see
#'\code{\link{read_s3}}).
#'
#'@param requests the "request" field from a CLF-formatted file, read in with
#'\code{\link{read_clf}} or \code{\link{read_combined}}.
#'
#'@return a data.frame of three columns - "method", "asset" and "protocol" -
#'representing, respectively, the HTTP method used ("GET"), the asset requested
#'("/favicon.ico") and the protocol used ("HTTP/1.0"). In cases where
#'the request is not intact (containing, for example, just the protocol
#'or just the asset) a row of empty strings will currently be returned.
#'In the future, this will be somewhat improved.
#'
#'@seealso \code{\link{read_clf}} and \code{\link{read_combined}} for reading
#'in these files.
#'
#'@examples
#'# Grab CLF data and split out the request.
#'data <- read_combined(system.file("extdata/combined_log.clf", package = "webreadr"))
#'requests <- split_clf(data$request)
#'
#'# An example using S3 files
#'s3_data <- read_s3(system.file("extdata/s3.log", package = "webreadr"))
#'s3_requests <- split_clf(s3_data$uri)
#'
#'@export
split_clf <- function(requests){
internal_split_clf(requests)
}
#'@title split the "status_code" field in a Squid-formatted dataset.
#'@description the Squid data format (which can be read in with
#'\code{\link{read_squid}}) stores the squid response and the HTTP status
#'code as a single field. \code{\link{split_squid}} allows you to split
#'these into a data.frame of two distinct columns.
#'
#'@param status_codes a \code{status_code} column from a Squid file read in
#'with \code{\link{read_squid}}
#'
#'@return a data.frame of two columns - "squid_code" and "http_status" -
#'representing, respectively, the Squid response to the request and the
#'HTTP status of it. In cases where the status code is not intact (containing,
#'for example, just the squid_code) a row of empty strings will currently be returned.
#'In the future, this will be somewhat improved.
#'
#'@seealso \code{\link{read_squid}} for reading these files in,
#'and \code{\link{split_clf}} for similar parsing of multi-field
#'columns in Common/Combined Log Format (CLF) data.
#'
#'@examples
#'#Read in an example Squid file provided with the webtools package, then split out the codes
#'data <- read_squid(system.file("extdata/log.squid", package = "webreadr"))
#'statuses <- split_squid(data$status_code)
#'
#'@export
split_squid <- function(status_codes){
internal_split_squid(status_codes)
}
|
/scratch/gouwar.j/cran-all/cranData/webreadr/R/splitters.R
|
#Organically grows or reduces collectors and column names for Amazon CloudFront files to compensate for changes
#in the number of fields. Kind of icky but it works and looks great from the user end, so..
aws_header_select <- function(header_fields){
field_names <- c("date", "time", "x-edge-location", "sc-bytes", "c-ip", "cs-method",
"cs(Host)", "cs-uri-stem", "sc-status", "cs(Referer)", "cs(User-Agent)", "cs-uri-query",
"cs(Cookie)", "x-edge-result-type", "x-edge-request-id", "x-host-header", "cs-protocol", "cs-bytes",
"time-taken")
new_names <- c("date", "time", "edge_location", "bytes_sent", "ip_address", "http_method", "host", "path",
"status_code", "referer", "user_agent", "query", "cookie", "result_type", "request_id",
"host_header", "protocol", "bytes_received", "time_elapsed")
collectors <- list(col_character(), col_character(), col_character(), col_integer(), col_character(),
col_character(), col_character(), col_character(), col_integer(), col_character(),
col_character(), col_character(), col_character(), col_character(), col_character(),
col_character(), col_character(), col_character(), col_number())
if(length(header_fields) == length(field_names) && all(header_fields == field_names)){
return(list(new_names, collectors))
}
out_names <- character()
out_collectors <- list()
for(field in header_fields){
location <- which(field_names == field)[1]
out_names <- append(out_names, new_names[location])
out_collectors <- c(out_collectors, collectors[location])
}
if(anyNA(out_names)){
stop("Your file contains unrecognised fields")
}
return(list(out_names, out_collectors))
}
unix_to_posix <- function(ts){
return(as.POSIXct(ts, origin = '1970-01-01', tz = "UTC"))
}
|
/scratch/gouwar.j/cran-all/cranData/webreadr/R/utilities.R
|
#' @title A package for reading various common forms of request log
#' @description see the \href{https://github.com/Ironholds/webreadr/blob/master/vignettes/Introduction.Rmd}{introductory vignette}
#' for more details!
#' @name webreadr
#' @useDynLib webreadr
#' @importFrom Rcpp sourceCpp
#' @import readr
NULL
|
/scratch/gouwar.j/cran-all/cranData/webreadr/R/webreadr.R
|
## ------------------------------------------------------------------------
library(webreadr)
#read in an example file that comes with the webtools package
data <- read_combined(system.file("extdata/combined_log.clf", package = "webreadr"))
#And if we look at the format...
str(data)
## ------------------------------------------------------------------------
requests <- split_clf(data$request)
str(requests)
|
/scratch/gouwar.j/cran-all/cranData/webreadr/inst/doc/Introduction.R
|
---
title: "Introduction to webreadr"
author: "Oliver Keyes"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to webreadr}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
# Reading web access logs
R, as a language, is used for analysing pretty much everything from genomic data to financial information. It's also
used to analyse website access logs, and R lacks a good framework for doing that; the URL decoder isn't vectorised,
the file readers don't have convenient defaults, and good luck normalising IP addresses at scale.
Enter <code>webreadr</code>, which contains convenient wrappers and functions for reading, munging and formatting
data from access logs and other sources of web request data.
## File reading
Base R has read.delim, which is convenient but much slower for file reading than Hadley's new [readr](https://github.com/hadley/readr)
package. <code>webtools</code> defines a set of wrapper functions around readr's <code>read_delim</code>, designed
for common access log formats.
The most common historical log format is the [Combined Log Format](http://httpd.apache.org/docs/1.3/logs.html#combined); this is used as one of the default formats for [nginx](http://nginx.org/) and the [Varnish caching system](https://www.varnish-cache.org/docs/trunk/reference/varnishncsa.html). <code>webtools</code>
lets you read it in trivially with <code>read\_combined</code>:
```{r}
library(webreadr)
#read in an example file that comes with the webtools package
data <- read_combined(system.file("extdata/combined_log.clf", package = "webreadr"))
#And if we look at the format...
str(data)
```
As you can see, the types have been appropriately set, the date/times have been parsed, and sensible header names have been set.
The same thing can be done with the Common Log Format, used by Apache default configurations and as one of the defaults for
Squid caching servers, using <code>read\_clf</code>. The other squid default format can be read with <code>read\_squid</code>.
Amazon's AWS files are also supported, with <code>read\_aws</code>, which includes automatic field detection, and S3 bucket
access logs can be read with <code>read\_s3</code>.
## Splitting combined fields
One of the things you'll notice about the example above is the "request" field - it contains not only the actual asset
requested, but also the HTTP method used and the protocol used. That's pretty inconvenient for people looking to do something
productive with the data.
Normally you'd split each field out into a list, and then curse and recombine them into a data.frame and hope that
doing so didn't hit R's memory limit during the "unlist" stage, and it'd take an absolute age. Or, you could just split them
up directly into a data frame using <code>split\_clf</code>:
```{r}
requests <- split_clf(data$request)
str(requests)
```
This is faster than manual splitting-and-data.frame-ing, easier on the end user, and less likely to end in unexpected segfaults with
large datasets. It also works on the <code>uri</code> within S3 access logs.
A similar function, <code>split\_squid</code>, exists for the `status\_code` field in files read in with <code>read_squid</code>, which suffer from a similar problem.
## Other ideas
If you have ideas for other URL handlers that would make access log processing easier, the best approach
is to either [request it](https://github.com/Ironholds/webtools/issues) or [add it](https://github.com/Ironholds/webtools/pulls)!
|
/scratch/gouwar.j/cran-all/cranData/webreadr/inst/doc/Introduction.Rmd
|
---
title: "Introduction to webreadr"
author: "Oliver Keyes"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to webreadr}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
# Reading web access logs
R, as a language, is used for analysing pretty much everything from genomic data to financial information. It's also
used to analyse website access logs, and R lacks a good framework for doing that; the URL decoder isn't vectorised,
the file readers don't have convenient defaults, and good luck normalising IP addresses at scale.
Enter <code>webreadr</code>, which contains convenient wrappers and functions for reading, munging and formatting
data from access logs and other sources of web request data.
## File reading
Base R has read.delim, which is convenient but much slower for file reading than Hadley's new [readr](https://github.com/hadley/readr)
package. <code>webtools</code> defines a set of wrapper functions around readr's <code>read_delim</code>, designed
for common access log formats.
The most common historical log format is the [Combined Log Format](http://httpd.apache.org/docs/1.3/logs.html#combined); this is used as one of the default formats for [nginx](http://nginx.org/) and the [Varnish caching system](https://www.varnish-cache.org/docs/trunk/reference/varnishncsa.html). <code>webtools</code>
lets you read it in trivially with <code>read\_combined</code>:
```{r}
library(webreadr)
#read in an example file that comes with the webtools package
data <- read_combined(system.file("extdata/combined_log.clf", package = "webreadr"))
#And if we look at the format...
str(data)
```
As you can see, the types have been appropriately set, the date/times have been parsed, and sensible header names have been set.
The same thing can be done with the Common Log Format, used by Apache default configurations and as one of the defaults for
Squid caching servers, using <code>read\_clf</code>. The other squid default format can be read with <code>read\_squid</code>.
Amazon's AWS files are also supported, with <code>read\_aws</code>, which includes automatic field detection, and S3 bucket
access logs can be read with <code>read\_s3</code>.
## Splitting combined fields
One of the things you'll notice about the example above is the "request" field - it contains not only the actual asset
requested, but also the HTTP method used and the protocol used. That's pretty inconvenient for people looking to do something
productive with the data.
Normally you'd split each field out into a list, and then curse and recombine them into a data.frame and hope that
doing so didn't hit R's memory limit during the "unlist" stage, and it'd take an absolute age. Or, you could just split them
up directly into a data frame using <code>split\_clf</code>:
```{r}
requests <- split_clf(data$request)
str(requests)
```
This is faster than manual splitting-and-data.frame-ing, easier on the end user, and less likely to end in unexpected segfaults with
large datasets. It also works on the <code>uri</code> within S3 access logs.
A similar function, <code>split\_squid</code>, exists for the `status\_code` field in files read in with <code>read_squid</code>, which suffer from a similar problem.
## Other ideas
If you have ideas for other URL handlers that would make access log processing easier, the best approach
is to either [request it](https://github.com/Ironholds/webtools/issues) or [add it](https://github.com/Ironholds/webtools/pulls)!
|
/scratch/gouwar.j/cran-all/cranData/webreadr/vignettes/Introduction.Rmd
|
#' @title Search Bing
#' @description Improve your workflow by searching Bing directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords bing internet workflow
#' @import utils
#' @examples
#' bing("my search terms")
#' @export
bing <- function(search_terms) {
message("Opening Bing search for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.bing.com/search?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/bing.R
|
#' Find DOI's and other bibliographic metadata
#' @description Search crossref.org directly from the R console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords DOI bibliography internet workflow
#' @importFrom utils URLencode browseURL
#' @examples
#' crossref("my source")
#' @export
crossref <- function(search_terms) {
message("Opening crossref.org search for \"", search_terms, "\" in browser")
utils::browseURL(paste0("http://search.crossref.org/?q=", utils::URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/crossref.R
|
#' Search Duckduckgo
#' @description Improve your workflow by searching with duckduckgo.com directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords duckduckgo internet workflow
#' @examples
#' duckduckgo("my search terms")
#' ddg("r-project")
#' @export
duckduckgo <- function(search_terms) {
message("Opening Duckduckgo search for \"", search_terms, "\" in browser")
browseURL(paste0("https://duckduckgo.com/?q=", URLencode(search_terms)))
}
#' @export
#' @rdname duckduckgo
ddg <- duckduckgo
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/duckduckgo.R
|
#' Search GitHub
#' @description Improve your workflow by searching GitHub directly from R console.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords github internet workflow
#' @examples
#' github("ggplot extensions")
#' @export
github <- function(search_terms) {
message("Opening GitHub search for \"", search_terms, "\" in browser")
browseURL(paste0("https://github.com/search?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/github.R
|
#' Search Google
#' @description Improve your workflow by searching google directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords google internet workflow
#' @examples
#' google("my search terms")
#' @export
google <- function(search_terms) {
message("Opening Google search for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.google.com/search?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/google.R
|
#' Search Google Scholar
#' @description Improve your workflow by searching Google Scholar directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords google scholar internet workflow
#' @examples
#' google_scholar("my search terms")
#' @export
google_scholar <- function(search_terms) {
message("Opening Google Scholar search for \"", search_terms, "\" in browser")
utils::browseURL(paste0("https://scholar.google.com/scholar?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/google_scholar.R
|
#' Search Qwant
#' @description Improve your workflow by searching Qwant directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords qwant internet workflow
#' @examples
#' qwant("my search terms")
#' @export
qwant <- function(search_terms) {
message("Opening Qwant search for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.qwant.com/?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/qwant.R
|
#' Search r-bloggers.com
#' @description Improve your workflow by searching r-bloggers.com directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords r-bloggers internet workflow
#' @examples
#' r_bloggers("my search terms")
#' @export
r_bloggers <- function(search_terms) {
message("Opening r-bloggers.com search for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.r-bloggers.com/?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/r_bloggers.R
|
#' Search rdocumentation.org
#' @description Improve your workflow by searching rdocumentation.org directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords rdocumentation internet workflow
#' @examples
#' rdocumentation("my search terms")
#' rdoc("package I am looking for")
#' @export
rdocumentation <- function(search_terms) {
message("Opening Rdocumentation search for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.rdocumentation.org/search?q=", URLencode(search_terms)))
}
#' @export
#' @rdname rdocumentation
rdoc <- rdocumentation
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/rdocumentation.R
|
#' Search rdrr.io
#' @description Improve your workflow by searching rdrr.io directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords rdrr.io internet workflow
#' @examples
#' rdrr_io("my search terms")
#' rdrr("my search terms")
#' @export
rdrr_io <- function(search_terms) {
message("Opening rdrr.io search for \"", search_terms, "\" in browser")
browseURL(paste0("https://rdrr.io/search?q=", URLencode(search_terms)))
}
#' @export
#' @rdname rdrr_io
rdrr <- rdrr_io
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/rdrr_io.R
|
#' Search Reddit
#' @description Improve your workflow by searching Reddit directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords reddit internet workflow
#' @examples
#' reddit("my search terms")
#' @export
reddit <- function(search_terms) {
message("Searching Reddit for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.reddit.com/search?q=", URLencode(search_terms)))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/reddit.r
|
#' Search Stackoverflow
#' @description Improve your workflow by searching Stackoverflow directly from R console.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords web workflow stackoverflow
#' @examples
#' stackoverflow("r date conversion")
#' so("r ggplot2 geom_smooth()")
#' @export
stackoverflow <- function(search_terms) {
message("Opening Stackoverflow search for \"", search_terms, "\" in browser")
browseURL(paste0("https://stackoverflow.com/search?q=", URLencode(search_terms)))
}
#' @export
#' @rdname stackoverflow
so <- stackoverflow
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/stackoverflow.R
|
#' Search Twitter
#' @description Improve your workflow by searching Twitter directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @param lang Specify in which language Twitter should be accessed One of c("en", "de", "es" "fr") for English, German, Spanish and French, respectively.
#' @keywords wikipedia internet workflow
#' @examples
#' twitter("rstudiotips")
#' @export
twitter <- function(search_terms, lang = c("en", "de", "es", "fr")) {
if (missing(lang))
lang <- Sys.getenv("LANG")
# if system language contains "en" use English Twitter version
if (grepl("en", lang)) {
message("Opening Twitter search for \"", search_terms, "\" in browser")
browseURL(paste0("https://twitter.com/search?q=", URLencode(search_terms), "&lang=en"))
}
# if system language contains "de" use German Twitter version
else if (grepl("de", lang)) {
message("\u00D6ffne Twitter Suche f\u00FCr \"", search_terms, "\" im Browser")
browseURL(paste0("https://twitter.com/search?q=", URLencode(search_terms), "&lang=de"))
}
# if system language contains "es" use Spanish Twitter version
else if (grepl("es", lang)) {
message("Abrir b\u00FAsqueda de Twitter para \"", search_terms, "\" en buscador")
browseURL(paste0("https://twitter.com/search?q=", URLencode(search_terms), "&lang=es"))
}
# if system language contains "fr" use French Twitter version
else if (grepl("fr", lang)) {
message("Ouvrir Twitter recherche pour \"", search_terms, "\" en navigateur")
browseURL(paste0("https://twitter.com/search?q=", URLencode(search_terms), "&lang=fr"))
}
# if "lang" is not specified and default system language is not
# English, German, Spanish or French, use the English version
else {
message("Opening Twitter search for \"", search_terms, "\" in browser")
browseURL(paste0("https://twitter.com/search?q=", URLencode(search_terms), "&lang=en"))
}
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/twitter.R
|
#' Access Domain
#' @description Improve your workflow by accessing web directly from R console.
#' @param address The web address you want to open, encapsulated in " ".
#' @param https if FALSE "http" will be used instead of the default "https".
#' @param suppressWWW if TRUE "www" will be suppressed and the user input will follow directly after https://
#' @keywords web workflow
#' @examples
#' web("r-project.org")
#' @export
web <- function(address, https = TRUE, suppressWWW = FALSE) {
if (https==TRUE) {
a <- paste0("https://")
}
else {
a <- paste0("http://")
}
if (suppressWWW==FALSE) {
b <- paste0("www.", address)
}
else {
b <- paste0(address)
}
message("Opening ", a, b, " in browser")
browseURL(paste0(a, b))
}
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/web.R
|
#' Search Wikipedia
#' @description Improve your workflow by searching Wikipedia directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @param lang In which language Wikipedia should be accessed. One of c("en", "de", "es" "fr") for English, German, Spanish and French, respectively.
#' @keywords wikipedia internet workflow
#' @examples
#' wikipedia("my search terms")
#' wp("my search terms")
#' @export
wikipedia <- function(search_terms, lang = c("en", "de", "es", "fr")) {
if (missing(lang))
lang <- Sys.getenv("LANG")
# if system language contains "en" use English Wikipedia version
if (grepl("en", lang)) {
message("Opening Wikipedia search for \"", search_terms, "\" in browser")
browseURL(paste0("https://en.wikipedia.org/w/index.php?search=", URLencode(search_terms)))
}
# if system language contains "de" use German Wikipedia version
else if (grepl("de", lang)) {
message("\u00D6ffne Wikipedia Suche f\u00FCr \"", search_terms, "\" im Browser")
browseURL(paste0("https://de.wikipedia.org/w/index.php?search=", URLencode(search_terms)))
}
# if system language contains "es" use Spanish Wikipedia version
else if (grepl("es", lang)) {
message("Abriendo b\u00FAsqueda de Wikipedia \"", search_terms, "\" en browser")
browseURL(paste0("https://es.wikipedia.org/w/index.php?search=", URLencode(search_terms)))
}
# if system language contains "fr" use French Wikipedia version
else if (grepl("fr", lang)) {
message("Ouvrir Wikipedia recherche pour \"", search_terms, "\" en navigateur")
browseURL(paste0("https://fr.wikipedia.org/w/index.php?search=", URLencode(search_terms)))
}
# if "lang" is not specified and default system language is not
# English, German, Spanish or French, use the English version
else {
message("Opening Wikipedia search for \"", search_terms, "\" in browser")
browseURL(paste0("https://en.wikipedia.org/w/index.php?search=", URLencode(search_terms)))
}
}
#' @export
#' @rdname wikipedia
wp <- wikipedia
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/wikipedia.R
|
#' Search WolframAlpha
#' @description Improve your workflow by searching WolframAlpha directly from the console without having to switching to the browser and
#' opening a new tab first.
#' @param search_terms Search terms encapsulated in " ".
#' @keywords wolframalpha internet workflow
#' @examples
#' wolframalpha("my search terms")
#' wolfram("my search terms")
#' @export
wolframalpha <- function(search_terms) {
message("Searching WolframAlpha for \"", search_terms, "\" in browser")
browseURL(paste0("https://www.wolframalpha.com/input/?i=", URLencode(search_terms)))
}
#' @export
#' @rdname wolframalpha
wolfram <- wolframalpha
|
/scratch/gouwar.j/cran-all/cranData/websearchr/R/wolframalpha.r
|
#' Take a screenshot of a Shiny app
#'
#' \code{appshot} performs a \code{\link{webshot}} using two different methods
#' depending upon the object provided. If a 'character' is provided (pointing to
#' an app.R file or app directory) an isolated background R process is launched
#' to run the Shiny application. The current R process then captures the
#' \code{\link{webshot}}. When a Shiny application object is supplied to
#' \code{appshot}, it is reversed: the Shiny application runs in the current R
#' process and an isolated background R process is launched to capture a
#' \code{\link{webshot}}. The reason it is reversed in the second case has to do
#' with scoping: although it would be preferable to run the Shiny application in
#' a background process and call \code{webshot} from the current process, with
#' Shiny application objects, there are potential scoping errors when run this
#' way.
#'
#' @inheritParams webshot
#' @param app A Shiny app object, or a string naming an app directory.
#' @param port Port that Shiny will listen on.
#' @param envvars A named character vector or named list of environment
#' variables and values to set for the Shiny app's R process. These will be
#' unset after the process exits. This can be used to pass configuration
#' information to a Shiny app.
#' @param webshot_timeout The maximum number of seconds the phantom application
#' is allowed to run before killing the process. If a delay argument is
#' supplied (in \code{...}), the delay value is added to the timeout value.
#'
#' @param ... Other arguments to pass on to \code{\link{webshot}}.
#'
#' @rdname appshot
#' @examples
#' if (interactive()) {
#' appdir <- system.file("examples", "01_hello", package="shiny")
#'
#' # With a Shiny directory
#' appshot(appdir, "01_hello.png")
#'
#' # With a Shiny App object
#' shinyapp <- shiny::shinyAppDir(appdir)
#' appshot(shinyapp, "01_hello_app.png")
#' }
#'
#' @export
appshot <- function(app, file = "webshot.png", ...,
port = getOption("shiny.port"), envvars = NULL) {
UseMethod("appshot")
}
#' @rdname appshot
#' @export
appshot.character <- function(
app,
file = "webshot.png", ...,
port = getOption("shiny.port"),
envvars = NULL
) {
port <- available_port(port)
url <- shiny_url(port)
# Run app in background with envvars
p <- r_background_process(
function(...) {
shiny::runApp(...)
},
args = list(
appDir = app,
port = port,
display.mode = "normal",
launch.browser = FALSE
),
envvars = envvars
)
on.exit({
p$kill()
})
# Wait for app to start
wait_until_server_exists(url)
# Get screenshot
fileout <- webshot(url, file = file, ...)
invisible(fileout)
}
#' @rdname appshot
#' @export
appshot.shiny.appobj <- function(
app,
file = "webshot.png", ...,
port = getOption("shiny.port"),
envvars = NULL,
webshot_timeout = 60
) {
port <- available_port(port)
url <- shiny_url(port)
args <- list(
url = url,
file = file,
...,
timeout = webshot_app_timeout()
)
p <- r_background_process(
function(url, file, ..., timeout) {
# Wait for app to start
wait <- utils::getFromNamespace("wait_until_server_exists", "webshot")
wait(url, timeout = timeout)
webshot::webshot(url = url, file = file, ...)
},
args,
envvars = envvars
)
on.exit({
p$kill()
})
# add a delay to the webshot_timeout if it exists
if(!is.null(args$delay)) {
webshot_timeout <- webshot_timeout + args$delay
}
start_time <- as.numeric(Sys.time())
# Add a shiny app observer which checks every 200ms to see if the background r session is alive
shiny::observe({
# check the r session rather than the file to avoid race cases or random issues
if (p$is_alive()) {
if ((as.numeric(Sys.time()) - start_time) <= webshot_timeout) {
# try again later
shiny::invalidateLater(200)
} else {
# timeout has occured. close the app and R session
message("webshot timed out")
p$kill()
shiny::stopApp()
}
} else {
# r_bg session has stopped, close the app
shiny::stopApp()
}
return()
})
# run the app
shiny::runApp(app, port = port, display.mode = "normal", launch.browser = FALSE)
# return webshot::webshot file value
invisible(p$get_result()) # safe to call as the r_bg must have ended
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/appshot.R
|
#' Resize an image
#'
#' This does not change size of the image in pixels, nor does it affect
#' appearance -- it is lossless compression. This requires GraphicsMagick
#' (recommended) or ImageMagick to be installed.
#'
#' @param filename Character vector containing the path of images to resize.
#' @param geometry Scaling specification. Can be a percent, as in \code{"50\%"},
#' or pixel dimensions like \code{"120x120"}, \code{"120x"}, or \code{"x120"}.
#' Any valid ImageMagick geometry specifation can be used. If \code{filename}
#' contains multiple images, this can be a vector to specify distinct sizes
#' for each image.
#'
#' @examples
#' if (interactive()) {
#' # Can be chained with webshot() or appshot()
#' webshot("https://www.r-project.org/", "r-small-1.png") %>%
#' resize("75%")
#'
#' # Generate image that is 400 pixels wide
#' webshot("https://www.r-project.org/", "r-small-2.png") %>%
#' resize("400x")
#' }
#' @export
resize <- function(filename, geometry) {
mapply(resize_one, filename = filename, geometry = geometry,
SIMPLIFY = FALSE, USE.NAMES = FALSE)
structure(filename, class = "webshot")
}
resize_one <- function(filename, geometry) {
# Handle missing phantomjs
if (is.null(filename)) return(NULL)
# First look for graphicsmagick, then imagemagick
prog <- Sys.which("gm")
if (prog == "") {
# ImageMagick 7 has a "magick" binary
prog <- Sys.which("magick")
}
if (prog == "") {
if (is_windows()) {
prog <- find_magic()
} else {
prog <- Sys.which("convert")
}
}
if (prog == "")
stop("None of `gm`, `magick`, or `convert` were found in path. GraphicsMagick or ImageMagick must be installed and in path.")
args <- c(filename, "-resize", geometry, filename)
if (names(prog) %in% c("gm", "magick")) {
args <- c("convert", args)
}
res <- system2(prog, args)
if (res != 0)
stop ("Resizing with `gm convert`, `magick convert` or `convert` failed.")
filename
}
#' Shrink file size of a PNG
#'
#' This does not change size of the image in pixels, nor does it affect
#' appearance -- it is lossless compression. This requires the program
#' \code{optipng} to be installed.
#'
#' If other operations like resizing are performed, shrinking should occur as
#' the last step. Otherwise, if the resizing happens after file shrinking, it
#' will be as if the shrinking didn't happen at all.
#'
#' @param filename Character vector containing the path of images to resize.
#' Must be PNG files.
#'
#' @examples
#' if (interactive()) {
#' webshot("https://www.r-project.org/", "r-shrink.png") %>%
#' shrink()
#' }
#' @export
shrink <- function(filename) {
mapply(shrink_one, filename = filename, SIMPLIFY = FALSE, USE.NAMES = FALSE)
structure(filename, class = "webshot")
}
shrink_one <- function(filename) {
# Handle missing phantomjs
if (is.null(filename)) return(NULL)
optipng <- Sys.which("optipng")
if (optipng == "")
stop("optipng not found in path. optipng must be installed and in path.")
res <- system2('optipng', filename)
if (res != 0)
stop ("Shrinking with `optipng` failed.")
filename
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/image.R
|
#' @importFrom magrittr %>%
#' @export
magrittr::`%>%`
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/pipe.R
|
r_background_process <- function(..., envvars = NULL) {
if (is.null(envvars)) {
envvars <- callr::rcmd_safe_env()
}
callr::r_bg(..., env = envvars)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/process.R
|
#' Take a snapshot of an R Markdown document
#'
#' This function can handle both static Rmd documents and Rmd documents with
#' \code{runtime: shiny}.
#'
#' @inheritParams appshot
#' @param doc The path to a Rmd document.
#' @param delay Time to wait before taking screenshot, in seconds. Sometimes a
#' longer delay is needed for all assets to display properly. If NULL (the
#' default), then it will use 0.2 seconds for static Rmd documents, and 3
#' seconds for Rmd documents with runtime:shiny.
#' @param rmd_args A list of additional arguments to pass to either
#' \code{\link[rmarkdown]{render}} (for static Rmd documents) or
#' \code{\link[rmarkdown]{run}} (for Rmd documents with runtime:shiny).
#'
#' @examples
#' if (interactive()) {
#' # rmdshot("rmarkdown_file.Rmd", "snapshot.png")
#'
#' # R Markdown file
#' input_file <- system.file("examples/knitr-minimal.Rmd", package = "knitr")
#' rmdshot(input_file, "minimal_rmd.png")
#'
#' # Shiny R Markdown file
#' input_file <- system.file("examples/shiny.Rmd", package = "webshot")
#' rmdshot(input_file, "shiny_rmd.png", delay = 5)
#' }
#'
#' @export
rmdshot <- function(doc, file = "webshot.png", ..., delay = NULL, rmd_args = list(),
port = getOption("shiny.port"), envvars = NULL) {
runtime <- rmarkdown::yaml_front_matter(doc)$runtime
if (is_shiny(runtime)) {
if (is.null(delay)) delay <- 3
rmdshot_shiny(doc, file, ..., delay = delay, rmd_args = rmd_args,
port = port, envvars = envvars)
} else {
if (is.null(delay)) delay <- 0.2
outfile <- tempfile("webshot", fileext = ".html")
do.call(rmarkdown::render, c(list(doc, output_file = outfile), rmd_args))
webshot(outfile, file = file, ...)
}
}
rmdshot_shiny <- function(doc, file, ..., rmd_args, port, envvars) {
port <- available_port(port)
url <- shiny_url(port)
# Run app in background with envvars
p <- r_background_process(
function(...) {
rmarkdown::run(...)
},
args = append(
list(file = doc, shiny_args = list(port = port)),
rmd_args
),
envvars = envvars
)
on.exit({
p$kill()
})
# Wait for app to start
wait_until_server_exists(url)
fileout <- webshot(url, file = file, ...)
invisible(fileout)
}
# Borrowed from rmarkdown
is_shiny <- function (runtime) {
!is.null(runtime) && grepl("^shiny", runtime)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/rmdshot.R
|
phantom_run <- function(args, wait = TRUE, quiet = FALSE) {
phantom_bin <- find_phantom(quiet = quiet)
# Handle missing phantomjs
if (is.null(phantom_bin)) return(NULL)
# Make sure args is a char vector
args <- as.character(args)
p <- callr::process$new(
phantom_bin,
args = args,
stdout = "|", stderr = "|",
supervise = TRUE
)
if (isTRUE(wait)) {
on.exit({
p$kill()
})
cat_n <- function(txt) {
if (length(txt) > 0) {
cat(txt, sep = "\n")
}
}
while(p$is_alive()) {
p$wait(200) # wait until min(c(time_ms, process ends))
cat_n(p$read_error_lines())
cat_n(p$read_output_lines())
}
}
p$get_exit_status()
}
# Find PhantomJS from PATH, APPDATA, system.file('webshot'), ~/bin, etc
find_phantom <- function(quiet = FALSE) {
path <- Sys.which( "phantomjs" )
if (path != "") return(path)
for (d in phantom_paths()) {
exec <- if (is_windows()) "phantomjs.exe" else "phantomjs"
path <- file.path(d, exec)
if (utils::file_test("-x", path)) break else path <- ""
}
if (path == "") {
# It would make the most sense to throw an error here. However, that would
# cause problems with CRAN. The CRAN checking systems may not have phantomjs
# and may not be capable of installing phantomjs (like on Solaris), and any
# packages which use webshot in their R CMD check (in examples or vignettes)
# will get an ERROR. We'll issue a message and return NULL; other
if(!quiet) {
message(
"PhantomJS not found. You can install it with webshot::install_phantomjs(). ",
"If it is installed, please make sure the phantomjs executable ",
"can be found via the PATH variable."
)
}
return(NULL)
}
path.expand(path)
}
phantomjs_cmd_result <- function(args, wait = TRUE, quiet = FALSE) {
# Retrieve and store output from STDOUT
utils::capture.output(invisible(phantom_run(args = args, wait = wait, quiet = quiet)),
type = "output")
}
phantomjs_version <- function() {
phantomjs_cmd_result("--version", quiet = TRUE)
}
#' Determine if PhantomJS is Installed
#'
#' Verifies that a version of PhantomJS is installed and available for use
#' on the user's computer.
#'
#' @return \code{TRUE} if the PhantomJS is installed. Otherwise, \code{FALSE}
#' if PhantomJS is not installed.
#'
#' @export
is_phantomjs_installed <- function() {
!is.null(find_phantom(quiet = TRUE))
}
is_phantomjs_version_latest <- function(requested_version) {
# Ensure phantomjs is installed if not, request an update
if (!is_phantomjs_installed()) {
return(FALSE)
}
# Obtain the installed version
installed_phantomjs_version <- phantomjs_version()
# For versions 2.5.0-beta and 2.5.0-beta2, phantomjs reports its version to be
# "2.5.0-development".
#
# However, for the requested version, we have the names "2.5.0-beta" and
# "2.5.0-beta2".
#
# For simplicity, we'll just remove the "-development" or "-beta" or "-beta2"
# so they all map to "2.5.0".
installed_phantomjs_version <- sub("-development", "", installed_phantomjs_version)
requested_version <- sub("-beta.*", "", requested_version)
# Check if the installed version is latest compared to requested version.
as.package_version(installed_phantomjs_version) >= requested_version
}
#' Install PhantomJS
#'
#' Download the zip package, unzip it, and copy the executable to a system
#' directory in which \pkg{webshot} can look for the PhantomJS executable.
#'
#' @details This function was designed primarily to help Windows users since it
#' is cumbersome to modify the \code{PATH} variable. Mac OS X users may
#' install PhantomJS via Homebrew. If you download the package from the
#' PhantomJS website instead, please make sure the executable can be found via
#' the \code{PATH} variable.
#'
#' On Windows, the directory specified by the environment variable
#' \code{APPDATA} is used to store \file{phantomjs.exe}. On OS X, the
#' directory \file{~/Library/Application Support} is used. On other platforms
#' (such as Linux), the directory \file{~/bin} is used. If these directories
#' are not writable, the directory \file{PhantomJS} under the installation
#' directory of the \pkg{webshot} package will be tried. If this directory
#' still fails, you will have to install PhantomJS by yourself.
#'
#' If PhantomJS is not already installed on the computer, this function will
#' attempt to install it. However, if the version of PhantomJS installed is
#' greater than or equal to the requested version, this function will not
#' perform the installation procedure again unless the \code{force} parameter
#' is set to \code{TRUE}. As a result, this function may also be used to
#' reinstall or downgrade the version of PhantomJS found.
#'
#' @param version The version number of PhantomJS.
#' @param baseURL The base URL for the location of PhantomJS binaries for
#' download. If the default download site is unavailable, you may specify an
#' alternative mirror, such as
#' \code{"https://bitbucket.org/ariya/phantomjs/downloads/"}.
#' @param force Install PhantomJS even if the version installed is the latest or
#' if the requested version is older. This is useful to reinstall or downgrade
#' the version of PhantomJS.
#' @return \code{NULL} (the executable is written to a system directory).
#' @export
install_phantomjs <- function(version = '2.1.1',
baseURL = 'https://github.com/wch/webshot/releases/download/v0.3.1/',
force = FALSE) {
if (!force && is_phantomjs_version_latest(version)) {
message('It seems that the version of `phantomjs` installed is ',
'greater than or equal to the requested version.',
'To install the requested version or downgrade to another version, ',
'use `force = TRUE`.')
return(invisible())
}
if (!grepl("/$", baseURL))
baseURL <- paste0(baseURL, "/")
owd <- setwd(tempdir())
on.exit(setwd(owd), add = TRUE)
if (is_windows()) {
zipfile <- sprintf('phantomjs-%s-windows.zip', version)
download(paste0(baseURL, zipfile), zipfile, mode = 'wb')
utils::unzip(zipfile)
zipdir <- sub('.zip$', '', zipfile)
exec <- file.path(zipdir, 'bin', 'phantomjs.exe')
} else if (is_osx()) {
zipfile <- sprintf('phantomjs-%s-macosx.zip', version)
download(paste0(baseURL, zipfile), zipfile, mode = 'wb')
utils::unzip(zipfile)
zipdir <- sub('.zip$', '', zipfile)
exec <- file.path(zipdir, 'bin', 'phantomjs')
Sys.chmod(exec, '0755') # chmod +x
} else if (is_linux()) {
zipfile <- sprintf(
'phantomjs-%s-linux-%s.tar.bz2', version,
if (grepl('64', Sys.info()[['machine']])) 'x86_64' else 'i686'
)
download(paste0(baseURL, zipfile), zipfile, mode = 'wb')
utils::untar(zipfile)
zipdir <- sub('.tar.bz2$', '', zipfile)
exec <- file.path(zipdir, 'bin', 'phantomjs')
Sys.chmod(exec, '0755') # chmod +x
} else {
# Unsupported platform, like Solaris
message("Sorry, this platform is not supported.")
return(invisible())
}
success <- FALSE
dirs <- phantom_paths()
for (destdir in dirs) {
dir.create(destdir, showWarnings = FALSE)
success <- file.copy(exec, destdir, overwrite = TRUE)
if (success) break
}
unlink(c(zipdir, zipfile), recursive = TRUE)
if (!success) stop(
'Unable to install PhantomJS to any of these dirs: ',
paste(dirs, collapse = ', ')
)
message('phantomjs has been installed to ', normalizePath(destdir))
invisible()
}
# Possible locations of the PhantomJS executable
phantom_paths <- function() {
if (is_windows()) {
path <- Sys.getenv('APPDATA', '')
path <- if (dir_exists(path)) file.path(path, 'PhantomJS')
} else if (is_osx()) {
path <- '~/Library/Application Support'
path <- if (dir_exists(path)) file.path(path, 'PhantomJS')
} else {
path <- '~/bin'
}
path <- c(path, file.path(system.file(package = 'webshot'), 'PhantomJS'))
path
}
dir_exists <- function(path) utils::file_test('-d', path)
# Given a vector or list, drop all the NULL items in it
dropNulls <- function(x) {
x[!vapply(x, is.null, FUN.VALUE=logical(1))]
}
is_windows <- function() .Platform$OS.type == "windows"
is_osx <- function() Sys.info()[['sysname']] == 'Darwin'
is_linux <- function() Sys.info()[['sysname']] == 'Linux'
is_solaris <- function() Sys.info()[['sysname']] == 'SunOS'
# Find an available TCP port (to launch Shiny apps)
available_port <- function(port = NULL, min = 3000, max = 9000) {
if (!is.null(port)) return(port)
# Unsafe port list from shiny::runApp()
valid_ports <- setdiff(min:max, c(3659, 4045, 6000, 6665:6669, 6697))
# Try up to 20 ports
for (port in sample(valid_ports, 20)) {
handle <- NULL
# Check if port is open
tryCatch(
handle <- httpuv::startServer("127.0.0.1", port, list()),
error = function(e) { }
)
if (!is.null(handle)) {
httpuv::stopServer(handle)
return(port)
}
}
stop("Cannot find an available port")
}
# Wrapper for utils::download.file which works around a problem with R 3.3.0 and
# 3.3.1. In these versions, download.file(method="libcurl") issues a HEAD
# request to check if a file is available, before sending the GET request. This
# causes problems when downloading attached files from GitHub binary releases
# (like the PhantomJS binaries), because the url for the GET request returns a
# 403 for HEAD requests. See
# https://stat.ethz.ch/pipermail/r-devel/2016-June/072852.html
download <- function(url, destfile, mode = "w") {
if (getRversion() >= "3.3.0") {
download_no_libcurl(url, destfile, mode = mode)
} else if (is_windows() && getRversion() < "3.2") {
# Older versions of R on Windows need setInternet2 to download https.
download_old_win(url, destfile, mode = mode)
} else {
utils::download.file(url, destfile, mode = mode)
}
}
# Adapted from downloader::download, but avoids using libcurl.
download_no_libcurl <- function(url, ...) {
# Windows
if (is_windows()) {
method <- "wininet"
utils::download.file(url, method = method, ...)
} else {
# If non-Windows, check for libcurl/curl/wget/lynx, then call download.file with
# appropriate method.
if (nzchar(Sys.which("wget")[1])) {
method <- "wget"
} else if (nzchar(Sys.which("curl")[1])) {
method <- "curl"
# curl needs to add a -L option to follow redirects.
# Save the original options and restore when we exit.
orig_extra_options <- getOption("download.file.extra")
on.exit(options(download.file.extra = orig_extra_options))
options(download.file.extra = paste("-L", orig_extra_options))
} else if (nzchar(Sys.which("lynx")[1])) {
method <- "lynx"
} else {
stop("no download method found")
}
utils::download.file(url, method = method, ...)
}
}
# Adapted from downloader::download, for R<3.2 on Windows
download_old_win <- function(url, ...) {
# If we directly use setInternet2, R CMD CHECK gives a Note on Mac/Linux
seti2 <- `::`(utils, 'setInternet2')
# Check whether we are already using internet2 for internal
internet2_start <- seti2(NA)
# If not then temporarily set it
if (!internet2_start) {
# Store initial settings, and restore on exit
on.exit(suppressWarnings(seti2(internet2_start)))
# Needed for https. Will get warning if setInternet2(FALSE) already run
# and internet routines are used. But the warnings don't seem to matter.
suppressWarnings(seti2(TRUE))
}
method <- "internal"
# download.file will complain about file size with something like:
# Warning message:
# In download.file(url, ...) : downloaded length 19457 != reported length 200
# because apparently it compares the length with the status code returned (?)
# so we supress that
utils::download.file(url, method = method, ...)
}
# Fix local filenames like "c:/path/file.html" to "file:///c:/path/file.html"
# because that's the format used by casperjs and the webshot.js script.
fix_windows_url <- function(url) {
if (!is_windows()) return(url)
fix_one <- function(x) {
# If it's a "c:/path/file.html" path, or contains any backslashs, like
# "c:\path", "\\path\\file.html", or "/path\\file.html", we need to fix it
# up. However, we need to leave paths that are already URLs alone.
if (grepl("^[a-zA-Z]:[/\\]", x) ||
(!grepl(":", x, fixed = TRUE) && grepl("\\", x, fixed = TRUE)))
{
paste0("file:///", normalizePath(x, winslash = "/"))
} else {
x
}
}
vapply(url, fix_one, character(1), USE.NAMES = FALSE)
}
# Borrowed from animation package, with some adaptations.
find_magic = function() {
# try to look for ImageMagick in the Windows Registry Hive, the Program Files
# directory and the LyX installation
if (!inherits(try({
magick.path = utils::readRegistry('SOFTWARE\\ImageMagick\\Current')$BinPath
}, silent = TRUE), 'try-error')) {
if (nzchar(magick.path)) {
convert = normalizePath(file.path(magick.path, 'convert.exe'), "/", mustWork = FALSE)
}
} else if (
nzchar(prog <- Sys.getenv('ProgramFiles')) &&
length(magick.dir <- list.files(prog, '^ImageMagick.*')) &&
length(magick.path <- list.files(file.path(prog, magick.dir), pattern = '^convert\\.exe$',
full.names = TRUE, recursive = TRUE))
) {
convert = normalizePath(magick.path[1], "/", mustWork = FALSE)
} else if (!inherits(try({
magick.path = utils::readRegistry('LyX.Document\\Shell\\open\\command', 'HCR')
}, silent = TRUE), 'try-error')) {
convert = file.path(dirname(gsub('(^\"|\" \"%1\"$)', '', magick.path[[1]])), c('..', '../etc'),
'imagemagick', 'convert.exe')
convert = convert[file.exists(convert)]
if (length(convert)) {
convert = normalizePath(convert, "/", mustWork = FALSE)
} else {
warning('No way to find ImageMagick!')
return("")
}
} else {
warning('ImageMagick not installed yet!')
return("")
}
if (!file.exists(convert)) {
# Found an ImageMagick installation, but not the convert.exe binary.
warning("ImageMagick's convert.exe not found at ", convert)
return("")
}
return(convert)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/utils.R
|
shiny_url <- function(port) {
sprintf("http://127.0.0.1:%d/", port)
}
server_exists <- function(url) {
!inherits(
try({ suppressWarnings(readLines(url, 1)) }, silent = TRUE),
"try-error"
)
}
webshot_app_timeout <- function() {
getOption("webshot.app.timeout", 60)
}
wait_until_server_exists <- function(
url,
timeout = webshot_app_timeout()
) {
cur_time <- function() {
as.numeric(Sys.time())
}
start <- cur_time()
while(!server_exists(url)) {
if (cur_time() - start > timeout) {
stop(
'It took more than ', timeout, ' seconds to launch the Shiny Application. ',
'There may be something wrong. The process has been killed. ',
'If the app needs more time to be launched, set ',
'options(webshot.app.timeout) to a larger value.',
call. = FALSE
)
}
Sys.sleep(0.25)
}
TRUE
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/wait.R
|
#' Take a screenshot of a URL
#'
#' @param url A vector of URLs to visit.
#' @param file A vector of names of output files. Should end with \code{.png},
#' \code{.pdf}, or \code{.jpeg}. If several screenshots have to be taken and
#' only one filename is provided, then the function appends the index number
#' of the screenshot to the file name.
#' @param vwidth Viewport width. This is the width of the browser "window".
#' @param vheight Viewport height This is the height of the browser "window".
#' @param cliprect Clipping rectangle. If \code{cliprect} and \code{selector}
#' are both unspecified, the clipping rectangle will contain the entire page.
#' This can be the string \code{"viewport"}, in which case the clipping
#' rectangle matches the viewport size, or it can be a four-element numeric
#' vector specifying the top, left, width, and height. When taking screenshots
#' of multiple URLs, this parameter can also be a list with same length as
#' \code{url} with each element of the list being "viewport" or a
#' four-elements numeric vector. This option is not compatible with
#' \code{selector}.
#' @param selector One or more CSS selectors specifying a DOM element to set the
#' clipping rectangle to. The screenshot will contain these DOM elements. For
#' a given selector, if it has more than one match, only the first one will be
#' used. This option is not compatible with \code{cliprect}. When taking
#' screenshots of multiple URLs, this parameter can also be a list with same
#' length as \code{url} with each element of the list containing a vector of
#' CSS selectors to use for the corresponding URL.
#' @param delay Time to wait before taking screenshot, in seconds. Sometimes a
#' longer delay is needed for all assets to display properly.
#' @param expand A numeric vector specifying how many pixels to expand the
#' clipping rectangle by. If one number, the rectangle will be expanded by
#' that many pixels on all sides. If four numbers, they specify the top,
#' right, bottom, and left, in that order. When taking screenshots of multiple
#' URLs, this parameter can also be a list with same length as \code{url} with
#' each element of the list containing a single number or four numbers to use
#' for the corresponding URL.
#' @param zoom A number specifying the zoom factor. A zoom factor of 2 will
#' result in twice as many pixels vertically and horizontally. Note that using
#' 2 is not exactly the same as taking a screenshot on a HiDPI (Retina)
#' device: it is like increasing the zoom to 200% in a desktop browser and
#' doubling the height and width of the browser window. This differs from
#' using a HiDPI device because some web pages load different,
#' higher-resolution images when they know they will be displayed on a HiDPI
#' device (but using zoom will not report that there is a HiDPI device).
#' @param eval An optional string with JavaScript code which will be evaluated
#' after opening the page and waiting for \code{delay}, but before calculating
#' the clipping region and taking the screenshot. See the Casper API
#' for more information about what commands can be used to control the web
#' page. NOTE: This is experimental and likely to change!
#' @param debug Print out debugging messages from PhantomJS and CasperJS. This can help to
#' diagnose problems.
#' @param useragent The User-Agent header used to request the URL. Changing the
#' User-Agent can mitigate rendering issues for some websites.
#'
#' @examples
#' if (interactive()) {
#'
#' # Whole web page
#' webshot("https://github.com/rstudio/shiny")
#'
#' # Might need a longer delay for all assets to display
#' webshot("http://rstudio.github.io/leaflet", delay = 0.5)
#'
#' # One can also take screenshots of several URLs with only one command.
#' # This is more efficient than calling 'webshot' multiple times.
#' webshot(c("https://github.com/rstudio/shiny",
#' "http://rstudio.github.io/leaflet"),
#' delay = 0.5)
#'
#' # Clip to the viewport
#' webshot("http://rstudio.github.io/leaflet", "leaflet-viewport.png",
#' cliprect = "viewport")
#'
#' # Manual clipping rectangle
#' webshot("http://rstudio.github.io/leaflet", "leaflet-clip.png",
#' cliprect = c(200, 5, 400, 300))
#'
#' # Using CSS selectors to pick out regions
#' webshot("http://rstudio.github.io/leaflet", "leaflet-menu.png", selector = ".list-group")
#' webshot("http://reddit.com/", "reddit-top.png",
#' selector = c("input[type='text']", "#header-bottom-left"))
#'
#' # Expand selection region
#' webshot("http://rstudio.github.io/leaflet", "leaflet-boxes.png",
#' selector = "#installation", expand = c(10, 50, 0, 50))
#'
#' # If multiple matches for a given selector, it uses the first match
#' webshot("http://rstudio.github.io/leaflet", "leaflet-p.png", selector = "p")
#' webshot("https://github.com/rstudio/shiny/", "shiny-stats.png",
#' selector = "ul.numbers-summary")
#'
#' # Send commands to eval
#' webshot("http://www.reddit.com/", "reddit-input.png",
#' selector = c("#search", "#login_login-main"),
#' eval = "casper.then(function() {
#' // Check the remember me box
#' this.click('#rem-login-main');
#' // Enter username and password
#' this.sendKeys('#login_login-main input[type=\"text\"]', 'my_username');
#' this.sendKeys('#login_login-main input[type=\"password\"]', 'password');
#'
#' // Now click in the search box. This results in a box expanding below
#' this.click('#search input[type=\"text\"]');
#' // Wait 500ms
#' this.wait(500);
#' });"
#' )
#'
#' # Result can be piped to other commands like resize() and shrink()
#' webshot("https://www.r-project.org/", "r-small.png") %>%
#' resize("75%") %>%
#' shrink()
#'
#' # Requests can change the User-Agent header
#' webshot(
#' "https://www.rstudio.com/products/rstudio/download/",
#' "rstudio.png",
#' useragent = "Mozilla/5.0 (Macintosh; Intel Mac OS X)"
#' )
#'
#' # See more examples in the package vignette
# vignette("intro", package = "webshot")
#' }
#'
#' @seealso \code{\link{appshot}} for taking screenshots of Shiny applications.
#' @export
webshot <- function(
url = NULL,
file = "webshot.png",
vwidth = 992,
vheight = 744,
cliprect = NULL,
selector = NULL,
expand = NULL,
delay = 0.2,
zoom = 1,
eval = NULL,
debug = FALSE,
useragent = NULL
) {
if (is.null(url)) {
stop("Need url.")
}
# Convert params cliprect, selector and expand to list if necessary
if(!is.null(cliprect) && !is.list(cliprect)) cliprect <- list(cliprect)
if(!is.null(selector) && !is.list(selector)) selector <- list(selector)
if(!is.null(expand) && !is.list(expand)) expand <- list(expand)
# Check length of arguments
arg_list <- list(
url = url,
file = file,
vwidth = vwidth,
vheight = vheight,
cliprect = cliprect,
selector = selector,
expand = expand,
delay = delay,
zoom = zoom,
eval = eval,
debug = debug,
options = options
)
arg_length <- vapply(arg_list, length, numeric(1))
max_arg_length <- max(arg_length)
if (any(! arg_length %in% c(0, 1, max_arg_length))) {
stop("All arguments should have same length or be single elements or NULL")
}
# If url is of length one replicate it to match the maximal length of arguments
if (length(url) < max_arg_length) url <- rep(url, max_arg_length)
# If user provides only one file name but wants several screenshots, then the
# below code generates as many file names as URLs following the pattern
# "filename001.png", "filename002.png", ... (or whatever extension it is)
if (length(url) > 1 && length(file) == 1) {
file <- vapply(1:length(url), FUN.VALUE = character(1), function(i) {
replacement <- sprintf("%03d.\\1", i)
gsub("\\.(.{3,4})$", replacement, file)
})
}
if (is_windows()) {
url <- fix_windows_url(url)
}
if (!is.null(cliprect) && !is.null(selector)) {
stop("Can't specify both cliprect and selector.")
} else if (is.null(selector) && !is.null(cliprect)) {
cliprect <- lapply(cliprect, function(x) {
if (is.character(x)) {
if (x == "viewport") {
x <- c(0, 0, vwidth, vheight)
} else {
stop("Invalid value for cliprect: ", x)
}
} else {
if (!is.numeric(x) || length(x) != 4) {
stop("'cliprect' must be a 4-element numeric vector or a list of such vectors")
}
}
x
})
}
# check that expand is a vector of length 1 or 4 or a list of such vectors
if (!is.null(expand)) {
lengths <- vapply(expand, length, numeric(1))
if (any(!lengths %in% c(1, 4))) {
stop("'expand' must be a vector with one or four numbers, or a list of such vectors.")
}
}
# Create the table that contains all options for each screenshot
optsList <- data.frame(url = url, file = file, vwidth = vwidth, vheight = vheight)
# Params selector, cliprect and expand can be either a vector that need to be
# concatenated or a list of such vectors. This function can be used to convert
# them into a character vector with the desired format.
argToVec <- function(arg) {
vapply(arg, FUN.VALUE = character(1), function(x) {
if (any(is.null(x)) || any(is.na(x))) NA_character_
else paste(x, collapse = ",")
})
}
if (!is.null(cliprect)) optsList$cliprect <- argToVec(cliprect)
if (!is.null(selector)) optsList$selector <- argToVec(selector)
if (!is.null(expand)) optsList$expand <- argToVec(expand)
if (!is.null(delay)) optsList$delay <- delay
if (!is.null(zoom)) optsList$zoom <- zoom
if (!is.null(eval)) optsList$eval <- eval
if (!is.null(useragent)) optsList$options <- jsonlite::toJSON(
list(pageSettings = list(userAgent = useragent)),
auto_unbox = TRUE
)
optsList$debug <- debug
args <- list(
# Workaround for SSL problem: https://github.com/wch/webshot/issues/51
# https://stackoverflow.com/questions/22461345/casperjs-status-fail-on-a-webpage
"--ignore-ssl-errors=true",
system.file("webshot.js", package = "webshot"),
jsonlite::toJSON(optsList)
)
res <- phantom_run(args)
# Handle missing phantomjs
if (is.null(res)) return(NULL)
if (res != 0) {
stop("webshot.js returned failure value: ", res)
}
structure(file, class = "webshot")
}
knit_print.webshot <- function(x, ...) {
lapply(x, function(filename) {
res <- readBin(filename, "raw", file.size(filename))
ext <- gsub(".*[.]", "", basename(filename))
structure(list(image = res, extension = ext), class = "html_screenshot")
})
}
#' @export
print.webshot <- function(x, ...) {
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/webshot.R
|
register_s3_method <- function(pkg, generic, class, fun = NULL) {
stopifnot(is.character(pkg), length(pkg) == 1)
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
if (is.null(fun)) {
fun <- get(paste0(generic, ".", class), envir = parent.frame())
} else {
stopifnot(is.function(fun))
}
if (pkg %in% loadedNamespaces()) {
registerS3method(generic, class, fun, envir = asNamespace(pkg))
}
# Always register hook in case package is later unloaded & reloaded
setHook(
packageEvent(pkg, "onLoad"),
function(...) {
registerS3method(generic, class, fun, envir = asNamespace(pkg))
}
)
}
.onLoad <- function(...) {
# webshot provides methods for knitr::knit_print, but knitr isn't a Depends
# or Imports of htmltools, only an Enhances. This code snippet manually
# registers our method(s) with S3 once both webshot and knitr are loaded.
register_s3_method("knitr", "knit_print", "webshot")
}
|
/scratch/gouwar.j/cran-all/cranData/webshot/R/zzz.R
|
---
title: "Shiny Example"
author: "RStudio"
date: "2/28/2018"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
This R Markdown document is made interactive using Shiny. Unlike the more traditional workflow of creating static reports, you can now create documents that allow your readers to change the assumptions underlying your analysis and see the results immediately.
To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Inputs and Outputs
You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change. This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot.
```{r eruptions, echo=FALSE}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
## Embedded Application
It's also possible to embed an entire Shiny application within an R Markdown document using the `shinyAppDir` function. This example embeds a Shiny application located in another directory:
```{r tabsets, echo=FALSE}
shinyAppDir(
system.file("examples/06_tabsets", package = "shiny"),
options = list(
width = "100%", height = 550
)
)
```
Note the use of the `height` parameter to determine how much vertical space the embedded application should occupy.
You can also use the `shinyApp` function to define an application inline rather then in an external directory.
In all of R code chunks above the `echo = FALSE` attribute is used. This is to prevent the R code within the chunk from rendering in the document alongside the Shiny components.
|
/scratch/gouwar.j/cran-all/cranData/webshot/inst/examples/shiny.Rmd
|
#' Take a screenshot of a Shiny app
#'
#' \code{appshot} performs a \code{\link{webshot}} using two different methods
#' depending upon the object provided. If a 'character' is provided (pointing to
#' an app.R file or app directory) an isolated background R process is launched
#' to run the Shiny application. The current R process then captures the
#' \code{\link{webshot}}. When a Shiny application object is supplied to
#' \code{appshot}, it is reversed: the Shiny application runs in the current R
#' process and an isolated background R process is launched to capture a
#' \code{\link{webshot}}. The reason it is reversed in the second case has to do
#' with scoping: although it would be preferable to run the Shiny application in
#' a background process and call \code{webshot} from the current process, with
#' Shiny application objects, there are potential scoping errors when run this
#' way.
#'
#' @inheritParams webshot
#' @param app A Shiny app object, or a string naming an app directory.
#' @param port Port that Shiny will listen on.
#' @param envvars A named character vector or named list of environment
#' variables and values to set for the Shiny app's R process. These will be
#' unset after the process exits. This can be used to pass configuration
#' information to a Shiny app.
#' @param webshot_timeout The maximum number of seconds the phantom application
#' is allowed to run before killing the process. If a delay argument is
#' supplied (in \code{...}), the delay value is added to the timeout value.
#'
#' @param ... Other arguments to pass on to \code{\link{webshot}}.
#' @template webshot-return
#'
#' @rdname appshot
#' @examples
#' if (interactive()) {
#' appdir <- system.file("examples", "01_hello", package="shiny")
#'
#' # With a Shiny directory
#' appshot(appdir, "01_hello.png")
#'
#' # With a Shiny App object
#' shinyapp <- shiny::shinyAppDir(appdir)
#' appshot(shinyapp, "01_hello_app.png")
#' }
#'
#' @export
appshot <- function(app, file = "webshot.png", ...,
port = getOption("shiny.port"), envvars = NULL) {
UseMethod("appshot")
}
#' @rdname appshot
#' @export
appshot.character <- function(
app,
file = "webshot.png", ...,
port = getOption("shiny.port"),
envvars = NULL
) {
port <- available_port(port)
url <- shiny_url(port)
# Run app in background with envvars
p <- r_background_process(
function(...) {
shiny::runApp(...)
},
args = list(
appDir = app,
port = port,
display.mode = "normal",
launch.browser = FALSE
),
envvars = envvars
)
on.exit({
if (p$is_alive()) {
p$interrupt()
p$wait(2)
if (p$is_alive()) {
p$kill()
}
}
})
# Wait for app to start
wait_until_server_exists(url, p)
# Get screenshot
fileout <- webshot(url, file = file, ...)
invisible(fileout)
}
#' @rdname appshot
#' @export
appshot.shiny.appobj <- function(
app,
file = "webshot.png", ...,
port = getOption("shiny.port"),
envvars = NULL,
webshot_timeout = 60
) {
port <- available_port(port)
url <- shiny_url(port)
args <- list(
url = url,
file = file,
...,
timeout = webshot_app_timeout()
)
p <- r_background_process(
function(url, file, ..., timeout) {
# Wait for app to start
# Avoid ::: for internal function.
wait <- utils::getFromNamespace("wait_until_server_exists", "webshot2")
wait(url, timeout = timeout)
webshot2::webshot(url = url, file = file, ...)
},
args,
envvars = envvars
)
on.exit({
p$kill()
})
# add a delay to the webshot_timeout if it exists
if (!is.null(args$delay)) {
webshot_timeout <- webshot_timeout + args$delay
}
start_time <- as.numeric(Sys.time())
# Add a shiny app observer which checks every 200ms to see if the background r session is alive
shiny::observe({
# check the r session rather than the file to avoid race cases or random issues
if (p$is_alive()) {
if ((as.numeric(Sys.time()) - start_time) <= webshot_timeout) {
# try again later
shiny::invalidateLater(200)
} else {
# timeout has occured. close the app and R session
message("webshot timed out")
p$kill()
shiny::stopApp()
}
} else {
# r_bg session has stopped, close the app
shiny::stopApp()
}
return()
})
# run the app
shiny::runApp(app, port = port, display.mode = "normal", launch.browser = FALSE)
# return webshot2::webshot file value
invisible(p$get_result()) # safe to call as the r_bg must have ended
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/appshot.R
|
#' Resize an image
#'
#' This does not change size of the image in pixels, nor does it affect
#' appearance -- it is lossless compression. This requires GraphicsMagick
#' (recommended) or ImageMagick to be installed.
#'
#' @param filename Character vector containing the path of images to resize.
#' @param geometry Scaling specification. Can be a percent, as in \code{"50\%"},
#' or pixel dimensions like \code{"120x120"}, \code{"120x"}, or \code{"x120"}.
#' Any valid ImageMagick geometry specification can be used. If \code{filename}
#' contains multiple images, this can be a vector to specify distinct sizes
#' for each image.
#' @return The `filename` supplied but with a class value of `"webshot"`.
#'
#' @examples
#' if (interactive()) {
#' # Can be chained with webshot() or appshot()
#' webshot("https://www.r-project.org/", "r-small-1.png") %>%
#' resize("75%")
#'
#' # Generate image that is 400 pixels wide
#' webshot("https://www.r-project.org/", "r-small-2.png") %>%
#' resize("400x")
#' }
#' @export
resize <- function(filename, geometry) {
mapply(resize_one, filename = filename, geometry = geometry,
SIMPLIFY = FALSE, USE.NAMES = FALSE)
structure(filename, class = "webshot")
}
resize_one <- function(filename, geometry) {
# Handle missing phantomjs
if (is.null(filename)) return(NULL)
# First look for graphicsmagick, then imagemagick
prog <- Sys.which("gm")
if (prog == "") {
# ImageMagick 7 has a "magick" binary
prog <- Sys.which("magick")
}
if (prog == "") {
if (is_windows()) {
prog <- find_magic()
} else {
prog <- Sys.which("convert")
}
}
if (prog == "")
stop("None of `gm`, `magick`, or `convert` were found in path. GraphicsMagick or ImageMagick must be installed and in path.")
args <- c(filename, "-resize", geometry, filename)
if (names(prog) %in% c("gm", "magick")) {
args <- c("convert", args)
}
res <- system2(prog, args)
if (res != 0)
stop("Resizing with `gm convert`, `magick convert` or `convert` failed.")
filename
}
#' Shrink file size of a PNG
#'
#' This does not change size of the image in pixels, nor does it affect
#' appearance -- it is lossless compression. This requires the program
#' \code{optipng} to be installed.
#'
#' If other operations like resizing are performed, shrinking should occur as
#' the last step. Otherwise, if the resizing happens after file shrinking, it
#' will be as if the shrinking didn't happen at all.
#'
#' @param filename Character vector containing the path of images to resize.
#' Must be PNG files.
#' @return The `filename` supplied but with a class value of `"webshot"`.
#'
#' @examples
#' if (interactive()) {
#' webshot("https://www.r-project.org/", "r-shrink.png") %>%
#' shrink()
#' }
#' @export
shrink <- function(filename) {
mapply(shrink_one, filename = filename, SIMPLIFY = FALSE, USE.NAMES = FALSE)
structure(filename, class = "webshot")
}
shrink_one <- function(filename) {
# Handle missing phantomjs
if (is.null(filename)) return(NULL)
optipng <- Sys.which("optipng")
if (optipng == "")
stop("optipng not found in path. optipng must be installed and in path.")
res <- system2("optipng", filename)
if (res != 0)
stop("Shrinking with `optipng` failed.")
filename
}
# Borrowed from animation package, with some adaptations.
find_magic <- function() {
# try to look for ImageMagick in the Windows Registry Hive, the Program Files
# directory and the LyX installation
if (!inherits(try({
magick_path <- utils::readRegistry("SOFTWARE\\ImageMagick\\Current")$BinPath
}, silent = TRUE), "try-error")) {
if (nzchar(magick_path)) {
convert <- normalizePath(
file.path(magick_path, "convert.exe"), "/",
mustWork = FALSE
)
}
} else if (
nzchar(prog <- Sys.getenv("ProgramFiles")) &&
length(magick_dir <- list.files(prog, "^ImageMagick.*")) &&
length(magick_path <- list.files(
file.path(prog, magick_dir), pattern = "^convert\\.exe$",
full.names = TRUE, recursive = TRUE))
) {
convert <- normalizePath(magick_path[1], "/", mustWork = FALSE)
} else if (!inherits(try({
magick_path <- utils::readRegistry(
"LyX.Document\\Shell\\open\\command",
"HCR"
)
}, silent = TRUE), "try-error")) {
convert <- file.path(
dirname(gsub("(^\"|\" \"%1\"$)", "", magick_path[[1]])),
c("..", "../etc"),
"imagemagick",
"convert.exe"
)
convert <- convert[file.exists(convert)]
if (length(convert)) {
convert <- normalizePath(convert, "/", mustWork = FALSE)
} else {
warning("No way to find ImageMagick!")
return("")
}
} else {
warning("ImageMagick not installed yet!")
return("")
}
if (!file.exists(convert)) {
# Found an ImageMagick installation, but not the convert.exe binary.
warning("ImageMagick's convert.exe not found at ", convert)
return("")
}
return(convert)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/image.R
|
#' @importFrom magrittr %>%
#' @export
magrittr::`%>%`
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/pipe.R
|
r_background_process <- function(..., envvars = NULL) {
if (is.null(envvars)) {
envvars <- callr::rcmd_safe_env()
}
callr::r_bg(..., env = envvars)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/process.R
|
#' Take a snapshot of an R Markdown document
#'
#' This function can handle both static Rmd documents and Rmd documents with
#' \code{runtime: shiny}.
#'
#' @inheritParams appshot
#' @param doc The path to a Rmd document.
#' @param delay Time to wait before taking screenshot, in seconds. Sometimes a
#' longer delay is needed for all assets to display properly. If NULL (the
#' default), then it will use 0.2 seconds for static Rmd documents, and 3
#' seconds for Rmd documents with runtime:shiny.
#' @param rmd_args A list of additional arguments to pass to either
#' \code{\link[rmarkdown]{render}} (for static Rmd documents) or
#' \code{\link[rmarkdown]{run}} (for Rmd documents with runtime:shiny).
#' @template webshot-return
#'
#' @examples
#' if (interactive()) {
#' # R Markdown file
#' input_file <- system.file("examples/knitr-minimal.Rmd", package = "knitr")
#' rmdshot(input_file, "minimal_rmd.png")
#'
#' # Shiny R Markdown file
#' input_file <- system.file("examples/shiny.Rmd", package = "webshot")
#' rmdshot(input_file, "shiny_rmd.png", delay = 5)
#' }
#'
#' @export
rmdshot <- function(
doc,
file = "webshot.png",
...,
delay = NULL,
rmd_args = list(),
port = getOption("shiny.port"),
envvars = NULL
) {
runtime <- rmarkdown::yaml_front_matter(doc)$runtime
if (is_shiny(runtime)) {
if (is.null(delay)) delay <- 3
rmdshot_shiny(doc, file, ..., delay = delay, rmd_args = rmd_args,
port = port, envvars = envvars)
} else {
if (is.null(delay)) delay <- 0.2
outfile <- tempfile("webshot", fileext = ".html")
do.call(rmarkdown::render, c(list(doc, output_file = outfile), rmd_args))
webshot(file_url(outfile), file = file, ...)
}
}
rmdshot_shiny <- function(doc, file, ..., rmd_args, port, envvars) {
port <- available_port(port)
url <- shiny_url(port)
# Run app in background with envvars
p <- r_background_process(
function(...) {
rmarkdown::run(...)
},
args = list(
file = doc,
shiny_args = list(port = port),
render_args = rmd_args
),
envvars = envvars
)
on.exit({
p$kill()
})
# Wait for app to start
wait_until_server_exists(url, p)
fileout <- webshot(url, file = file, ...)
invisible(fileout)
}
# Borrowed from rmarkdown
is_shiny <- function(runtime) {
!is.null(runtime) && grepl("^shiny", runtime)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/rmdshot.R
|
# =============================================================================
# System
# =============================================================================
is_windows <- function() .Platform$OS.type == "windows"
is_mac <- function() Sys.info()[["sysname"]] == "Darwin"
is_linux <- function() Sys.info()[["sysname"]] == "Linux"
# =============================================================================
# Data manipulation
# =============================================================================
# Convert a list of vectors of the same length (like a data frame) to a list of
# lists, each of which is a one-row "slice" of the input (like a D3 data
# structure). The input list must be named, and the names must be unique.
long_to_wide <- function(x) {
if (length(x) == 0)
return(x)
lapply(seq_along(x[[1]]), function(n) {
lapply(stats::setNames(names(x), names(x)), function(name) {
x[[name]][[n]]
})
})
}
# =============================================================================
# Network-related stuff
# =============================================================================
# Find an available TCP port (to launch Shiny apps)
available_port <- function(port = NULL, min = 3000, max = 9000) {
if (!is.null(port)) return(port)
# Unsafe port list from shiny::runApp()
valid_ports <- setdiff(min:max, c(3659, 4045, 6000, 6665:6669, 6697))
# Try up to 20 ports
for (port in sample(valid_ports, 20)) {
handle <- NULL
# Check if port is open
tryCatch(
handle <- httpuv::startServer("127.0.0.1", port, list()),
error = function(e) { }
)
if (!is.null(handle)) {
handle$stop()
return(port)
}
}
stop("Cannot find an available port")
}
# Returns TRUE if a string is a URL (of form "http://...", "ftp://...",
# "file://..." and so on), FALSE otherwise.
is_url <- function(x) {
grepl("^[a-zA-Z]+://", x)
}
# Given the path to a file, return a file:// URL.
file_url <- function(filename) {
if (is_windows() && getRversion() < R_system_version("4.2.0")) {
enc2 <- identity
} else {
enc2 <- enc2utf8
}
file <- sub("(.*)#[^#]*", "\\1", filename)
anchor_suffix <- sub(file, "", filename)
enc2(paste0(
"file:///",
normalizePath(path = file, mustWork = TRUE),
anchor_suffix
))
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/utils.R
|
shiny_url <- function(port) {
sprintf("http://127.0.0.1:%d/", port)
}
server_exists <- function(url_id) {
# Using a url object instead of the url as a string because readLines() with
# url string will cause failed connections to stay open
url_obj <- url(url_id)
on.exit({close(url_obj)}, add = TRUE)
ret <- !inherits(
try({suppressWarnings(readLines(url_obj, 1))}, silent = TRUE),
"try-error"
)
ret
}
webshot_app_timeout <- function() {
getOption("webshot.app.timeout", 60)
}
wait_until_server_exists <- function(
url,
p,
timeout = webshot_app_timeout()
) {
cur_time <- function() {
as.numeric(Sys.time())
}
start <- cur_time()
while (!server_exists(url)) {
if (cur_time() - start > timeout) {
stop(
"It took more than ", timeout,
" seconds to launch the Shiny Application. ",
"There may be something wrong. The process has been killed. ",
"If the app needs more time to be launched, set ",
"options(webshot.app.timeout) to a larger value.",
call. = FALSE
)
}
# Check if there was a failure in starting app server
if (!p$is_alive()) {
stop(
"App has failed with error(s):\n",
paste(p$read_error_lines(), collapse = "\n"),
call. = FALSE
)
}
Sys.sleep(0.25)
}
TRUE
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/wait.R
|
#' @import chromote
#' @import later
#' @import promises
#'
NULL
#' Take a screenshot of a URL
#'
#' @param url A vector of URLs to visit. If multiple URLs are provided, it will
#' load and take screenshots of those web pages in parallel.
#' @param file A vector of names of output files. Should end with an image file
#' type (\code{.png}, \code{.jpg}, \code{.jpeg}, or \code{.webp}) or
#' \code{.pdf}. If several screenshots have to be taken and only one filename
#' is provided, then the function appends the index number of the screenshot
#' to the file name. For PDF output, it is just like printing the page to PDF
#' in a browser; \code{selector}, \code{cliprect}, \code{expand}, and
#' \code{zoom} will not be used for PDFs.
#' @param vwidth Viewport width. This is the width of the browser "window".
#' @param vheight Viewport height This is the height of the browser "window".
#' @param selector One or more CSS selectors specifying a DOM element to set the
#' clipping rectangle to. The screenshot will contain these DOM elements. For
#' a given selector, if it has more than one match, all matching elements will
#' be used. This option is not compatible with \code{cliprect}. When taking
#' screenshots of multiple URLs, this parameter can also be a list with same
#' length as \code{url} with each element of the list containing a vector of
#' CSS selectors to use for the corresponding URL.
#' @param cliprect Clipping rectangle. If \code{cliprect} and \code{selector}
#' are both unspecified, the clipping rectangle will contain the entire page.
#' This can be the string \code{"viewport"}, in which case the clipping
#' rectangle matches the viewport size, or it can be a four-element numeric
#' vector specifying the left, top, width, and height. (Note that the order of
#' left and top is reversed from the original webshot package.) When taking
#' screenshots of multiple URLs, this parameter can also be a list with same
#' length as \code{url} with each element of the list being "viewport" or a
#' four-elements numeric vector. This option is not compatible with
#' \code{selector}.
#' @param delay Time to wait before taking screenshot, in seconds. Sometimes a
#' longer delay is needed for all assets to display properly.
#' @param expand A numeric vector specifying how many pixels to expand the
#' clipping rectangle by. If one number, the rectangle will be expanded by
#' that many pixels on all sides. If four numbers, they specify the top,
#' right, bottom, and left, in that order. When taking screenshots of multiple
#' URLs, this parameter can also be a list with same length as \code{url} with
#' each element of the list containing a single number or four numbers to use
#' for the corresponding URL.
#' @param zoom A number specifying the zoom factor. A zoom factor of 2 will
#' result in twice as many pixels vertically and horizontally. Note that using
#' 2 is not exactly the same as taking a screenshot on a HiDPI (Retina)
#' device: it is like increasing the zoom to 200% in a desktop browser and
#' doubling the height and width of the browser window. This differs from
#' using a HiDPI device because some web pages load different,
#' higher-resolution images when they know they will be displayed on a HiDPI
#' device (but using zoom will not report that there is a HiDPI device).
#' @param useragent The User-Agent header used to request the URL.
#' @param max_concurrent (Currently not implemented)
#' @param quiet If `TRUE`, status updates via console messages are suppressed.
#' @template webshot-return
#'
#' @examples
#' if (interactive()) {
#'
#' # Whole web page
#' webshot("https://github.com/rstudio/shiny")
#'
#' # Might need a delay for all assets to display
#' webshot("http://rstudio.github.io/leaflet", delay = 0.5)
#'
#' # One can also take screenshots of several URLs with only one command.
#' # This is more efficient than calling 'webshot' multiple times.
#' webshot(c("https://github.com/rstudio/shiny",
#' "http://rstudio.github.io/leaflet"),
#' delay = 0.5)
#'
#' # Clip to the viewport
#' webshot("http://rstudio.github.io/leaflet", "leaflet-viewport.png",
#' cliprect = "viewport")
#'
#' # Specific size
#' webshot("https://www.r-project.org", vwidth = 1600, vheight = 900,
#' cliprect = "viewport")
#'
#' # Manual clipping rectangle
#' webshot("http://rstudio.github.io/leaflet", "leaflet-clip.png",
#' cliprect = c(200, 5, 400, 300))
#'
#' # Using CSS selectors to pick out regions
#' webshot("http://rstudio.github.io/leaflet", "leaflet-menu.png", selector = ".list-group")
#' # With multiple selectors, the screenshot will contain all selected elements
#' webshot("http://reddit.com/", "reddit-top.png",
#' selector = c("[aria-label='Home']", "input[type='search']"))
#'
#' # Expand selection region
#' webshot("http://rstudio.github.io/leaflet", "leaflet-boxes.png",
#' selector = "#installation", expand = c(10, 50, 0, 50))
#'
#' # If multiple matches for a given selector, it will take a screenshot that
#' # contains all matching elements.
#' webshot("http://rstudio.github.io/leaflet", "leaflet-p.png", selector = "p")
#' webshot("https://github.com/rstudio/shiny/", "shiny-stats.png",
#' selector = "ul.numbers-summary")
#'
#' # Result can be piped to other commands like resize() and shrink()
#' webshot("https://www.r-project.org/", "r-small.png") %>%
#' resize("75%") %>%
#' shrink()
#'
#' }
#'
#' @export
webshot <- function(
url = NULL,
file = "webshot.png",
vwidth = 992,
vheight = 744,
selector = NULL,
cliprect = NULL,
expand = NULL,
delay = 0.2,
zoom = 1,
useragent = NULL,
max_concurrent = getOption("webshot.concurrent", default = 6),
quiet = getOption("webshot.quiet", default = FALSE)
) {
if (length(url) == 0) {
stop("Need url.")
}
# Ensure urls are either web URLs or local file URLs.
url <- vapply(url,
function(x) {
if (!is_url(x)) {
# `url` is a filename, not an actual URL. Convert to file:// format.
file_url(x)
} else {
x
}
},
character(1)
)
# Convert params cliprect, selector and expand to list if necessary, because
# they can be vectors.
if (!is.null(cliprect) && !is.list(cliprect)) cliprect <- list(cliprect)
if (!is.null(selector) && !is.list(selector)) selector <- list(selector)
if (!is.null(expand) && !is.list(expand)) expand <- list(expand)
if (is.null(selector)) {
selector <- "html"
}
# If user provides only one file name but wants several screenshots, then the
# below code generates as many file names as URLs following the pattern
# "filename001.png", "filename002.png", ... (or whatever extension it is)
if (length(url) > 1 && length(file) == 1) {
file <- vapply(1:length(url), FUN.VALUE = character(1), function(i) {
replacement <- sprintf("%03d.\\1", i)
gsub("\\.(.{3,4})$", replacement, file)
})
}
# Check length of arguments and replicate if necessary
args_all <- list(
url = url,
file = file,
vwidth = vwidth,
vheight = vheight,
selector = selector,
cliprect = cliprect,
expand = expand,
delay = delay,
zoom = zoom,
useragent = useragent
)
n_urls <- length(url)
args_all <- mapply(args_all, names(args_all),
FUN = function(arg, name) {
if (length(arg) == 0) {
return(vector(mode = "list", n_urls))
} else if (length(arg) == 1) {
return(rep(arg, n_urls))
} else if (length(arg) == n_urls) {
return(arg)
} else {
stop("Argument `", name, "` should be NULL, length 1, or same length as `url`.")
}
},
SIMPLIFY = FALSE
)
args_all <- long_to_wide(args_all)
cm <- default_chromote_object()
# A list of promises for the screenshots
res <- lapply(args_all,
function(args) {
new_session_screenshot(cm,
args$url, args$file, args$vwidth, args$vheight, args$selector,
args$cliprect, args$expand, args$delay, args$zoom, args$useragent,
quiet
)
}
)
p <- promise_all(.list = res)
res <- cm$wait_for(p)
res <- structure(unlist(res), class = "webshot")
res
}
new_session_screenshot <- function(
chromote,
url,
file,
vwidth,
vheight,
selector,
cliprect,
expand,
delay,
zoom,
useragent,
quiet
) {
filetype <- tolower(tools::file_ext(file))
filetypes <- c(webshot_image_types(), "pdf")
if (!filetype %in% filetypes) {
stop("File extension must be one of: ", paste(filetypes, collapse = ", "))
}
if (is.null(selector)) {
selector <- "html"
}
if (is.character(cliprect)) {
if (cliprect == "viewport") {
cliprect <- c(0, 0, vwidth, vheight)
} else {
stop("Invalid value for cliprect: ", cliprect)
}
} else {
if (!is.null(cliprect) && !(is.numeric(cliprect) && length(cliprect) == 4)) {
stop("`cliprect` must be a vector with four numbers, or a list of such vectors")
}
}
s <- NULL
p <- chromote$new_session(wait_ = FALSE,
width = vwidth,
height = vheight
)$
then(function(session) {
s <<- session
if (!is.null(useragent)) {
s$Network$setUserAgentOverride(userAgent = useragent)
}
res <- s$Page$loadEventFired(wait_ = FALSE)
s$Page$navigate(url, wait_ = FALSE)
res
})$
then(function(value) {
if (delay > 0) {
promise(function(resolve, reject) {
later(
function() {
resolve(value)
},
delay
)
})
} else {
value
}
})$
then(function(value) {
if (filetype %in% webshot_image_types()) {
s$screenshot(
filename = file, selector = selector, cliprect = cliprect,
expand = expand, scale = zoom,
show = FALSE, wait_ = FALSE
)
} else if (filetype == "pdf") {
s$screenshot_pdf(filename = file, wait_ = FALSE)
}
})$
then(function(value) {
if (!isTRUE(quiet)) message(url, " screenshot completed")
normalizePath(value)
})$
finally(function() {
s$close()
})
p
}
webshot_image_types <- function() {
c("png", "jpg", "jpeg", "webp")
}
knit_print.webshot <- function(x, ...) {
lapply(x, function(filename) {
res <- readBin(filename, "raw", file.size(filename))
ext <- gsub(".*[.]", "", basename(filename))
structure(list(image = res, extension = ext), class = "html_screenshot")
})
}
#' @export
print.webshot <- function(x, ...) {
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/webshot.R
|
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/webshot2/R/webshot2-package.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.