content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' @include AllClasses.R AllGenerics.R
NULL
#' @describeIn relations Retrieve the relations
#' @export
setMethod("relations",
signature = signature(object = "TidySet"),
function(object) {
slot(object, "relations")
}
)
#' @rdname relations
#' @export
replace_relations <- function(object, value) {
UseMethod("replace_relations")
}
#' @export
#' @method replace_relations TidySet
replace_relations.TidySet <- function(object, value) {
relations(object) <- value
}
#' @describeIn relations Modify the relations
#' @export
setMethod("relations<-",
signature = signature(object = "TidySet"),
function(object, value) {
slot(object, "relations") <- value
validObject(object)
object
}
)
`.relations<-` <- function(object, value) {
slot(object, "relations") <- value
}
#' @describeIn relations Return the number of unique relations
#' @export
setMethod("nRelations",
signature = signature(object = "TidySet"),
function(object) {
r <- slot(object, "relations")
nrow(unique(r[, c("sets", "elements")]))
}
)
#' @describeIn is.fuzzy Check if it is fuzzy
#' @export
setMethod("is.fuzzy",
signature = signature(object = "TidySet"),
function(object) {
if (all(relations(object)$fuzzy == 1)) {
FALSE
} else {
TRUE
}
}
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/relations.R
|
#' @include AllGenerics.R
NULL
#' @describeIn remove_relation Removes a relation between elements and sets.
#' @export
setMethod("remove_relation",
signature = signature(
object = "TidySet",
elements = "characterORfactor",
sets = "characterORfactor"
),
function(object, elements, sets) {
new_object <- remove_relations(object, elements, sets)
new_object <- remove_sets(new_object, object %s-s% new_object)
new_object <- remove_elements(new_object, object %e-e% new_object)
validObject(new_object)
new_object
}
)
#' @describeIn remove_element Removes everything related to an element
#' @export
setMethod("remove_element",
signature = signature(
object = "TidySet",
elements = "characterORfactor"
),
function(object, elements) {
new_object <- remove_elements(object, elements)
new_object <- rm_relations_with_elements(new_object, elements)
new_object <- remove_sets(new_object, object %s-s% new_object)
validObject(new_object)
new_object
}
)
#' @describeIn remove_set Removes everything related to a set
#' @export
setMethod("remove_set",
signature = signature(
object = "TidySet",
sets = "characterORfactor"
),
function(object, sets) {
new_object <- rm_relations_with_sets(object, sets)
new_object <- remove_elements(new_object, object %e-e% new_object)
new_object <- remove_sets(new_object, sets)
validObject(new_object)
new_object
}
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/remove.R
|
#' @include AllGenerics.R AllClasses.R
NULL
#' @describeIn remove_column Remove columns to any slot
#' @export
setMethod("remove_column",
signature = signature(
object = "TidySet",
slot = "character",
column_names = "character"
),
function(object, slot, column_names) {
original <- slot(object, slot)
remove <- colnames(original) %in% column_names
slot(object, slot) <- original[, !remove]
object
}
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/remove_column.R
|
#' @include AllGenerics.R
NULL
#' @describeIn rename_set Rename sets
#' @export rename_set
setMethod("rename_set",
signature = signature(object = "TidySet"),
function(object, old, new) {
membership <- name_sets(object) %in% old
if (!any(membership)) {
stop("All sets must be found on the TidySet", call. = FALSE)
}
if (is.factor(new)) {
new <- as.character(new)
}
new <- rep(new, length.out = sum(membership))
name_sets(object)[membership] <- new
validObject(object)
object
}
)
#' @describeIn rename_elements Rename elements
#' @export rename_elements
setMethod("rename_elements",
signature = signature(object = "TidySet"),
function(object, old, new) {
membership <- name_elements(object) %in% old
if (!any(membership)) {
stop("All elements must be found on the TidySet", call. = FALSE)
}
if (is.factor(new)) {
new <- as.character(new)
}
new <- rep(new, length.out = sum(membership))
name_elements(object)[membership] <- new
validObject(object)
object
}
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/rename.R
|
#' @include AllClasses.R AllGenerics.R
#' @importFrom dplyr select
#' @importFrom rlang !!
#' @export
dplyr::select
#' select from a TidySet
#'
#' Use select to extract the columns of a TidySet object. You can use activate
#' with filter or use the specific function. The S3 method filters using all
#' the information on the TidySet.
#' @param .data The TidySet object
#' @param ... The name of the columns you want to keep, remove or rename.
#' @return A TidySet object
#' @export
#' @seealso [dplyr::select()] and [activate()]
#' @family methods
#' @examples
#' relations <- data.frame(
#' sets = c(rep("a", 5), "b", rep("a2", 5), "b2"),
#' elements = rep(letters[seq_len(6)], 2),
#' fuzzy = runif(12)
#' )
#' a <- tidySet(relations)
#' a <- mutate_element(a,
#' type = c(rep("Gene", 4), rep("lncRNA", 2))
#' )
#' a <- mutate_set(a, Group = c("UFM", "UAB", "UPF", "MIT"))
#' b <- select(a, -type)
#' elements(b)
#' b <- select_element(a, elements)
#' elements(b)
#' # Select sets
#' select_set(a, sets)
#' @rdname select_
#' @method select TidySet
#' @export
select.TidySet <- function(.data, ...) {
if (is.null(active(.data))) {
out <- dplyr::select(as.data.frame(.data), ...)
df2TS(.data, df = out)
} else {
switch(
active(.data),
elements = select_element(.data, ...),
sets = select_set(.data, ...),
relations = select_relation(.data, ...)
)
}
}
#' @rdname select_
#' @export
select_set <- function(.data, ...) {
UseMethod("select_set")
}
#' @rdname select_
#' @export
select_element <- function(.data, ...) {
UseMethod("select_element")
}
#' @rdname select_
#' @export
select_relation <- function(.data, ...) {
UseMethod("select_relation")
}
#' @export
#' @method select_set TidySet
select_set.TidySet <- function(.data, ...) {
sets <- sets(.data)
out <- dplyr::select(sets, ...)
.data@sets <- out
validObject(.data)
.data
}
#' @export
#' @method select_element TidySet
select_element.TidySet <- function(.data, ...) {
elements <- elements(.data)
out <- dplyr::select(elements, ...)
.data@elements <- out
validObject(.data)
.data
}
#' @export
#' @method select_relation TidySet
select_relation.TidySet <- function(.data, ...) {
relations <- relations(.data)
out <- dplyr::select(relations, ...)
.data@relations <- out
validObject(.data)
.data
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/select.R
|
#' @include AllClasses.R AllGenerics.R
NULL
#' @describeIn sets Retrieve the sets information
#' @export
setMethod("sets",
signature = signature(object = "TidySet"),
function(object) {
slot(object, "sets")
}
)
#' @describeIn sets Modify the sets information
#' @export
#' @examples
#' sets(TS) <- data.frame(sets = c("B", "A"))
setMethod("sets<-",
signature = signature(object = "TidySet"),
function(object, value) {
slot(object, "sets") <- value
validObject(object)
object
}
)
#' @rdname sets
#' @export
#' @examples
#' TS2 <- replace_sets(TS, data.frame(sets = c("A", "B", "C")))
#' sets(TS2)
replace_sets <- function(object, value) {
UseMethod("replace_sets")
}
#' @export
#' @method replace_sets TidySet
replace_sets.TidySet <- function(object, value) {
sets(object) <- value
object
}
#' @describeIn sets Return the number of sets
#' @export
#' @examples
#' nSets(TS)
#' nSets(TS2)
setMethod("nSets",
signature = signature(object = "TidySet"),
function(object) {
nrow(slot(object, "sets"))
}
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/set.R
|
#' Size
#'
#' Calculate the size of the elements or sets, using the fuzzy values as
#' probabilities. First it must have active either sets or elements.
#' @param object A TidySet object
#' @param ... Character vector with the name of elements or sets you want to
#' calculate the size of.
#' @export
#' @seealso A related concept [cardinality()]. It is calculated using
#' [length_set()].
#' @return The size of the elements or sets. If there is no active slot or it
#' is the relations slot returns the TidySet object with a warning.
#' @examples
#' rel <- data.frame(
#' sets = c(rep("A", 5), "B", "C"),
#' elements = c(letters[seq_len(6)], letters[6])
#' )
#' TS <- tidySet(rel)
#' TS <- activate(TS, "elements")
#' size(TS)
#' TS <- activate(TS, "sets")
#' size(TS)
#' # With fuzzy sets
#' relations <- data.frame(
#' sets = c(rep("A", 5), "B", "C"),
#' elements = c(letters[seq_len(6)], letters[6]),
#' fuzzy = runif(7)
#' )
#' TS <- tidySet(relations)
#' TS <- activate(TS, "elements")
#' size(TS)
#' TS <- activate(TS, "sets")
#' size(TS)
size <- function(object, ...) {
UseMethod("size")
}
#' @export
#' @method size TidySet
size.TidySet <- function(object, ...) {
a <- active(object)
if (is.null(a) || a == "relations") {
msg <- paste(
"Unable to calculate the size,",
"activate either elements or sets."
)
warning(msg)
return(object)
} else {
switch(a,
elements = element_size(object, ...),
sets = set_size(object, ...)
)
}
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/size.R
|
#' @include AllClasses.R AllGenerics.R
NULL
#' @describeIn subtract Elements present in sets but not in other sets
#' @export
setMethod("subtract",
signature = signature(
object = "TidySet",
set_in = "characterORfactor",
not_in = "characterORfactor"
),
function(object, set_in, not_in, name = NULL, keep = TRUE,
keep_relations = keep, keep_elements = keep,
keep_sets = keep) {
old_relations <- relations(object)
test_set_in <- set_in %in% old_relations$sets
if (!any(test_set_in)) {
stop("No set from set_in could be found ", call. = FALSE)
}
if (!all(test_set_in)) {
warning("sets", set_in[test_set_in], "could not be found",
call. = FALSE
)
}
sub_set2 <- not_in %in% old_relations$sets
if (!any(sub_set2)) {
stop("No set from not_in could be found", call. = FALSE)
}
if (!all(sub_set2)) {
warning("sets", not_in[sub_set2], "could not be found",
call. = FALSE
)
}
sub_set <- old_relations$sets %in% set_in
relations <- old_relations[sub_set, , drop = FALSE]
remove_elements <- elements_in_set(object, not_in)
relations <- relations[!relations$elements %in% remove_elements, ,
drop = FALSE
]
if (is.null(name)) {
name <- naming(
sets1 = set_in, middle = "minus",
sets2 = not_in
)
}
if (nrow(relations) >= 1) {
relations$sets <- name
}
object <- add_sets(object, name)
object <- replace_interactions(object, relations, keep_relations)
object <- droplevels(
object, !keep_elements, !keep_sets,
!keep_relations
)
validObject(object)
object
}
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/subtract.R
|
#' @include AllClasses.R
NULL
#' Create a TidySet object
#'
#' These functions help to create a \code{TidySet} object from
#' `data.frame`, `list`, `matrix`, and `GO3AnnDbBimap`.
#' They can create both fuzzy and standard sets.
#'
#' Elements or sets without any relation are not shown when printed.
#' @param relations An object to be coerced to a TidySet.
#' @return A TidySet object.
#' @examples
#' relations <- data.frame(
#' sets = c(rep("a", 5), "b"),
#' elements = letters[seq_len(6)]
#' )
#' tidySet(relations)
#' relations2 <- data.frame(
#' sets = c(rep("A", 5), "B"),
#' elements = letters[seq_len(6)],
#' fuzzy = runif(6)
#' )
#' tidySet(relations2)
#' @export
#' @seealso [`TidySet`]
tidySet <- function(relations) {
UseMethod("tidySet")
}
#' @describeIn tidySet Given the relations in a data.frame
#' @method tidySet data.frame
#' @export
tidySet.data.frame <- function(relations) {
check_colnames <- all(c("sets", "elements") %in% colnames(relations))
if (ncol(relations) < 2 || !check_colnames) {
stop("Unable to create a TidySet object.\n",
"The data.frame does not have the sets and elements columns.",
call. = FALSE
)
}
if (!is.ch_fct(relations$sets)) {
stop("Sets should be a factor or a character.", call. = FALSE)
}
if (!is.ch_fct(relations$elements)) {
stop("Elements should be a factor or a character.", call. = FALSE)
}
sets <- data.frame(
sets = unique(relations$sets),
stringsAsFactors = FALSE
)
elements <- data.frame(
elements = unique(relations$elements),
stringsAsFactors = FALSE
)
if (!"fuzzy" %in% colnames(relations)) {
fuzzy <- rep(1, nrow(relations))
relations <- cbind.data.frame(relations, fuzzy,
stringsAsFactors = FALSE)
} else if (!is.numeric(relations$fuzzy)) {
stop("Fuzzy column should be a numeric column with numbers ",
"between 0 and 1.", call. = FALSE)
}
# Just in case
rownames(relations) <- seq_len(nrow(relations))
new("TidySet", sets = sets, elements = elements, relations = relations)
}
#' @export
#' @describeIn tidySet Convert to a TidySet from a list.
#' @examples
#' # A
#' x <- list("A" = letters[1:5], "B" = LETTERS[3:7])
#' tidySet(x)
#' # A fuzzy set taken encoded as a list
#' A <- runif(5)
#' names(A) <- letters[1:5]
#' B <- runif(5)
#' names(B) <- letters[3:7]
#' relations <- list(A, B)
#' tidySet(relations)
#' # Will error
#' # x <- list("A" = letters[1:5], "B" = LETTERS[3:7], "c" = runif(5))
#' # a <- tidySet(x) # Only characters or factors are allowed as elements.
tidySet.list <- function(relations) {
char <- vapply(relations, is.character, logical(1L))
num <- vapply(relations, is.numeric, logical(1L))
fact <- vapply(relations, is.factor, logical(1L))
if (!all(char | fact) && !all(num)) {
stop("The list should have either characters or named numeric vectors",
call. = FALSE
)
}
if (is.null(names(relations))) {
set_names <- paste0("Set", seq_along(relations))
names(relations) <- set_names[length(relations)]
}
if (all(char | fact)) {
relations <- lapply(relations, unique)
elements <- unlist(relations, FALSE, FALSE)
fuzzy <- rep(1, length(elements))
} else if (all(num)) {
elements <- unlist(lapply(relations, names), FALSE, FALSE)
if (is.null(elements)) {
stop("The numeric vectors should be named", call. = FALSE)
}
fuzzy <- unlist(relations, FALSE, FALSE)
}
sets_size <- lengths(relations)
sets_size[sets_size == 0] <- 1
sets <- rep(names(relations), sets_size)
if (length(elements) == 0) {
return(new("TidySet", sets = data.frame(sets = sets),
elements = data.frame(elements = character()),
relations = data.frame(elements = character(),
sets = character(),
fuzzy = numeric())))
}
size <- c(length(elements), length(sets), length(fuzzy))
min_size <- min(size)
relations <- data.frame(elements = elements[seq_len(min_size)],
sets = sets[seq_len(min_size)],
fuzzy = fuzzy,
stringsAsFactors = FALSE
)
TS <- tidySet.data.frame(relations = relations)
if (size[1] > min_size) {
e <- elements[seq(from = min_size + 1, to = size[1])]
add_elements(TS, e)
}
if (size[2] > min_size) {
s <- sets[seq(from = min_size + 1, to = size[2])]
TS <- add_sets(TS, s)
}
TS
}
#' @describeIn tidySet Convert an incidence matrix into a TidySet
#' @export
#' @examples
#' M <- matrix(c(1, 0.5, 1, 0), ncol = 2,
#' dimnames = list(c("A", "B"), c("a", "b")))
#' tidySet(M)
tidySet.matrix <- function(relations) {
if (anyDuplicated(colnames(relations))) {
stop("There are duplicated colnames.", call. = FALSE)
}
if (anyDuplicated(rownames(relations))) {
stop("There are duplicated rownames.", call. = FALSE)
}
if (!is.numeric(relations)) {
stop("The incidence should be a numeric matrix.", call. = FALSE)
}
# Preparation
incid <- relations
elements <- rownames(incid)
sets <- colnames(incid)
relations <- as.data.frame(which(incid != 0, arr.ind = TRUE))
colnames(relations) <- c("elements", "sets")
# Replace by names
relations[, 1] <- elements[relations[, 1]]
relations[, 2] <- sets[relations[, 2]]
fuzzy <- apply(relations, 1, function(x) {
incid[x[1], x[2]]
})
relations <- cbind.data.frame(relations, fuzzy, stringsAsFactors = FALSE)
tidySet(relations = relations)
}
#' @describeIn tidySet Convert Go3AnnDbBimap into a TidySet object.
#' @export
tidySet.Go3AnnDbBimap <- function(relations) {
# Prepare the data
df <- as.data.frame(relations)
colnames(df) <- c("elements", "sets", "Evidence", "Ontology")
# # Transform each evidence code into its own column
# e_s <- paste(df$elements, df$sets)
# tt <- as(table(e_s, df$Evidence), "matrix")
# tt2 <- as.data.frame(tt)
# tt2$elements <- gsub(" GO:.*", "", rownames(tt2))
# tt2$sets <- gsub(".* ", "", rownames(tt2))
# rownames(tt2) <- NULL
#
# df2 <- cbind(tt2, nEvidence = rowSums(tt))
# df3 <- merge(df2, unique(df[, c("sets", "Ontology")]))
TS <- tidySet.data.frame(df)
move_to(TS, "relations", "sets", "Ontology")
}
#' @describeIn tidySet Convert TidySet into a TidySet object.
#' @export
tidySet.TidySet <- function(relations) {
relations
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/tidy-set.R
|
#' @include AllClasses.R AllGenerics.R operations.R
NULL
#' Join sets
#'
#' Given a TidySet merges several sets into the new one using the logic
#' defined on FUN.
#'
#' The default uses the `max` function following the [standard fuzzy
#' definition](https://en.wikipedia.org/wiki/Fuzzy_set_operations), but it can be
#' changed. See examples below.
#' @param object A TidySet object.
#' @param sets The name of the sets to be used.
#' @param name The name of the new set. By defaults joins the sets with an
#' \ifelse{latex}{\out{$\cap$}}{\ifelse{html}{\out{∩}}{}}.
#' @param FUN A function to be applied when performing the union.
#' The standard union is the "max" function, but you can provide any other
#' function that given a numeric vector returns a single number.
#' @param keep A logical value if you want to keep.
#' @param keep_relations A logical value if you wan to keep old relations.
#' @param keep_elements A logical value if you wan to keep old elements.
#' @param keep_sets A logical value if you wan to keep old sets.
#' @param ... Other named arguments passed to `FUN`.
#' @return A \code{TidySet} object.
#' @export
#' @family methods that create new sets
#' @family methods
#' @seealso [union_probability()]
#' @examples
#' # Classical set
#' rel <- data.frame(
#' sets = c(rep("A", 5), "B", "B"),
#' elements = c(letters[seq_len(6)], "a")
#' )
#' TS <- tidySet(rel)
#' union(TS, c("B", "A"))
#' # Fuzzy set
#' rel <- data.frame(
#' sets = c(rep("A", 5), "B", "B"),
#' elements = c(letters[seq_len(6)], "a"),
#' fuzzy = runif(7)
#' )
#' TS2 <- tidySet(rel)
#' # Standard default logic
#' union(TS2, c("B", "A"), "C")
#' # Probability logic
#' union(TS2, c("B", "A"), "C", FUN = union_probability)
union <- function(object, ...) {
UseMethod("union")
}
# #' @export
# union.default <- function(object, ...) {
# stopifnot(length(list(...)) == 1)
# base::union(object, ...)
# }
#' @rdname union
#' @export
#' @method union TidySet
union.TidySet <- function(object, sets, name = NULL, FUN = "max", keep = FALSE,
keep_relations = keep,
keep_elements = keep,
keep_sets = keep, ...) {
if (is.null(name)) {
name <- naming(sets1 = sets)
} else if (length(name) != 1) {
stop("The new union can only have one name", call. = FALSE)
}
object <- add_sets(object, name)
relations <- relations(object)
union <- relations[relations$sets %in% sets, , drop = FALSE]
if (is.factor(union$sets)) {
levels(union$sets)[levels(union$sets) %in% sets] <- name
} else {
union$sets[union$sets %in% sets] <- name
}
union <- fapply(union, FUN, ... = ...)
object <- replace_interactions(object, union, keep_relations)
droplevels(object, !keep_elements, !keep_sets, !keep_relations)
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/union.R
|
#' Union closed sets
#'
#' Tests if a given object is union-closed.
#' @export
#' @inheritParams union
#' @return A logical value: `TRUE` if the combinations of sets produce already
#' existing sets, `FALSE` otherwise.
#' @examples
#' l <- list(A = "1",
#' B = c("1", "2"),
#' C = c("2", "3", "4"),
#' D = c("1", "2", "3", "4")
#' )
#' TS <- tidySet(l)
#' union_closed(TS)
#' union_closed(TS, sets = c("A", "B", "C"))
#' union_closed(TS, sets = c("A", "B", "C", "D"))
union_closed <- function(object, ...) {
UseMethod("union_closed")
}
#' @rdname union_closed
#' @export
#' @method union_closed TidySet
union_closed.TidySet <- function(object, sets = NULL, ...) {
if (is.null(sets)) {
sets <- name_sets(object)
} else {
stopifnot("All sets should be in the object" =
all(sets %in% name_sets(object)))
}
elements_sets <- lapply(sets, elements_in_set, object = object)
elements_combn <- combn(sets, 2, elements_in_set,
object = object, simplify = FALSE)
# Sort vector o make it easier to search
elements_sets <- elements_sets[order(lengths(elements_sets))]
for (set2 in elements_combn) {
set2 <- unique(set2)
v <- vector(length = length(sets))
for (s in seq_along(elements_sets)) {
ess <- elements_sets[[s]]
same_length <- length(set2) == length(ess)
no_outside_left <- length(setdiff(set2, ess)) == 0
no_outside_right <- length(setdiff(ess, set2)) == 0
if (same_length && no_outside_left && no_outside_right) {
v[s] <- TRUE
# If one set already matches do not look further
break
}
}
if (!any(v)) {
return(FALSE)
}
}
TRUE
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/union_closed.R
|
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
#' @return The result of the left-hand side (lhs) is passed to the right-hand
#' side (rhs).
NULL
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/utils-pipe.R
|
# for autocomplete: https://stackoverflow.com/a/52348809
#' @importFrom utils .DollarNames
#' @export
.DollarNames.TidySet <- function(x, pattern = "") {
#x is the .CompletionEnv
# Get the columns of each slot and provide it without merging everything
r <- relations(x)[1:2, , drop = FALSE]
s <- sets(x)[1:2, , drop = FALSE]
e <- elements(x)[1:2, , drop = FALSE]
l <- lapply(list(r, s, e), colnames)
unique(unlist(l, FALSE, FALSE))
}
in_slots <- function(x, fun, ...) {
l <- list(Elements = slot(x, "elements"),
Relations = slot(x, "relations"),
Sets = slot(x, "sets"))
sapply(l, fun, ...)
}
# For usethis::use_release helper when making a release
release_bullets <- function() {
c("Run `pkgdown::check_pkgdown()`")
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/utils.R
|
#' @importFrom methods setClassUnion
setClassUnion("characterORfactor", c("character", "factor"))
check_colnames_slot <- function(object, slot, colname) {
array_names <- colnames(slot(object, slot))
if (length(array_names) == 0) {
paste0(
"Missing required colnames for ", slot,
". See tidySet documentation."
)
} else if (check_colnames(array_names, colname)) {
paste0(colname, " column is not present on slot ", slot, ".")
}
}
check_colnames <- function(array_names, colname) {
all(!colname %in% array_names)
}
is.ch_fct <- function(x) {
is.character(x) || is.factor(x)
}
is.valid <- function(object) {
errors <- c()
# Check that the slots have the right columns
errors <- c(errors, check_colnames_slot(object, "elements", "elements"))
errors <- c(errors, check_colnames_slot(object, "sets", "sets"))
errors <- c(errors, check_colnames_slot(object, "relations", "elements"))
errors <- c(errors, check_colnames_slot(object, "relations", "sets"))
errors <- c(errors, check_colnames_slot(object, "relations", "fuzzy"))
# Check that the columns contain the least information required
elements <- object@elements$elements
if (length(unique(elements)) != length(elements)) {
errors <- c(errors, "Elements on the element slot must be unique")
}
sets <- object@sets$sets
if (length(unique(sets)) != length(sets)) {
errors <- c(errors, "Sets on the sets slot must be unique")
}
# Check the type of data
if (!is.ch_fct(sets)) {
errors <- c(errors, "Sets must be characters or factors")
}
if (!is.ch_fct(elements)) {
errors <- c(errors, "Elements must be characters or factors")
}
# Check that the slots don't have duplicated information
colnames_elements <- colnames(object@elements)
colnames_sets <- colnames(object@sets)
if (length(intersect(colnames_elements, colnames_sets)) != 0) {
errors <- c(
errors,
"Sets and elements can't share a column name.",
"You might want to add a column to the relations instead"
)
}
relations <- slot(object, "relations")
errors <- c(errors, valid_relations(relations, sets, elements))
if (length(errors) == 0) {
TRUE
} else {
errors
}
}
is_valid <- function(x) {
if (is.logical(is.valid(x))) {
TRUE
} else {
FALSE
}
}
# relations should be a data.frame
# sets should be a vector
# elements should be a vector
valid_relations <- function(relations, sets, elements) {
errors <- character()
# A TS with no relations is a valid set.
# if (nrow(relations) == 0) {
# errors <- c(errors, "No relations found.")
# }
if (!"fuzzy" %in% colnames(relations)) {
errors <- c(errors, "A fuzzy column must be present.")
} else if (length(relations$fuzzy) != 0) {
fuzz <- relations$fuzzy
if (!is.numeric(fuzz) || min(fuzz) < 0 || max(fuzz) > 1) {
errors <- c(errors,
"fuzzy column is restricted to a number between 0 and 1."
)
}
}
# Check that there are duplicated ids
es <- paste(relations$elements, relations$sets)
# Check that relations have the same fuzzy value when the
if (anyDuplicated(es) != 0 && !all(fuzz == 1)) {
fuzziness <- tapply(fuzz, es, FUN = n_distinct)
if (!all(fuzziness == 1)) {
msg <- paste0(
"A relationship between an element",
" and a set must have a single fuzzy value"
, collapse = " ")
errors <- c(errors, msg)
}
}
if (!all(relations$sets %in% sets)) {
msg <- paste0("The TidySet has elements with a",
" relationship with a missing set.", collapse = " ")
errors <- c(errors, msg)
}
if (!all(relations$elements %in% elements)) {
msg <- paste0("The TidySet has elements with a",
" relationship with a missing element.", collapse = " ")
errors <- c(errors, msg)
}
errors
}
# sets should be a data.frame
valid_sets <- function(sets) {
errors <- character()
if (!is.data.frame(sets)) {
errors <- c(errors, "Should be a data.frame.")
}
if (!"sets" %in% names(sets)) {
errors <- c(errors, "There isn't a sets column.")
}
if (is.null(sets$sets)) {
errors <- c(errors, paste0("Missing column sets."))
}
errors
}
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/validity.R
|
#' A subset of symbols related to sets
#'
#' Name and symbol of operations related to sets, including intersection
#' and union among others:
#' @references
#' \url{https://www.fileformat.info/info/unicode/category/Sm/list.htm}
#' @export
#' @examples
#' set_symbols
set_symbols <- c(
"intersection" = "\u2229",
"union" = "\u222A",
"complement" = "\u2201",
"negation" = "\u00AC",
"subsetOrEqual" = "\u2286",
"supersetOrEqual" = "\u2287",
"notSubset" = "\u2284",
"notSuperset" = "\u2285",
"element" = "\u2208",
"notElement" = "\u2209",
"empty" = "\u2205",
"contains" = "\u220B",
"notContained" = "\u220C",
"minus" = "\u2216",
"product" = "\u2A2F",
"conditional" = "|"
)
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/R/zzz.R
|
## ----setup, message=FALSE, warning=FALSE, include=FALSE-----------------------
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
## ----from_list, message=FALSE-------------------------------------------------
library("BaseSet")
gene_lists <- list(
geneset1 = c("A", "B"),
geneset2 = c("B", "C", "D")
)
tidy_set <- tidySet(gene_lists)
tidy_set
## ----metadata, message=FALSE--------------------------------------------------
gene_data <- data.frame(
stat1 = c( 1, 2, 3, 4 ),
info1 = c("a", "b", "c", "d")
)
tidy_set <- add_column(tidy_set, "elements", gene_data)
set_data <- data.frame(
Group = c( 100 , 200 ),
Column = c("abc", "def")
)
tidy_set <- add_column(tidy_set, "sets", set_data)
tidy_set
## ----getters------------------------------------------------------------------
relations(tidy_set)
elements(tidy_set)
sets(tidy_set)
## -----------------------------------------------------------------------------
gene_data <- data.frame(
stat2 = c( 4, 4, 3, 5 ),
info2 = c("a", "b", "c", "d")
)
tidy_set$info1 <- NULL
tidy_set[, "elements", c("stat2", "info2")] <- gene_data
tidy_set[, "sets", "Group"] <- c("low", "high")
tidy_set
## ----tidyset_data.frame-------------------------------------------------------
relations <- data.frame(elements = c("a", "b", "c", "d", "e", "f"),
sets = c("A", "A", "A", "A", "A", "B"),
fuzzy = c(1, 1, 1, 1, 1, 1))
TS <- tidySet(relations)
TS
## ----tidySet_matrix-----------------------------------------------------------
m <- matrix(c(0, 0, 1, 1, 1, 1, 0, 1, 0), ncol = 3, nrow = 3,
dimnames = list(letters[1:3], LETTERS[1:3]))
m
tidy_set <- tidySet(m)
tidy_set
## ----as.list------------------------------------------------------------------
as.list(tidy_set)
## ----incidence----------------------------------------------------------------
incidence(tidy_set)
## ----union--------------------------------------------------------------------
BaseSet::union(tidy_set, sets = c("C", "B"), name = "D")
## ----intersection-------------------------------------------------------------
intersection(tidy_set, sets = c("A", "B"), name = "D", keep = TRUE)
## ----intersection2------------------------------------------------------------
intersection(tidy_set, sets = c("A", "B"), name = "D", keep = FALSE)
## ----complement---------------------------------------------------------------
complement_set(tidy_set, sets = c("A", "B"))
## ----complement2--------------------------------------------------------------
complement_set(tidy_set, sets = c("A", "B"), name = "F")
## ----subtract-----------------------------------------------------------------
out <- subtract(tidy_set, set_in = "A", not_in = "B", name = "A-B")
out
name_sets(out)
subtract(tidy_set, set_in = "B", not_in = "A", keep = FALSE)
## ----n------------------------------------------------------------------------
nElements(tidy_set)
nSets(tidy_set)
nRelations(tidy_set)
## ----set_size-----------------------------------------------------------------
set_size(tidy_set)
## ----element_size-------------------------------------------------------------
element_size(tidy_set)
## ----name---------------------------------------------------------------------
name_elements(tidy_set)
name_elements(tidy_set) <- paste0("Gene", seq_len(nElements(tidy_set)))
name_elements(tidy_set)
name_sets(tidy_set)
name_sets(tidy_set) <- paste0("Geneset", seq_len(nSets(tidy_set)))
name_sets(tidy_set)
## ----tidyverse----------------------------------------------------------------
library("dplyr")
m_TS <- tidy_set %>%
activate("relations") %>%
mutate(Important = runif(nRelations(tidy_set)))
m_TS
## ----deactivate---------------------------------------------------------------
set_modified <- m_TS %>%
activate("elements") %>%
mutate(Pathway = if_else(elements %in% c("Gene1", "Gene2"),
"pathway1",
"pathway2"))
set_modified
set_modified %>%
deactivate() %>% # To apply a filter independently of where it is
filter(Pathway == "pathway1")
## ----group--------------------------------------------------------------------
# A new group of those elements in pathway1 and with Important == 1
set_modified %>%
deactivate() %>%
group(name = "new", Pathway == "pathway1")
## ----group2-------------------------------------------------------------------
set_modified %>%
group("pathway1", elements %in% c("Gene1", "Gene2"))
## ----group_by-----------------------------------------------------------------
set_modified %>%
deactivate() %>%
group_by(Pathway, sets) %>%
count()
## ----moving-------------------------------------------------------------------
elements(set_modified)
out <- move_to(set_modified, "elements", "relations", "Pathway")
relations(out)
## ----sessionInfo, echo=FALSE--------------------------------------------------
sessionInfo()
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/inst/doc/BaseSet.R
|
---
title: "BaseSet"
abstract: >
Describes the background of the package, important functions defined in the
package and some of the applications and usages.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
html_document:
fig_caption: true
code_folding: show
self_contained: yes
toc_float:
collapsed: true
toc_depth: 3
author:
- name: Lluís Revilla
email: [email protected]
vignette: >
%\VignetteIndexEntry{BaseSet}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
%\DeclareUnicodeCharacter{2229}{$\cap$}
%\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options:
chunk_output_type: console
---
```{r setup, message=FALSE, warning=FALSE, include=FALSE}
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
```
# Getting started
This vignette explains how to work with sets using this package.
The package provides a class to store the information efficiently and functions to work with it.
# The TidySet class
To create a `TidySet` object, to store associations between elements and sets
image we have several genes associated with a characteristic.
```{r from_list, message=FALSE}
library("BaseSet")
gene_lists <- list(
geneset1 = c("A", "B"),
geneset2 = c("B", "C", "D")
)
tidy_set <- tidySet(gene_lists)
tidy_set
```
This is then stored internally in three slots `relations()`, `elements()`, and `sets()` slots.
If you have more information for each element or set it can be added:
```{r metadata, message=FALSE}
gene_data <- data.frame(
stat1 = c( 1, 2, 3, 4 ),
info1 = c("a", "b", "c", "d")
)
tidy_set <- add_column(tidy_set, "elements", gene_data)
set_data <- data.frame(
Group = c( 100 , 200 ),
Column = c("abc", "def")
)
tidy_set <- add_column(tidy_set, "sets", set_data)
tidy_set
```
This data is stored in one of the three slots, which can be directly accessed using their getter methods:
```{r getters}
relations(tidy_set)
elements(tidy_set)
sets(tidy_set)
```
You can add as much information as you want, with the only restriction for a "fuzzy" column for the `relations()`. See the Fuzzy sets vignette: `vignette("Fuzzy sets", "BaseSet")`.
You can also use the standard R approach with `[`:
```{r}
gene_data <- data.frame(
stat2 = c( 4, 4, 3, 5 ),
info2 = c("a", "b", "c", "d")
)
tidy_set$info1 <- NULL
tidy_set[, "elements", c("stat2", "info2")] <- gene_data
tidy_set[, "sets", "Group"] <- c("low", "high")
tidy_set
```
Observe that one can add, replace or delete
# Creating a TidySet
As you can see it is possible to create a TidySet from a list.
More commonly you can create it from a data.frame:
```{r tidyset_data.frame}
relations <- data.frame(elements = c("a", "b", "c", "d", "e", "f"),
sets = c("A", "A", "A", "A", "A", "B"),
fuzzy = c(1, 1, 1, 1, 1, 1))
TS <- tidySet(relations)
TS
```
It is also possible from a matrix:
```{r tidySet_matrix}
m <- matrix(c(0, 0, 1, 1, 1, 1, 0, 1, 0), ncol = 3, nrow = 3,
dimnames = list(letters[1:3], LETTERS[1:3]))
m
tidy_set <- tidySet(m)
tidy_set
```
Or they can be created from a GeneSet and GeneSetCollection objects.
Additionally it has several function to read files related to sets like the OBO files (`getOBO`) and GAF (`getGAF`)
# Converting to other formats
It is possible to extract the gene sets as a `list`, for use with functions such as `lapply`.
```{r as.list}
as.list(tidy_set)
```
Or if you need to apply some network methods and you need a matrix, you can create it with `incidence`:
```{r incidence}
incidence(tidy_set)
```
# Operations with sets
To work with sets several methods are provided. In general you can provide a new name for the resulting set of the operation, but if you don't one will be automatically provided using `naming()`. All methods work with fuzzy and non-fuzzy sets
## Union
You can make a union of two sets present on the same object.
```{r union}
BaseSet::union(tidy_set, sets = c("C", "B"), name = "D")
```
## Intersection
```{r intersection}
intersection(tidy_set, sets = c("A", "B"), name = "D", keep = TRUE)
```
The keep argument used here is if you want to keep all the other previous sets:
```{r intersection2}
intersection(tidy_set, sets = c("A", "B"), name = "D", keep = FALSE)
```
## Complement
We can look for the complement of one or several sets:
```{r complement}
complement_set(tidy_set, sets = c("A", "B"))
```
Observe that we haven't provided a name for the resulting set but we can provide one if we prefer to
```{r complement2}
complement_set(tidy_set, sets = c("A", "B"), name = "F")
```
## Subtract
This is the equivalent of `setdiff`, but clearer:
```{r subtract}
out <- subtract(tidy_set, set_in = "A", not_in = "B", name = "A-B")
out
name_sets(out)
subtract(tidy_set, set_in = "B", not_in = "A", keep = FALSE)
```
See that in the first case there isn't any element present in B not in set A, but the new set is stored.
In the second use case we focus just on the elements that are present on B but not in A.
# Additional information
The number of unique elements and sets can be obtained using the `nElements()` and `nSets()` methods.
```{r n}
nElements(tidy_set)
nSets(tidy_set)
nRelations(tidy_set)
```
If you wish to know all in a single call you can use `dim(tidy_set)`: `r dim(tidy_set)`.
This summary doesn't provide the number of relations of each set.
You can quickly obtain that with `lengths(tidy_set)`: `r lengths(tidy_set)`
The size of each set can be obtained using the `set_size()` method.
```{r set_size}
set_size(tidy_set)
```
Conversely, the number of sets associated with each gene is returned by the
`element_size()` function.
```{r element_size}
element_size(tidy_set)
```
The identifiers of elements and sets can be inspected and renamed using `name_elements` and
```{r name}
name_elements(tidy_set)
name_elements(tidy_set) <- paste0("Gene", seq_len(nElements(tidy_set)))
name_elements(tidy_set)
name_sets(tidy_set)
name_sets(tidy_set) <- paste0("Geneset", seq_len(nSets(tidy_set)))
name_sets(tidy_set)
```
# Using `dplyr` verbs
You can also use `mutate()`, `filter()`, `select()`, `group_by()` and other `dplyr` verbs with TidySets.
You usually need to activate which three slots you want to affect with `activate()`:
```{r tidyverse}
library("dplyr")
m_TS <- tidy_set %>%
activate("relations") %>%
mutate(Important = runif(nRelations(tidy_set)))
m_TS
```
You can use activate to select what are the verbs modifying:
```{r deactivate}
set_modified <- m_TS %>%
activate("elements") %>%
mutate(Pathway = if_else(elements %in% c("Gene1", "Gene2"),
"pathway1",
"pathway2"))
set_modified
set_modified %>%
deactivate() %>% # To apply a filter independently of where it is
filter(Pathway == "pathway1")
```
If you think you need `group_by` usually this could mean that you need a new set.
You can create a new one with `group`.
```{r group}
# A new group of those elements in pathway1 and with Important == 1
set_modified %>%
deactivate() %>%
group(name = "new", Pathway == "pathway1")
```
```{r group2}
set_modified %>%
group("pathway1", elements %in% c("Gene1", "Gene2"))
```
You can use `group_by()` but it won't return a `TidySet`.
```{r group_by}
set_modified %>%
deactivate() %>%
group_by(Pathway, sets) %>%
count()
```
After grouping or mutating sometimes we might be interested in moving a column describing something to other places. We can do by this with:
```{r moving}
elements(set_modified)
out <- move_to(set_modified, "elements", "relations", "Pathway")
relations(out)
```
# Session info {.unnumbered}
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/inst/doc/BaseSet.Rmd
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
run_vignette <- requireNamespace("GSEABase", quietly = TRUE) &&
requireNamespace("GO.db", quietly = TRUE) &&
requireNamespace("reactome.db", quietly = TRUE) &&
requireNamespace("org.Hs.eg.db", quietly = TRUE) &&
requireNamespace("ggplot2", quietly = TRUE) &&
requireNamespace("forcats", quietly = TRUE)
## ----setupr, message=FALSE----------------------------------------------------
library("BaseSet", quietly = TRUE)
library("dplyr", quietly = TRUE)
## ----prepare_GO, message=FALSE, eval=run_vignette-----------------------------
# # We load some libraries
# library("org.Hs.eg.db", quietly = TRUE)
# library("GO.db", quietly = TRUE)
# library("ggplot2", quietly = TRUE)
# # Prepare the data
# h2GO_TS <- tidySet(org.Hs.egGO)
# h2GO <- as.data.frame(org.Hs.egGO)
## ----evidence_ontology, eval=run_vignette-------------------------------------
# library("forcats", include.only = "fct_reorder2", quietly = TRUE)
# h2GO %>%
# group_by(Evidence, Ontology) %>%
# count(name = "Freq") %>%
# ungroup() %>%
# mutate(Evidence = fct_reorder2(Evidence, Ontology, -Freq),
# Ontology = case_match(Ontology,
# "CC" ~ "Cellular Component",
# "MF" ~ "Molecular Function",
# "BP" ~ "Biological Process",
# .default = NA)) %>%
# ggplot() +
# geom_col(aes(Evidence, Freq)) +
# facet_grid(~Ontology) +
# theme_minimal() +
# coord_flip() +
# labs(x = element_blank(), y = element_blank(),
# title = "Evidence codes for each ontology")
## ----nEvidence_plot, eval=run_vignette----------------------------------------
# h2GO_TS %>%
# relations() %>%
# group_by(elements, sets) %>%
# count(sort = TRUE, name = "Annotations") %>%
# ungroup() %>%
# count(Annotations, sort = TRUE) %>%
# ggplot() +
# geom_col(aes(Annotations, n)) +
# theme_minimal() +
# labs(x = "Evidence codes", y = "Annotations",
# title = "Evidence codes for each annotation",
# subtitle = "in human") +
# scale_x_continuous(breaks = 1:7)
## ----numbers, eval=run_vignette-----------------------------------------------
# # Add all the genes and GO terms
# h2GO_TS <- add_elements(h2GO_TS, keys(org.Hs.eg.db)) %>%
# add_sets(grep("^GO:", keys(GO.db), value = TRUE))
#
# sizes_element <- element_size(h2GO_TS) %>%
# arrange(desc(size))
# sum(sizes_element$size == 0)
# sum(sizes_element$size != 0)
#
# sizes_set <- set_size(h2GO_TS) %>%
# arrange(desc(size))
# sum(sizes_set$size == 0)
# sum(sizes_set$size != 0)
## ----plots_GO, eval=run_vignette----------------------------------------------
# sizes_element %>%
# filter(size != 0) %>%
# ggplot() +
# geom_histogram(aes(size), binwidth = 1) +
# theme_minimal() +
# labs(x = "# sets per element", y = "Count")
#
# sizes_set %>%
# filter(size != 0) %>%
# ggplot() +
# geom_histogram(aes(size), binwidth = 1) +
# theme_minimal() +
# labs(x = "# elements per set", y = "Count")
## ----distr_sizes, eval=run_vignette-------------------------------------------
# head(sizes_set, 10)
## ----fuzzy_setup, eval=run_vignette-------------------------------------------
# nr <- h2GO_TS %>%
# relations() %>%
# dplyr::select(sets, Evidence) %>%
# distinct() %>%
# mutate(fuzzy = case_match(Evidence,
# "EXP" ~ 0.9,
# "IDA" ~ 0.8,
# "IPI" ~ 0.8,
# "IMP" ~ 0.75,
# "IGI" ~ 0.7,
# "IEP" ~ 0.65,
# "HEP" ~ 0.6,
# "HDA" ~ 0.6,
# "HMP" ~ 0.5,
# "IBA" ~ 0.45,
# "ISS" ~ 0.4,
# "ISO" ~ 0.32,
# "ISA" ~ 0.32,
# "ISM" ~ 0.3,
# "RCA" ~ 0.2,
# "TAS" ~ 0.15,
# "NAS" ~ 0.1,
# "IC" ~ 0.02,
# "ND" ~ 0.02,
# "IEA" ~ 0.01,
# .default = 0.01)) %>%
# dplyr::select(sets = "sets", elements = "Evidence", fuzzy = fuzzy)
## ----fuzzy_setup2, eval=run_vignette------------------------------------------
# ts <- h2GO_TS %>%
# relations() %>%
# dplyr::select(-Evidence) %>%
# rbind(nr) %>%
# tidySet() %>%
# mutate_element(Type = ifelse(grepl("^[0-9]+$", elements), "gene", "evidence"))
## ----cardinality, eval=run_vignette-------------------------------------------
# ts %>%
# dplyr::filter(Type != "Gene") %>%
# cardinality() %>%
# arrange(desc(cardinality)) %>%
# head()
## ----size_go, eval=run_vignette-----------------------------------------------
# ts %>%
# filter(sets %in% c("GO:0008152", "GO:0003674", "GO:0005575"),
# Type != "gene") %>%
# set_size()
## ----evidence_go, eval=run_vignette-------------------------------------------
# go_terms <- c("GO:0008152", "GO:0003674", "GO:0005575")
# ts %>%
# filter(sets %in% go_terms & Type != "gene")
## ----prepare_reactome, eval=run_vignette--------------------------------------
# # We load some libraries
# library("reactome.db")
#
# # Prepare the data (is easier, there isn't any ontoogy or evidence column)
# h2p <- as.data.frame(reactomeEXTID2PATHID)
# colnames(h2p) <- c("sets", "elements")
# # Filter only for human pathways
# h2p <- h2p[grepl("^R-HSA-", h2p$sets), ]
#
# # There are duplicate relations with different evidence codes!!:
# summary(duplicated(h2p[, c("elements", "sets")]))
# h2p <- unique(h2p)
# # Create a TidySet and
# h2p_TS <- tidySet(h2p) %>%
# # Add all the genes
# add_elements(keys(org.Hs.eg.db))
## ----numbers_pathways, eval=run_vignette--------------------------------------
# sizes_element <- element_size(h2p_TS) %>%
# arrange(desc(size))
# sum(sizes_element$size == 0)
# sum(sizes_element$size != 0)
#
# sizes_set <- set_size(h2p_TS) %>%
# arrange(desc(size))
## ----pathways_plots, eval=run_vignette----------------------------------------
# sizes_element %>%
# filter(size != 0) %>%
# ggplot() +
# geom_histogram(aes(size), binwidth = 1) +
# scale_y_log10() +
# theme_minimal() +
# labs(x = "# sets per element", y = "Count")
#
# sizes_set %>%
# ggplot() +
# geom_histogram(aes(size), binwidth = 1) +
# scale_y_log10() +
# theme_minimal() +
# labs(x = "# elements per set", y = "Count")
## ----distr_sizes_pathways, eval=run_vignette----------------------------------
# head(sizes_set, 10)
## ----sessionInfo, echo=FALSE--------------------------------------------------
sessionInfo()
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/inst/doc/advanced.R
|
---
title: "Advanced examples"
abstract: >
This vignette assumes you are familiar with set operations from the basic vignette.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
html_document:
fig_caption: true
code_folding: show
self_contained: yes
toc_float:
collapsed: true
toc_depth: 3
author:
- name: Lluís Revilla
email: [email protected]
vignette: >
%\VignetteIndexEntry{Advanced examples}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteDepends{GO.db}
%\VignetteDepends{reactome.db}
%\VignetteDepends{GSEABase}
%\VignetteDepends{org.Hs.eg.db}
%\DeclareUnicodeCharacter{2229}{$\cap$}
%\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
run_vignette <- requireNamespace("GSEABase", quietly = TRUE) &&
requireNamespace("GO.db", quietly = TRUE) &&
requireNamespace("reactome.db", quietly = TRUE) &&
requireNamespace("org.Hs.eg.db", quietly = TRUE) &&
requireNamespace("ggplot2", quietly = TRUE) &&
requireNamespace("forcats", quietly = TRUE)
```
# Initial setup
To show compatibility with tidy workflows we will use magrittr pipe operator and the
dplyr verbs.
```{r setupr, message=FALSE}
library("BaseSet", quietly = TRUE)
library("dplyr", quietly = TRUE)
```
# Human gene ontology
We will explore the genes with assigned gene ontology terms.
These terms describe what is the process and role of the genes.
The links are annotated with different [evidence codes](https://geneontology.org/docs/guide-go-evidence-codes/) to indicate how such annotation is supported.
```{r prepare_GO, message=FALSE, eval=run_vignette}
# We load some libraries
library("org.Hs.eg.db", quietly = TRUE)
library("GO.db", quietly = TRUE)
library("ggplot2", quietly = TRUE)
# Prepare the data
h2GO_TS <- tidySet(org.Hs.egGO)
h2GO <- as.data.frame(org.Hs.egGO)
```
We can now explore if there are differences in evidence usage for each ontology in gene ontology:
```{r evidence_ontology, eval=run_vignette}
library("forcats", include.only = "fct_reorder2", quietly = TRUE)
h2GO %>%
group_by(Evidence, Ontology) %>%
count(name = "Freq") %>%
ungroup() %>%
mutate(Evidence = fct_reorder2(Evidence, Ontology, -Freq),
Ontology = case_match(Ontology,
"CC" ~ "Cellular Component",
"MF" ~ "Molecular Function",
"BP" ~ "Biological Process",
.default = NA)) %>%
ggplot() +
geom_col(aes(Evidence, Freq)) +
facet_grid(~Ontology) +
theme_minimal() +
coord_flip() +
labs(x = element_blank(), y = element_blank(),
title = "Evidence codes for each ontology")
```
We can see that biological process are more likely to be defined by IMP evidence code that means inferred from mutant phenotype.
While inferred from physical interaction (IPI) is almost exclusively used to assign molecular functions.
This graph doesn't consider that some relationships are better annotated than other:
```{r nEvidence_plot, eval=run_vignette}
h2GO_TS %>%
relations() %>%
group_by(elements, sets) %>%
count(sort = TRUE, name = "Annotations") %>%
ungroup() %>%
count(Annotations, sort = TRUE) %>%
ggplot() +
geom_col(aes(Annotations, n)) +
theme_minimal() +
labs(x = "Evidence codes", y = "Annotations",
title = "Evidence codes for each annotation",
subtitle = "in human") +
scale_x_continuous(breaks = 1:7)
```
We can see that mostly all the annotations are done with a single evidence code.
So far we have explored the code that it is related to a gene but how many genes don't have any annotation?
```{r numbers, eval=run_vignette}
# Add all the genes and GO terms
h2GO_TS <- add_elements(h2GO_TS, keys(org.Hs.eg.db)) %>%
add_sets(grep("^GO:", keys(GO.db), value = TRUE))
sizes_element <- element_size(h2GO_TS) %>%
arrange(desc(size))
sum(sizes_element$size == 0)
sum(sizes_element$size != 0)
sizes_set <- set_size(h2GO_TS) %>%
arrange(desc(size))
sum(sizes_set$size == 0)
sum(sizes_set$size != 0)
```
So we can see that both there are more genes without annotation and more gene ontology terms without a (direct) gene annotated.
```{r plots_GO, eval=run_vignette}
sizes_element %>%
filter(size != 0) %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
theme_minimal() +
labs(x = "# sets per element", y = "Count")
sizes_set %>%
filter(size != 0) %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
theme_minimal() +
labs(x = "# elements per set", y = "Count")
```
As you can see on the second plot we have very large values but that are on associated on many genes:
```{r distr_sizes, eval=run_vignette}
head(sizes_set, 10)
```
## Using fuzzy values
This could radically change if we used fuzzy values.
We could assign a fuzzy value to each evidence code given the lowest fuzzy value for the [IEA (Inferred from Electronic Annotation)](https://wiki.geneontology.org/index.php/Inferred_from_Electronic_Annotation_(IEA)) evidence.
The highest values would be for evidence codes coming from experiments or alike.
```{r fuzzy_setup, eval=run_vignette}
nr <- h2GO_TS %>%
relations() %>%
dplyr::select(sets, Evidence) %>%
distinct() %>%
mutate(fuzzy = case_match(Evidence,
"EXP" ~ 0.9,
"IDA" ~ 0.8,
"IPI" ~ 0.8,
"IMP" ~ 0.75,
"IGI" ~ 0.7,
"IEP" ~ 0.65,
"HEP" ~ 0.6,
"HDA" ~ 0.6,
"HMP" ~ 0.5,
"IBA" ~ 0.45,
"ISS" ~ 0.4,
"ISO" ~ 0.32,
"ISA" ~ 0.32,
"ISM" ~ 0.3,
"RCA" ~ 0.2,
"TAS" ~ 0.15,
"NAS" ~ 0.1,
"IC" ~ 0.02,
"ND" ~ 0.02,
"IEA" ~ 0.01,
.default = 0.01)) %>%
dplyr::select(sets = "sets", elements = "Evidence", fuzzy = fuzzy)
```
We have several evidence codes for the same ontology, this would result on different fuzzy values for each relation.
Instead, we extract this and add them as new sets and elements and add an extra column to classify what are those elements:
```{r fuzzy_setup2, eval=run_vignette}
ts <- h2GO_TS %>%
relations() %>%
dplyr::select(-Evidence) %>%
rbind(nr) %>%
tidySet() %>%
mutate_element(Type = ifelse(grepl("^[0-9]+$", elements), "gene", "evidence"))
```
Now we can see which gene ontologies are more supported by the evidence:
```{r cardinality, eval=run_vignette}
ts %>%
dplyr::filter(Type != "Gene") %>%
cardinality() %>%
arrange(desc(cardinality)) %>%
head()
```
Surprisingly the most supported terms are protein binding, nucleus and cytosol.
I would expect them to be the top three terms for cellular component, biological function and molecular function.
Calculating set sizes would be interesting but it requires computing a big number of combinations that make it last long and require many memory available.
```{r size_go, eval=run_vignette}
ts %>%
filter(sets %in% c("GO:0008152", "GO:0003674", "GO:0005575"),
Type != "gene") %>%
set_size()
```
Unexpectedly there is few evidence for the main terms:
```{r evidence_go, eval=run_vignette}
go_terms <- c("GO:0008152", "GO:0003674", "GO:0005575")
ts %>%
filter(sets %in% go_terms & Type != "gene")
```
In fact those terms are arbitrarily decided or inferred from electronic analysis.
# Human pathways
Now we will repeat the same analysis with pathways:
```{r prepare_reactome, eval=run_vignette}
# We load some libraries
library("reactome.db")
# Prepare the data (is easier, there isn't any ontoogy or evidence column)
h2p <- as.data.frame(reactomeEXTID2PATHID)
colnames(h2p) <- c("sets", "elements")
# Filter only for human pathways
h2p <- h2p[grepl("^R-HSA-", h2p$sets), ]
# There are duplicate relations with different evidence codes!!:
summary(duplicated(h2p[, c("elements", "sets")]))
h2p <- unique(h2p)
# Create a TidySet and
h2p_TS <- tidySet(h2p) %>%
# Add all the genes
add_elements(keys(org.Hs.eg.db))
```
Now that we have everything ready we can start measuring some things...
```{r numbers_pathways, eval=run_vignette}
sizes_element <- element_size(h2p_TS) %>%
arrange(desc(size))
sum(sizes_element$size == 0)
sum(sizes_element$size != 0)
sizes_set <- set_size(h2p_TS) %>%
arrange(desc(size))
```
We can see there are more genes without pathways than genes with pathways.
```{r pathways_plots, eval=run_vignette}
sizes_element %>%
filter(size != 0) %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
scale_y_log10() +
theme_minimal() +
labs(x = "# sets per element", y = "Count")
sizes_set %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
scale_y_log10() +
theme_minimal() +
labs(x = "# elements per set", y = "Count")
```
As you can see on the second plot we have very large values but that are on associated on many genes:
```{r distr_sizes_pathways, eval=run_vignette}
head(sizes_set, 10)
```
# Session info {.unnumbered}
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/inst/doc/advanced.Rmd
|
## ----setup, message=FALSE, warning=FALSE, include=FALSE-----------------------
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
library("BaseSet")
library("dplyr")
## ----fuzzy--------------------------------------------------------------------
set.seed(4567) # To be able to have exact replicates
relations <- data.frame(sets = c(rep("A", 5), "B", "C"),
elements = c(letters[seq_len(6)], letters[6]),
fuzzy = runif(7))
fuzzy_set <- tidySet(relations)
## ----union--------------------------------------------------------------------
BaseSet::union(fuzzy_set, sets = c("A", "B"))
BaseSet::union(fuzzy_set, sets = c("A", "B"), name = "D")
## ----union_logic--------------------------------------------------------------
BaseSet::union(fuzzy_set, sets = c("A", "B"), FUN = function(x){sqrt(sum(x))})
## ----intersection-------------------------------------------------------------
intersection(fuzzy_set, sets = c("B", "C"), keep = FALSE)
intersection(fuzzy_set, sets = c("B", "C"), keep = FALSE, FUN = "mean")
## ----complement---------------------------------------------------------------
complement_set(fuzzy_set, sets = "A", keep = FALSE)
## ----complement_previous------------------------------------------------------
filter(fuzzy_set, sets == "A")
complement_set(fuzzy_set, sets = "A", keep = FALSE, FUN = function(x){1-x^2})
## ----subtract-----------------------------------------------------------------
subtract(fuzzy_set, set_in = "A", not_in = "B", keep = FALSE, name = "A-B")
# Or the opposite B-A, but using the default name:
subtract(fuzzy_set, set_in = "B", not_in = "A", keep = FALSE)
## ----set_size-----------------------------------------------------------------
set_size(fuzzy_set)
## ----element_size-------------------------------------------------------------
element_size(fuzzy_set)
## ----cells_0------------------------------------------------------------------
sc_classification <- data.frame(
elements = c("D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14",
"D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18", "D2ex_1", "D2ex_10",
"D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14", "D2ex_15", "D2ex_16",
"D2ex_17", "D2ex_18", "D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12",
"D2ex_13", "D2ex_14", "D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18",
"D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14",
"D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18"),
sets = c("alpha", "alpha", "alpha", "alpha", "alpha", "alpha", "alpha",
"alpha", "alpha", "alpha", "endothel", "endothel", "endothel",
"endothel", "endothel", "endothel", "endothel", "endothel",
"endothel", "endothel", "delta", "delta", "delta", "delta", "delta",
"delta", "delta", "delta", "delta", "delta", "beta", "beta", "beta",
"beta", "beta", "beta", "beta", "beta", "beta", "beta"),
fuzzy = c(0.18, 0.169, 0.149, 0.192, 0.154, 0.161, 0.169, 0.197, 0.162, 0.201,
0.215, 0.202, 0.17, 0.227, 0.196, 0.215, 0.161, 0.195, 0.178,
0.23, 0.184, 0.172, 0.153, 0.191, 0.156, 0.167, 0.165, 0.184,
0.162, 0.194, 0.197, 0.183, 0.151, 0.208, 0.16, 0.169, 0.169,
0.2, 0.154, 0.208), stringsAsFactors = FALSE)
head(sc_classification)
## ----cells_classification-----------------------------------------------------
sc_classification %>%
group_by(elements) %>%
filter(fuzzy == max(fuzzy)) %>%
group_by(sets) %>%
count()
## ----cells_subset-------------------------------------------------------------
scTS <- tidySet(sc_classification) # Conversion of format
sample_cells <- scTS %>%
element_size() %>%
group_by(elements) %>%
filter(probability == max(probability))
sample_cells
## ----celltypes----------------------------------------------------------------
scTS %>%
set_size() %>%
group_by(sets) %>%
filter(probability == max(probability))
## ----sessionInfo, echo=FALSE--------------------------------------------------
sessionInfo()
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/inst/doc/fuzzy.R
|
---
title: "Fuzzy sets"
abstract: >
Describes the fuzzy sets, interpretation and how to work with them.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
html_document:
fig_caption: true
code_folding: show
self_contained: yes
toc_float:
collapsed: true
toc_depth: 3
author:
- name: Lluís Revilla
email: [email protected]
vignette: >
%\VignetteIndexEntry{Fuzzy sets}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
%\DeclareUnicodeCharacter{2229}{$\cap$}
%\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options:
chunk_output_type: console
---
```{r setup, message=FALSE, warning=FALSE, include=FALSE}
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
library("BaseSet")
library("dplyr")
```
# Getting started
This vignettes supposes that you already read the "About BaseSet" vignette.
This vignette explains what are the fuzzy sets and how to use them.
As all methods for "normal" sets are available for fuzzy sets this vignette focuses on how to create, use them.
# What are fuzzy sets and why/when use them ?
Fuzzy sets are generalizations of classical sets where there is some vagueness, one doesn't know for sure something on this relationship between the set and the element.
This vagueness can be on the assignment to a set and/or on the membership on the set.
One way these vagueness arise is when classifying a continuous scale on a categorical scale, for example: when the temperature is 20ºC is it hot or not? If the temperature drops to 15ºC is it warm?
When does the switch happen from warm to hot?
In fuzzy set theories the step from a continuous scale to a categorical scale is performed by the [membership function](https://en.wikipedia.org/wiki/Membership_function_(mathematics)) and is called [fuzzification](https://en.wikipedia.org/wiki/Fuzzy_logic#Fuzzification).
When there is a degree of membership and uncertainty on the membership it is considered a [type-2 fuzzy set](https://en.wikipedia.org/wiki/Type-2_fuzzy_sets_and_systems).
We can understand it with using as example a paddle ball, it can be used for tennis or paddle (membership), but until we don't test it bouncing on the court we won't be sure (assignment) if it is a paddle ball or a tennis ball.
We could think about a ball equally good for tennis and paddle (membership) but which two people thought it is for tennis and the other for paddle.
These voting/rating system is also a common scenario where fuzzy sets arise.
When several graders/people need to agree but compromise on a middle ground.
One modern example of this is ratting apps where several people vote between 1 and 5 an app and the displayed value takes into consideration all the votes.
As you can see when one does have some vagueness or uncertainty then fuzzy logic is a good choice.
There have been developed several logic and methods.
# Creating a fuzzy set
To create a fuzzy set you need to have a column named "fuzzy" if you create it
from a `data.frame` or have a named numeric vector if you create it from a `list`.
These values are restricted to a numeric value between 0 and 1.
The value indicates the strength, membership, truth value (or probability) of the relationship between
the element and the set.
```{r fuzzy}
set.seed(4567) # To be able to have exact replicates
relations <- data.frame(sets = c(rep("A", 5), "B", "C"),
elements = c(letters[seq_len(6)], letters[6]),
fuzzy = runif(7))
fuzzy_set <- tidySet(relations)
```
# Working with fuzzy sets
We can work with fuzzy sets as we do with normal sets.
But if you remember that at the end of the previous vignette we used an Important column, now it is already included as fuzzy.
This allows us to use this information for union and intersection methods and other operations:
## Union
You can make a union of two sets present on the same object.
```{r union}
BaseSet::union(fuzzy_set, sets = c("A", "B"))
BaseSet::union(fuzzy_set, sets = c("A", "B"), name = "D")
```
We get a new set with all the elements on both sets.
There isn't an element in both sets A and B, so the fuzzy values here do not change.
If we wanted to use other logic we can with provide it with the FUN argument.
```{r union_logic}
BaseSet::union(fuzzy_set, sets = c("A", "B"), FUN = function(x){sqrt(sum(x))})
```
There are several logic see for instance `?sets::fuzzy_logic`.
You should pick the operators that fit on the framework of your data.
Make sure that the defaults arguments of logic apply to your data obtaining process.
## Intersection
However if we do the intersection between B and C we can see some changes on the fuzzy value:
```{r intersection}
intersection(fuzzy_set, sets = c("B", "C"), keep = FALSE)
intersection(fuzzy_set, sets = c("B", "C"), keep = FALSE, FUN = "mean")
```
Different logic on the `union()`, `intersection()`, `complement()`, and `cardinality()`, we get different fuzzy values.
Depending on the nature of our fuzziness and the intended goal we might apply one or other rules.
## Complement
We can look for the complement of one or several sets:
```{r complement}
complement_set(fuzzy_set, sets = "A", keep = FALSE)
```
Note that the values of the complement are `1-fuzzy` but can be changed:
```{r complement_previous}
filter(fuzzy_set, sets == "A")
complement_set(fuzzy_set, sets = "A", keep = FALSE, FUN = function(x){1-x^2})
```
## Subtract
This is the equivalent of `setdiff`, but clearer:
```{r subtract}
subtract(fuzzy_set, set_in = "A", not_in = "B", keep = FALSE, name = "A-B")
# Or the opposite B-A, but using the default name:
subtract(fuzzy_set, set_in = "B", not_in = "A", keep = FALSE)
```
Note that here there is also a subtraction of the fuzzy value.
# Sizes
If we consider the fuzzy values as probabilities then the size of a set is not fixed.
To calculate the size of a given set we have `set_size()`:
```{r set_size}
set_size(fuzzy_set)
```
Or an element can be in 0 sets:
```{r element_size}
element_size(fuzzy_set)
```
In this example we can see that it is more probable that the element "a" is not
present than the element "f" being present in one set.
# Interpretation
Sometimes it can be a bit hard to understand what do the fuzzy sets mean on your analysis.
To better understand let's dive a bit in the interpretation with an example:
Imagine you have your experiment where you collected data from a sample of cells for each cell (our elements).
Then you used some program to classify which type of cell it is (alpha, beta, delta, endothelial), this are our sets.
The software returns a probability for each type it has: the higher, the more confident it is of the assignment:
```{r cells_0}
sc_classification <- data.frame(
elements = c("D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14",
"D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18", "D2ex_1", "D2ex_10",
"D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14", "D2ex_15", "D2ex_16",
"D2ex_17", "D2ex_18", "D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12",
"D2ex_13", "D2ex_14", "D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18",
"D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14",
"D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18"),
sets = c("alpha", "alpha", "alpha", "alpha", "alpha", "alpha", "alpha",
"alpha", "alpha", "alpha", "endothel", "endothel", "endothel",
"endothel", "endothel", "endothel", "endothel", "endothel",
"endothel", "endothel", "delta", "delta", "delta", "delta", "delta",
"delta", "delta", "delta", "delta", "delta", "beta", "beta", "beta",
"beta", "beta", "beta", "beta", "beta", "beta", "beta"),
fuzzy = c(0.18, 0.169, 0.149, 0.192, 0.154, 0.161, 0.169, 0.197, 0.162, 0.201,
0.215, 0.202, 0.17, 0.227, 0.196, 0.215, 0.161, 0.195, 0.178,
0.23, 0.184, 0.172, 0.153, 0.191, 0.156, 0.167, 0.165, 0.184,
0.162, 0.194, 0.197, 0.183, 0.151, 0.208, 0.16, 0.169, 0.169,
0.2, 0.154, 0.208), stringsAsFactors = FALSE)
head(sc_classification)
```
Our question is **which type of cells did we have on the original sample?**
We can easily answer this by looking at the relations that have higher confidence of the relationship for each cell.
```{r cells_classification}
sc_classification %>%
group_by(elements) %>%
filter(fuzzy == max(fuzzy)) %>%
group_by(sets) %>%
count()
```
There is a cell that can be in two cell types, because we started with 10 cells and we have 11 elements here.
However, how likely is that a cell is placed to just a single set?
```{r cells_subset}
scTS <- tidySet(sc_classification) # Conversion of format
sample_cells <- scTS %>%
element_size() %>%
group_by(elements) %>%
filter(probability == max(probability))
sample_cells
```
There must be some cell misclassification: we have `r nElements(scTS)` cells in this example but there are `r sum(sample_cells$size)` cells that the maximum probability predicted for these types is a single cell type.
Even the cell that had two equal probabilities for two cell types is more probable to be in no one of these cell types than in any of them.
Ideally the predicted number of cells per type and the cells with higher confidence about the type should match.
We can also look the other way around: How good is the prediction of a cell type for each cell?
```{r celltypes}
scTS %>%
set_size() %>%
group_by(sets) %>%
filter(probability == max(probability))
```
We can see that for each cell type it is probable to have at least one cell and in the endothelial cell type two cells is the most probable outcome.
However, these probabilities are lower than the probabilities of cells being assigned a cell type.
This would mean that this method is not a good method or that the cell types are not specific enough for the cell.
In summary, the cells that we had most probable are not those 4 cell types except in two cells were it might be.
# Session info {.unnumbered}
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/inst/doc/fuzzy.Rmd
|
---
title: "BaseSet"
abstract: >
Describes the background of the package, important functions defined in the
package and some of the applications and usages.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
html_document:
fig_caption: true
code_folding: show
self_contained: yes
toc_float:
collapsed: true
toc_depth: 3
author:
- name: Lluís Revilla
email: [email protected]
vignette: >
%\VignetteIndexEntry{BaseSet}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
%\DeclareUnicodeCharacter{2229}{$\cap$}
%\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options:
chunk_output_type: console
---
```{r setup, message=FALSE, warning=FALSE, include=FALSE}
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
```
# Getting started
This vignette explains how to work with sets using this package.
The package provides a class to store the information efficiently and functions to work with it.
# The TidySet class
To create a `TidySet` object, to store associations between elements and sets
image we have several genes associated with a characteristic.
```{r from_list, message=FALSE}
library("BaseSet")
gene_lists <- list(
geneset1 = c("A", "B"),
geneset2 = c("B", "C", "D")
)
tidy_set <- tidySet(gene_lists)
tidy_set
```
This is then stored internally in three slots `relations()`, `elements()`, and `sets()` slots.
If you have more information for each element or set it can be added:
```{r metadata, message=FALSE}
gene_data <- data.frame(
stat1 = c( 1, 2, 3, 4 ),
info1 = c("a", "b", "c", "d")
)
tidy_set <- add_column(tidy_set, "elements", gene_data)
set_data <- data.frame(
Group = c( 100 , 200 ),
Column = c("abc", "def")
)
tidy_set <- add_column(tidy_set, "sets", set_data)
tidy_set
```
This data is stored in one of the three slots, which can be directly accessed using their getter methods:
```{r getters}
relations(tidy_set)
elements(tidy_set)
sets(tidy_set)
```
You can add as much information as you want, with the only restriction for a "fuzzy" column for the `relations()`. See the Fuzzy sets vignette: `vignette("Fuzzy sets", "BaseSet")`.
You can also use the standard R approach with `[`:
```{r}
gene_data <- data.frame(
stat2 = c( 4, 4, 3, 5 ),
info2 = c("a", "b", "c", "d")
)
tidy_set$info1 <- NULL
tidy_set[, "elements", c("stat2", "info2")] <- gene_data
tidy_set[, "sets", "Group"] <- c("low", "high")
tidy_set
```
Observe that one can add, replace or delete
# Creating a TidySet
As you can see it is possible to create a TidySet from a list.
More commonly you can create it from a data.frame:
```{r tidyset_data.frame}
relations <- data.frame(elements = c("a", "b", "c", "d", "e", "f"),
sets = c("A", "A", "A", "A", "A", "B"),
fuzzy = c(1, 1, 1, 1, 1, 1))
TS <- tidySet(relations)
TS
```
It is also possible from a matrix:
```{r tidySet_matrix}
m <- matrix(c(0, 0, 1, 1, 1, 1, 0, 1, 0), ncol = 3, nrow = 3,
dimnames = list(letters[1:3], LETTERS[1:3]))
m
tidy_set <- tidySet(m)
tidy_set
```
Or they can be created from a GeneSet and GeneSetCollection objects.
Additionally it has several function to read files related to sets like the OBO files (`getOBO`) and GAF (`getGAF`)
# Converting to other formats
It is possible to extract the gene sets as a `list`, for use with functions such as `lapply`.
```{r as.list}
as.list(tidy_set)
```
Or if you need to apply some network methods and you need a matrix, you can create it with `incidence`:
```{r incidence}
incidence(tidy_set)
```
# Operations with sets
To work with sets several methods are provided. In general you can provide a new name for the resulting set of the operation, but if you don't one will be automatically provided using `naming()`. All methods work with fuzzy and non-fuzzy sets
## Union
You can make a union of two sets present on the same object.
```{r union}
BaseSet::union(tidy_set, sets = c("C", "B"), name = "D")
```
## Intersection
```{r intersection}
intersection(tidy_set, sets = c("A", "B"), name = "D", keep = TRUE)
```
The keep argument used here is if you want to keep all the other previous sets:
```{r intersection2}
intersection(tidy_set, sets = c("A", "B"), name = "D", keep = FALSE)
```
## Complement
We can look for the complement of one or several sets:
```{r complement}
complement_set(tidy_set, sets = c("A", "B"))
```
Observe that we haven't provided a name for the resulting set but we can provide one if we prefer to
```{r complement2}
complement_set(tidy_set, sets = c("A", "B"), name = "F")
```
## Subtract
This is the equivalent of `setdiff`, but clearer:
```{r subtract}
out <- subtract(tidy_set, set_in = "A", not_in = "B", name = "A-B")
out
name_sets(out)
subtract(tidy_set, set_in = "B", not_in = "A", keep = FALSE)
```
See that in the first case there isn't any element present in B not in set A, but the new set is stored.
In the second use case we focus just on the elements that are present on B but not in A.
# Additional information
The number of unique elements and sets can be obtained using the `nElements()` and `nSets()` methods.
```{r n}
nElements(tidy_set)
nSets(tidy_set)
nRelations(tidy_set)
```
If you wish to know all in a single call you can use `dim(tidy_set)`: `r dim(tidy_set)`.
This summary doesn't provide the number of relations of each set.
You can quickly obtain that with `lengths(tidy_set)`: `r lengths(tidy_set)`
The size of each set can be obtained using the `set_size()` method.
```{r set_size}
set_size(tidy_set)
```
Conversely, the number of sets associated with each gene is returned by the
`element_size()` function.
```{r element_size}
element_size(tidy_set)
```
The identifiers of elements and sets can be inspected and renamed using `name_elements` and
```{r name}
name_elements(tidy_set)
name_elements(tidy_set) <- paste0("Gene", seq_len(nElements(tidy_set)))
name_elements(tidy_set)
name_sets(tidy_set)
name_sets(tidy_set) <- paste0("Geneset", seq_len(nSets(tidy_set)))
name_sets(tidy_set)
```
# Using `dplyr` verbs
You can also use `mutate()`, `filter()`, `select()`, `group_by()` and other `dplyr` verbs with TidySets.
You usually need to activate which three slots you want to affect with `activate()`:
```{r tidyverse}
library("dplyr")
m_TS <- tidy_set %>%
activate("relations") %>%
mutate(Important = runif(nRelations(tidy_set)))
m_TS
```
You can use activate to select what are the verbs modifying:
```{r deactivate}
set_modified <- m_TS %>%
activate("elements") %>%
mutate(Pathway = if_else(elements %in% c("Gene1", "Gene2"),
"pathway1",
"pathway2"))
set_modified
set_modified %>%
deactivate() %>% # To apply a filter independently of where it is
filter(Pathway == "pathway1")
```
If you think you need `group_by` usually this could mean that you need a new set.
You can create a new one with `group`.
```{r group}
# A new group of those elements in pathway1 and with Important == 1
set_modified %>%
deactivate() %>%
group(name = "new", Pathway == "pathway1")
```
```{r group2}
set_modified %>%
group("pathway1", elements %in% c("Gene1", "Gene2"))
```
You can use `group_by()` but it won't return a `TidySet`.
```{r group_by}
set_modified %>%
deactivate() %>%
group_by(Pathway, sets) %>%
count()
```
After grouping or mutating sometimes we might be interested in moving a column describing something to other places. We can do by this with:
```{r moving}
elements(set_modified)
out <- move_to(set_modified, "elements", "relations", "Pathway")
relations(out)
```
# Session info {.unnumbered}
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/vignettes/BaseSet.Rmd
|
---
title: "Advanced examples"
abstract: >
This vignette assumes you are familiar with set operations from the basic vignette.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
html_document:
fig_caption: true
code_folding: show
self_contained: yes
toc_float:
collapsed: true
toc_depth: 3
author:
- name: Lluís Revilla
email: [email protected]
vignette: >
%\VignetteIndexEntry{Advanced examples}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteDepends{GO.db}
%\VignetteDepends{reactome.db}
%\VignetteDepends{GSEABase}
%\VignetteDepends{org.Hs.eg.db}
%\DeclareUnicodeCharacter{2229}{$\cap$}
%\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
run_vignette <- requireNamespace("GSEABase", quietly = TRUE) &&
requireNamespace("GO.db", quietly = TRUE) &&
requireNamespace("reactome.db", quietly = TRUE) &&
requireNamespace("org.Hs.eg.db", quietly = TRUE) &&
requireNamespace("ggplot2", quietly = TRUE) &&
requireNamespace("forcats", quietly = TRUE)
```
# Initial setup
To show compatibility with tidy workflows we will use magrittr pipe operator and the
dplyr verbs.
```{r setupr, message=FALSE}
library("BaseSet", quietly = TRUE)
library("dplyr", quietly = TRUE)
```
# Human gene ontology
We will explore the genes with assigned gene ontology terms.
These terms describe what is the process and role of the genes.
The links are annotated with different [evidence codes](https://geneontology.org/docs/guide-go-evidence-codes/) to indicate how such annotation is supported.
```{r prepare_GO, message=FALSE, eval=run_vignette}
# We load some libraries
library("org.Hs.eg.db", quietly = TRUE)
library("GO.db", quietly = TRUE)
library("ggplot2", quietly = TRUE)
# Prepare the data
h2GO_TS <- tidySet(org.Hs.egGO)
h2GO <- as.data.frame(org.Hs.egGO)
```
We can now explore if there are differences in evidence usage for each ontology in gene ontology:
```{r evidence_ontology, eval=run_vignette}
library("forcats", include.only = "fct_reorder2", quietly = TRUE)
h2GO %>%
group_by(Evidence, Ontology) %>%
count(name = "Freq") %>%
ungroup() %>%
mutate(Evidence = fct_reorder2(Evidence, Ontology, -Freq),
Ontology = case_match(Ontology,
"CC" ~ "Cellular Component",
"MF" ~ "Molecular Function",
"BP" ~ "Biological Process",
.default = NA)) %>%
ggplot() +
geom_col(aes(Evidence, Freq)) +
facet_grid(~Ontology) +
theme_minimal() +
coord_flip() +
labs(x = element_blank(), y = element_blank(),
title = "Evidence codes for each ontology")
```
We can see that biological process are more likely to be defined by IMP evidence code that means inferred from mutant phenotype.
While inferred from physical interaction (IPI) is almost exclusively used to assign molecular functions.
This graph doesn't consider that some relationships are better annotated than other:
```{r nEvidence_plot, eval=run_vignette}
h2GO_TS %>%
relations() %>%
group_by(elements, sets) %>%
count(sort = TRUE, name = "Annotations") %>%
ungroup() %>%
count(Annotations, sort = TRUE) %>%
ggplot() +
geom_col(aes(Annotations, n)) +
theme_minimal() +
labs(x = "Evidence codes", y = "Annotations",
title = "Evidence codes for each annotation",
subtitle = "in human") +
scale_x_continuous(breaks = 1:7)
```
We can see that mostly all the annotations are done with a single evidence code.
So far we have explored the code that it is related to a gene but how many genes don't have any annotation?
```{r numbers, eval=run_vignette}
# Add all the genes and GO terms
h2GO_TS <- add_elements(h2GO_TS, keys(org.Hs.eg.db)) %>%
add_sets(grep("^GO:", keys(GO.db), value = TRUE))
sizes_element <- element_size(h2GO_TS) %>%
arrange(desc(size))
sum(sizes_element$size == 0)
sum(sizes_element$size != 0)
sizes_set <- set_size(h2GO_TS) %>%
arrange(desc(size))
sum(sizes_set$size == 0)
sum(sizes_set$size != 0)
```
So we can see that both there are more genes without annotation and more gene ontology terms without a (direct) gene annotated.
```{r plots_GO, eval=run_vignette}
sizes_element %>%
filter(size != 0) %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
theme_minimal() +
labs(x = "# sets per element", y = "Count")
sizes_set %>%
filter(size != 0) %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
theme_minimal() +
labs(x = "# elements per set", y = "Count")
```
As you can see on the second plot we have very large values but that are on associated on many genes:
```{r distr_sizes, eval=run_vignette}
head(sizes_set, 10)
```
## Using fuzzy values
This could radically change if we used fuzzy values.
We could assign a fuzzy value to each evidence code given the lowest fuzzy value for the [IEA (Inferred from Electronic Annotation)](https://wiki.geneontology.org/index.php/Inferred_from_Electronic_Annotation_(IEA)) evidence.
The highest values would be for evidence codes coming from experiments or alike.
```{r fuzzy_setup, eval=run_vignette}
nr <- h2GO_TS %>%
relations() %>%
dplyr::select(sets, Evidence) %>%
distinct() %>%
mutate(fuzzy = case_match(Evidence,
"EXP" ~ 0.9,
"IDA" ~ 0.8,
"IPI" ~ 0.8,
"IMP" ~ 0.75,
"IGI" ~ 0.7,
"IEP" ~ 0.65,
"HEP" ~ 0.6,
"HDA" ~ 0.6,
"HMP" ~ 0.5,
"IBA" ~ 0.45,
"ISS" ~ 0.4,
"ISO" ~ 0.32,
"ISA" ~ 0.32,
"ISM" ~ 0.3,
"RCA" ~ 0.2,
"TAS" ~ 0.15,
"NAS" ~ 0.1,
"IC" ~ 0.02,
"ND" ~ 0.02,
"IEA" ~ 0.01,
.default = 0.01)) %>%
dplyr::select(sets = "sets", elements = "Evidence", fuzzy = fuzzy)
```
We have several evidence codes for the same ontology, this would result on different fuzzy values for each relation.
Instead, we extract this and add them as new sets and elements and add an extra column to classify what are those elements:
```{r fuzzy_setup2, eval=run_vignette}
ts <- h2GO_TS %>%
relations() %>%
dplyr::select(-Evidence) %>%
rbind(nr) %>%
tidySet() %>%
mutate_element(Type = ifelse(grepl("^[0-9]+$", elements), "gene", "evidence"))
```
Now we can see which gene ontologies are more supported by the evidence:
```{r cardinality, eval=run_vignette}
ts %>%
dplyr::filter(Type != "Gene") %>%
cardinality() %>%
arrange(desc(cardinality)) %>%
head()
```
Surprisingly the most supported terms are protein binding, nucleus and cytosol.
I would expect them to be the top three terms for cellular component, biological function and molecular function.
Calculating set sizes would be interesting but it requires computing a big number of combinations that make it last long and require many memory available.
```{r size_go, eval=run_vignette}
ts %>%
filter(sets %in% c("GO:0008152", "GO:0003674", "GO:0005575"),
Type != "gene") %>%
set_size()
```
Unexpectedly there is few evidence for the main terms:
```{r evidence_go, eval=run_vignette}
go_terms <- c("GO:0008152", "GO:0003674", "GO:0005575")
ts %>%
filter(sets %in% go_terms & Type != "gene")
```
In fact those terms are arbitrarily decided or inferred from electronic analysis.
# Human pathways
Now we will repeat the same analysis with pathways:
```{r prepare_reactome, eval=run_vignette}
# We load some libraries
library("reactome.db")
# Prepare the data (is easier, there isn't any ontoogy or evidence column)
h2p <- as.data.frame(reactomeEXTID2PATHID)
colnames(h2p) <- c("sets", "elements")
# Filter only for human pathways
h2p <- h2p[grepl("^R-HSA-", h2p$sets), ]
# There are duplicate relations with different evidence codes!!:
summary(duplicated(h2p[, c("elements", "sets")]))
h2p <- unique(h2p)
# Create a TidySet and
h2p_TS <- tidySet(h2p) %>%
# Add all the genes
add_elements(keys(org.Hs.eg.db))
```
Now that we have everything ready we can start measuring some things...
```{r numbers_pathways, eval=run_vignette}
sizes_element <- element_size(h2p_TS) %>%
arrange(desc(size))
sum(sizes_element$size == 0)
sum(sizes_element$size != 0)
sizes_set <- set_size(h2p_TS) %>%
arrange(desc(size))
```
We can see there are more genes without pathways than genes with pathways.
```{r pathways_plots, eval=run_vignette}
sizes_element %>%
filter(size != 0) %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
scale_y_log10() +
theme_minimal() +
labs(x = "# sets per element", y = "Count")
sizes_set %>%
ggplot() +
geom_histogram(aes(size), binwidth = 1) +
scale_y_log10() +
theme_minimal() +
labs(x = "# elements per set", y = "Count")
```
As you can see on the second plot we have very large values but that are on associated on many genes:
```{r distr_sizes_pathways, eval=run_vignette}
head(sizes_set, 10)
```
# Session info {.unnumbered}
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/vignettes/advanced.Rmd
|
---
title: "Fuzzy sets"
abstract: >
Describes the fuzzy sets, interpretation and how to work with them.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
html_document:
fig_caption: true
code_folding: show
self_contained: yes
toc_float:
collapsed: true
toc_depth: 3
author:
- name: Lluís Revilla
email: [email protected]
vignette: >
%\VignetteIndexEntry{Fuzzy sets}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
%\DeclareUnicodeCharacter{2229}{$\cap$}
%\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options:
chunk_output_type: console
---
```{r setup, message=FALSE, warning=FALSE, include=FALSE}
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE,
warning = TRUE,
comment = "#>")
library("BaseSet")
library("dplyr")
```
# Getting started
This vignettes supposes that you already read the "About BaseSet" vignette.
This vignette explains what are the fuzzy sets and how to use them.
As all methods for "normal" sets are available for fuzzy sets this vignette focuses on how to create, use them.
# What are fuzzy sets and why/when use them ?
Fuzzy sets are generalizations of classical sets where there is some vagueness, one doesn't know for sure something on this relationship between the set and the element.
This vagueness can be on the assignment to a set and/or on the membership on the set.
One way these vagueness arise is when classifying a continuous scale on a categorical scale, for example: when the temperature is 20ºC is it hot or not? If the temperature drops to 15ºC is it warm?
When does the switch happen from warm to hot?
In fuzzy set theories the step from a continuous scale to a categorical scale is performed by the [membership function](https://en.wikipedia.org/wiki/Membership_function_(mathematics)) and is called [fuzzification](https://en.wikipedia.org/wiki/Fuzzy_logic#Fuzzification).
When there is a degree of membership and uncertainty on the membership it is considered a [type-2 fuzzy set](https://en.wikipedia.org/wiki/Type-2_fuzzy_sets_and_systems).
We can understand it with using as example a paddle ball, it can be used for tennis or paddle (membership), but until we don't test it bouncing on the court we won't be sure (assignment) if it is a paddle ball or a tennis ball.
We could think about a ball equally good for tennis and paddle (membership) but which two people thought it is for tennis and the other for paddle.
These voting/rating system is also a common scenario where fuzzy sets arise.
When several graders/people need to agree but compromise on a middle ground.
One modern example of this is ratting apps where several people vote between 1 and 5 an app and the displayed value takes into consideration all the votes.
As you can see when one does have some vagueness or uncertainty then fuzzy logic is a good choice.
There have been developed several logic and methods.
# Creating a fuzzy set
To create a fuzzy set you need to have a column named "fuzzy" if you create it
from a `data.frame` or have a named numeric vector if you create it from a `list`.
These values are restricted to a numeric value between 0 and 1.
The value indicates the strength, membership, truth value (or probability) of the relationship between
the element and the set.
```{r fuzzy}
set.seed(4567) # To be able to have exact replicates
relations <- data.frame(sets = c(rep("A", 5), "B", "C"),
elements = c(letters[seq_len(6)], letters[6]),
fuzzy = runif(7))
fuzzy_set <- tidySet(relations)
```
# Working with fuzzy sets
We can work with fuzzy sets as we do with normal sets.
But if you remember that at the end of the previous vignette we used an Important column, now it is already included as fuzzy.
This allows us to use this information for union and intersection methods and other operations:
## Union
You can make a union of two sets present on the same object.
```{r union}
BaseSet::union(fuzzy_set, sets = c("A", "B"))
BaseSet::union(fuzzy_set, sets = c("A", "B"), name = "D")
```
We get a new set with all the elements on both sets.
There isn't an element in both sets A and B, so the fuzzy values here do not change.
If we wanted to use other logic we can with provide it with the FUN argument.
```{r union_logic}
BaseSet::union(fuzzy_set, sets = c("A", "B"), FUN = function(x){sqrt(sum(x))})
```
There are several logic see for instance `?sets::fuzzy_logic`.
You should pick the operators that fit on the framework of your data.
Make sure that the defaults arguments of logic apply to your data obtaining process.
## Intersection
However if we do the intersection between B and C we can see some changes on the fuzzy value:
```{r intersection}
intersection(fuzzy_set, sets = c("B", "C"), keep = FALSE)
intersection(fuzzy_set, sets = c("B", "C"), keep = FALSE, FUN = "mean")
```
Different logic on the `union()`, `intersection()`, `complement()`, and `cardinality()`, we get different fuzzy values.
Depending on the nature of our fuzziness and the intended goal we might apply one or other rules.
## Complement
We can look for the complement of one or several sets:
```{r complement}
complement_set(fuzzy_set, sets = "A", keep = FALSE)
```
Note that the values of the complement are `1-fuzzy` but can be changed:
```{r complement_previous}
filter(fuzzy_set, sets == "A")
complement_set(fuzzy_set, sets = "A", keep = FALSE, FUN = function(x){1-x^2})
```
## Subtract
This is the equivalent of `setdiff`, but clearer:
```{r subtract}
subtract(fuzzy_set, set_in = "A", not_in = "B", keep = FALSE, name = "A-B")
# Or the opposite B-A, but using the default name:
subtract(fuzzy_set, set_in = "B", not_in = "A", keep = FALSE)
```
Note that here there is also a subtraction of the fuzzy value.
# Sizes
If we consider the fuzzy values as probabilities then the size of a set is not fixed.
To calculate the size of a given set we have `set_size()`:
```{r set_size}
set_size(fuzzy_set)
```
Or an element can be in 0 sets:
```{r element_size}
element_size(fuzzy_set)
```
In this example we can see that it is more probable that the element "a" is not
present than the element "f" being present in one set.
# Interpretation
Sometimes it can be a bit hard to understand what do the fuzzy sets mean on your analysis.
To better understand let's dive a bit in the interpretation with an example:
Imagine you have your experiment where you collected data from a sample of cells for each cell (our elements).
Then you used some program to classify which type of cell it is (alpha, beta, delta, endothelial), this are our sets.
The software returns a probability for each type it has: the higher, the more confident it is of the assignment:
```{r cells_0}
sc_classification <- data.frame(
elements = c("D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14",
"D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18", "D2ex_1", "D2ex_10",
"D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14", "D2ex_15", "D2ex_16",
"D2ex_17", "D2ex_18", "D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12",
"D2ex_13", "D2ex_14", "D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18",
"D2ex_1", "D2ex_10", "D2ex_11", "D2ex_12", "D2ex_13", "D2ex_14",
"D2ex_15", "D2ex_16", "D2ex_17", "D2ex_18"),
sets = c("alpha", "alpha", "alpha", "alpha", "alpha", "alpha", "alpha",
"alpha", "alpha", "alpha", "endothel", "endothel", "endothel",
"endothel", "endothel", "endothel", "endothel", "endothel",
"endothel", "endothel", "delta", "delta", "delta", "delta", "delta",
"delta", "delta", "delta", "delta", "delta", "beta", "beta", "beta",
"beta", "beta", "beta", "beta", "beta", "beta", "beta"),
fuzzy = c(0.18, 0.169, 0.149, 0.192, 0.154, 0.161, 0.169, 0.197, 0.162, 0.201,
0.215, 0.202, 0.17, 0.227, 0.196, 0.215, 0.161, 0.195, 0.178,
0.23, 0.184, 0.172, 0.153, 0.191, 0.156, 0.167, 0.165, 0.184,
0.162, 0.194, 0.197, 0.183, 0.151, 0.208, 0.16, 0.169, 0.169,
0.2, 0.154, 0.208), stringsAsFactors = FALSE)
head(sc_classification)
```
Our question is **which type of cells did we have on the original sample?**
We can easily answer this by looking at the relations that have higher confidence of the relationship for each cell.
```{r cells_classification}
sc_classification %>%
group_by(elements) %>%
filter(fuzzy == max(fuzzy)) %>%
group_by(sets) %>%
count()
```
There is a cell that can be in two cell types, because we started with 10 cells and we have 11 elements here.
However, how likely is that a cell is placed to just a single set?
```{r cells_subset}
scTS <- tidySet(sc_classification) # Conversion of format
sample_cells <- scTS %>%
element_size() %>%
group_by(elements) %>%
filter(probability == max(probability))
sample_cells
```
There must be some cell misclassification: we have `r nElements(scTS)` cells in this example but there are `r sum(sample_cells$size)` cells that the maximum probability predicted for these types is a single cell type.
Even the cell that had two equal probabilities for two cell types is more probable to be in no one of these cell types than in any of them.
Ideally the predicted number of cells per type and the cells with higher confidence about the type should match.
We can also look the other way around: How good is the prediction of a cell type for each cell?
```{r celltypes}
scTS %>%
set_size() %>%
group_by(sets) %>%
filter(probability == max(probability))
```
We can see that for each cell type it is probable to have at least one cell and in the endothelial cell type two cells is the most probable outcome.
However, these probabilities are lower than the probabilities of cells being assigned a cell type.
This would mean that this method is not a good method or that the cell types are not specific enough for the cell.
In summary, the cells that we had most probable are not those 4 cell types except in two cells were it might be.
# Session info {.unnumbered}
```{r sessionInfo, echo=FALSE}
sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/BaseSet/vignettes/fuzzy.Rmd
|
#' @title Preparation of Data for Germination Percentages
#'
#' @param Data Dataframe with Temperature in Row and Time in Column
#' @param TSeed Total Number of Seeds
#' @param GPercentage Vector of Germination Fractions
#' @import stats
#' @return
#' \itemize{
#' \item InterData: Final Data for Estimation
#' }
#' @export
#'
#' @examples
#' library(BaseTempSeed)
#' Interdata<-TempInter(Data=Data,GPercentage=c(0.1,0.2, 0.3,0.4, 0.5,0.6, 0.7,.8,0.9))
#'
#' @references
#' \itemize{
#'\item Ellis, R. H., Simon, G., & Covell, S. (1987). The Influence of Temperature on Seed Germination Rate in Grain LegumesIII. A Comparison of Five Faba Bean Genotypes at Constant Temperatures Using a New Screening Method. Journal of Experimental Botany, 38(6), 1033–1043.
#'\item Garcia-Huidobro, J., Monteith, J. L., & Squire, G. R. (1982). Time, temperature and germination of pearl millet (Pennisetum typhoides S. & H.) I. Constant temperature. Journal of experimental botany, 33(2), 288-296.
#'}
TempInter<-function(Data,TSeed=50,GPercentage=c(0.1, 0.25, 0.5, 0.75, 0.9)){
data <- as.data.frame(Data)
tot_seed <- TSeed# Total number of seeds taken in petridish
g <- GPercentage # Germination percentages to be interpolated
final <- NULL
for (n in 1:nrow(data)) {
.in <- as.vector(data[n, -1])
times <- as.numeric(names(.in))
cum_sum <- cumsum(.in)
p_germ <- cum_sum/tot_seed
g_inter <- subset(g, g<=max(p_germ))
values <- approx(p_germ, times, g_inter, ties = "max")
inter_time <- values$y
na_data <- rep(NA, length(g)-length(inter_time))
inter_final <- append(inter_time, na_data)
final <- rbind(final, inter_final)
}
colnames(final) <- paste0(g*100,"%")
rownames(final) <- data[, 1]
InterData<-final
return(InterData)
}
#' @title Estimation of Base Temperature
#'
#' @param Data Output TempInter Function
#' @import stats NlcOptim
#' @return
#' \itemize{
#' \item Coefficients: Estimate of Coefficients
#' }
#' @export
#'
#' @examples
#' library("BaseTempSeed")
#' Inter_data <- TempInter(Data=Data,GPercentage=c(0.1,0.2, 0.3,0.4, 0.5,0.6, 0.7,.8,0.9))
#' Est<-EstCoeff(Inter_data)
#' @references
#' \itemize{
#'\item Ellis, R. H., Simon, G., & Covell, S. (1987). The Influence of Temperature on Seed Germination Rate in Grain LegumesIII. A Comparison of Five Faba Bean Genotypes at Constant Temperatures Using a New Screening Method. Journal of Experimental Botany, 38(6), 1033–1043.
#'\item Garcia-Huidobro, J., Monteith, J. L., & Squire, G. R. (1982). Time, temperature and germination of pearl millet (Pennisetum typhoides S. & H.) I. Constant temperature. Journal of experimental botany, 33(2), 288-296.
#'}
EstCoeff<-function(Data){
Inter_data<-Data
int<-t(na.omit(t(Inter_data)))
if(ncol(int)!=ncol(Inter_data)){
message(paste0("Interpolation at fraction ",names(attr(int,"na.action"))," has missing value at ","temperature"," ",as.vector(attr(int,"na.action"))," and this fraction is/are ommited"))
Inter_data<-Inter_data[,!(colnames(Inter_data) %in% (names(attr(int,"na.action"))))]
}
reg_data <- 1/Inter_data
Coeff <- NULL
for (c in 1:ncol(reg_data)) {
# c=1
reg<-lm(reg_data[,c]~as.numeric(row.names(reg_data)))
Coef<-as.vector(reg$coefficients)
names(Coef)<-c("Alpha", "Beta")
Coeff<-rbind(Coeff,Coef)
}
# x_write
coeff_vector<-as.vector(t(Coeff))
name<-paste0("x","[",rep(seq(1,2*ncol(reg_data))),"]")
x_name<-NULL
for (i in seq(1,length(name),2)) {
R<-rep(name[i:(i+1)],nrow(reg_data))
x_name<-append(x_name,R)
}
y_data<-as.vector(reg_data)
temperature<-rep(as.numeric(row.names(reg_data)),ncol(reg_data))
e=1
a=2*(e-1)+1
b=a+1
equation<-(paste0("(",y_data[e],"-",noquote(x_name[a]),"-",temperature[e],"*",noquote(x_name[b]),")^2"))
for (e in 2:length(y_data)) {
a=2*(e-1)+1
b=a+1
eq<-(paste0("(",y_data[e],"-",noquote(x_name[a]),"-",temperature[e],"*",noquote(x_name[b]),")^2"))
equation<-paste0(equation,"+",eq)
}
objfunc <- function(x) {
return(eval(parse(text=equation)
))
}
f <- NULL
for (p in 2:ncol(reg_data)) {
f <- rbind(f, paste0(paste0("x","[1]"),"*",paste0("x","[",2*p,"]")," -", paste0("x","[",2,"]"),"*",paste0("x","[",(2*p-1),"]")
))
}
constr <- function(x) {
f
return(list(ceq=eval((parse(text=f))),c=NULL))
}
sol <- solnl(coeff_vector, objfun = objfunc, confun = constr)
estimate<-as.vector(sol$par)
alpha_est_seq<- (estimate[seq_len(length(estimate)) %% 2==1])
beta_est_seq<-(estimate[seq_len(length(estimate)) %% 2==0])
tb<- mean(-alpha_est_seq/beta_est_seq)
beta_est_seq1<- -alpha_est_seq/tb
Coefficients<-data.frame(Aplha=alpha_est_seq, Beta=beta_est_seq1)
rownames(Coefficients)<-colnames(reg_data)
return(Coefficients)
}
#' This is data to be included in my package
#' @name Data
#' @docType data
#' @keywords datasets
#' @usage data(Data)
#' @format A data frame with 5 rows and 19 column
NULL
|
/scratch/gouwar.j/cran-all/cranData/BaseTempSeed/R/BasetempSeed.R
|
#' @noRd
BbA_cols <- function(...) {
BbAcols <- c(
`red` = "#d11141",
`green` = "#00b159",
`blue` = "#00aedb",
`orange` = "#f37735",
`yellow` = "#ffc425",
`light grey` = "#cccccc",
`dark grey` = "#8c8c8c")
cols <- c(...)
if (is.null(cols)) return (BbAcols)
BbAcols[cols]
}
#' @noRd
BbA_pal <- function(palette = "main", reverse = FALSE, ...) {
BbApal <- list(
`main` = BbA_cols("blue", "green", "yellow"),
`cool` = BbA_cols("blue", "green"),
`hot` = BbA_cols("yellow", "orange", "red"),
`mixed` = BbA_cols("blue", "green", "yellow", "orange", "red"),
`grey` = BbA_cols("light grey", "dark grey"),
`bwr` = c("blue", "white", "red")
)
if (length(palette)==1 & is.character(palette)) {
pal <- BbApal[[palette]]
} else {
pal <- palette
}
if (reverse) pal <- rev(pal)
colorRampPalette(pal, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/BbA_pal.R
|
#' R function CreateRadialPlot by William D. Vickers, freely downloadable from the web
#' @param plot.data plot.data
#' @param axis.labels axis.labels
#' @param grid.min grid.min
#' @param grid.mid grid.mid
#' @param grid.max grid.max
#' @param centre.y centre.y
#' @param plot.extent.x.sf plot.extent.x.sf
#' @param plot.extent.y.sf plot.extent.y.sf
#' @param x.centre.range x.centre.range
#' @param label.centre.y label.centre.y
#' @param grid.line.width grid.line.width
#' @param gridline.min.linetype gridline.min.linetype
#' @param gridline.mid.linetype gridline.mid.linetype
#' @param gridline.max.linetype gridline.max.linetype
#' @param gridline.min.colour gridline.min.colour
#' @param gridline.mid.colour gridline.mid.colour
#' @param gridline.max.colour gridline.max.colour
#' @param grid.label.size grid.label.size
#' @param gridline.label.offset gridline.label.offset
#' @param label.gridline.min label.gridline.min
#' @param axis.label.offset axis.label.offset
#' @param axis.label.size axis.label.size
#' @param axis.line.colour axis.line.colour
#' @param group.line.width group.line.width
#' @param group.point.size group.point.size
#' @param background.circle.colour background.circle.colour
#' @param background.circle.transparency background.circle.transparency
#' @param plot.legend plot.legend
#' @param legend.title legend.title
#' @param legend.text.size legend.text.size
#' @param titolo plot title
#' @importFrom ggplot2 theme_bw
#' @importFrom ggplot2 element_blank
#' @importFrom ggplot2 theme_bw
#' @importFrom ggplot2 element_rect
#' @importFrom ggplot2 geom_path
#' @importFrom ggplot2 geom_polygon
#' @importFrom ggplot2 geom_text
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 xlab
#' @importFrom ggplot2 ylab
#' @importFrom ggplot2 coord_equal
#' @references Vickers D.W. (2006) Multi-Level Integrated Classifications Based on the 2001 Census, PhD Thesis, School of Geography, The University of Leeds
#' @details A description of the function can be found at the following link: \url{http://rstudio-pubs-static.s3.amazonaws.com/5795_e6e6411731bb4f1b9cc7eb49499c2082.html}
CreateRadialPlot <- function(plot.data,
axis.labels=colnames(plot.data)[-1],
grid.min=-0.5, #10,
grid.mid=0, #50,
grid.max=0.5, #100,
centre.y=grid.min - ((1/9)*(grid.max-grid.min)),
plot.extent.x.sf=1.2,
plot.extent.y.sf=1.2,
x.centre.range=0.02*(grid.max-centre.y),
label.centre.y=FALSE,
grid.line.width=0.5,
gridline.min.linetype="longdash",
gridline.mid.linetype="longdash",
gridline.max.linetype="longdash",
gridline.min.colour="grey",
gridline.mid.colour="blue",
gridline.max.colour="grey",
grid.label.size=4,
gridline.label.offset=-0.02*(grid.max-centre.y),
label.gridline.min=TRUE,
axis.label.offset=1.15,
axis.label.size=2.5,
axis.line.colour="grey",
group.line.width=1,
group.point.size=4,
background.circle.colour="yellow",
background.circle.transparency=0.2,
plot.legend=if (nrow(plot.data)>1) TRUE else FALSE,
legend.title="Player",
legend.text.size=grid.label.size,
titolo=FALSE ) {
x <- y <- text <- axis.no <- NULL
var.names <- colnames(plot.data)[-1] #'Short version of variable names
#axis.labels [if supplied] is designed to hold 'long version' of variable names
#with line-breaks indicated using \n
# Calculate total plot extent as radius of outer circle x a user-specifiable scaling factor
plot.extent.x=(grid.max+abs(centre.y))*plot.extent.x.sf
plot.extent.y=(grid.max+abs(centre.y))*plot.extent.y.sf
#Check supplied data makes sense
if (length(axis.labels) != ncol(plot.data)-1)
return("Error: 'axis.labels' contains the wrong number of axis labels")
if(min(plot.data[,-1])<centre.y)
return("Error: plot.data' contains value(s) < centre.y")
if(max(plot.data[,-1])>grid.max)
return("Error: 'plot.data' contains value(s) > grid.max")
#Declare required internal functions
CalculateGroupPath <- function(df) {
#Converts variable values into a set of radial x-y coordinates
#Code adapted from a solution posted by Tony M to
#http://stackoverflow.com/questions/9614433/creating-radar-chart-a-k-a-star-plot-spider-plot-using-ggplot2-in-r
#Args:
# df: Col 1 - group ('unique' cluster / group ID of entity)
# Col 2-n: v1.value to vn.value - values (e.g. group/cluser mean or median) of variables v1 to v.n
path <- as.factor(as.character(df[,1]))
##find increment
angles = seq(from=0, to=2*pi, by=(2*pi)/(ncol(df)-1))
##create graph data frame
graphData= data.frame(seg="", x=0,y=0)
graphData=graphData[-1,]
for(i in levels(path)){
pathData = subset(df, df[,1]==i)
for(j in c(2:ncol(df))){
#pathData[,j]= pathData[,j]
graphData=rbind(graphData, data.frame(group=i,
x=pathData[,j]*sin(angles[j-1]),
y=pathData[,j]*cos(angles[j-1])))
}
##complete the path by repeating first pair of coords in the path
graphData=rbind(graphData, data.frame(group=i,
x=pathData[,2]*sin(angles[1]),
y=pathData[,2]*cos(angles[1])))
}
#Make sure that name of first column matches that of input data (in case !="group")
colnames(graphData)[1] <- colnames(df)[1]
graphData #data frame returned by function
}
CalculateAxisPath = function(var.names,min,max) {
#Caculates x-y coordinates for a set of radial axes (one per variable being plotted in radar plot)
#Args:
#var.names - list of variables to be plotted on radar plot
#min - MININUM value required for the plotted axes (same value will be applied to all axes)
#max - MAXIMUM value required for the plotted axes (same value will be applied to all axes)
#var.names <- c("v1","v2","v3","v4","v5")
n.vars <- length(var.names) # number of vars (axes) required
#Cacluate required number of angles (in radians)
angles <- seq(from=0, to=2*pi, by=(2*pi)/n.vars)
#calculate vectors of min and max x+y coords
min.x <- min*sin(angles)
min.y <- min*cos(angles)
max.x <- max*sin(angles)
max.y <- max*cos(angles)
#Combine into a set of uniquely numbered paths (one per variable)
axisData <- NULL
for (i in 1:n.vars) {
a <- c(i,min.x[i],min.y[i])
b <- c(i,max.x[i],max.y[i])
axisData <- rbind(axisData,a,b)
}
#Add column names + set row names = row no. to allow conversion into a data frame
colnames(axisData) <- c("axis.no","x","y")
rownames(axisData) <- seq(1:nrow(axisData))
#Return calculated axis paths
as.data.frame(axisData)
}
funcCircleCoords <- function(center = c(0,0), r = 1, npoints = 100){
#Adapted from Joran's response to http://stackoverflow.com/questions/6862742/draw-a-circle-with-ggplot2
tt <- seq(0,2*pi,length.out = npoints)
xx <- center[1] + r * cos(tt)
yy <- center[2] + r * sin(tt)
return(data.frame(x = xx, y = yy))
}
### Convert supplied data into plottable format
# (a) add abs(centre.y) to supplied plot data
#[creates plot centroid of 0,0 for internal use, regardless of min. value of y
# in user-supplied data]
plot.data.offset <- plot.data
plot.data.offset[,2:ncol(plot.data)]<- plot.data[,2:ncol(plot.data)]+abs(centre.y)
#print(plot.data.offset)
# (b) convert into radial coords
group <-NULL
group$path <- CalculateGroupPath(plot.data.offset)
#print(group$path)
# (c) Calculate coordinates required to plot radial variable axes
axis <- NULL
axis$path <- CalculateAxisPath(var.names,grid.min+abs(centre.y),grid.max+abs(centre.y))
#print(axis$path)
# (d) Create file containing axis labels + associated plotting coordinates
#Labels
axis$label <- data.frame(
text=axis.labels,
x=NA,
y=NA )
#print(axis$label)
#axis label coordinates
n.vars <- length(var.names)
angles = seq(from=0, to=2*pi, by=(2*pi)/n.vars)
axis$label$x <- sapply(1:n.vars, function(i, x) {((grid.max+abs(centre.y))*axis.label.offset)*sin(angles[i])})
axis$label$y <- sapply(1:n.vars, function(i, x) {((grid.max+abs(centre.y))*axis.label.offset)*cos(angles[i])})
#print(axis$label)
# (e) Create Circular grid-lines + labels
#Calculate the cooridinates required to plot circular grid-lines for three user-specified
#y-axis values: min, mid and max [grid.min; grid.mid; grid.max]
gridline <- NULL
gridline$min$path <- funcCircleCoords(c(0,0),grid.min+abs(centre.y),npoints = 360)
gridline$mid$path <- funcCircleCoords(c(0,0),grid.mid+abs(centre.y),npoints = 360)
gridline$max$path <- funcCircleCoords(c(0,0),grid.max+abs(centre.y),npoints = 360)
#print(head(gridline$max$path))
#gridline labels
gridline$min$label <- data.frame(x=gridline.label.offset,y=grid.min+abs(centre.y),
text=as.character(grid.min))
############## gridline$max$label <- data.frame(x=gridline.label.offset,y=grid.max+abs(centre.y),
############## text=as.character(grid.max))
gridline$max$label <- data.frame(x=gridline.label.offset,y=grid.max+abs(centre.y),
text="")
############## gridline$mid$label <- data.frame(x=gridline.label.offset,y=grid.mid+abs(centre.y),
############## text=as.character(grid.mid))
gridline$mid$label <- data.frame(x=gridline.label.offset,y=grid.mid+abs(centre.y),
text="")
#print(gridline$min$label)
#print(gridline$max$label)
#print(gridline$mid$label)
### Start building up the radar plot
# Delcare 'theme_clear', with or without a plot legend as required by user
#[default = no legend if only 1 group [path] being plotted]
theme_clear <- theme_bw() +
theme(axis.text.y=element_blank(),
axis.text.x=element_blank(),
axis.ticks=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.border=element_blank(),
legend.key=element_rect(linetype="blank"))
if (plot.legend==FALSE) theme_clear <- theme_clear + theme(legend.position="none")
#Base-layer = axis labels + plot extent
# [need to declare plot extent as well, since the axis labels don't always
# fit within the plot area automatically calculated by ggplot, even if all
# included in first plot; and in any case the strategy followed here is to first
# plot right-justified labels for axis labels to left of Y axis for x< (-x.centre.range)],
# then centred labels for axis labels almost immediately above/below x= 0
# [abs(x) < x.centre.range]; then left-justified axis labels to right of Y axis [x>0].
# This building up the plot in layers doesn't allow ggplot to correctly
# identify plot extent when plotting first (base) layer]
#base layer = axis labels for axes to left of central y-axis [x< -(x.centre.range)]
base <- ggplot(axis$label) + xlab(NULL) + ylab(NULL) + coord_equal() +
geom_text(data=subset(axis$label,axis$label$x < (-x.centre.range)),
aes(x=x,y=y,label=text),size=axis.label.size,hjust=1) +
scale_x_continuous(limits=c(-plot.extent.x,plot.extent.x)) +
scale_y_continuous(limits=c(-plot.extent.y,plot.extent.y))
# + axis labels for any vertical axes [abs(x)<=x.centre.range]
base <- base + geom_text(data=subset(axis$label,abs(axis$label$x)<=x.centre.range),
aes(x=x,y=y,label=text),size=axis.label.size,hjust=0.5)
# + axis labels for any vertical axes [x>x.centre.range]
base <- base + geom_text(data=subset(axis$label,axis$label$x>x.centre.range),
aes(x=x,y=y,label=text),size=axis.label.size,hjust=0)
# + theme_clear [to remove grey plot background, grid lines, axis tick marks and axis text]
base <- base + theme_clear
# + background circle against which to plot radar data
base <- base + geom_polygon(data=gridline$max$path,aes(x,y),
fill=background.circle.colour,
alpha=background.circle.transparency)
# + radial axes
base <- base + geom_path(data=axis$path,aes(x=x,y=y,group=axis.no),
colour=axis.line.colour)
# ... + group (cluster) 'paths'
base <- base + geom_path(data=group$path,aes(x=x,y=y,group=group,colour=group),
size=group.line.width)
# ... + group points (cluster data)
base <- base + geom_point(data=group$path,aes(x=x,y=y,group=group,colour=group),size=group.point.size)
#... + amend Legend title
if (plot.legend==TRUE) base <- base + labs(colour=legend.title,size=legend.text.size)
# ... + circular grid-lines at 'min', 'mid' and 'max' y-axis values
base <- base + geom_path(data=gridline$min$path,aes(x=x,y=y),
lty=gridline.min.linetype,colour=gridline.min.colour,size=grid.line.width)
base <- base + geom_path(data=gridline$mid$path,aes(x=x,y=y),
lty=gridline.mid.linetype,colour=gridline.mid.colour,size=grid.line.width)
base <- base + geom_path(data=gridline$max$path,aes(x=x,y=y),
lty=gridline.max.linetype,colour=gridline.max.colour,size=grid.line.width)
# ... + grid-line labels (max; ave; min) [only add min. gridline label if required]
if (label.gridline.min==TRUE) {
base <- base + geom_text(aes(x=x,y=y,label=text),data=gridline$min$label,fontface="bold",size=grid.label.size, hjust=1) }
base <- base + geom_text(aes(x=x,y=y,label=text),data=gridline$mid$label,fontface="bold",size=grid.label.size, hjust=1)
base <- base + geom_text(aes(x=x,y=y,label=text),data=gridline$max$label,fontface="bold",size=grid.label.size, hjust=1)
# ... + centre.y label if required [i.e. value of y at centre of plot circle]
if (label.centre.y==TRUE) {
centre.y.label <- data.frame(x=0, y=0, text=as.character(centre.y))
base <- base + geom_text(aes(x=x,y=y,label=text),data=centre.y.label,fontface="bold",size=grid.label.size, hjust=0.5) }
# titolo
if(titolo==TRUE){
base <- base + labs(title = plot.data[1,1])
}
return(base)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/CreateRadialPlot.R
|
#' Multidimensional scaling (MDS) in 2 dimensions
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a numeric matrix, data frame or \code{"dist"} object (see \code{\link[stats]{dist}}).
#' @param std logical; if TRUE, \code{data} columns are standardized (centered and scaled).
#' @return An object of class \code{MDSmap}, i.e. a list with 4 objects:
#' @return * \code{points}, a 2-column vector of the fitted configuration (see \code{\link[MASS]{isoMDS}});
#' @return * \code{stress}, the final stress achieved in percent (see \code{\link[MASS]{isoMDS}});
#' @return * \code{data}, the input data frame;
#' @return * \code{std}, the logical \code{std} input.
#' @seealso \code{\link[MASS]{isoMDS}}, \code{\link{plot.MDSmap}}.
#' @details If \code{data} is an object of class \code{"dist"}, \code{std} is not active and \code{data} is directly inputted into \code{MASS::isoMDS}.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' data <- with(Pbox, data.frame(PTS, P3M, P2M, REB=OREB+DREB, AST, TOV, STL, BLK))
#' selp <- which(Pbox$MIN >= 1500)
#' data <- data[selp, ]
#' id <- Pbox$Player[selp]
#' mds <- MDSmap(data)
#' plot(mds, labels=id, z.var="P2M", level.plot=FALSE, palette=rainbow)
#' @export
#' @importFrom directlabels geom_dl
#' @importFrom ggplot2 geom_contour
#' @importFrom MASS isoMDS
#' @importFrom ggplot2 geom_tile
#' @importFrom ggplot2 scale_fill_gradientn
#' @importFrom ggplot2 annotate
#' @importFrom ggplot2 coord_cartesian
#' @importFrom ggplot2 xlim
#' @importFrom ggplot2 ylim
#' @importFrom stats loess
#' @importFrom stats loess.control
#' @importFrom stats predict
#' @importFrom stats cmdscale
#' @importFrom stats dist
#' @importFrom stats sd
#' @importFrom grDevices rainbow
MDSmap <- function(data, std=TRUE) {
if (!is.matrix(data) & !is.data.frame(data) & (!inherits(data, "dist"))) {
stop("'data' must be a matrix, a data frame, or a distance matrix")
}
if (!inherits(data, "dist")) {
if (std) {
data_for_dist <- scale(data)
} else {
data_for_dist <- data
}
dist.mat <- dist(data_for_dist)
} else {
dist.mat <- data
}
# MDS - 2 dimensions
out <- MASS::isoMDS(dist.mat, k=2, y=cmdscale(dist.mat, 2), maxit=100)
out[["data"]] <- data
out[["std"]] <- std
class(out) <- append("MDSmap", class(out))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/MDSmap.R
|
#' Opponents box scores dataset - NBA 2017-2018
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @description In this data frame cases (rows) are teams and variables (columns) are referred to achievements of the opponents in the NBA 2017-2018 Championship
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#'
#' @format A data frame with 30 rows and 23 variables:
#' \describe{
#' \item{Team}{Analyzed team, character}
#' \item{GP}{Games Played, numeric}
#' \item{MIN}{Minutes Played, numeric}
#' \item{PTS}{Points Made, numeric}
#' \item{W}{Games won, numeric}
#' \item{L}{Games lost, numeric}
#' \item{P2M}{2-Point Field Goals (Made), numeric}
#' \item{P2A}{2-Point Field Goals (Attempted), numeric}
#' \item{P2p}{2-Point Field Goals (Percentage), numeric}
#' \item{P3M}{3-Point Field Goals (Made), numeric}
#' \item{P3A}{3-Point Field Goals (Attempted), numeric}
#' \item{P3p}{3-Point Field Goals (Percentage), numeric}
#' \item{FTM}{Free Throws (Made), numeric}
#' \item{FTA}{Free Throws (Attempted), numeric}
#' \item{FTp}{Free Throws (Percentage), numeric}
#' \item{OREB}{Offensive Rebounds, numeric}
#' \item{DREB}{Defensive Rebounds, numeric}
#' \item{AST}{Assists, numeric}
#' \item{TOV}{Turnovers, numeric}
#' \item{STL}{Steals, numeric}
#' \item{BLK}{Blocks, numeric}
#' \item{PF}{Personal Fouls, numeric}
#' \item{PM}{Plus/Minus, numeric}
#' }
"Obox"
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/Obox.R
|
#' Play-by-play dataset - NBA 2017-2018
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @description In this play-by-play data frame (NBA 2017-2018 Championship), the cases (rows) are the events occurred during the analyzed games and the variables (columns) are descriptions of the events in terms of type, time, players involved, score, area of the court.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#'
#' @format A data.frame with 37430 rows and 48 variables:
#' \describe{
#' \item{game_id}{Identification code for the game}
#' \item{data_set}{Season: years and type (Regular or Playoffs)}
#' \item{date}{Date of the game}
#' \item{a1 ... a5; h1 ... h5}{Five players on the court (away team; home team)}
#' \item{period}{Quarter (>= 5: over-time)}
#' \item{away_score; home_score}{Score of the away/home team}
#' \item{remaining_time}{Time left in the quarter (h:mm:ss)}
#' \item{elapsed}{Time played in the quarter (h:mm:ss)}
#' \item{play_length}{Time since the immediately preceding event (h:mm:ss)}
#' \item{play_id}{Identification code for the play}
#' \item{team}{Team responsible for the event}
#' \item{event_type}{Type of event}
#' \item{assist}{Player who made the assist}
#' \item{away; home}{Players for the jump ball}
#' \item{block}{Player who blocked the shot}
#' \item{entered; left}{Player who entered/left the court}
#' \item{num}{Sequence number of the free throw}
#' \item{opponent}{Player who made the foul}
#' \item{outof}{Number of free throws accorded}
#' \item{player}{Player responsible for the event}
#' \item{points}{Scored points}
#' \item{possession}{Player who the jump ball is tipped to}
#' \item{reason}{Reason of the turnover}
#' \item{result}{Result of the shot (made or missed)}
#' \item{steal}{Player who stole the ball}
#' \item{type}{Type of play}
#' \item{shot_distance}{Field shots: distance from the basket}
#' \item{original_x ; original_y; converted_x ; converted_y}{Coordinates of the shooting player. \code{original}: tracking coordinate system half court, (0,0) center of the basket; \code{converted}: coordinates in feet full court, (0,0) bottom-left corner}
#' \item{description}{Textual description of the event}
#' }
#' @source \url{https://github.com/sndmrc/BasketballAnalyzeR}
"PbP.BDB"
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/PbP.BDB.R
|
#' Adapts the standard file supplied by BigDataBall to the format required by BasketballAnalyzeR
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a play-by-play data frame supplied by \href{https://www.bigdataball.com/}{BigDataBall}.
#' @return A play-by-play data frame.
#' @seealso \code{\link{PbP.BDB}}
#' @return The data frame generated by \code{PbPmanipulation} has the same variables of \code{PbP.BDB} (when necessary, coerced from one data type to another, e.g from factor to numeric) plus the following five additional variables:
#' @return * \code{periodTime}, time played in the quarter (in seconds)
#' @return * \code{totalTime}, time played in the match (in seconds)
#' @return * \code{playlength}, time since the immediately preceding event (in seconds)
#' @return * \code{ShotType}, type of shot (FT, 2P, 3P)
#' @return * \code{oppTeam}, name of the opponent team
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' @export
#' @importFrom stringr str_sub
#' @importFrom operators %~%
#' @importFrom operators %!~%
#' @importFrom readr parse_number
# PbPmanipulation <- function(data, playTeam="GSW") {
PbPmanipulation <- function(data) {
#### Convert shot distance and x-y coordinates to numeric
num_vars <- c("shot_distance","original_x","original_y","converted_x","converted_y")
data[,num_vars] <- sapply(data[,num_vars], function(x) suppressWarnings(as.numeric(as.character(x))))
#### Drop empty levels from factors
fact_vars <- sapply(data, function(x) is.factor(x))
data[,fact_vars] <- lapply(data[,fact_vars], function(x) droplevels(x))
#### Extract minutes and seconds and calculate the total time played
Minutes <- as.numeric(stringr::str_sub(data$remaining_time,-5,-4))
Seconds <- as.numeric(stringr::str_sub(data$remaining_time,-2,-1))
period.length <- 12
data$periodTime = period.length*60 - (Minutes*60 + Seconds)
data$totalTime = data$periodTime + period.length*60*(data$period-1)
#### Add play length
data$playlength <- as.numeric(stringr::str_sub(data$play_length,-2,-1))
#### Add shot type
filt <- (data$result!="")
mat <- data[filt,]
mat$ShotType <- ifelse(mat$event_type!="free throw" & mat$description%~%"3PT","3P",
ifelse(mat$event_type!="free throw" & mat$description%!~%"3PT","2P","FT"))
data$ShotType[filt] <- mat$ShotType
data$ShotType <- as.factor(data$ShotType)
# Clean game_id
data$game_id <- readr::parse_number(as.character(data$game_id))
# Creat oppTeam
games <- unique(data$game_id)
data$oppTeam <- ""
for (gm in games) {
idx <- data$game_id==gm & data$team!=""
team_vec <- data[idx,"team"]
tbl <- table(team_vec)
playing_teams <- names(tbl)[tbl!=0]
opp_team <- ifelse(team_vec==playing_teams[1], playing_teams[2], playing_teams[1])
#opp_team <- playing_teams[playing_teams!=playTeam]
data[idx,"oppTeam"] <- opp_team
}
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/PbPmanipulation.R
|
#' Players box scores dataset - NBA 2017-2018
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @description In this data frame, cases (rows) are players and variables (columns) are referred to the individual achievements in the NBA 2017-2018 Championship
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#'
#' @format A data.frame with 605 rows and 22 variables:
#' \describe{
#' \item{Team}{Analyzed team, character}
#' \item{Player}{Analyzed player, character}
#' \item{GP}{Games Played, numeric}
#' \item{MIN}{Minutes Played, numeric}
#' \item{PTS}{Points Made, numeric}
#' \item{P2M}{2-Point Field Goals (Made), numeric}
#' \item{P2A}{2-Point Field Goals (Attempted), numeric}
#' \item{P2p}{2-Point Field Goals (Percentage), numeric}
#' \item{P3M}{3-Point Field Goals (Made), numeric}
#' \item{P3A}{3-Point Field Goals (Attempted), numeric}
#' \item{P3p}{3-Point Field Goals (Percentage), numeric}
#' \item{FTM}{Free Throws (Made), numeric}
#' \item{FTA}{Free Throws (Attempted), numeric}
#' \item{FTp}{Free Throws (Percentage), numeric}
#' \item{OREB}{Offensive Rebounds, numeric}
#' \item{DREB}{Defensive Rebounds, numeric}
#' \item{AST}{Assists, numeric}
#' \item{TOV}{Turnovers, numeric}
#' \item{STL}{Steals, numeric}
#' \item{BLK}{Blocks, numeric}
#' \item{PF}{Personal Fouls, numeric}
#' \item{PM}{Plus/Minus, numeric}
#' }
"Pbox"
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/Pbox.R
|
#' Tadd dataset - NBA 2017-2018
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @description In this data frame, the cases (rows) are the analyzed teams and the variables (columns) are qualitative information such as Conference, Division, final rank, qualification for Playoffs for the NBA 2017-2018 Championship.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#'
#' @format A data frame with 30 rows and 6 variables:
#' \describe{
#' \item{Team}{Analyzed team (long name), factor}
#' \item{team}{Analyzed team (short name), factor}
#' \item{Conference}{Conference, factor}
#' \item{Division}{Division, factor}
#' \item{Rank}{Rank (end season), numeric}
#' \item{Playoff}{Playoff qualification (Yes or No), factor}
#' }
"Tadd"
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/Tadd.R
|
#' Teams box scores dataset - NBA 2017-2018
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @description In this data frame, cases (rows) are teams and variables (columns) are referred to team achievements in the different games in the NBA 2017-2018 Championship.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#'
#' @format A data frame with 30 rows and 23 variables:
#' \describe{
#' \item{Team}{Analyzed team, character}
#' \item{GP}{Games Played, numeric}
#' \item{MIN}{Minutes Played, numeric}
#' \item{PTS}{Points Made, numeric}
#' \item{W}{Games won, numeric}
#' \item{L}{Games lost, numeric}
#' \item{P2M}{2-Point Field Goals (Made), numeric}
#' \item{P2A}{2-Point Field Goals (Attempted), numeric}
#' \item{P2p}{2-Point Field Goals (Percentage), numeric}
#' \item{P3M}{3-Point Field Goals (Made), numeric}
#' \item{P3A}{3-Point Field Goals (Attempted), numeric}
#' \item{P3p}{3-Point Field Goals (Percentage), numeric}
#' \item{FTM}{Free Throws (Made), numeric}
#' \item{FTA}{Free Throws (Attempted), numeric}
#' \item{FTp}{Free Throws (Percentage), numeric}
#' \item{OREB}{Offensive Rebounds, numeric}
#' \item{DREB}{Defensive Rebounds, numeric}
#' \item{AST}{Assists, numeric}
#' \item{TOV}{Turnovers, numeric}
#' \item{STL}{Steals, numeric}
#' \item{BLK}{Blocks, numeric}
#' \item{PF}{Personal Fouls, numeric}
#' \item{PM}{Plus/Minus, numeric}
#' }
"Tbox"
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/Tbox.R
|
#' Investigates the network of assists-shots in a team
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame whose rows are field shots and columns are variables to be specified in \code{assist}, \code{player}, \code{points}, \code{event.type} (see Details).
#' @param assist character, indicating the name of the variable with players who made the assists, if any.
#' @param player character, indicating the name of the variable with players who made the shot.
#' @param points character, indicating the name of the variable with points.
#' @param event.type character, indicating the name of the variable with type of event (mandatory categories are \code{"miss"} for missed field shots and \code{"shot"} for field goals).
#' @details The \code{data} data frame could also be a play-by-play dataset provided that rows corresponding to events different from field shots are not coded as \code{"shot"} in the \code{event.type} variable.
#' @return A \code{list} with 3 elements, \code{assistTable} (a table), \code{nodeStats} (a data frame), and \code{assistNet} (a network object). See Details.
#' @return \code{assistTable}, the cross-table of assists made and received by the players.
#' @return \code{nodeStats}, a data frame with the following variables:
#' @return * \code{FGM} (fields goals made),
#' @return * \code{FGM_AST} (field goals made thanks to a teammate's assist),
#' @return * \code{FGM_ASTp} (percentage of \code{FGM_AST} over \code{FGM}),
#' @return * \code{FGPTS} (points scored with field goals),
#' @return * \code{FGPTS_AST} (points scored thanks to a teammate's assist),
#' @return * \code{FGPTS_ASTp} (percentage of \code{FGPTS_AST} over \code{FGPTS}),
#' @return * \code{AST} (assists made),
#' @return * \code{ASTPTS} (point scored by assist's teammates).
#' @return \code{assistNet}, an object of class \code{network} that can be used for further network analysis with specific R packages (see \code{\link[network]{network}})
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' PbP.GSW <- subset(PbP, team=="GSW")
#' out <- assistnet(PbP.GSW)
#' plot(out, layout="circle", edge.thr=30, node.col="FGM_ASTp", node.size="ASTPTS")
#' @export
#' @importFrom network set.vertex.attribute
#' @importFrom tidyr replace_na
assistnet <- function(data, assist="assist", player="player", points="points", event.type="event_type") {
FGM <- FGM_AST <- FGM_ASTp <- FGPTS <- FGPTS_AST <- FGPTS_ASTp <- NULL
data <- droplev_by_col(data)
data <- data %>%
dplyr::rename(assist=!!assist, player=!!player, points=!!points, event.type=!!event.type)
data_no_assist <- data %>%
dplyr::filter(assist!="")
data_no_assist <- droplev_by_col(data_no_assist)
assist_player <- data_no_assist %>%
dplyr::select(assist, player)
all_ast_plr <- sort(unique(unlist(assist_player)))
assist_player$assist <- factor(assist_player$assist, levels=all_ast_plr)
assist_player$player <- factor(assist_player$player, levels=all_ast_plr)
tbl <- as.matrix(table(assist_player, useNA="no"))
if (nrow(tbl)!=ncol(tbl)) {
stop("The number of players in 'assist' and 'player' variables are not the same.")
}
# Calculate some player/node statistics
nodeData1 <- data %>%
dplyr::group_by(player) %>%
dplyr::filter(event.type=="shot") %>%
dplyr::summarise(FGM=dplyr::n(),
FGM_AST=sum(assist!=""),
FGM_ASTp=100*FGM_AST/FGM,
FGPTS=sum(points),
FGPTS_AST=sum(points*(assist!="")),
FGPTS_ASTp=FGPTS_AST/FGPTS) %>%
as.data.frame()
nodeData2 <- data %>%
dplyr::filter(assist!="") %>%
dplyr::group_by(assist) %>%
dplyr::summarise(AST=dplyr::n(), ASTPTS=sum(points)) %>%
as.data.frame()
nodeData <- merge(nodeData1, nodeData2, by.x="player", by.y="assist", all=T)
net <- network::network(tbl, matrix.type="adjacency", directed=TRUE,
ignore.eval=FALSE, names.eval="N")
out <- list(assistTable=tbl, nodeStats=nodeData, assistNet=net)
class(out) <- append("assistnet", class(out))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/assistnet.R
|
#' Draws a bar-line plot
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{ [email protected]})
#' @param data a data frame.
#' @param id character, name of the ID variable.
#' @param bars character vector, names of the bar variables.
#' @param line character, name of the line variable.
#' @param order.by character, name of the variable used to order bars (on the x-axis).
#' @param decreasing logical; if \code{TRUE}, decreasing order.
#' @param labels.bars character vector, labels for the bar variables.
#' @param label.line character, label for the line variable on the second y-axis (on the right).
#' @param title character, plot title.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} object
#' @examples
#' dts <- subset(Pbox, Team=="Houston Rockets" & MIN>=500)
#' barline(data=dts, id="Player", bars=c("P2p","P3p","FTp"),
#' line="MIN", order.by="Player",
#' labels.bars=c("2P","3P","FT"), title="Houston Rockets")
#' @export
#' @importFrom magrittr "%>%"
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 aes
#' @importFrom ggplot2 geom_bar
#' @importFrom ggplot2 scale_fill_brewer
#' @importFrom ggplot2 theme
#' @importFrom ggplot2 ggtitle
#' @importFrom ggplot2 element_text
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_y_continuous
#' @importFrom ggplot2 sec_axis
#' @importFrom plyr "."
barline <- function(data, id, bars, line, order.by=id, decreasing=TRUE, labels.bars=NULL, label.line=NULL, title=NULL) {
Line <- Value <- Variables <- rsum <- x <- y <- ID <- NULL
if (is.null(labels.bars)) {
labels.bars=bars
}
if (is.null(label.line)) {
label.line=line
}
df1 <- data %>%
dplyr::select(id, bars, line) %>%
tidyr::gather(key="Variables", value="Value", bars) %>%
dplyr::rename(ID=!!id) %>%
dplyr::mutate(Variables=factor(Variables, levels=bars))
if (!is.factor(df1$ID)) {
df1$ID <- factor(df1$ID)
}
var_ord <- data[[order.by]]
if (class(var_ord)=="factor") {
ord_df1 <- order(levels(var_ord), decreasing=decreasing)
ord_df2 <- match(levels(df1$ID)[ord_df1], data[[id]])
} else {
ord_df2 <- order(var_ord, decreasing=decreasing)
ord_df1 <- match(data[ord_df2, id], levels(df1$ID))
}
df1 <- df1 %>%
dplyr::mutate(ID=factor(ID,levels=levels(ID)[ord_df1]))
df2 <- data %>%
dplyr::select(id, bars, line) %>%
dplyr::mutate(Line = !!rlang::sym(line)) %>%
dplyr::rename(ID=!!id) %>%
dplyr::mutate(rsum=rowSums(dplyr::select(., bars))) %>%
dplyr::mutate(y=Line*max(rsum)/max(Line)) %>%
dplyr::slice(ord_df2) %>%
dplyr::mutate(x=1:dplyr::n())
p <- ggplot(data=df1, aes(x=ID, y=Value, fill=Variables,
text=paste("Team:",ID,"<br>Variable:",Variables))) +
geom_bar(stat="identity") +
scale_fill_brewer(labels=labels.bars, palette="Paired") +
theme(legend.position="top") + ggtitle(title) +
labs(x="", caption=paste("Bars ordered by",order.by)) +
theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.25),
panel.background = element_blank()) +
geom_line(data=df2, mapping=aes(x=x, y=y), lwd=1.5, col='grey', inherit.aes=F) +
scale_y_continuous(name="Variables", limits=c(0,NA),
sec.axis=sec_axis(~.*max(df2$Line)/max(df2$rsum), name=label.line))
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/barline.R
|
#' Draws a bubble plot
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame.
#' @param id character, name of the ID variable.
#' @param x character, name of the x-axis variable.
#' @param y character, name of the y-axis variable.
#' @param col character, name of variable on the color axis.
#' @param size character, name of variable on the size axis.
#' @param text.col character, name of variable for text colors.
#' @param text.size integer, text font size.
#' @param scale.size logical; if \code{TRUE}, size variable is rescaled between 0 and 100.
#' @param labels character vector, variable labels (on legend and axis).
#' @param mx numeric, x-coordinate of the vertical axis; default is the mean value of \code{x} variable.
#' @param my numeric, y-coordinate of the horizontal axis; default is the mean value of \code{y} variable.
#' @param mcol numeric, midpoint of the diverging scale (see \code{\link{scale_colour_gradient2}}); default is the mean value of \code{col} variable.
#' @param title character, plot title.
#' @param repel logical; if \code{TRUE}, activate text repelling.
#' @param text.legend logical; if \code{TRUE}, show the legend for text color.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} object
#' @examples
#' X <- with(Tbox, data.frame(T=Team, P2p=P2p, P3p=P3p, FTp=FTp, AS=P2A+P3A+FTA))
#' labs <- c("2-point shots (% made)","3-point shots (% made)",
#' "free throws (% made)","Total shots attempted")
#' bubbleplot(X, id="T", x="P2p", y="P3p", col="FTp",
#' size="AS", labels=labs)
#' @export
#' @importFrom ggplot2 scale_fill_gradient2
#' @importFrom ggplot2 scale_size_area
#' @importFrom ggplot2 guide_legend
#' @importFrom ggplot2 geom_hline
#' @importFrom ggplot2 geom_vline
#' @importFrom dplyr mutate
bubbleplot <- function(data, id, x, y, col, size, text.col=NULL, text.size=2.5, scale.size=TRUE, labels = NULL, mx = NULL, my = NULL,
mcol = NULL, title = NULL, repel = TRUE, text.legend=TRUE) {
ID <- textColor <- NULL
if (is.null(text.col)) {
dts <- data %>%
dplyr::mutate(ID = !!rlang::sym(id) , x = !!rlang::sym(x), y = !!rlang::sym(y),
col = !!rlang::sym(col), size = !!rlang::sym(size)) %>%
dplyr::select(ID, x, y, col, size)
} else {
dts <- data %>%
dplyr::mutate(ID = !!rlang::sym(id) , x = !!rlang::sym(x), y = !!rlang::sym(y),
col = !!rlang::sym(col), size = !!rlang::sym(size),
textColor=!!rlang::sym(text.col)) %>%
dplyr::select(ID, x, y, col, size, textColor)
}
if (is.null(labels)) {
labels <- names(dts)[-1]
}
if (is.null(mx))
mx <- mean(dts$x)
if (is.null(my))
my <- mean(dts$y)
if (is.null(mcol) & !is.factor(dts$col))
mcol <- mean(dts$col)
xmin <- min(dts$x) - (mx - min(dts$x))/4
xmax <- max(dts$x) + (max(dts$x) - mx)/4
ymin <- min(dts$y) - (my - min(dts$y))/4
ymax <- max(dts$y) + (max(dts$y) - my)/4
if (scale.size) {
dts$size <- (dts$size - min(dts$size))/(max(dts$size) - min(dts$size)) * 100
}
p <- ggplot(dts, aes(x = x, y = y, label = ID)) +
geom_point(aes(size = size, fill = col), shape = 21, colour = "white") +
scale_size_area(max_size = 10, guide = guide_legend(override.aes = list(colour = "black", fill="black"))) +
geom_hline(yintercept = my) + geom_vline(xintercept = mx) +
labs(x = labels[1], y = labels[2], fill = labels[3], size = labels[4], title = title) +
xlim(xmin, xmax) + ylim(ymin, ymax)
if (!is.factor(dts$col)) {
p <- p + scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = mcol)
}
if (is.null(text.col)) {
if (repel) {
p <- p + ggrepel::geom_text_repel(size = text.size)
} else {
p <- p + geom_text(size = text.size)
}
} else {
if (repel) {
p <- p + ggrepel::geom_text_repel(aes(color=textColor), size = text.size, show.legend=text.legend)
} else {
p <- p + geom_text(aes(color=textColor), size = text.size, show.legend=text.legend)
}
}
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/bubbleplot.R
|
#' Correlation analysis
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a numeric matrix or data frame (see \code{\link[stats]{cor}}).
#' @param threshold numeric, correlation cutoff (default 0); correlations in absolute value below \code{threshold} are set to 0.
#' @param sig.level numeric, significance level (default 0.95); correlations with p-values greater that \code{1-sig.level} are set to 0.
#' @seealso \code{\link{plot.corranalysis}}.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A list with the following elements:
#' * \code{corr.mtx} (the complete correlation matrix)
#' * \code{corr.mtx.trunc} (the truncated correlation matrix)
#' * \code{cor.mtest} (the output of the significance test on correlations; see \code{\link[corrplot]{cor.mtest}})
#' * \code{threshold} correlation cutoff
#' * \code{sig.level} significance level
#' @examples
#' data <- data.frame(Pbox$PTS,Pbox$P3M,Pbox$P2M,
#' Pbox$OREB + Pbox$DREB,Pbox$AST,
#' Pbox$TOV,Pbox$STL,Pbox$BLK)/Pbox$MIN
#' names(data) <- c("PTS","P3M","P2M","REB","AST","TOV","STL","BLK")
#' data <- subset(data, Pbox$MIN >= 500)
#' out <- corranalysis(data, threshold = 0.5)
#' plot(out)
#' @export
#' @importFrom corrplot cor.mtest
#' @importFrom stats cor
corranalysis <- function(data, threshold = 0, sig.level = 0.95) {
cor_mtx <- stats::cor(data, use = "pairwise.complete.obs")
cor_mtest <- corrplot::cor.mtest(data)
cor_mtx_trunc <- cor_mtx
cor_mtx_trunc[cor_mtest$p > (1-sig.level)] <- 0
cor_mtx_trunc[cor_mtx^2 < threshold^2] <- 0
diag(cor_mtx_trunc) <- 0
lst <- list(cor.mtx = cor_mtx, cor.mtx.trunc = cor_mtx_trunc,
cor.mtest = cor_mtest, threshold = threshold, sig.level = sig.level)
class(lst) <- append("corranalysis", class(lst))
invisible(lst)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/corranalysis.R
|
#' Computes and plots kernel density estimation of shots with respect to a concurrent variable
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame whose rows are shots and with the following columns: \code{ShotType}, \code{player}, \code{points} and at least one of \code{playlength}, \code{periodTime}, \code{totalTime}, \code{shot_distance} (the column specified in \code{var}, see Details).
#' @param var character, a string giving the name of the numerical variable according to which the shot density is estimated. Available options: \code{"playlength"}, \code{"periodTime"}, \code{"totalTime"}, \code{"shot_distance"}.
#' @param shot.type character, a string giving the type of shots to be analyzed. Available options: \code{"2P"}, \code{"3P"}, \code{"FT"}, \code{"field"}.
#' @param thresholds numerical vector with two thresholds defining the range boundaries that divide the area under the density curve into three regions. If \code{NULL} default values are used.
#' @param best.scorer logical; if TRUE, displays the player who scored the highest number of points in the corresponding interval.
#' @param period.length numeric, the length of a quarter in minutes (default: 12 minutes as in NBA).
#' @param bw numeric, the value for the smoothing bandwidth of the kernel density estimator or a character string giving a rule to choose the bandwidth (see \link[stats]{density}).
#' @param title character, plot title.
#' @details The \code{data} data frame could also be a play-by-play dataset provided that rows corresponding to events different from shots have \code{NA} in the \code{ShotType} variable.
#' @details Required columns:
#' @details * \code{ShotType}, a factor with the following levels: \code{"2P"}, \code{"3P"}, \code{"FT"} (and \code{NA} for events different from shots)
#' @details * \code{player}, a factor with the name of the player who made the shot
#' @details * \code{points}, a numeric variable (integer) with the points scored by made shots and \code{0} for missed shots
#' @details * \code{playlength}, a numeric variable with time between the shot and the immediately preceding event
#' @details * \code{periodTime}, a numeric variable with seconds played in the quarter when the shot is attempted
#' @details * \code{totalTime}, a numeric variable with seconds played in the whole match when the shot is attempted
#' @details * \code{shot_distance}, a numeric variable with the distance of the shooting player from the basket (in feet)
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} plot
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' data.team <- subset(PbP, team=="GSW" & result!="")
#' densityplot(data=data.team, shot.type="2P", var="playlength", best.scorer=TRUE)
#' data.opp <- subset(PbP, team!="GSW" & result!="")
#' densityplot(data=data.opp, shot.type="2P", var="shot_distance", best.scorer=TRUE)
#' @export
#' @importFrom stats density
densityplot <- function(data, var, shot.type="field", thresholds=NULL, best.scorer=FALSE,
period.length=12, bw=NULL, title=NULL) {
ShotType <- NULL
if (shot.type=="FT" & (var=="playlength" | var=="shot_distance")) {
warning("'shot.type' and 'var': invalid selection")
}
if (is.null(title)) {
title <- shot.type
}
if (is.null(bw)) {
bw <- "nrd0"
}
if (shot.type!="FT" | (var!="playlength" & var!="shot_distance")) {
if (shot.type!="field") {
mat <- subset(data, ShotType==shot.type)
} else {
mat <- subset(data, ShotType=="2P" | ShotType=="3P")
}
mat <- droplev_by_col(mat)
x <- mat[, var]
if (var=="playlength") {
xrng <- c(0, 24)
} else if (var=="totalTime") {
xrng <- c(0, period.length*4*60)
} else if (var=="periodTime") {
xrng <- c(0, period.length*60)
} else if (var=="shot_distance") {
if (shot.type=="field") {
xrng <- c(0, 60)
} else if (shot.type=="2P") {
xrng <- c(0, 22)
} else if (shot.type=="3P") {
xrng <- c(22, 60)
}
}
den <- stats::density(x, bw=bw, from=xrng[1], to=xrng[2])
den <- as.data.frame(den[c("x", "y")])
####
if (var=="playlength") {
####
if (is.null(thresholds)) {
thr <- c(5, 20)
} else {
thr <- thresholds
}
p <- plot_shotdensity(mat, den, var=var, thr=thr, xrng=xrng, ntks=25,
xadj=c(0,0,24), yadj=c(2,2,2,0.1), best.scorer=best.scorer, title=title, xlab="Play length")
####
} else if (var=="totalTime") {
####
if (is.null(thresholds)) {
thr <- period.length*60*c(2, 3)
} else {
thr <- thresholds
}
p <- plot_shotdensity(mat, den, var=var, thr=thr, xrng=xrng, ntks=10, title=title,
xadj=c(0,0,period.length*60*4), yadj=c(2,2,2,10), best.scorer=best.scorer, xlab="Total time")
####
} else if (var=="periodTime") {
####
if (is.null(thresholds)) {
thr <- period.length*60*c(1/2,3/4)
} else {
thr <- thresholds
}
p <- plot_shotdensity(mat, den, var=var, thr=thr, xrng=xrng, ntks=10, title=title,
xadj=c(0,0,period.length*60), yadj=c(2,2,2,10), best.scorer=best.scorer, xlab="Period time")
####
} else if (var=="shot_distance") {
####
if (is.null(thresholds)) {
if (shot.type=="field") {
thr <- c(4, 22)
} else if (shot.type=="2P") {
thr <- c(4, 18)
} else if (shot.type=="3P") {
thr <- c(25, 30)
}
} else {
thr <- thresholds
}
if (shot.type=="field") {
xadj <- c(0,0,36)
yadj <- c(2,2,2,0.5)
} else if (shot.type=="2P") {
xadj <- c(0,0,22)
yadj <- c(2,2,4,0.5)
} else if (shot.type=="3P") {
xadj <- c(22, 0, 60)
yadj <- c(6,2,2,0.5)
}
p <- plot_shotdensity(mat, den, var=var, thr=thr, xrng=c(0,60), ntks=21,
xadj=xadj, yadj=yadj, best.scorer=best.scorer, title=title, xlab="Shot distance")
}
p <- p + theme_bw()
}
return(p)
}
#' @noRd
plot_shotdensity <- function(mat, den, var, thr, xrng, ntks, xadj, yadj, title=NULL, best.scorer=FALSE, xlab=NULL) {
droplev_by_col <- function(data) {
idx <- sapply(data, class)=="factor"
data[, idx] <- lapply(data[, idx], droplevels)
return(data)
}
y <- NULL
x <- mat[, var]
n <- nrow(mat)
m1 <- droplev_by_col(mat[x <= thr[1], ])
n1 <- nrow(m1)
p1 <- round(n1/n*100,0)
m1p <- round(sum(m1$result=="made")/n1*100,0)
m2 <- droplev_by_col(mat[x <= thr[2] & x > thr[1], ])
n2 <- nrow(m2)
p2 <- round(n2/n*100,0)
m2p <- round(sum(m2$result=="made")/n2*100,0)
m3 <- droplev_by_col(mat[x > thr[2], ])
n3 <- n - (n1+n2)
p3 <- 100-(p1+p2)
m3p <- round(sum(m3$result=="made")/n3*100,0)
x1 <- (thr[1] + xadj[1])/2
x2 <- (thr[1] + thr[2] + xadj[2])/2
x3 <- (thr[2] + xadj[3])/2
y1 <- mean(den$y[den$x<(x1 + yadj[4]) & den$x>(x1 - yadj[4])])/yadj[1]
y2 <- mean(den$y[den$x<(x2 + yadj[4]) & den$x>(x2 - yadj[4])])/yadj[2]
y3 <- mean(den$y[den$x<(x3 + yadj[4]) & den$x>(x3 - yadj[4])])/yadj[3]
p <- ggplot(den,aes(x,y))+
geom_line(col='gray',lwd=2) +
geom_ribbon(data=subset(den,x<=thr[1]),aes(x=x, ymax=y, ymin=0), fill="blue", alpha=0.3) +
geom_ribbon(data=subset(den,x<=thr[2] & x>thr[1]),aes(x=x, ymax=y, ymin=0), fill="blue", alpha=0.5) +
geom_ribbon(data=subset(den,x>thr[2]),aes(x=x, ymax=y, ymin=0), fill="red", alpha=0.3) +
annotate("text", label = paste(as.character(p1),"%",sep=""), x = x1, y = y1, size = 5, colour = "blue") +
annotate("text", label = as.character(n1), x = x1, y = y1, size = 4, colour = "blue",vjust = 2) +
annotate("text", label = paste("(",as.character(m1p),"% made)",sep=""), x = x1, y = y1, size = 4, colour = "blue",vjust = 4) +
annotate("text", label = paste(as.character(p2),"%",sep=""), x = x2, y = y2, size = 5, colour = "blue") +
annotate("text", label = as.character(n2), x = x2, y = y2, size = 4, colour = "blue",vjust = 2) +
annotate("text", label = paste("(",as.character(m2p),"% made)",sep=""), x = x2, y = y2, size = 4, colour = "blue",vjust = 4) +
annotate("text", label = paste(as.character(p3),"%",sep=""), x = x3, y = y3, size = 5, colour = "red") +
annotate("text", label = as.character(n3), x = x3, y = y3, size = 4, colour = "red",vjust = 2) +
annotate("text", label = paste("(",as.character(m3p),"% made)",sep=""), x = x3, y = y3, size = 4, colour = "red",vjust = 4) +
labs(title = title) +
scale_x_continuous(name=xlab, limits=c(xrng[1], xrng[2]), breaks=seq(xrng[1],xrng[2],length.out=ntks),
labels=seq(xrng[1],xrng[2],length.out=ntks)) +
scale_y_continuous(name="Frequency of shots", limits=c(0, NA),labels=NULL)
if (best.scorer) {
points1 <- tapply(m1$points, m1$player, sum, na.rm=T)
mpoints1 <- max(points1, na.rm=T)
wp1 <- points1[points1==mpoints1]
np <- length(wp1)
if (np>1) {
wp1 <- wp1[1]
attr(wp1,"names") <- paste(np," players",sep="")
}
points2 <- tapply(m2$points,m2$player,sum)
mpoints2 <- max(points2,na.rm=T)
wp2 <- points2[points2==mpoints2]
np <- length(wp2)
if (np>1) {
wp2 <- wp2[1]
attr(wp2,"names") <- paste(np," players",sep="")
}
points3 <- tapply(m3$points,m3$player,sum)
mpoints3 <- max(points3,na.rm=T)
wp3 <- points3[points3==mpoints3]
np <- length(wp3)
if (np>1) {
wp3 <- wp3[1]
attr(wp3,"names") <- paste(np," players",sep="")
}
p <- p +
annotate("text", label = "Best scorer:", x = x1, y = y1, size = 4, colour = "blue",vjust = -5) +
annotate("text", label = attr(wp1,"names"), x = x1, y = y1, size = 4, colour = "blue",vjust = -3.5) +
annotate("text", label = paste("(", as.character(wp1)," points)",sep=""), x = x1, y = y1, size = 4, colour = "blue",vjust = -2) +
#
annotate("text", label = "Best scorer:", x = x2, y = y2, size = 4, colour = "blue",vjust = -5) +
annotate("text", label = attr(wp2,"names"), x = x2, y = y2, size = 4, colour = "blue",vjust = -3.5) +
annotate("text", label = paste("(", as.character(wp2)," points)",sep=""), x = x2, y = y2, size = 4, colour = "blue",vjust = -2) +
#
annotate("text", label = "Best scorer:", x = x3, y = y3, size = 4, colour = "red",vjust = -5) +
annotate("text", label = attr(wp3,"names"), x = x3, y = y3, size = 4, colour = "red",vjust = -3.5)+
annotate("text", label = paste("(", as.character(wp3)," points)",sep=""), x = x3, y = y3, size = 4, colour = "red",vjust = -2)
}
return(p)
}
#' @noRd
droplev_by_col <- function(data) {
idx <- sapply(data, class)=="factor"
data[, idx] <- lapply(data[, idx], droplevels)
return(data)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/densityplot.r
|
#' Add lines of NBA court to an existing ggplot2 plot
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param p a ggplot2 object.
#' @param size numeric, line size.
#' @param col line color.
#' @param full logical; if TRUE draws a complete NBA court; if FALSE draws a half court.
#' @return A ggplot2 object
#' @examples
#' library(ggplot2)
#' p <- ggplot(data.frame(x=0, y=0), aes(x,y)) + coord_fixed()
#' drawNBAcourt(p)
#' @export
drawNBAcourt <- function(p, size=1.5, col="black", full=FALSE) {
crcl <- function(x0, y0, r, span=r, nsteps=100) {
x <- seq(x0-span,x0+span,length.out=nsteps)
ylo <- y0-sqrt(r^2-(x-x0)^2)
yup <- y0+sqrt(r^2-(x-x0)^2)
data.frame(x=x, ylo=ylo, yup=yup)
}
x <- y <- ylo <- yup <- NULL
outbox <- data.frame(x=c(-25,-25,25,25,-25),
y=c(-47,0,0,-47,-47))
FT <- crcl(0,-28,6)
halfcourt <- crcl(0,0,6)
key <- data.frame(x=-c(-8,-8,8,8,-8),y=-c(47,28,28,47,47))
keyins <- data.frame(x=c(-6,-6,6,6,-6),y=-c(47,28,28,47,47))
restr <- crcl(x0=0, y0=-41.25, r=4, nsteps=200)
rim <- crcl(x0=0, y0=-41.75, r=0.75)
backboard <- data.frame(x=c(-3,3), y=-c(43,43))
crcl3pt <- crcl(x0=0, y0=-41.75, r=23.75, span=22)
ln3pt <- data.frame(x=c(-22,-22,crcl3pt$x,22,22),
ylo=c(-47,-47+169/12,crcl3pt$ylo,-47+169/12,-47),
yup=c(-47,-47+169/12,crcl3pt$yup,-47+169/12,-47))
p <- p +
###outside box:
geom_path(data=outbox, aes(x, y), size=size, color=col) +
###halfcourt semicircle:
geom_path(data=halfcourt, aes(x=x, y=ylo), size=size, color=col) +
###solid FT semicircle above FT line:
geom_path(data=FT, aes(x=x, y=yup), size=size, color=col) +
###dashed FT semicircle below FT line:
geom_path(data=FT, aes(x=x, y=ylo), linetype='dashed', size=size, color=col) +
###key:
geom_path(data=key, aes(x, y), size=size, color=col) +
###box inside the key:
geom_path(data=keyins, aes(x, y), size=size, color=col) +
###restricted area semicircle:
geom_path(data=restr, aes(x=x, y=yup), size=size, color=col) +
###rim:
geom_path(data=rim, aes(x=x, y=ylo), size=size, color=col) +
geom_path(data=rim, aes(x=x, y=yup), size=size, color=col) +
###backboard:
geom_path(data=backboard, aes(x, y), lineend='butt', size=size, color=col) +
###three-point line:
geom_path(data=ln3pt, aes(x=x, y=yup), size=size, color=col)
if (full) {
p <- p +
###outside box:
geom_path(data=outbox, aes(x,-y), size=size, color=col) +
###halfcourt semicircle:
geom_path(data=halfcourt, aes(x=x, y=-ylo), size=size, color=col) +
###solid FT semicircle above FT line:
geom_path(data=FT, aes(x=x, y=-yup), size=size, color=col) +
###dashed FT semicircle below FT line:
geom_path(data=FT, aes(x=x, y=-ylo), linetype='dashed', size=size, color=col) +
###key:
geom_path(data=key, aes(x, -y), size=size, color=col) +
###box inside the key:
geom_path(data=keyins, aes(x, -y), size=size, color=col) +
###restricted area semicircle:
geom_path(data=restr, aes(x=x, y=-yup), size=size, color=col) +
###rim:
geom_path(data=rim, aes(x=x, y=-ylo), size=size, color=col) +
geom_path(data=rim, aes(x=x, y=-yup), size=size, color=col) +
###backboard:
geom_path(data=backboard, aes(x, -y), lineend='butt', size=size, color=col) +
###three-point line:
geom_path(data=ln3pt, aes(x=x, y=-yup), size=size, color=col)
}
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/drawNBAcourt.R
|
#' Plots expected points of shots as a function of the distance from the basket (default) or another variable
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame whose rows are field shots and with the following columns: \code{points}, \code{event_type}, \code{player} (only if the \code{players} argument is not \code{NULL}) and at least one of \code{playlength}, \code{periodTime}, \code{totalTime}, \code{shot_distance} (the column specified in \code{var}, see Details).
#' @param var character, a string giving the name of the numerical variable according to which the expected points are estimated; available options \code{"playlength"}, \code{"periodTime"}, \code{"totalTime"}, \code{"shot_distance"} (default).
#' @param players subset of players to be displayed (optional; it can be used only if the \code{player} column is present in \code{data}).
#' @param bw numeric, smoothing bandwidth of the kernel density estimator (see \code{\link[stats]{ksmooth}}).
#' @param period.length numeric, the length of a quarter in minutes (default: 12 minutes as in NBA).
#' @param x.range numerical vector or character; available options: \code{NULL} (x-axis range defined by \code{ggplot2}, the default), \code{"auto"} (internally defined x-axis range), or a 2-component numerical vector (user-defined x-axis range).
#' @param title character, plot title.
#' @param palette color palette.
#' @param team logical; if \code{TRUE}, draws the expected points for all the shots in data.
#' @param col.team character, color of the expected points line for all the shots in data (default \code{"gray"}).
#' @param col.hline character, color of the dashed horizontal line (default \code{"black"}) denoting the expected points for all the shots in data, not conditional to the variable in the x-axis.
#' @param legend logical, if \code{TRUE}, color legend is displayed (only when \code{players} is not \code{NULL}).
#' @param xlab character, x-axis label.
#' @details The \code{data} data frame could also be a play-by-play dataset provided that rows corresponding to events different from field shots have values different from \code{"shot"} or \code{"miss"} in the \code{even_type} variable.
#' @details Required columns:
#' @details * \code{event_type}, a factor with the following levels: \code{"shot"} for made field shots and \code{"miss"} for missed field shots
#' @details * \code{player}, a factor with the name of the player who made the shot
#' @details * \code{points}, a numeric variable (integer) with the points scored by made shots and \code{0} for missed shots
#' @details * \code{playlength}, a numeric variable with time between the shot and the immediately preceding event
#' @details * \code{periodTime}, a numeric variable with seconds played in the quarter when the shot is attempted
#' @details * \code{totalTime}, a numeric variable with seconds played in the whole match when the shot is attempted
#' @details * \code{shot_distance}, a numeric variable with the distance of the shooting player from the basket (in feet)
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} plot
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' PbP.GSW <- subset(PbP, team=="GSW" & !is.na(shot_distance))
#' plrys <- c("Stephen Curry","Kevin Durant")
#' expectedpts(data=PbP.GSW, bw=10, players=plrys, col.team='dodgerblue',
#' palette=colorRampPalette(c("gray","black")), col.hline="red")
#' @export
expectedpts <- function(data, var="shot_distance", players=NULL, bw=10, period.length=12, palette=gg_color_hue, team=TRUE,
col.team="gray", col.hline="black", xlab=NULL, x.range="auto", title=NULL, legend=TRUE) {
event_type <- player <- Player <- NULL
data <- data %>% dplyr::select(dplyr::one_of(var, "points", "player", "event_type")) %>%
dplyr::filter(event_type=="shot" | event_type=="miss")
x <- data[, var]
y <- data$points
if (length(x.range)==1 & is.character(x.range)) {
if (x.range=="auto") {
if (var=="playlength") {
xrng <- c(0, 24)
ntks <- 25
} else if (var=="totalTime") {
xrng <- c(0, period.length*4*60)
ntks <- 10
} else if (var=="periodTime") {
xrng <- c(0, period.length*60)
ntks <- 10
} else if (var=="shot_distance") {
xrng <- range(x, na.rm=TRUE)
ntks <- NULL
}
}
} else if (length(x.range)==2 & is.numeric(x.range)) {
xrng <- x.range
if (xrng[1]<min(x,na.rm=T)) xrng[1]=min(x,na.rm=T)
if (xrng[2]>max(x,na.rm=T)) xrng[2]=max(x,na.rm=T)
ntks <- NULL
} else if (is.null(x.range)) {
xrng <- NULL
ntks <- NULL
}
if (var=="playlength") {
if (is.null(xlab)) xlab <- "Play length"
} else if (var=="totalTime") {
if (is.null(xlab)) xlab <- "Total time"
} else if (var=="periodTime") {
if (is.null(xlab)) xlab <- "Period time"
} else if (var=="shot_distance") {
if (is.null(xlab)) xlab <- "Shot distance"
} else {
if (is.null(xlab)) xlab <- var
}
if (team) {
ksm <- stats::ksmooth(x=x, y=y, bandwidth=bw, kernel='normal')
ksm <- as.data.frame(ksm[c("x", "y")])
ksm$Player <- "Team"
if (!is.null(xrng)) {
ksm <- subset(ksm, x>=xrng[1] & x<=xrng[2])
}
}
npl <- 0
if (!is.null(players)) {
npl <- length(players)
kmslst <- vector(npl+1, mode="list")
for (k in 1:npl) {
playerk <- players[k]
datak <- subset(data, player==playerk)
xk <- datak[, var]
yk <- datak$points
ksm_k <- stats::ksmooth(x=xk, y=yk, bandwidth=bw, kernel='normal')
ksm_k <- as.data.frame(ksm_k[c("x", "y")])
ksm_k$Player <- playerk
if (!is.null(xrng)) {
ksm_k <- subset(ksm_k, x>=xrng[1] & x<=xrng[2])
}
kmslst[[k]] <- ksm_k
}
if (team) kmslst[[npl+1]] <- ksm
ksm <- do.call(rbind, kmslst)
players <- sort(unique(ksm$Player))
cols <- palette(npl+1)
cols[players=="Team"] <- col.team
p <- ggplot(ksm, aes(x=x, y=y, color=Player)) +
geom_line(size=1.5) +
scale_color_manual(values=cols, breaks=players)
} else {
p <- ggplot(ksm, aes(x=x, y=y)) +
geom_line(color = col.team, size=1.5)
}
p <- p + geom_hline(yintercept=mean(y), col=col.hline, linetype=2, size=1.2) +
labs(title = title) +
scale_y_continuous(name="Expected Points") +
theme_bw()
if (!legend) {
p <- p + theme(legend.position="none")
}
if (!is.null(ntks) & !is.null(xrng)) {
p <- p + scale_x_continuous(name=xlab, limits=c(xrng[1], xrng[2]),
breaks=seq(xrng[1],xrng[2],length.out=ntks),
labels=seq(xrng[1],xrng[2],length.out=ntks))
} else if (is.null(ntks) & !is.null(xrng)) {
p <- p + xlim(xrng) + xlab(xlab)
} else {
p <- p + xlab(xlab)
}
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/expectedpts.R
|
#' Calculates possessions, pace, offensive and defensive rating, and Four Factors
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param TEAM a data frame whose rows are the analyzed teams and with columns referred to the team achievements in the considered games (a box score); required variables: \code{Team}, \code{P2A}, \code{P2M}, \code{P3A}, \code{P3M}, \code{FTA}, \code{FTM}, \code{OREB}, \code{DREB}, \code{TOV}, \code{MIN} (see Details).
#' @param OPP a data frame whose rows are the analyzed teams and with columns referred to the achievements of the opponents of each team in the considered game; required variables: \code{Team}, \code{P2A}, \code{P2M}, \code{P3A}, \code{P3M}, \code{FTA}, \code{FTM}, \code{OREB}, \code{DREB}, \code{TOV}, \code{MIN} (see Details).
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @seealso \code{\link{plot.fourfactors}}
#' @details The rows of the \code{TEAM} and the \code{OPP} data frames must be referred to the same teams in the same order.
#' @details Required columms:
#' @details * \code{Team}, a factor with the name of the analyzed team
#' @details * \code{P2A}, a numeric variable (integer) with the number of 2-points shots attempted
#' @details * \code{P2M}, a numeric variable (integer) with the number of 2-points shots made
#' @details * \code{P3A}, a numeric variable (integer) with the number of 3-points shots attempted
#' @details * \code{P3M}, a numeric variable (integer) with the number of 3-points shots made
#' @details * \code{FTA}, a numeric variable (integer) with the number of free throws attempted
#' @details * \code{FTM}, a numeric variable (integer) with the number of free throws made
#' @details * \code{OREB}, a numeric variable (integer) with the number of offensive rebounds
#' @details * \code{DREB}, a numeric variable (integer) with the number of defensive rebounds
#' @details * \code{TOV}, a numeric variable (integer) with the number of turnovers
#' @details * \code{MIN}, a numeric variable (integer) with the number of minutes played
#' @return An object of class \code{fourfactors}, i.e. a data frame with the following columns:
#' @return * \code{Team}, a factor with the name of the analyzed team
#' @return * \code{POSS.Off}, a numeric variable with the number of possessions of each team calculated with the formula \eqn{POSS=(P2A+P3A)+0.44*FTA-OREB+TOV}
#' @return * \code{POSS.Def}, a numeric variable with the number of possessions of the opponents of each team calculated with the formula \eqn{POSS=(P2A+P3A)+0.44*FTA-OREB+TOV}
#' @return * \code{PACE.Off}, a numeric variable with the pace of each team (number of possessions per minute played)
#' @return * \code{PACE.Def}, a numeric variable with the pace of the opponents of each team (number of possessions per minute played)
#' @return * \code{ORtg}, a numeric variable with the offensive rating (the points scored by each team per 100 possessions)
#' @return * \code{DRtg}, a numeric variable with the defensive rating (the points scored by the opponents of each team per 100 possessions)
#' @return * \code{F1.Off}, a numeric variable with the offensive first factor (effective field goal percentage)
#' @return * \code{F2.Off}, a numeric variable with the offensive second factor (turnovers per possession)
#' @return * \code{F3.Off}, a numeric variable with the offensive third factor (rebouding percentage)
#' @return * \code{F4.Off}, a numeric variable with the offensive fourth factor (free throw rate)
#' @return * \code{F1.Def}, a numeric variable with the defensive first factor (effective field goal percentage)
#' @return * \code{F2.Def}, a numeric variable with the defensive second factor (turnovers per possession)
#' @return * \code{F3.Def}, a numeric variable with the defensive third factor (rebouding percentage)
#' @return * \code{F4.Def}, a numeric variable with the defensive fourth factor (free throw rate)
#' @examples
#' selTeams <- c(2,6,10,11)
#' FF <- fourfactors(Tbox[selTeams,], Obox[selTeams,])
#' plot(FF)
#' @export
fourfactors <- function(TEAM, OPP) {
# Checking errors
if (nrow(TEAM) != nrow(OPP)) {
stop("Error: TEAM and OPP dataframe must have the same number of rows.")
}
# Variables used in the calculation of Pace, Ratings, Four Factors
Team <- TEAM[["Team"]]
P2A.Off <- TEAM[["P2A"]]
P3A.Off <- TEAM[["P3A"]]
FTA.Off <- TEAM[["FTA"]]
OREB.Off <- TEAM[["OREB"]]
TO.Off <- TEAM[["TOV"]]
MIN.Off <- TEAM[["MIN"]]
P2M.Off <- TEAM[["P2M"]]
P3M.Off <- TEAM[["P3M"]]
FTM.Off <- TEAM[["FTM"]]
DREB.Off <- TEAM[["DREB"]]
P2A.Def <- OPP[["P2A"]]
P3A.Def <- OPP[["P3A"]]
FTA.Def <- OPP[["FTA"]]
OREB.Def <- OPP[["OREB"]]
TO.Def <- OPP[["TOV"]]
MIN.Def <- OPP[["MIN"]]
P2M.Def <- OPP[["P2M"]]
P3M.Def <- OPP[["P3M"]]
FTM.Def <- OPP[["FTM"]]
DREB.Def <- OPP[["DREB"]]
# Formula (2) of the Dean Oliver paper
# Possession and pace of the game
# Implies that defensive rebounds have no possession value
POSS.Off <- (P2A.Off + P3A.Off) + 0.44 * FTA.Off - OREB.Off + TO.Off
POSS.Def <- (P2A.Def + P3A.Def) + 0.44 * FTA.Def - OREB.Def + TO.Def
PACE.Off <- POSS.Off/MIN.Off
PACE.Def <- POSS.Def/MIN.Def
# Formulas (5) and (6) of the Dean Oliver paper
# Offensive (ORtg) and Defensive (DRtg) Ratings
ORtg <- round(100 * (2 * P2M.Off + 3 * P3M.Off + FTM.Off)/POSS.Off, 2)
DRtg <- round(100 * (2 * P2M.Def + 3 * P3M.Def + FTM.Def)/POSS.Def, 2)
# The four factors
F1.Off <- round(100 * (P2M.Off + 1.5 * P3M.Off)/(P2A.Off + P3A.Off), 2)
F1.Def <- round(100 * (P2M.Def + 1.5 * P3M.Def)/(P2A.Def + P3A.Def), 2)
F2.Off <- round(100 * TO.Off/POSS.Off, 2)
F2.Def <- round(100 * TO.Def/POSS.Def, 2)
F3.Off <- round(100 * OREB.Off/(OREB.Off + DREB.Def), 2)
F3.Def <- round(100 * DREB.Off/(DREB.Off + OREB.Def), 2)
F4.Off <- round(100 * FTM.Off/(P2A.Off + P3A.Off), 2)
F4.Def <- round(100 * FTM.Def/(P2A.Def + P3A.Def), 2)
FF <- data.frame(Team,
POSS.Off, POSS.Def,
PACE.Off, PACE.Def,
ORtg, DRtg,
F1.Off, F2.Off, F3.Off, F4.Off,
F1.Def, F2.Def, F3.Def, F4.Def)
class(FF) <- append("fourfactors", class(FF))
return(FF)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/fourfactors.R
|
#' @noRd
generateSectors <- function(nsect = 7, npts = 1000) {
x <- NULL
ang_start <- atan(106/(12 * 22))
# Upper circle (three-point line)
r1 <- 23.75; span1 <- 22
crcl1 <- crcl(x0 = 0, y0 = -41.75, r = r1, nsteps = npts)
# Middle circle (passing through the corner P=(8,-28) )
r2 <- sqrt(8^2 + (41.75 - 28)^2); span2 <- r2 * cos(ang_start)
crcl2 <- crcl(x0 = 0, y0 = -41.75, r = r2, nsteps = npts)
# Lower circle (restricted area semicircle)
r3 <- 4; span3 <- 4
crcl3 <- crcl(x0 = 0, y0 = -41.25, r = r3, nsteps = npts)
# Abscissa of the corners for A, B, C sectors
ang_step <- (pi - 2 * ang_start)/(nsect - 2)
angs <- ang_start + (0:(nsect - 2)) * ang_step
xpts1 <- r1 * cos(angs)
xpts2 <- r2 * cos(angs)
a <- tan(angs)
xpts3 <- ifelse(a > 0, (a + sqrt(63 + 64 * a^2))/(2 * (1 + a^2)),
(a - sqrt(63 + 64 * a^2))/(2 * (1 + a^2)))
### First three sectors at the bottom right of the court
cnt <- 1
sub_crcl4 <- subset(crcl3, x >= xpts3[1])
sec0A <- data.frame(x = c(0, 0, 4, 4, rev(sub_crcl4$x), r2 * cos(ang_start), r2 * cos(ang_start)),
y = c(-47, -43, -43, -41.25, rev(sub_crcl4$yup), -41.75 + r2 * sin(ang_start), -47))
sec0A$sector <- cnt
cnt <- cnt + 1
sec0B <- data.frame(x = c(r2 * cos(ang_start), r2 * cos(ang_start), 22, r1 * cos(ang_start)),
y = c(-47, -41.75 + r2 * sin(ang_start), -41.75 + r1 * sin(ang_start), -47))
sec0B$sector <- cnt
cnt <- cnt + 1
sec0C <- data.frame(x = c(22, 22, 25, 25),
y = c(-47, -41.75 + 22 * tan(ang_start), -41.75 + 25 * tan(ang_start), -47))
sec0C$sector <- cnt
cnt <- cnt + 1
sec0_left <- rbind(sec0A, sec0B, sec0C)
# Coordinates for drawing sector boundaries (lines)
segms <- matrix(0,nsect*2+2,3)
nsegm <- 1
segms[nsegm,] <- c(sub_crcl4$x[1], sub_crcl4$yup[1], nsegm)
segms[nsegm+1,] <- c(sec0C$x[3], sec0C$y[3], nsegm)
nsegm <- nsegm+2
segms[nsegm,] <- c(0, -43, nsegm)
segms[nsegm+1,] <- c(0, -47, nsegm)
nsegm <- nsegm+2
# Coordinates for drawing sector boundaries (arcs)
sub_crcl2 <- subset(crcl2, x <= xpts2[1] & x >= -xpts2[1])
arc <- data.frame(x=c(sub_crcl2$x[1], sub_crcl2$x, -sub_crcl2$x[1]),
y=c(-47, sub_crcl2$yup, -47))
##############################
sectsABC_list <- vector(nsect - 2, mode = "list")
for (k in 1:(nsect - 2)) {
sub_crcl1 <- subset(crcl1, x <= xpts1[k] & x >= xpts1[k + 1])
sub_crcl2 <- subset(crcl2, x <= xpts2[k] & x >= xpts2[k + 1])
sub_crcl3 <- subset(crcl3, x <= xpts3[k] & x >= xpts3[k + 1])
# Lower sector (A)
secA <- rbind(sub_crcl3[, c(1, 3)], sub_crcl2[nrow(sub_crcl2):1, c(1, 3)])
secA$sector <- cnt
cnt <- cnt + 1
# Middle sector (B)
secB <- rbind(sub_crcl2[, c(1, 3)], sub_crcl1[nrow(sub_crcl1):1, c(1, 3)])
secB$sector <- cnt
cnt <- cnt + 1
# Upper sector (C)
tan_angs <- tan(angs)
xs <- ifelse(tan_angs > 0, 25, -25)
ys <- -41.75 + 25 * abs(tan_angs)
xs <- ifelse(ys < 0, xs, 41.75/tan_angs)
ys <- ifelse(ys < 0, ys, 0)
pt1 <- data.frame(x = xs[k], yup = ys[k])
pt2 <- data.frame(x = xs[k + 1], yup = ys[k + 1])
if (xs[k] == xs[k + 1] | ys[k] == ys[k + 1]) {
secC <- rbind(sub_crcl1[, c(1, 3)], pt1, pt2)
} else {
vertex <- c(sign(xs[k + 1]) * 25, 0)
secC <- rbind(sub_crcl1[, c(1, 3)], pt1, vertex, pt2)
}
secC$sector <- cnt
cnt <- cnt + 1
sectsABC_list[[k]] <- rbind(secA, secB, secC)
segms[nsegm,] <- c(sub_crcl3$x[1], sub_crcl3$yup[1], nsegm)
segms[nsegm+1,] <- c(secC$x[nrow(secC)], secC$y[nrow(secC)], nsegm)
nsegm <- nsegm+2
}
sectsABC <- do.call(rbind, sectsABC_list)
names(sectsABC)[2] <- "y"
# sectsABC$sector <- factor(sectsABC$sector)
#############################
sec0A$x <- -sec0A$x
sec0A$sector <- cnt
cnt <- cnt + 1
sec0B$x <- -sec0B$x
sec0B$sector <- cnt
cnt <- cnt + 1
sec0C$x <- -sec0C$x
sec0C$sector <- cnt
cnt <- cnt + 1
sec0_right <- rbind(sec0A, sec0B, sec0C)
#############################
restr <- crcl(0, -41.25, 4, nsteps = 200)
pol_restric <- data.frame(x = c(-4, -4, restr$x, 4, 4),
y = c(-43, -41.25, restr$yup, -41.25, -43))
pol_restric$sector <- 0
sects <- rbind(pol_restric, sec0_left, sectsABC, sec0_right)
segms <- as.data.frame(segms)
names(segms) <- c("x","y","nsegm")
return(list(sects=sects, segms=segms, arc=arc))
}
#' @noRd
crcl <- function(x0, y0, r, span=r, nsteps=100) {
x <- seq(x0-span,x0+span,length.out=nsteps)
ylo <- y0-sqrt(r^2-(x-x0)^2)
yup <- y0+sqrt(r^2-(x-x0)^2)
data.frame(x=x, ylo=ylo, yup=yup)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/generateSectors.R
|
#' Agglomerative hierarchical clustering
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data numeric data frame.
#' @param k integer, number of clusters.
#' @param nclumax integer, maximum number of clusters (when \code{k=NULL}).
#' @param labels character, row labels.
#' @param linkage character, the agglomeration method to be used in \code{hclust} (see \code{method} in \link[stats]{hclust}).
#' @details The \code{hclustering} function performs a preliminary standardization of columns in \code{data}.
#' @seealso \code{\link{plot.hclustering}}, \code{\link[stats]{hclust}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{hclustering} object.
#' @return If \code{k} is \code{NULL}, the \code{hclustering} object is a list of 3 elements:
#' @return * \code{k} \code{NULL}
#' @return * \code{clusterRange} integer vector, values of \code{k} (from 1 to \code{nclumax}) at which the \emph{variance between} of the clusterization is evaluated
#' @return * \code{VarianceBetween} numeric vector, values of the \emph{variance between} evaluated for \code{k} in \code{clusterRange}
#' @return If \code{k} is not \code{NULL}, the \code{hclustering} object is a list of 5 elements:
#' @return * \code{k} integer, number of clusters
#' @return * \code{Subjects} data frame, subjects' cluster identifiers
#' @return * \code{ClusterList} list, clusters' composition
#' @return * \code{Profiles} data frame, clusters' profiles, i.e. the average of the variables within clusters and the cluster eterogeineity index (\code{CHI})
#' @return * \code{Hclust} an object of class \code{hclust}, see \code{\link[stats]{hclust}}
#' @examples
#' data <- with(Pbox, data.frame(PTS, P3M, REB=OREB+DREB, AST, TOV, STL, BLK, PF))
#' data <- subset(data, Pbox$MIN >= 1500)
#' ID <- Pbox$Player[Pbox$MIN >= 1500]
#' hclu1 <- hclustering(data)
#' plot(hclu1)
#' hclu2 <- hclustering(data, labels=ID, k=7)
#' plot(hclu2)
#' @export
#' @importFrom stats cutree
hclustering <- function(data, k = NULL, nclumax = 10, labels = NULL, linkage='ward.D') {
varb <- function(x) {
x <- stats::na.omit(x)
varb <- sum((x - mean(x))^2)/(length(x))
return(varb)
}
if (is.null(labels)) {
labels <- c(1:nrow(data))
}
if (!is.null(k)) {
k <- ceiling(k)
if (k<=1) stop('Number of clusters k not above 1')
}
namesvars <- names(data)
data <- scale(data)
nunits <- nrow(data)
nvars <- ncol(data)
rownames(data) <- labels
hcl <- stats::hclust(dist(data), method=linkage)
if (is.null(k)) {
varfra.nclu <- array(0, nclumax)
clu.k <- matrix(1, nunits, nclumax)
clumean <- matrix(0, nclumax, nvars * nclumax)
for (nclu in 2:nclumax) {
clu <- stats::cutree(hcl, k = nclu)
clumean <- matrix(unlist(by(data,clu,function(x) apply(x,2,mean))),ncol=nvars, byrow=TRUE)
tbl_clust <- table(clu)/nunits
varfra <- mapply(function(x, y) sum((x - mean(y))^2 * tbl_clust), as.data.frame(clumean), as.data.frame(data))
varnei <- apply(data, 2, function(x) sum(tapply(x, clu, varb) * tbl_clust))
varfra.nclu[nclu] <- sum(varfra)/sum(varfra + varnei)
clu.k[, nclu] <- clu
}
out <- list(k = k, ClusterRange = 1:nclumax, VarianceBetween = varfra.nclu)
} else {
nclu <- k
clu <- cutree(hcl, k = nclu)
clumean <- matrix(unlist(by(data,clu,function(x) apply(x,2,mean))),ncol=nvars, byrow=TRUE)
tbl_clust <- table(clu)/nunits
varfra <- mapply(function(x, y) sum((x - mean(y))^2 * tbl_clust), as.data.frame(clumean), as.data.frame(data))
varnei <- apply(data, 2, function(x) sum(tapply(x, clu, varb) * tbl_clust))
varfra.nclu <- sum(varfra)/sum(varfra + varnei) #in pratica una media degli eta ponderata con la varianza tot di ogni dimensione
clu.k <- clu
profiles <- as.data.frame(clumean)
names(profiles) <- namesvars
subjects.cluster <- data.frame(Label = labels, Cluster = clu)
vars <- t(apply(data, 2, function(x) tapply(x, subjects.cluster$Cluster, varb)))
#clustnames <- paste("Cluster", 1:k, "- CHI =", round(colMeans(vars), 2))
#profiles <- data.frame(profiles, clustnames)
profiles <- data.frame(ID=1:k, profiles, CHI=round(colMeans(vars), 2))
cluster.list <- by(subjects.cluster[, 1], subjects.cluster[, 2], list)
out <- list(k = k, Subjects = subjects.cluster, ClusterList = cluster.list, Profiles = profiles, Hclust=hcl)
}
class(out) <- append("hclustering", class(out))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/hclustering.R
|
#' Inequality analysis
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data numeric vector containing the achievements (e.g. scored points) of the players whose inequality has to be analyzed.
#' @param nplayers integer, number of players to include in the analysis (ranked in nondecreasing order according to the values in data).
#' @return A list with the following elements: \code{Lorenz} (cumulative distributions used to plot the Lorenz curve) and \code{Gini} (Gini coefficient).
#' @seealso \code{\link{plot.inequality}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' Pbox.BN <- subset(Pbox, Team=="Brooklyn Nets")
#' out <- inequality(Pbox.BN$PTS, nplayers=8)
#' print(out)
#' plot(out)
#' @export
inequality <- function(data, nplayers) {
x <- stats::na.omit(data)
x <- rev(sort(x, decreasing = T)[1:nplayers])
xtot <- sum(x)
xcum <- cbind((1:nplayers)/nplayers, cumsum(x)/xtot)
xcum <- rbind(c(0, 0), xcum)
xcummax <- xcum
xcummax[1:nplayers, 2] <- 0
gini <- round(100 * sum(xcum[, 1] - xcum[, 2])/sum(xcum[1:nplayers, 1]), 2)
lor <- data.frame(xcum)
names(lor) <- c("F", "Q")
lst <- list(Gini = gini, Lorenz = lor)
class(lst) <- append("inequality", class(lst))
return(lst)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/inequality.R
|
#' Reports whether x is a 'MDSmap' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{MDSmap}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{MDSmap} and FALSE otherwise.
#' @examples
#' data <- subset(Pbox, MIN >= 1500)
#' data <- data.frame(data$PTS, data$P3M, data$P2M, data$OREB + data$DREB, data$AST,
#' data$TOV,data$STL, data$BLK)
#' mds <- MDSmap(data)
#' is.MDSmap(mds)
#' @export
is.MDSmap <- function(x) {
inherits(x, "MDSmap")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.MDSmap.R
|
#' Reports whether x is a 'networkdata' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{assistnet}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{networkdata} and FALSE otherwise.
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' PbP.GSW <- subset(PbP, team=="GSW" & player!="")
#' out <- assistnet(PbP.GSW)
#' is.assistnet(out)
#' @export
is.assistnet <- function(x) {
inherits(x, "assistnet")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.assistnet.R
|
#' Reports whether x is a 'corranalysis' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{corranalysis}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{corranalysis} and FALSE otherwise.
#' @examples
#' data <- data.frame(Pbox$PTS,Pbox$P3M,Pbox$P2M,
#' Pbox$OREB + Pbox$DREB,Pbox$AST,
#' Pbox$TOV,Pbox$STL,Pbox$BLK)/Pbox$MIN
#' names(data) <- c("PTS","P3M","P2M","REB","AST","TOV","STL","BLK")
#' data <- subset(data, Pbox$MIN >= 500)
#' out <- corranalysis(data)
#' is.corranalysis(out)
#' @export
is.corranalysis <- function(x) {
inherits(x, "corranalysis")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.corranalysis.R
|
#' Reports whether x is a 'fourfactors' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{fourfactors}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{fourfactors} and FALSE otherwise.
#' @examples
#' selTeams <- c(2,6,10,11)
#' out <- fourfactors(Tbox[selTeams,], Obox[selTeams,])
#' is.fourfactors(out)
#' @export
is.fourfactors <- function(x) {
inherits(x, "fourfactors")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.fourfactors.R
|
#' Reports whether x is a 'hclustering' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{hclustering}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{hclustering} and FALSE otherwise.
#' @examples
#' data <- data.frame(Pbox$PTS,Pbox$P3M,
#' Pbox$OREB + Pbox$DREB, Pbox$AST,
#' Pbox$TOV, Pbox$STL, Pbox$BLK,Pbox$PF)
#' names(data) <- c("PTS","P3M","REB","AST","TOV","STL","BLK","PF")
#' data <- subset(data, Pbox$MIN >= 1500)
#' ID <- Pbox$Player[Pbox$MIN >= 1500]
#' hclu <- hclustering(data, labels=ID, k=7)
#' is.hclustering(hclu)
#' @export
is.hclustering <- function(x) {
inherits(x, "hclustering")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.hclustering.R
|
#' Reports whether x is a 'inequality' object.
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{inequality}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{inequality} and FALSE otherwise.
#' @examples
#' Pbox.BN <- subset(Pbox, Team=="Brooklyn Nets")
#' out <- inequality(Pbox.BN$PTS, npl=8)
#' is.inequality(out)
#' @export
is.inequality <- function(x) {
inherits(x, "inequality")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.inequality.R
|
#' Reports whether x is a 'kclustering' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{kclustering}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{kclustering} and FALSE otherwise.
#' @examples
#' FF <- fourfactors(Tbox,Obox)
#' X <- with(FF, data.frame(OD.Rtg=ORtg/DRtg,
#' F1.r=F1.Def/F1.Off, F2.r=F2.Off/F2.Def,
#' F3.O=F3.Def, F3.D=F3.Off))
#' X$P3M <- Tbox$P3M
#' X$STL.r <- Tbox$STL/Obox$STL
#' kclu <- kclustering(X)
#' is.kclustering(kclu)
#' @export
is.kclustering <- function(x) {
inherits(x, "kclustering")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.kclustering.R
|
#' Reports whether x is a 'simplereg' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{simplereg}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{simplereg} and FALSE otherwise.
#' @examples
#' Pbox.sel <- subset(Pbox, MIN >= 500)
#' X <- Pbox.sel$AST/Pbox.sel$MIN
#' Y <- Pbox.sel$TOV/Pbox.sel$MIN
#' Pl <- Pbox.sel$Player
#' out <- simplereg(x=X, y=Y, type="lin")
#' is.simplereg(out)
#' @export
is.simplereg <- function(x) {
inherits(x, "simplereg")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.simplereg.R
|
#' Reports whether x is a 'variability' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object to test.
#' @seealso \code{\link{variability}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return Returns TRUE if its argument is of class \code{variability} and FALSE otherwise.
#' @examples
#' Pbox.BC <- subset(Pbox, Team=="Oklahoma City Thunder" & MIN >= 500,
#' select=c("P2p","P3p","FTp","P2A","P3A","FTA"))
#' out <- variability(data=Pbox.BC, data.var=c("P2p","P3p","FTp"),
#' size.var=c("P2A","P3A","FTA"), weight=TRUE)
#' is.variability(out)
#' @export
is.variability <- function(x) {
inherits(x, "variability")
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/is.variability.R
|
#' K-means cluster analysis
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data numeric data frame.
#' @param k integer, number of clusters.
#' @param labels character, row labels.
#' @param nclumax integer, maximum number of clusters (when \code{k=NULL}) used for calculating the explained variance as function of the number of clusters.
#' @param nruns integer, run the k-means algorithm \code{nruns} times and chooses the best solution according to a maximum explained variance criterion.
#' @param iter.max integer, maximum number of iterations allowed in k-means clustering (see \link[stats]{kmeans}).
#' @param algorithm character, the algorithm used in k-means clustering (see \link[stats]{kmeans}).
#' @details The \code{kclustering} function performs a preliminary standardization of columns in \code{data}.
#' @seealso \code{\link{plot.kclustering}}, \code{\link[stats]{kmeans}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{kclustering} object.
#' @return If \code{k} is \code{NULL}, the \code{kclustering} object is a list of 3 elements:
#' @return * \code{k} \code{NULL}
#' @return * \code{clusterRange} integer vector, values of \code{k} (from 1 to \code{nclumax}) at which the \emph{variance between} of the clusterization is evaluated
#' @return * \code{VarianceBetween} numeric vector, values of the \emph{variance between} evaluated for \code{k} in \code{clusterRange}
#' @return If \code{k} is not \code{NULL}, the \code{kclustering} object is a list of 4 elements:
#' @return * \code{k} integer, number of clusters
#' @return * \code{Subjects} data frame, subjects' cluster identifiers
#' @return * \code{ClusterList} list, clusters' composition
#' @return * \code{Profiles} data frame, clusters' profiles, i.e. the average of the variables within clusters and the cluster eterogeineity index (\code{CHI})
#' @examples
#' FF <- fourfactors(Tbox,Obox)
#' X <- with(FF, data.frame(OD.Rtg=ORtg/DRtg,
#' F1.r=F1.Def/F1.Off, F2.r=F2.Off/F2.Def,
#' F3.O=F3.Def, F3.D=F3.Off))
#' X$P3M <- Tbox$P3M
#' X$STL.r <- Tbox$STL/Obox$STL
#' kclu1 <- kclustering(X)
#' plot(kclu1)
#' kclu2 <- kclustering(X, k=9)
#' plot(kclu2)
#' @export
kclustering <- function(data, k=NULL, labels=NULL, nclumax=10, nruns=10, iter.max=50, algorithm="Hartigan-Wong") {
varb <- function(x) {
x <- stats::na.omit(x)
varb <- sum((x - mean(x))^2)/(length(x))
return(varb)
}
if (is.null(labels)) {
labels <- c(1:nrow(data))
}
if (!is.null(k)) {
k <- ceiling(k)
if (k<=1) stop('Number of clusters k not above 1')
}
namesvars <- names(data)
data <- scale(data)
nunits <- nrow(data)
nvars <- ncol(data)
if (is.null(k)) {
varfra.nclu <- array(0, nclumax)
clu.k <- matrix(1, nunits, nclumax)
clumean <- matrix(0, nclumax, nvars * nclumax)
for (nclu in 2:nclumax) {
clu.r <- matrix(0, nunits, nruns)
clumean.r <- array(0, c(nclu, nvars, nruns))
varfra.tot.nruns <- array(0, nruns)
for (r in 1:nruns) {
ca.k <- stats::kmeans(data, nclu, algorithm=algorithm, iter.max=iter.max)
clu.r[, r] <- ca.k$cluster
clumean.r[, , r] <- ca.k$centers
tbl_clust <- table(ca.k$cluster)/nunits
varfra <- mapply(function(x, y) sum((x - mean(y))^2 * tbl_clust), as.data.frame(ca.k$centers), as.data.frame(data))
varnei <- apply(data, 2, function(x) sum(tapply(x, ca.k$cluster, varb) * tbl_clust))
varfra.tot.nruns[r] <- sum(varfra)/sum(varfra + varnei)
}
rm <- which.max(varfra.tot.nruns)
varfra.nclu[nclu] <- varfra.tot.nruns[rm]
clu.k[, nclu] <- clu.r[, rm]
clumean[1:nclu, ((nclu - 1) * nvars + 1):(nclu * nvars)] <- clumean.r[, , rm]
}
out <- list(k = k, ClusterRange = 1:nclumax, VarianceBetween = varfra.nclu)
} else {
nclu <- k
clu.r <- matrix(0, nunits, nruns)
clumean.r <- array(0, c(nclu, nvars, nruns))
varfra.tot.nruns <- array(0, nruns)
for (r in 1:nruns) {
ca.k <- stats::kmeans(data, nclu, algorithm = "Hartigan-Wong")
clu.r[, r] <- ca.k$cluster
clumean.r[, , r] <- ca.k$centers
tbl_clust <- table(ca.k$cluster)/nunits
varfra <- mapply(function(x, y) sum((x - mean(y))^2 * tbl_clust), as.data.frame(ca.k$centers), as.data.frame(data))
varnei <- apply(data, 2, function(x) sum(tapply(x, ca.k$cluster, varb) * tbl_clust))
varfra.tot.nruns[r] <- sum(varfra)/sum(varfra + varnei) #in pratica una media degli eta ponderata con la varianza tot di ogni dimensione
}
rm <- which.max(varfra.tot.nruns)
varfra.nclu <- varfra.tot.nruns[rm]
clu.k <- clu.r[, rm]
clumean <- clumean.r[, , rm]
profiles <- as.data.frame(clumean)
names(profiles) <- namesvars
subjects.cluster <- data.frame(Label = labels, Cluster = clu.k)
vars <- t(apply(data, 2, function(x) tapply(x, subjects.cluster$Cluster, varb)))
#clustnames <- paste("Cluster", 1:k, "- CHI =", round(colMeans(vars), 2))
#profiles <- data.frame(profiles, clustnames)
profiles <- data.frame(ID=1:k, profiles, CHI=round(colMeans(vars), 2))
cluster.list <- by(subjects.cluster[, 1], subjects.cluster[, 2], list)
out <- list(k = k, Subjects = subjects.cluster, ClusterList = cluster.list, Profiles = profiles)
}
class(out) <- append("kclustering", class(out))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/kclustering.R
|
#' Draws two-dimensional plots for multidimensional scaling (MDS) from a 'MDSmap' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{MDSmap}.
#' @param level.plot logical; if TRUE, draws a level plot, otherwise draws a scatter plot (not active if \code{zvar=NULL}).
#' @param z.var character vector; defines the set of variables (available in the \code{data} data frame of \code{\link{MDSmap}}) used to color-coding the points in the map (for scatter plots) or, alternatively, overlap to the map a colored level plot.
#' @param title character, plot title.
#' @param labels character vector, labels for (x, y) points (only for single scatter plot).
#' @param repel_labels logical; if \code{TRUE}, draw text labels using repelling (not for highlighted points) (see \code{\link[ggrepel]{geom_text_repel}}).
#' @param text_label logical; if \code{TRUE}, draw a rectangle behind the text labels (not active if \code{subset=NULL}).
#' @param subset logical vector, to select a subset of points to be highlighted.
#' @param col.subset character, color for the subset of points.
#' @param zoom numeric vector with 4 elements; \code{c(xmin,xmax,ymin,ymax)} for the x- and y-axis limits of the plot.
#' @param palette color palette.
#' @param contour logical; if \code{TRUE}, contour lines are plotted (not active if \code{level.plot=FALSE}).
#' @param ncol.arrange integer, number of columns when arranging multiple grobs on a page.
#' @param ... other graphical parameters.
#' @seealso \code{\link{MDSmap}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A single \code{ggplot2} plot or a list of \code{ggplot2} plots
#' @examples
#' data <- data.frame(Pbox$PTS, Pbox$P3M, Pbox$P2M, Pbox$OREB + Pbox$DREB, Pbox$AST,
#' Pbox$TOV,Pbox$STL, Pbox$BLK)
#' names(data) <- c('PTS','P3M','P2M','REB','AST','TOV','STL','BLK')
#' selp <- which(Pbox$MIN >= 1500)
#' data <- data[selp,]
#' id <- Pbox$Player[selp]
#' mds <- MDSmap(data)
#' plot(mds, labels=id, z.var="P2M", level.plot=FALSE, palette=rainbow)
#' @method plot MDSmap
#' @export
plot.MDSmap <- function(x, z.var = NULL, level.plot=TRUE, title = NULL, labels = NULL,
repel_labels = FALSE, text_label = TRUE, subset = NULL, col.subset = "gray50",
zoom = NULL, palette = NULL, contour = FALSE, ncol.arrange = NULL, ...) {
if (!is.MDSmap(x)) {
stop("Not a 'MDSmap' object")
}
X1 <- X2 <- Z <- '..level..' <- NULL
if (!is.null(z.var)) {
if (!inherits(data, "dist")) {
data <- x$data
} else {
stop("MDS was calculated using a distance matrix. Cannot find the 'z.var' variable")
}
}
if (!is.null(z.var)) {
if (is.numeric(z.var)) {
varnames <- names(data)[z.var]
} else if (is.character(z.var)) {
varnames <- z.var
} else {
stop("'z.var' must be a string or a number")
}
}
if (is.null(title)) {
title <- "MDS Map"
}
config <- data.frame(x$points)
stress <- x$stress
warn <- "BE CAREFUL: BAD FIT!!"
if (stress <= 5) {
warn <- "EXCELLENT FIT!!"
} else if (stress > 5 & stress <= 10) {
warn <- "GOOD FIT"
} else {
warn <- "FAIR FIT"
}
#subtitle <- paste("Stress Index = ", round(stress, 2), "% - ", warn, sep = "")
subtitle <- paste("Stress Index = ", round(stress, 2), "%", sep = "")
if (is.null(z.var)) { ### If 'z.var' is NULL
listPlots <- vector(1, mode = "list")
p <- scatterplot(data=config, data.var=c("X1","X2"), labels=labels, repel_labels=repel_labels,
text_label=text_label, subset=subset, col.subset = col.subset, zoom = zoom, title = title)
p <- p + xlab("") + ylab("") +
annotate(geom = "text", label = subtitle, x = Inf, y = Inf, hjust = 1, vjust = -1) +
coord_cartesian(clip = 'off')
listPlots[[1]] <- p
} else if (!is.null(z.var) & !level.plot) { ### If 'z.var' is not NULL & level.plot=FALSE
nv <- length(z.var)
listPlots <- vector(nv, mode = "list")
names(listPlots) <- varnames
for (k in 1:nv) {
vark <- varnames[k]
dts <- data.frame(config[, 1:2], subset(data, select = vark))
names(dts) <- c("X1", "X2", vark)
p <- scatterplot(data=dts, data.var=c("X1","X2"), z.var=vark, palette=palette,
labels=labels, repel_labels=repel_labels, text_label=text_label, subset=subset, col.subset = col.subset,
zoom = zoom, title = title)
p <- p + xlab("") + ylab("") +
annotate(geom = "text", label = subtitle, x = Inf, y = Inf, hjust = 1, vjust = -1) +
coord_cartesian(clip = 'off')
listPlots[[k]] <- p
}
} else if (!is.null(z.var) & level.plot) { ### If 'z.var' is not NULL & level.plot=TRUE
if (is.null(palette)) {
cols <- grDevices::rainbow(100, alpha = 1, start = 0.2, end = 1)
} else {
cols <- palette(100)
}
# List of level plots
nv <- length(z.var)
listPlots <- vector(nv, mode = "list")
names(listPlots) <- varnames
for (k in 1:nv) {
dts <- data.frame(config[, 1:2], subset(data, select = varnames[k]))
names(dts) <- c("D1", "D2", "Z")
xyz.fit <- stats::loess(Z ~ D1 + D2, dts, control = loess.control(surface = "direct"), degree = 2)
xnew <- seq(min(dts$D1), max(dts$D1), len = 60)
ynew <- seq(min(dts$D2), max(dts$D2), len = 60)
dts <- expand.grid(x = xnew, y = ynew)
names(dts) <- c("D1", "D2")
z <- stats::predict(xyz.fit, newdata = dts)
mtx_melt <- data.frame(X1 = rep(xnew, nrow(z)), X2 = rep(ynew, each = ncol(z)), Z = as.vector(z))
p <- ggplot(data = mtx_melt, aes(x = X1, y = X2, z = Z)) + geom_tile(aes(fill = Z)) +
scale_fill_gradientn(name = varnames[k], colours = cols) +
xlab("") + ylab("") + theme(panel.background = element_blank())
if (contour) {
p <- p + geom_contour(color = "black", alpha = 0.5, show.legend = TRUE) +
directlabels::geom_dl(aes(label = ..level..),
method = "far.from.others.borders", stat = "contour")
}
listPlots[[k]] <- p
}
}
# Arrange level plots
if (length(listPlots)>1) {
if (is.null(ncol.arrange)) {
ncol.arrange <- ceiling(sqrt(length(listPlots)))
}
p <- gridExtra::arrangeGrob(grobs = listPlots, ncol = ncol.arrange)
} else {
p <- listPlots[[1]]
}
grid::grid.draw(p)
invisible(listPlots)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.MDSmap.R
|
#' Plots a network from a 'assistnet' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{assistnet}.
#' @param layout character, network vertex layout algorithm (see \code{\link[sna]{gplot.layout}}) such as \code{"kamadakawai"} (the default).
#' @param layout.par a list of parameters for the network vertex layout algorithm (see \code{\link[sna]{gplot.layout}}).
#' @param edge.thr numeric, threshold for edge values; values below the threshold are set to 0.
#' @param edge.col.lim numeric vector of length two providing limits of the scale for edge color.
#' @param edge.col.lab character, label for edge color legend.
#' @param node.size character, indicating the name of the variable for node size (one of the columns of the \code{nodeStats} data frame in the \code{x} object, see \code{\link{assistnet}}).
#' @param node.size.lab character, label for node size legend.
#' @param node.col character, indicating the name of the variable for node color (one of the columns of the \code{nodeStats} data frame in the \code{x} object, see \code{\link{assistnet}}).
#' @param node.col.lim numeric vector of length two providing limits of the scale for node color.
#' @param node.col.lab character, label for node color legend.
#' @param node.pal color palette for node colors.
#' @param edge.pal color palette for edge colors.
#' @param ... other graphical parameters.
#' @seealso \code{\link{assistnet}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} object
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' PbP.GSW <- subset(PbP, team=="GSW" & player!="")
#' out <- assistnet(PbP.GSW)
#' plot(out, layout="circle", edge.thr=30, node.col="FGM_ASTp", node.size="ASTPTS")
#' @method plot assistnet
#' @export
#' @importFrom ggnetwork ggnetwork
#' @importFrom ggnetwork geom_nodes
#' @importFrom ggnetwork geom_nodetext_repel
#' @importFrom ggnetwork geom_edges
#' @importFrom ggplot2 guides
#' @importFrom ggplot2 arrow
#' @importFrom ggplot2 scale_alpha
#' @importFrom ggplot2 scale_size_continuous
#' @importFrom ggplot2 unit
#' @importFrom ggplot2 guide_colorbar
plot.assistnet <- function(x, layout="kamadakawai", layout.par=list(),
edge.thr=0, edge.col.lim=NULL, edge.col.lab=NULL,
node.size=NULL, node.size.lab=NULL,
node.col=NULL, node.col.lim=NULL, node.col.lab=NULL,
node.pal=colorRampPalette(c("white","blue", "red")),
edge.pal=colorRampPalette(c("white","blue", "red")), ...) {
if (!is.assistnet(x)) {
stop("Not a 'assistnet' object")
}
y <- xend <- yend <- N <- player <- vertex.names <- NULL
net <- x[["assistNet"]]
tbl <- x[["assistTable"]]
if (!is.null(node.size) & !is.null(node.col)) { ####
if (is.null(node.col.lab)) {
node.col.lab <- paste0("Node color:\n", node.col)
}
if (is.null(node.size.lab)) {
node.size.lab <- paste0("Node size:\n", node.size)
}
nodeData <- x[["nodeStats"]] %>%
dplyr::rename(node.size=!!node.size, node.col=!!node.col) %>%
dplyr::select(player, node.size, node.col)
plyrs1 <- dimnames(tbl)[[1]]
plyrs2 <- as.character(nodeData$player)
idx <- match(plyrs1, plyrs2)
if (any(plyrs1!=plyrs2[idx])) {
stop("Players in 'data' and 'node.data' are not exactly the same.")
}
nodeData <- nodeData[idx,]
network::set.vertex.attribute(net, "node.size", nodeData$node.size)
network::set.vertex.attribute(net, "node.col", nodeData$node.col)
if (is.null(node.col.lim)) {
node.col.lim <- range(nodeData$node.col)
}
}
if (is.null(edge.col.lim)) {
edge.col.lim <- range(tbl)
}
if (is.null(edge.col.lab)) {
edge.col.lab <- "Edge color:\nnumber of assists"
}
datanet <- ggnetwork::ggnetwork(net, layout=layout, layout.par=layout.par) %>%
dplyr::mutate(N = replace(N, N <= edge.thr, NA))
p <- ggplot(datanet, aes(x = x, y = y, xend = xend, yend = yend)) +
ggnetwork::geom_edges(aes(color=N, alpha=N), size=1.5, curvature=0.1,
arrow=ggplot2::arrow(length=unit(6, "pt"), type="closed")) +
scale_colour_gradientn(edge.col.lab, limits=edge.col.lim, colors=edge.pal(100),
na.value="transparent")
if (!is.null(node.size) & !is.null(node.col)) { ####
p <- p +
ggnetwork::geom_nodes(aes(size=node.size, fill=node.col), shape=21, color="gray") +
scale_size_continuous(node.size.lab, breaks=pretty(nodeData$node.size,n=5)) +
scale_fill_gradientn(node.col.lab, limits=node.col.lim, colors=node.pal(100)) +
guides(fill=guide_colorbar(order=1), size=guide_legend(order=3))
} else {
p <- p +
ggnetwork::geom_nodes(size=5, shape=21, alpha=0.5, color="gray", fill="gray")
}
p <- p +
ggnetwork::geom_nodetext_repel(aes(label=vertex.names)) +
scale_alpha(guide=FALSE) +
ggnetwork::theme_blank()
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.assistnet.R
|
#' Plots the correlation matrix and the correlation network from a 'corranalysis' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{corranalysis}.
#' @param horizontal logical; if TRUE, the two plots are arranged horizontally.
#' @param title character, plot title.
#' @param ... other graphical parameters
#' @return A \code{ggplot2} object
#' @seealso \code{\link{corranalysis}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' data <- data.frame(Pbox$PTS,Pbox$P3M,Pbox$P2M,
#' Pbox$OREB + Pbox$DREB,Pbox$AST,
#' Pbox$TOV,Pbox$STL,Pbox$BLK)/Pbox$MIN
#' names(data) <- c("PTS","P3M","P2M","REB","AST","TOV","STL","BLK")
#' data <- subset(data, Pbox$MIN >= 500)
#' out <- corranalysis(data, threshold=0.5)
#' plot(out)
#' @export
#' @method plot corranalysis
#' @importFrom ggplotify as.ggplot
#' @importFrom network network
#' @importFrom network set.edge.attribute
#' @importFrom network "%e%"
#' @importFrom GGally ggnet2
#' @importFrom grDevices colorRampPalette
#' @importFrom graphics par
#' @importFrom graphics plot.new
#' @importFrom graphics plot.window
#' @importFrom graphics points
#' @importFrom graphics polygon
#' @importFrom graphics rect
#' @importFrom graphics segments
#' @importFrom graphics strwidth
#' @importFrom graphics symbols
#' @importFrom graphics text
#' @importFrom graphics plot
#' @importFrom corrplot corrMatOrder
#' @importFrom corrplot corrRect.hclust
#' @importFrom corrplot colorlegend
#' @importFrom ggnetwork geom_nodes
#' @importFrom ggnetwork geom_edges
#' @importFrom ggnetwork ggnetwork
#' @importFrom ggnetwork theme_blank
#' @importFrom ggnetwork geom_nodetext_repel
#' @importFrom ggplot2 scale_alpha
#' @importFrom ggplot2 aes_string
#' @importFrom ggplot2 scale_colour_gradientn
#' @importFrom statnet.common order
plot.corranalysis <- function(x, horizontal = TRUE, title = NULL, ...) {
y <- xend <- yend <- edge.color <- vertex.names <- NULL
corr_plot_mixed <- function(cor_mtx, cor_mtest, sl) {
par(mar = c(0, 0, 0, 0), bg = "white")
corr_plot(cor_mtx, type = "upper", method = "ellipse", diag = F, tl.pos = "n", p.mat = cor_mtest$p, sig.level = sl)
corr_plot(cor_mtx, type = "lower", method = "number", diag = F, add = T, tl.pos = "n", cl.pos = "n", p.mat = cor_mtest$p, sig.level = sl)
}
if (!is.corranalysis(x)) {
stop("Not a 'corranalysis' object")
}
if (horizontal) ncol=2 else ncol=1
cor_mtx <- x[["cor.mtx"]]
cor_mtest <- x[["cor.mtest"]]
sig_lev <- x[["sig.level"]]
cor_mtx_trunc <- x[["cor.mtx.trunc"]]
# Correlation plot
txt <- substitute(corr_plot_mixed(cor_mtx, cor_mtest, 1-sig_lev))
p1 <- ggplotify::as.ggplot(as.expression(txt))
# Network of correlations
allzero <- all(cor_mtx_trunc==0)
if (allzero) {
cor_mtx_trunc[1:2,1:2] <- 0.01
}
net <- network::network(cor_mtx_trunc, matrix.type = "adjacency", ignore.eval = FALSE, names.eval = "weights")
netwt <- (net %e% "weights")
cols <- rev(colorRampPalette(c("#67001F", "#B2182B", "#D6604D",
"#F4A582", "#FDDBC7", "#FFFFFF", "#D1E5F0", "#92C5DE",
"#4393C3", "#2166AC", "#053061"))(200))
if (!allzero) {
network::set.edge.attribute(net, "edge.color", netwt)
datanet <- ggnetwork::ggnetwork(net, layout = "circle")
p2 <- ggplot(datanet, aes(x = x, y = y, xend = xend, yend = yend)) +
ggnetwork::geom_nodes(shape=21, fill="#D6EAF877", color="#3498DB77", size=15) +
ggnetwork::geom_edges(aes(color=edge.color), size=1.5) +
scale_colour_gradientn("", colors = cols, limits=c(-1,1)) +
scale_alpha(guide=FALSE) +
ggnetwork::geom_nodetext_repel(aes(label=vertex.names)) +
ggnetwork::theme_blank()
} else {
datanet <- ggnetwork::ggnetwork(net, layout = "circle")
p2 <- ggplot(datanet, aes(x = x, y = y, xend = xend, yend = yend)) +
ggnetwork::geom_nodes(shape=21, fill="#D6EAF877", color="#3498DB77", size=15) +
ggnetwork::geom_nodetext_repel(aes(label=vertex.names)) +
ggnetwork::theme_blank()
}
listPlot <- list(corrplot = p1, netplot = p2)
gridExtra::grid.arrange(grobs=listPlot, ncol = ncol)
invisible(listPlot)
}
#' @note pure function
#' @noRd
corr_plot <- function (corr, method = c("circle", "square", "ellipse", "number",
"shade", "color", "pie"), type = c("full", "lower", "upper"),
add = FALSE, col = NULL, bg = "white", title = "", is.corr = TRUE,
diag = TRUE, outline = FALSE, mar = c(0, 0, 0, 0), addgrid.col = NULL,
addCoef.col = NULL, addCoefasPercent = FALSE,
order = c("original", "AOE", "FPC", "hclust", "alphabet"),
hclust.method = c("complete","ward", "ward.D", "ward.D2", "single", "average",
"mcquitty","median", "centroid"),
addrect = NULL, rect.col = "black",
rect.lwd = 2, tl.pos = NULL, tl.cex = 1, tl.col = "red",
tl.offset = 0.4, tl.srt = 90, cl.pos = NULL, cl.lim = NULL,
cl.length = NULL, cl.cex = 0.8, cl.ratio = 0.15, cl.align.text = "c",
cl.offset = 0.5, number.cex = 1, number.font = 2, number.digits = NULL,
addshade = c("negative", "positive", "all"), shade.lwd = 1,
shade.col = "white", p.mat = NULL, sig.level = 0.05,
insig = c("pch", "p-value", "blank", "n", "label_sig"),
pch = 4, pch.col = "black", pch.cex = 3, plotCI = c("n", "square", "circle", "rect"),
lowCI.mat = NULL, uppCI.mat = NULL, na.label = "?", na.label.col = "black",
win.asp = 1, ...)
{
method <- match.arg(method)
type <- match.arg(type)
order <- match.arg(order)
hclust.method <- match.arg(hclust.method)
addshade <- match.arg(addshade)
insig <- match.arg(insig)
plotCI <- match.arg(plotCI)
if (win.asp != 1 && !(method %in% c("circle", "square"))) {
stop("Parameter 'win.asp' is supported only for circle and square methods.")
}
asp_rescale_factor <- min(1, win.asp)/max(1, win.asp)
stopifnot(asp_rescale_factor >= 0 && asp_rescale_factor <=
1)
if (!is.matrix(corr) && !is.data.frame(corr)) {
stop("Need a matrix or data frame!")
}
if (is.null(addgrid.col)) {
addgrid.col <- switch(method, color = NA, shade = NA,
"grey")
}
if (any(corr < cl.lim[1]) || any(corr > cl.lim[2])) {
stop("color limits should cover matrix")
}
if (is.null(cl.lim)) {
if (is.corr) {
cl.lim <- c(-1, 1)
}
else {
corr_tmp <- corr
diag(corr_tmp) <- ifelse(diag, diag(corr_tmp), NA)
cl.lim <- c(min(corr_tmp, na.rm = TRUE), max(corr_tmp,
na.rm = TRUE))
}
}
intercept <- 0
zoom <- 1
if (!is.corr) {
c_max <- max(corr, na.rm = TRUE)
c_min <- min(corr, na.rm = TRUE)
if (c_max <= 0) {
intercept <- -cl.lim[2]
zoom <- 1/(diff(cl.lim))
}
else if (c_min >= 0) {
intercept <- -cl.lim[1]
zoom <- 1/(diff(cl.lim))
}
else {
stopifnot(c_max * c_min < 0)
stopifnot(c_min < 0 && c_max > 0)
intercept <- 0
zoom <- 1/max(abs(cl.lim))
}
if (zoom == Inf) {
stopifnot(cl.lim[1] == 0 && cl.lim[2] == 0)
zoom <- 0
}
corr <- (intercept + corr) * zoom
}
cl.lim2 <- (intercept + cl.lim) * zoom
int <- intercept * zoom
if (is.corr) {
if (min(corr, na.rm = TRUE) < -1 - .Machine$double.eps^0.75 ||
max(corr, na.rm = TRUE) > 1 + .Machine$double.eps^0.75) {
stop("The matrix is not in [-1, 1]!")
}
}
if (is.null(col)) {
col <- rev(colorRampPalette(c("#67001F", "#B2182B", "#D6604D",
"#F4A582", "#FDDBC7", "#FFFFFF", "#D1E5F0", "#92C5DE",
"#4393C3", "#2166AC", "#053061"))(200))
}
n <- nrow(corr)
m <- ncol(corr)
min.nm <- min(n, m)
ord <- seq_len(min.nm)
if (order != "original") {
ord <- corrMatOrder(corr, order = order, hclust.method = hclust.method)
corr <- corr[ord, ord]
}
if (is.null(rownames(corr))) {
rownames(corr) <- seq_len(n)
}
if (is.null(colnames(corr))) {
colnames(corr) <- seq_len(m)
}
apply_mat_filter <- function(mat) {
x <- matrix(1:n * m, nrow = n, ncol = m)
switch(type, upper = mat[row(x) > col(x)] <- Inf, lower = mat[row(x) <
col(x)] <- Inf)
if (!diag) {
diag(mat) <- Inf
mat[1, 1] <- 0
mat[nrow(mat), ncol(mat)] <- 0
}
return(mat)
}
getPos.Dat <- function(mat) {
tmp <- apply_mat_filter(mat)
Dat <- tmp[is.finite(tmp)]
ind <- which(is.finite(tmp), arr.ind = TRUE)
Pos <- ind
Pos[, 1] <- ind[, 2]
Pos[, 2] <- -ind[, 1] + 1 + n
return(list(Pos, Dat))
}
getPos.NAs <- function(mat) {
tmp <- apply_mat_filter(mat)
ind <- which(is.na(tmp), arr.ind = TRUE)
Pos <- ind
Pos[, 1] <- ind[, 2]
Pos[, 2] <- -ind[, 1] + 1 + n
return(Pos)
}
Pos <- getPos.Dat(corr)[[1]]
if (any(is.na(corr)) && is.character(na.label)) {
PosNA <- getPos.NAs(corr)
}
else {
PosNA <- NULL
}
AllCoords <- rbind(Pos, PosNA)
n2 <- max(AllCoords[, 2])
n1 <- min(AllCoords[, 2])
nn <- n2 - n1
m2 <- max(AllCoords[, 1])
m1 <- min(AllCoords[, 1])
mm <- max(1, m2 - m1)
expand_expression <- function(s) {
ifelse(grepl("^[:=$]", s), parse(text = substring(s,
2)), s)
}
newrownames <- sapply(rownames(corr)[(n + 1 - n2):(n + 1 -
n1)], expand_expression)
newcolnames <- sapply(colnames(corr)[m1:m2], expand_expression)
DAT <- getPos.Dat(corr)[[2]]
len.DAT <- length(DAT)
rm(expand_expression)
assign.color <- function(dat = DAT, color = col) {
newcorr <- (dat + 1)/2
newcorr[newcorr <= 0] <- 0
newcorr[newcorr >= 1] <- 1 - 1e-16
color[floor(newcorr * length(color)) + 1]
}
col.fill <- assign.color()
isFALSE <- function(x) identical(x, FALSE)
isTRUE <- function(x) identical(x, TRUE)
if (isFALSE(tl.pos)) {
tl.pos <- "n"
}
if (is.null(tl.pos) || isTRUE(tl.pos)) {
tl.pos <- switch(type, full = "lt", lower = "ld", upper = "td")
}
if (isFALSE(cl.pos)) {
cl.pos <- "n"
}
if (is.null(cl.pos) || isTRUE(cl.pos)) {
cl.pos <- switch(type, full = "r", lower = "b", upper = "r")
}
if (isFALSE(outline)) {
col.border <- col.fill
}
else if (isTRUE(outline)) {
col.border <- "black"
}
else if (is.character(outline)) {
col.border <- outline
}
else {
stop("Unsupported value type for parameter outline")
}
oldpar <- par(mar = mar, bg = "white")
on.exit(par(oldpar), add = TRUE)
if (!add) {
plot.new()
xlabwidth <- max(strwidth(newrownames, cex = tl.cex))
ylabwidth <- max(strwidth(newcolnames, cex = tl.cex))
laboffset <- strwidth("W", cex = tl.cex) * tl.offset
for (i in 1:50) {
xlim <- c(m1 - 0.5 - laboffset - xlabwidth * (grepl("l",
tl.pos) | grepl("d", tl.pos)), m2 + 0.5 + mm *
cl.ratio * (cl.pos == "r") + xlabwidth * abs(cos(tl.srt *
pi/180)) * grepl("d", tl.pos)) + c(-0.35, 0.15) +
c(-1, 0) * grepl("l", tl.pos)
ylim <- c(n1 - 0.5 - nn * cl.ratio * (cl.pos == "b") -
laboffset, n2 + 0.5 + laboffset + ylabwidth *
abs(sin(tl.srt * pi/180)) * grepl("t", tl.pos)) +
c(-0.15, 0) + c(0, -1) * (type == "upper" &&
tl.pos != "n") + c(0, 1) * grepl("d", tl.pos)
plot.window(xlim, ylim, asp = 1, xaxs = "i", yaxs = "i")
x.tmp <- max(strwidth(newrownames, cex = tl.cex))
y.tmp <- max(strwidth(newcolnames, cex = tl.cex))
laboffset.tmp <- strwidth("W", cex = tl.cex) * tl.offset
if (max(x.tmp - xlabwidth, y.tmp - ylabwidth, laboffset.tmp -
laboffset) < 0.001) {
break
}
xlabwidth <- x.tmp
ylabwidth <- y.tmp
laboffset <- laboffset.tmp
if (i == 50) {
warning(c("Not been able to calculate text margin, ",
"please try again with a clean new empty window using ",
"{plot.new(); dev.off()} or reduce tl.cex"))
}
}
if (.Platform$OS.type == "windows") {
grDevices::windows.options(width = 7, height = 7 *
diff(ylim)/diff(xlim))
}
plot.window(xlim = xlim, ylim = ylim, asp = win.asp,
xlab = "", ylab = "", xaxs = "i", yaxs = "i")
}
laboffset <- strwidth("W", cex = tl.cex) * tl.offset
symbols(Pos, add = TRUE, inches = FALSE, rectangles = matrix(1,
len.DAT, 2), bg = bg, fg = bg)
if (method == "circle" && plotCI == "n") {
symbols(Pos, add = TRUE, inches = FALSE, circles = asp_rescale_factor *
0.9 * abs(DAT)^0.5/2, fg = col.border, bg = col.fill)
}
if (method == "ellipse" && plotCI == "n") {
ell.dat <- function(rho, length = 99) {
k <- seq(0, 2 * pi, length = length)
x <- cos(k + acos(rho)/2)/2
y <- cos(k - acos(rho)/2)/2
cbind(rbind(x, y), c(NA, NA))
}
ELL.dat <- lapply(DAT, ell.dat)
ELL.dat2 <- 0.85 * matrix(unlist(ELL.dat), ncol = 2,
byrow = TRUE)
ELL.dat2 <- ELL.dat2 + Pos[rep(1:length(DAT), each = 100),
]
polygon(ELL.dat2, border = col.border, col = col.fill)
}
if (is.null(number.digits)) {
number.digits <- switch(addCoefasPercent + 1, 2, 0)
}
stopifnot(number.digits%%1 == 0)
stopifnot(number.digits >= 0)
if (method == "number" && plotCI == "n") {
text(Pos[, 1], Pos[, 2], font = number.font, col = col.fill,
labels = round((DAT - int) * ifelse(addCoefasPercent,
100, 1)/zoom, number.digits), cex = number.cex)
}
NA_LABEL_MAX_CHARS <- 2
if (is.matrix(PosNA) && nrow(PosNA) > 0) {
stopifnot(is.matrix(PosNA))
if (na.label == "square") {
symbols(PosNA, add = TRUE, inches = FALSE, squares = rep(1,
nrow(PosNA)), bg = na.label.col, fg = na.label.col)
}
else if (nchar(na.label) %in% 1:NA_LABEL_MAX_CHARS) {
symbols(PosNA, add = TRUE, inches = FALSE, squares = rep(1,
nrow(PosNA)), fg = bg, bg = bg)
text(PosNA[, 1], PosNA[, 2], font = number.font,
col = na.label.col, labels = na.label, cex = number.cex,
...)
}
else {
stop(paste("Maximum number of characters for NA label is:",
NA_LABEL_MAX_CHARS))
}
}
if (method == "pie" && plotCI == "n") {
symbols(Pos, add = TRUE, inches = FALSE, circles = rep(0.5,
len.DAT) * 0.85, fg = col.border)
pie.dat <- function(theta, length = 100) {
k <- seq(pi/2, pi/2 - theta, length = 0.5 * length *
abs(theta)/pi)
x <- c(0, cos(k)/2, 0)
y <- c(0, sin(k)/2, 0)
cbind(rbind(x, y), c(NA, NA))
}
PIE.dat <- lapply(DAT * 2 * pi, pie.dat)
len.pie <- unlist(lapply(PIE.dat, length))/2
PIE.dat2 <- 0.85 * matrix(unlist(PIE.dat), ncol = 2,
byrow = TRUE)
PIE.dat2 <- PIE.dat2 + Pos[rep(1:length(DAT), len.pie),
]
polygon(PIE.dat2, border = "black", col = col.fill)
}
if (method == "shade" && plotCI == "n") {
symbols(Pos, add = TRUE, inches = FALSE, squares = rep(1,
len.DAT), bg = col.fill, fg = addgrid.col)
shade.dat <- function(w) {
x <- w[1]
y <- w[2]
rho <- w[3]
x1 <- x - 0.5
x2 <- x + 0.5
y1 <- y - 0.5
y2 <- y + 0.5
dat <- NA
if ((addshade == "positive" || addshade == "all") &&
rho > 0) {
dat <- cbind(c(x1, x1, x), c(y, y1, y1), c(x,
x2, x2), c(y2, y2, y))
}
if ((addshade == "negative" || addshade == "all") &&
rho < 0) {
dat <- cbind(c(x1, x1, x), c(y, y2, y2), c(x,
x2, x2), c(y1, y1, y))
}
return(t(dat))
}
pos_corr <- rbind(cbind(Pos, DAT))
pos_corr2 <- split(pos_corr, 1:nrow(pos_corr))
SHADE.dat <- matrix(stats::na.omit(unlist(lapply(pos_corr2,
shade.dat))), byrow = TRUE, ncol = 4)
segments(SHADE.dat[, 1], SHADE.dat[, 2], SHADE.dat[,
3], SHADE.dat[, 4], col = shade.col, lwd = shade.lwd)
}
if (method == "square" && plotCI == "n") {
draw_method_square(Pos, DAT, asp_rescale_factor, col.border,
col.fill)
}
if (method == "color" && plotCI == "n") {
draw_method_color(Pos, col.border, col.fill)
}
draw_grid(AllCoords, addgrid.col)
if (plotCI != "n") {
if (is.null(lowCI.mat) || is.null(uppCI.mat)) {
stop("Need lowCI.mat and uppCI.mat!")
}
if (order != "original") {
lowCI.mat <- lowCI.mat[ord, ord]
uppCI.mat <- uppCI.mat[ord, ord]
}
pos.lowNew <- getPos.Dat(lowCI.mat)[[1]]
lowNew <- getPos.Dat(lowCI.mat)[[2]]
pos.uppNew <- getPos.Dat(uppCI.mat)[[1]]
uppNew <- getPos.Dat(uppCI.mat)[[2]]
if (!method %in% c("circle", "square")) {
stop("Method shoud be circle or square if drawing confidence intervals.")
}
k1 <- (abs(uppNew) > abs(lowNew))
bigabs <- uppNew
bigabs[which(!k1)] <- lowNew[!k1]
smallabs <- lowNew
smallabs[which(!k1)] <- uppNew[!k1]
sig <- sign(uppNew * lowNew)
color_bigabs <- col[ceiling((bigabs + 1) * length(col)/2)]
color_smallabs <- col[ceiling((smallabs + 1) * length(col)/2)]
if (plotCI == "circle") {
symbols(pos.uppNew[, 1], pos.uppNew[, 2], add = TRUE,
inches = FALSE, circles = 0.95 * abs(bigabs)^0.5/2,
bg = ifelse(sig > 0, col.fill, color_bigabs),
fg = ifelse(sig > 0, col.fill, color_bigabs))
symbols(pos.lowNew[, 1], pos.lowNew[, 2], add = TRUE,
inches = FALSE, circles = 0.95 * abs(smallabs)^0.5/2,
bg = ifelse(sig > 0, bg, color_smallabs), fg = ifelse(sig >
0, col.fill, color_smallabs))
}
if (plotCI == "square") {
symbols(pos.uppNew[, 1], pos.uppNew[, 2], add = TRUE,
inches = FALSE, squares = abs(bigabs)^0.5, bg = ifelse(sig >
0, col.fill, color_bigabs), fg = ifelse(sig >
0, col.fill, color_bigabs))
symbols(pos.lowNew[, 1], pos.lowNew[, 2], add = TRUE,
inches = FALSE, squares = abs(smallabs)^0.5,
bg = ifelse(sig > 0, bg, color_smallabs), fg = ifelse(sig >
0, col.fill, color_smallabs))
}
if (plotCI == "rect") {
rect.width <- 0.25
rect(pos.uppNew[, 1] - rect.width, pos.uppNew[, 2] +
smallabs/2, pos.uppNew[, 1] + rect.width, pos.uppNew[,
2] + bigabs/2, col = col.fill, border = col.fill)
segments(pos.lowNew[, 1] - rect.width, pos.lowNew[,
2] + DAT/2, pos.lowNew[, 1] + rect.width, pos.lowNew[,
2] + DAT/2, col = "black", lwd = 1)
segments(pos.uppNew[, 1] - rect.width, pos.uppNew[,
2] + uppNew/2, pos.uppNew[, 1] + rect.width,
pos.uppNew[, 2] + uppNew/2, col = "black", lwd = 1)
segments(pos.lowNew[, 1] - rect.width, pos.lowNew[,
2] + lowNew/2, pos.lowNew[, 1] + rect.width,
pos.lowNew[, 2] + lowNew/2, col = "black", lwd = 1)
segments(pos.lowNew[, 1] - 0.5, pos.lowNew[, 2],
pos.lowNew[, 1] + 0.5, pos.lowNew[, 2], col = "grey70",
lty = 3)
}
}
if (!is.null(p.mat) && insig != "n") {
if (order != "original") {
p.mat <- p.mat[ord, ord]
}
pos.pNew <- getPos.Dat(p.mat)[[1]]
pNew <- getPos.Dat(p.mat)[[2]]
if (insig == "label_sig") {
if (!is.character(pch))
pch <- "*"
place_points <- function(sig.locs, point) {
text(pos.pNew[, 1][sig.locs], pos.pNew[, 2][sig.locs],
labels = point, col = pch.col, cex = pch.cex,
lwd = 2)
}
if (length(sig.level) == 1) {
place_points(sig.locs = which(pNew < sig.level),
point = pch)
}
else {
l <- length(sig.level)
for (i in seq_along(sig.level)) {
iter <- l + 1 - i
pchTmp <- paste(rep(pch, i), collapse = "")
if (i == length(sig.level)) {
locs <- which(pNew < sig.level[iter])
if (length(locs)) {
place_points(sig.locs = locs, point = pchTmp)
}
}
else {
locs <- which(pNew < sig.level[iter] & pNew >
sig.level[iter - 1])
if (length(locs)) {
place_points(sig.locs = locs, point = pchTmp)
}
}
}
}
}
else {
ind.p <- which(pNew > sig.level)
p_inSig <- length(ind.p) > 0
if (insig == "pch" && p_inSig) {
points(pos.pNew[, 1][ind.p], pos.pNew[, 2][ind.p],
pch = pch, col = pch.col, cex = pch.cex, lwd = 2)
}
if (insig == "p-value" && p_inSig) {
text(pos.pNew[, 1][ind.p], pos.pNew[, 2][ind.p],
round(pNew[ind.p], 2), col = pch.col)
}
if (insig == "blank" && p_inSig) {
symbols(pos.pNew[, 1][ind.p], pos.pNew[, 2][ind.p],
inches = FALSE, squares = rep(1, length(pos.pNew[,
1][ind.p])), fg = addgrid.col, bg = bg, add = TRUE)
}
}
}
if (cl.pos != "n") {
colRange <- assign.color(dat = cl.lim2)
ind1 <- which(col == colRange[1])
ind2 <- which(col == colRange[2])
colbar <- col[ind1:ind2]
if (is.null(cl.length)) {
cl.length <- ifelse(length(colbar) > 20, 11, length(colbar) +
1)
}
labels <- seq(cl.lim[1], cl.lim[2], length = cl.length)
if (cl.pos == "r") {
vertical <- TRUE
xlim <- c(m2 + 0.5 + mm * 0.02, m2 + 0.5 + mm * cl.ratio)
ylim <- c(n1 - 0.5, n2 + 0.5)
}
if (cl.pos == "b") {
vertical <- FALSE
xlim <- c(m1 - 0.5, m2 + 0.5)
ylim <- c(n1 - 0.5 - nn * cl.ratio, n1 - 0.5 - nn *
0.02)
}
colorlegend(colbar = colbar, labels = round(labels, 2),
offset = cl.offset, ratio.colbar = 0.3, cex = cl.cex,
xlim = xlim, ylim = ylim, vertical = vertical, align = cl.align.text)
}
if (tl.pos != "n") {
pos.xlabel <- cbind(m1:m2, n2 + 0.5 + laboffset)
pos.ylabel <- cbind(m1 - 0.5, n2:n1)
if (tl.pos == "td") {
if (type != "upper") {
stop("type should be \"upper\" if tl.pos is \"dt\".")
}
pos.ylabel <- cbind(m1:(m1 + nn) - 0.5, n2:n1)
}
if (tl.pos == "ld") {
if (type != "lower") {
stop("type should be \"lower\" if tl.pos is \"ld\".")
}
pos.xlabel <- cbind(m1:m2, n2:(n2 - mm) + 0.5 + laboffset)
}
if (tl.pos == "d") {
pos.ylabel <- cbind(m1:(m1 + nn) - 0.5, n2:n1)
pos.ylabel <- pos.ylabel[1:min(n, m), ]
symbols(pos.ylabel[, 1] + 0.5, pos.ylabel[, 2], add = TRUE,
bg = bg, fg = addgrid.col, inches = FALSE, squares = rep(1,
length(pos.ylabel[, 1])))
text(pos.ylabel[, 1] + 0.5, pos.ylabel[, 2], newcolnames[1:min(n,
m)], col = tl.col, cex = tl.cex, ...)
}
else {
text(pos.xlabel[, 1], pos.xlabel[, 2], newcolnames,
srt = tl.srt, adj = ifelse(tl.srt == 0, c(0.5,
0), c(0, 0)), col = tl.col, cex = tl.cex, offset = tl.offset,
...)
text(pos.ylabel[, 1], pos.ylabel[, 2], newrownames,
col = tl.col, cex = tl.cex, pos = 2, offset = tl.offset,
...)
}
} else {
pos.ylabel <- cbind(m1:(m1 + nn) - 0.5, n2:n1)
pos.ylabel <- pos.ylabel[1:min(n, m), ]
text(pos.ylabel[, 1] + 0.5, pos.ylabel[, 2], newcolnames[1:min(n,
m)], col = tl.col, cex = tl.cex, ...)
}
title(title, ...)
if (!is.null(addCoef.col) && method != "number") {
text(Pos[, 1], Pos[, 2], col = addCoef.col, labels = round((DAT -
int) * ifelse(addCoefasPercent, 100, 1)/zoom, number.digits),
cex = number.cex, font = number.font)
}
if (type == "full" && plotCI == "n" && !is.null(addgrid.col)) {
rect(m1 - 0.5, n1 - 0.5, m2 + 0.5, n2 + 0.5, border = addgrid.col)
}
if (!is.null(addrect) && order == "hclust" && type == "full") {
corrRect.hclust(corr, k = addrect, method = hclust.method,
col = rect.col, lwd = rect.lwd)
}
invisible(corr)
}
#' @note pure function
#' @noRd
draw_method_color <- function (coords, fg, bg)
{
symbols(coords, squares = rep(1, nrow(coords)), fg = fg,
bg = bg, add = TRUE, inches = FALSE)
}
#' @note pure function
#' @noRd
draw_method_square <- function (coords, values, asp_rescale_factor, fg, bg)
{
symbols(coords, add = TRUE, inches = FALSE, squares = asp_rescale_factor *
abs(values)^0.5, bg = bg, fg = fg)
}
#' @note pure function
#' @noRd
draw_grid <- function(coords, fg) {
symbols(coords, add = TRUE, inches = FALSE, fg = fg, bg = NA,
rectangles = matrix(1, nrow = nrow(coords), ncol = 2))
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.corranalysis.R
|
#' Plot possessions, pace, offensive and defensive rating, and Four Factors from a 'fourfactors' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{fourfactors}.
#' @param title character, plot title.
#' @param ... other graphical parameters.
#' @return A list of four \code{ggplot2} plots.
#' @details The height of the bars in the two four factor plots are given by the difference between the team value and the average on the analyzed teams.
#' @seealso \code{\link{fourfactors}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' selTeams <- c(2,6,10,11)
#' FF <- fourfactors(Tbox[selTeams,], Obox[selTeams,])
#' plot(FF)
#' @importFrom ggrepel geom_text_repel
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 labs
#' @importFrom ggplot2 position_dodge
#' @importFrom ggplot2 theme_minimal
#' @method plot fourfactors
#' @export
plot.fourfactors <- function(x, title=NULL, ...) {
if (!is.fourfactors(x)) {
stop("Not a 'fourfactors' object")
}
PACE.Off <- PACE.Def <- ORtg <- DRtg <- Factor <- CentValue <- Value <- NULL
################################
ttl <- "PACE"
if(!is.null(title)) {
ttl <- paste(ttl, "-", title)
}
PACEplot <- ggplot(data=x, aes(x=PACE.Off, y=PACE.Def, label=Team,
text=paste("Team:",Team,"<br>PACE Team:",PACE.Off,"<br>PACE Opp:",PACE.Def))) +
geom_point() +
ggrepel::geom_text_repel(aes(label=Team))+
labs(title=ttl)+
labs(x = "Pace (Possessions per minute) of the Team") +
labs(y = "Pace (Possessions per minute) of the Opponents")
################################
ttl <- "ORtg and DRtg"
if(!is.null(title)) {
ttl <- paste(ttl, "-", title)
}
RTgplot <- ggplot(data=x, aes(x=ORtg, y=DRtg, label=Team,
text=paste("Team:",Team,"<br>Offensive rating:",ORtg,"<br>Defensive rating:",DRtg))) +
geom_point() +
ggrepel::geom_text_repel(aes(label = Team))+
labs(title = ttl)+
labs(x = "Offensive Rating of the Team (ORtg)") +
labs(y = "Offensive Rating of the Opponents (DRtg)")
RTgplot
###
nr <- nrow(x)
Team <- x[["Team"]]
################################
x_lbls <- c("1:eFG% (Off)","2:TO.Off Ratio (Off)","3:REB% (Off)","4:FT Rate (Off)")
ttl <- "Offensive Four Factors"
if(!is.null(title)) {
ttl <- paste(ttl, "-", title)
}
F1.Off <- x[["F1.Off"]]
F2.Off <- x[["F2.Off"]]
F3.Off <- x[["F3.Off"]]
F4.Off <- x[["F4.Off"]]
F1S.Off <- F1.Off - mean(F1.Off)
F2S.Off <- F2.Off - mean(F2.Off)
F3S.Off <- F3.Off - mean(F3.Off)
F4S.Off <- F4.Off - mean(F4.Off)
FFS.Off <- data.frame(Team = rep(Team, 4),
Factor = rep(x_lbls, each=nr),
CentValue = c(F1S.Off,F2S.Off,F3S.Off,F4S.Off),
Value = c(F1.Off,F2.Off,F3.Off,F4.Off))
FFOplot <- ggplot(data=FFS.Off, aes(x=Factor, y=CentValue, fill=Team,
text=paste("Team:",Team,"<br>Factor:",Factor,"<br>Value:",Value))) +
geom_bar(stat="identity", color="black", position=position_dodge()) +
theme_minimal() + labs(title = ttl)
################################
x_lbls <- c("1:eFG% (Def)","2:TO.Off Ratio (Def)","3:REB% (Def)","4:FT Rate (Def)")
ttl <- "Defensive Four Factors"
if(!is.null(title)) {
ttl <- paste(ttl, "-", title)
}
F1.Def <- x[["F1.Def"]]
F2.Def <- x[["F2.Def"]]
F3.Def <- x[["F3.Def"]]
F4.Def <- x[["F4.Def"]]
F1S.Def <- F1.Def - mean(F1.Def)
F2S.Def <- F2.Def - mean(F2.Def)
F3S.Def <- F3.Def - mean(F3.Def)
F4S.Def <- F4.Def - mean(F4.Def)
FFS.Def <- data.frame(Team = rep(Team, 4),
Factor = rep(x_lbls, each=nr),
CentValue = c(F1S.Def,F2S.Def,F3S.Def,F4S.Def),
Value = c(F1.Def,F2.Def,F3.Def,F4.Def))
FFDplot <- ggplot(data=FFS.Def, aes(x=Factor, y=CentValue, fill=Team,
text=paste("Team:",Team,"<br>Factor:",Factor,"<br>Value:",Value))) +
geom_bar(stat="identity", color="black", position=position_dodge()) +
theme_minimal() + labs(title = ttl)
listPlots <- list(PACEplot=PACEplot, RTgplot=RTgplot, FFOplot=FFOplot, FFDplot=FFDplot)
gridExtra::grid.arrange(grobs=listPlots, ncol=2)
invisible(listPlots)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.fourfactors.R
|
#' Plots hierarchical clustering from a 'hclustering' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{hclustering}.
#' @param title character or vector of characters (when plotting radial plots of cluster profiles; see Value), plot title(s).
#' @param profiles logical; if \code{TRUE}, displays radial plots of cluster profiles (active if \code{x$k} is not \code{NULL}; see Value).
#' @param ncol.arrange integer, number of columns when arranging multiple grobs on a page (active when plotting radial plots of cluster profiles; see Value).
#' @param circlize logical; if \code{TRUE}, plots a circular dendrogram (active when plotting a dendrogram; see Value).
#' @param horiz logical; if \code{TRUE}, plots an horizontal dendrogram (active when plotting a non circular dendrogram; see Value).
#' @param cex.labels numeric, the magnification to be used for labels (active when plotting a dendrogram; see Value).
#' @param colored.labels logical; if \code{TRUE}, assigns different colors to labels of different clusters (active when plotting a dendrogram; see Value).
#' @param colored.branches logical; if \code{TRUE}, assigns different colors to branches of different clusters (active when plotting a dendrogram; see Value).
#' @param rect logical; if \code{TRUE}, draws rectangles around the branches in order to highlight the corresponding clusters (active when plotting a dendrogram; see Value).
#' @param lower.rect numeric, a value of how low should the lower part of the rect be (active when plotting a dendrogram; see option \code{lower_rect} of \code{\link[dendextend]{rect.dendrogram}}).
#' @param min.mid.max numeric vector with 3 elements: lower bound, middle dashed line, upper bound for radial axis (active when plotting radial plots of cluster profiles; see Value).
#' @param ... other graphical parameters.
#' @seealso \code{\link{hclustering}}, \code{\link{radialprofile}}.
#' @return If \code{x$k} is \code{NULL}, \code{plot.hclustering} returns a single \code{ggplot2} object, displaying the pattern of the explained variance vs the number of clusters.
#' @return If \code{x$k} is not \code{NULL} and \code{profiles=FALSE}, \code{plot.hclustering} returns a single \code{ggplot2} object, displaying the dendrogram.
#' @return If \code{x$k} is not \code{NULL} and \code{profiles=TRUE}, \code{plot.hclustering} returns a list of \code{ggplot2} objects, displaying the radial plots of the cluster profiles.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' data <- with(Pbox, data.frame(PTS, P3M, REB=OREB+DREB, AST, TOV, STL, BLK, PF))
#' data <- subset(data, Pbox$MIN >= 1500)
#' ID <- Pbox$Player[Pbox$MIN >= 1500]
#' hclu1 <- hclustering(data)
#' plot(hclu1)
#' hclu2 <- hclustering(data, labels=ID, k=7)
#' plot(hclu2)
#' @method plot hclustering
#' @export
#' @importFrom dendextend circlize_dendrogram
#' @importFrom dendextend plot_horiz.dendrogram
#' @importFrom dendextend rect.dendrogram
#' @importFrom dendextend set
#' @importFrom stats as.dendrogram
plot.hclustering <- function(x, title = NULL, profiles=FALSE, ncol.arrange = NULL, circlize=FALSE, horiz=TRUE, cex.labels=0.7, colored.labels=TRUE, colored.branches=FALSE, rect=FALSE, lower.rect=NULL, min.mid.max=NULL, ...) {
if (!is.hclustering(x)) {
stop("Not a 'hclustering' object")
}
circ_dend <- function(dend) {
dendextend::circlize_dendrogram(dend)
}
plot_horiz_dend <- function(dend, k, rect, lower.rect) {
plot.new()
oldmar <- par("mar")
mar <- oldmar
mar[c(1,3)] <- 0
par(mar=mar)
dendextend::plot_horiz.dendrogram(dend, side=T)
if (rect) {
usr <- par("usr")
if (is.null(lower.rect)) lower.rect <- usr[1]-(usr[2]-usr[1])/9
dendextend::rect.dendrogram(dend, k=k, horiz = T, lty=2, lwd=1, border="grey50", lower_rect=lower.rect)
}
par(oldmar)
}
plot_dend <- function(dend, k, rect, lower.rect) {
plot.new()
oldmar <- par("mar")
mar <- oldmar
mar[c(2,3,4)] <- 1
par(mar=mar)
plot(dend)
if (rect) {
usr <- par("usr")
if (is.null(lower.rect)) lower.rect <- usr[3]-(usr[4]-usr[3])/9
dendextend::rect.dendrogram(dend, k=k, horiz = F, lty=2, lwd=1, border="grey50", lower_rect=lower.rect)
}
par(oldmar)
}
y <- label <- NULL
k <- x[["k"]]
if (is.null(k)) {
varfra.nclu <- x[["VarianceBetween"]]
nclumax <- max(x[["ClusterRange"]])
df1 <- data.frame(x = 1:nclumax, y = varfra.nclu * 100)
df2 <- data.frame(x = 3:nclumax, y = round((varfra.nclu[3:nclumax]/varfra.nclu[2:(nclumax - 1)] - 1) * 100, 2))
df2$label <- paste("+", df2$y, "%", sep = "")
df3 <- data.frame(x = 2:nclumax, y = round((varfra.nclu[2:nclumax]) * 100, 2))
df3$label <- paste(df3$y, "%", sep = "")
p <- ggplot(data = df1, aes(x, y)) +
geom_line() +
geom_point(size = 5, colour = "white") +
geom_point(size = 2) +
geom_text(data = df2, aes(x = x, y = y, label = label), vjust = +2) +
geom_line(data = df2, aes(x = x, y = y), linetype = 2) +
geom_point(data = df2, aes(x = x, y = y), size = 6, colour = "white") +
geom_point(data = df2, aes(x = x, y = y), shape = 0, size = 2) +
geom_text(data = df3, aes(x = x, y = y, label = label), vjust = +2) +
scale_x_continuous(breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1))))) +
xlab("Number of clusters") + ylab("BD/TD - Increments") +
theme_bw()
} else {
if (profiles) {
prfls <- x[["Profiles"]]
if (is.null(ncol.arrange)) {
ncol.arrange <- ceiling(sqrt(nrow(prfls)))
}
if (is.null(title)) {
#title <- prfls$clustnames
title <- paste("Cluster", prfls$ID, "- CHI =", prfls$CHI)
} else if (length(title)!=nrow(prfls)) {
stop("The length of 'title' is not equal to the number of clusters")
}
#pos.clst.nm <- which(names(prfls)=="clustnames")
pos.clst.nm <- which(names(prfls) %in% c("ID", "CHI"))
if (is.null(min.mid.max)) {
ming <- min(prfls[, -pos.clst.nm])
maxg <- max(prfls[, -pos.clst.nm])
midg <- 0
min.mid.max <- c(ming,midg,maxg)
}
p <- radialprofile(data = prfls[, -pos.clst.nm], title = title, ncol.arrange = ncol.arrange,
std=FALSE, min.mid.max=min.mid.max)
} else {
hcl <- x[["Hclust"]]
dend <- hcl %>%
stats::as.dendrogram() %>%
dendextend::set("labels_cex", cex.labels)
if (colored.labels) dend <- dend %>% dendextend::set("labels_colors", k=k)
if (colored.branches) {
lbl_clu1 <- x[["Subjects"]]
lbl_clu2 <- dendextend::cutree(hcl, k=k, order_clusters_as_data=FALSE)
lbl_clu1 <- lbl_clu1[match(names(lbl_clu2), row.names(lbl_clu1)),]
tbl <- table(lbl_clu1$Cluster,lbl_clu2)
lbls <- apply(tbl,2,which.max)
dend <- dend %>% dendextend::color_branches(k=k, groupLabels=lbls)
}
if (circlize) {
xpr <- substitute(circ_dend(dend))
p <- ggplotify::as.ggplot(as.expression(xpr))
} else {
if (horiz) {
xpr <- substitute(plot_horiz_dend(dend, k, rect, lower.rect))
p <- ggplotify::as.ggplot(as.expression(xpr))
} else {
xpr <- substitute(plot_dend(dend, k, rect, lower.rect))
p <- ggplotify::as.ggplot(as.expression(xpr))
}
}
p <- p+labs(title=title)
}
}
if (!is.ggplot(p)) {
invisible(p)
} else {
return(p)
}
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.hclustering.R
|
#' Plot Lorenz curve from a 'inequality' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{inequality}.
#' @param title character, plot title.
#' @param ... other graphical parameters.
#' @return A \code{ggplot2} object.
#' @seealso \code{\link{inequality}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' Pbox.BN <- subset(Pbox, Team=="Brooklyn Nets")
#' out <- inequality(Pbox.BN$PTS, nplayers=8)
#' print(out)
#' plot(out)
#' @method plot inequality
#' @export
#' @importFrom ggplot2 geom_ribbon
plot.inequality <- function(x, title = NULL, ...) {
if (!is.inequality(x)) {
stop("Not an object of class 'inequality'")
}
Q <- Qmax <- NULL
if (is.null(title)) {
title <- "Lorenz curve"
}
lor <- x[["Lorenz"]]
gini <- x[["Gini"]]
lor <- 100*lor
lor$Qmax <- c(rep(0,nrow(lor)-1), max(lor$Q))
p <- ggplot(data = lor, aes(F, Q)) +
theme(panel.background = element_rect(fill = "transparent"), plot.title = element_text(size = 12)) +
geom_ribbon(aes(x = F, ymax = F, ymin = Q), fill = "dodgerblue4", alpha = 1) +
geom_line(aes(y = Q), col = "dodgerblue", lwd = 1.2) +
geom_line(aes(y = Qmax), col = "dodgerblue", lwd = 1.2) +
geom_line(aes(y = F), col = "dodgerblue", lwd = 1.2) +
annotate("text", x = 25, y = 80, label = paste("Gini index = ", gini, "%", sep = ""), size = 5) +
labs(title=title, x="", y="")
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.inequality.R
|
#' Plot k-means clustering from a 'kclustering' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{kclustering}.
#' @param title character or vector of characters (when plotting radial plots of cluster profiles; see Value), plot title(s).
#' @param ncol.arrange integer, number of columns when arranging multiple grobs on a page (active when plotting radial plots of cluster profiles; see Value).
#' @param min.mid.max numeric vector with 3 elements: lower bound, middle dashed line, upper bound for radial axis (active when plotting radial plots of cluster profiles; see Value).
#' @param ... other graphical parameters.
#' @seealso \code{\link{kclustering}}, \code{\link{radialprofile}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return If \code{x$k} is \code{NULL}, \code{plot.kclustering} returns a single \code{ggplot2} object, displaying the pattern of the explained variance vs the number of clusters.
#' @return If \code{x$k} is not \code{NULL}, \code{plot.kclustering} returns a list of \code{ggplot2} objects, displaying the radial plots of the cluster profiles.
#' @examples
#' FF <- fourfactors(Tbox,Obox)
#' X <- with(FF, data.frame(OD.Rtg=ORtg/DRtg,
#' F1.r=F1.Def/F1.Off, F2.r=F2.Off/F2.Def,
#' F3.O=F3.Def, F3.D=F3.Off))
#' X$P3M <- Tbox$P3M
#' X$STL.r <- Tbox$STL/Obox$STL
#' kclu1 <- kclustering(X)
#' plot(kclu1)
#' kclu2 <- kclustering(X, k=9)
#' plot(kclu2)
#' @method plot kclustering
#' @export
plot.kclustering <- function(x, title = NULL, ncol.arrange = NULL, min.mid.max = NULL, ...) {
if (!is.kclustering(x)) {
stop("Not a 'kclustering' object")
}
y <- label <- NULL
k <- x[["k"]]
if (is.null(k)) {
varfra.nclu <- x[["VarianceBetween"]]
nclumax <- max(x[["ClusterRange"]])
df1 <- data.frame(x = 1:nclumax, y = varfra.nclu * 100)
df2 <- data.frame(x = 3:nclumax, y = round((varfra.nclu[3:nclumax]/varfra.nclu[2:(nclumax - 1)] - 1) * 100, 2))
df2$label <- paste("+", df2$y, "%", sep = "")
df3 <- data.frame(x = 2:nclumax, y = round((varfra.nclu[2:nclumax]) * 100, 2))
df3$label <- paste(df3$y, "%", sep = "")
p <- ggplot(data = df1, aes(x, y)) +
geom_line() +
geom_point(size = 5, colour = "white") +
geom_point(size = 2) +
geom_line(data = df2, aes(x = x, y = y), linetype = 2) +
geom_point(data = df2, aes(x = x, y = y), size = 6, colour = "white") +
geom_point(data = df2, aes(x = x, y = y), shape = 0, size = 2) +
ggrepel::geom_text_repel(data = df2, aes(x = x, y = y, label = label), vjust = +2) +
ggrepel::geom_text_repel(data = df3, aes(x = x, y = y, label = label), vjust = +2) +
scale_x_continuous(breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1))))) +
xlab("Number of clusters") + ylab("BD/TD - Increments") +
theme_bw()
} else {
profiles <- x[["Profiles"]]
if (is.null(ncol.arrange)) {
ncol.arrange <- ceiling(sqrt(nrow(profiles)))
}
if (is.null(title)) {
#title <- profiles$clustnames
title <- paste("Cluster", profiles$ID, "- CHI =", profiles$CHI)
} else if (length(title)!=nrow(profiles)) {
stop("The length of 'title' is not equal to the number of clusters")
}
#pos.clst.nm <- which(names(profiles)=="clustnames")
pos.clst.nm <- which(names(profiles) %in% c("ID", "CHI"))
if (is.null(min.mid.max)) {
ming <- min(profiles[, -pos.clst.nm])
maxg <- max(profiles[, -pos.clst.nm])
midg <- 0
min.mid.max <- c(ming,midg,maxg)
}
p <- radialprofile(data=profiles[,-pos.clst.nm], title=title, ncol.arrange=ncol.arrange,
std=FALSE, min.mid.max=min.mid.max)
}
if (!is.ggplot(p)) {
invisible(p)
} else {
return(p)
}
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.kclustering.R
|
#' Plot simple regression from a 'simplereg' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an object of class \code{simplereg}.
#' @param labels character, labels for subjects.
#' @param subset an optional vector specifying a subset of observations to be highlighted in the graph or \code{subset='quant'} to highligh observations with coordinates above and below the upper and lower quantiles of the variables on the x- and y-axis (\code{Lx}, \code{Ux}, \code{Ly}, \code{Uy}).
#' @param Lx numeric; if \code{subset='quant'}, lower quantile for the variable on the x-axis (default = 0.01).
#' @param Ux numeric; if \code{subset='quant'}, upper quantile for the variable on the x-axis (default = 0.99).
#' @param Ly numeric; if \code{subset='quant'}, lower quantile for the variable on the y-axis (default = 0.01).
#' @param Uy numeric; if \code{subset='quant'}, upper quantile for the variable on the y-axis (default = 0.99).
#' @param title character, plot title.
#' @param xtitle character, x-axis label.
#' @param ytitle character, y-axis label.
#' @param repel logical, if \code{TRUE} (the default) text labels repel away from each other.
#' @param ... other graphical parameters.
#' @seealso \code{\link{simplereg}}
#' @return A \code{ggplot2} object
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' Pbox.sel <- subset(Pbox, MIN >= 500)
#' X <- Pbox.sel$AST/Pbox.sel$MIN
#' Y <- Pbox.sel$TOV/Pbox.sel$MIN
#' Pl <- Pbox.sel$Player
#' mod <- simplereg(x=X, y=Y, type="lin")
#' plot(mod)
#' @method plot simplereg
#' @export
#' @importFrom stats coef
#' @importFrom stats quantile
#' @importFrom ggplot2 geom_abline
plot.simplereg <- function(x, labels = NULL, subset = NULL, Lx = 0.01, Ux = 0.99, Ly = 0.01,
Uy = 0.99, title = "Simple regression", xtitle = NULL, ytitle = NULL, repel = TRUE, ...) {
if (!is.simplereg(x)) {
stop("Not a 'simplereg' object")
}
label <- y <- NULL
xx <- x[["x"]]
yy <- x[["y"]]
type = x[["type"]]
mod <- x[["Model"]]
R2 <- x[["R2"]]
R2text <- paste(round(R2, 4) * 100, "*'%'", sep = "")
if (!is.null(subset)) {
if (subset[1] == "quant") {
subset <- which(xx < stats::quantile(xx, Lx) | xx > stats::quantile(xx, Ux) | yy <
stats::quantile(yy, Ly) | yy > stats::quantile(yy, Uy))
}
} else if (is.null(subset) & !is.null(labels)) {
subset <- 1:length(xx)
}
if (is.null(labels)) {
labels <- as.character(1:length(xx))
}
df1 <- data.frame(x = xx, y = yy, label = labels)
df2 <- df1[subset, ]
p <- ggplot(data = df1, aes(x = x, y = y)) + geom_point()
if (repel) {
p <- p + geom_text_repel(data = df2, aes(x = x, y = y, label = label), color = "blue")
} else {
p <- p + geom_text(data = df2, aes(x = x, y = y, label = label), color = "blue")
}
if (type == "lin") {
b <- coef(mod)
p <- p + geom_abline(slope = b[2], intercept = b[1], lwd = 1, color = "lightsteelblue4")
if (b[2] > 0) {
lbl <- paste("'Y =", round(b[1], 2), "+", round(b[2], 2), "X'*~~~~~~~~ R^2 ==",
R2text)
} else {
lbl <- paste("'Y =", round(b[1], 2), "-", round(abs(b[2]), 2), "X'*~~~~~~~~ R^2 ==",
R2text)
}
} else if (type == "pol") {
idx <- order(xx)
df3 <- data.frame(x = xx[idx], y = mod$fitted[idx])
lbl <- paste0("R^2 == ", R2text)
p <- p + geom_line(data = df3, aes(x = x, y = y), color = "olivedrab3", lwd = 1)
} else if (type == "ks") {
lbl <- paste0("R^2 == ", R2text)
p <- p + geom_line(aes(x = mod$x, y = mod$y), color = "olivedrab3", lwd = 1)
}
p <- p + annotate(geom = "text", label = lbl, x = Inf, y = Inf, hjust = 1, vjust = -0.5, parse = TRUE) +
coord_cartesian(clip = 'off') +
labs(title = title, x = xtitle, y = ytitle) +
theme_bw()
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.simplereg.R
|
#' Plots a variability diagram from a 'variability' object
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x an aobject of class \code{variability}.
#' @param title character, plot title.
#' @param ylim numeric vector of length two, y-axis limits.
#' @param ylab character, y-axis label.
#' @param size.lim numeric vector of length two, set limits of the bubbles' size scale (see \code{limits} of \code{\link[ggplot2]{scale_size}}).
#' @param max.circle numeric, maximum size of the \code{size} plotting symbol (see \code{range} of \code{\link[ggplot2]{scale_size}}).
#' @param leg.brk numeric vector, breaks for bubbles' size legend (see \code{breaks} of \code{\link[ggplot2]{scale_size}}).
#' @param n.circle integer; if \code{leg.brk=NULL}, set a sequence of about \code{n.circle+1} equally spaced 'round' values which cover the range of the values used to set the bubbles' size.
#' @param leg.pos character or numeric vector of length two, legend position; available options \code{"none"}, \code{"left"}, \code{"right"} (default), \code{"bottom"}, \code{"top"}, or a \code{c(x,y)} numeric vector (\code{x} and \code{y} are coordinates of the legend box; their values should be between 0 and 1; \code{c(0,0)} corresponds to the bottom-left and \code{c(1,1)} corresponds to the top-right position).
#' @param leg.just character or numeric vector of length two; anchor point for positioning legend inside plot (\code{"left"} (default), \code{"center"}, \code{"right"} or two-element numeric vector) or the justification according to the plot area when positioned outside the plot.
#' @param leg.nrow integer, number of rows of the bubbles' size legend.
#' @param leg.title character, title of the bubbles' size legend.
#' @param leg.title.pos character, position of the legend title; available options: \code{"top"} (default for a vertical legend), \code{"bottom"}, \code{"left"} (default for a horizontal legend), or \code{"right"}.
#' @param ... other graphical parameters.
#' @seealso \code{\link{variability}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} object
#' @examples
#' Pbox.BC <- subset(Pbox, Team=="Oklahoma City Thunder" & MIN >= 500,
#' select=c("P2p","P3p","FTp","P2A","P3A","FTA"))
#' out <- variability(data=Pbox.BC, data.var=c("P2p","P3p","FTp"),
#' size.var=c("P2A","P3A","FTA"), weight=TRUE)
#' plot(out, leg.brk=c(10,25,50,100,500,1000), max.circle=30)
#' @method plot variability
#' @export
plot.variability <- function(x, title="Variability diagram", ylim=NULL, ylab=NULL,
size.lim=NULL, max.circle=25, n.circle=4,
leg.brk=NULL, leg.pos="right", leg.just="left",
leg.nrow=NULL, leg.title=NULL, leg.title.pos="top", ...) {
if (!is.variability(x)) {
stop("Not an object of class 'variability'")
}
id <- V1 <- V2 <- NULL
df.data <- x[["data"]]
df.size <- x[["size"]]
weight <- x[["weight"]]
rg <- x[["range"]]
if (!is.null(x$VC)) {
vc <- x[["VC"]]
VC <- TRUE
} else {
VC <- FALSE
}
nc.data <- ncol(df.data)
nc.size <- ncol(df.size)
nr <- nrow(df.data)
if (nc.data == nc.size) {
df3 <- data.frame(id = rep(1:nc.data, each = nr),
V1 = utils::stack(df.data)$values,
V2 = utils::stack(df.size)$values)
} else if (nc.size == 1) {
df3 <- data.frame(id = rep(1:nc.data, each = nr),
V1 = utils::stack(df.data)$values,
V2 = rep(df.size, nc.data))
}
names(df3) <- c("id", "V1", "V2")
if (is.null(ylim)) {
ylim <- range(df3$V1)
}
if (is.null(size.lim)) {
size.lim <- range(df3$V2)
}
if (is.null(leg.brk)) {
leg.brk <- pretty(df3$V2, n=n.circle)
}
if (is.null(leg.title)) {
leg.title <- paste(names(df.size), collapse="\n")
}
p <- ggplot(df3, aes(x=id, y=V1)) +
geom_point(aes(size=V2), shape = 21, colour = "dodgerblue") +
scale_x_continuous(name = "", limits = c(0, nc.data + 1),
breaks = 0:(nc.data + 1),
labels = c("", names(df.data), "")) +
annotate("text", x = 0:nc.data, y = rep(9*ylim[2]/8, nc.data+1),
label = c(" Range: ", round(rg, 2)), size = 4)
if (VC) {
p <- p + annotate("text", x = 0:nc.data, y = rep(10*ylim[2]/8, nc.data+1),
label = c(" VC: ", round(vc, 2)), size = 4)
}
p <- p +
scale_size_continuous(breaks=sort(leg.brk, decreasing=FALSE), limits=size.lim, range=c(1,max.circle)) +
theme(legend.position=leg.pos, legend.justification=leg.just,
#panel.background=element_rect(fill="transparent", colour="gray50"),
#panel.grid.major=element_blank(), panel.grid.minor=element_blank(),
legend.key = element_rect(fill="transparent", colour="transparent")) +
labs(title=title, y=ylab) +
guides(size=guide_legend(title=leg.title, nrow=leg.nrow, title.position=leg.title.pos))
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/plot.variability.R
|
#' Draws radial plots for player profiles
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame.
#' @param perc logical; if \code{perc=TRUE}, \code{std=FALSE} and \code{min.mid.max=NULL}, set axes range between 0 and 100 and set the middle dashed line at 50.
#' @param std logical; if \code{std=TRUE}, variables are preliminarily standardized.
#' @param title character vector, titles for radial plots.
#' @param ncol.arrange integer, number of columns in the grid of arranged plots.
#' @param min.mid.max numeric vector with 3 elements: lower bound, middle dashed line, upper bound for radial axis.
#' @seealso \code{\link{plot.kclustering}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A list of \code{ggplot2} radial plots or, if \code{ncol.arrange=NULL}, a single \code{ggplot2} plot of arranged radial plots
#' @examples
#' data("Pbox")
#' Pbox.PG <- Pbox[1:6,]
#' X <- data.frame(Pbox.PG$P2M, Pbox.PG$P3M, Pbox.PG$OREB+Pbox.PG$DREB,
#' Pbox.PG$AST, Pbox.PG$TO)/Pbox.PG$MIN
#' names(X) <- c("P2M","P3M","REB","AST","TO")
#' radialprofile(data=X, ncol.arrange=3, title=Pbox.PG$Player)
#' @export
#' @importFrom gridExtra grid.arrange
radialprofile <- function(data, perc = FALSE, std = TRUE, title = NULL,
ncol.arrange = NULL, min.mid.max=NULL) {
# Set plot titles
if (is.null(title)) {
group <- 1:nrow(data)
} else {
if (length(title)==nrow(data)) {
group <- factor(title)
} else {
stop("The length of 'title' is not equal to the number of rows of 'data'")
}
}
profile <- cbind(group, data)
# Remove rows with missing values
if (any(is.na(profile[, -1]))) {
rowsNA <- apply(profile[, -1], 1, function(x) any(is.na(x)))
warning(paste("Removed", sum(rowsNA), "rows containing missing values"),
call. = FALSE)
if (length(title) == nrow(profile)) {
title <- title[!rowsNA]
}
profile <- profile[!rowsNA, ]
}
npl <- nrow(profile)
# Set defaults
if (npl == 1 & std == TRUE) {
warning("One subject: std parameter set to FALSE")
std <- FALSE
}
if (std == TRUE) {
profile[, -1] <- scale(profile[, -1])
}
if (is.null(min.mid.max)) {
if (perc & !std) {
ming <- 0
midg <- 50
maxg <- 100
} else if (!perc & std) {
mn <- min(profile[, -1])
mx <- max(profile[, -1])
ming <- -max(mn,mx)
midg <- 0
maxg <- max(mn,mx)
} else {
ming <- min(profile[, -1])
midg <- (min(profile[, -1]) + max(profile[, -1]))/2
maxg <- max(profile[, -1])
}
} else {
ming <- min.mid.max[1]
midg <- min.mid.max[2]
maxg <- min.mid.max[3]
}
# List of radial plots
listggplots <- vector(npl, mode = "list")
for (i in 1:npl) {
X <- profile[i, ]
listggplots[[i]] <- CreateRadialPlot(X, grid.min = ming, grid.mid = midg, grid.max = maxg,
label.gridline.min = F, gridline.mid.colour = "dodgerblue", group.line.width = 0.7,
group.point.size = 2, label.centre.y = F, background.circle.colour = "dodgerblue",
plot.extent.x.sf = 1.2, plot.extent.y.sf = 1.2, titolo = TRUE)
}
names(listggplots) <- profile[, 1]
# Arrange radial plots
if (is.null(ncol.arrange)) {
ncol.arrange - ceiling(sqrt(length(listggplots)))
}
gridExtra::grid.arrange(grobs = listggplots, ncol = ncol.arrange)
invisible(listggplots)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/radialprofile.R
|
#' Draws a scatter plot or a matrix of scatter plots
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data an object of class \code{data.frame}.
#' @param data.var character or numeric vector, name or column number of variables (in \code{data} object) used on the axes of scatter plot(s).
#' @param z.var character or number, name or column number of variable (in \code{data} object) used to assign colors to points (see Details).
#' @param palette color palette (active when plotting a single scatter plot; see Value).
#' @param labels character vector, labels for points (active when plotting a single scatter plot, see Value).
#' @param subset logical or numeric vector, to select a subset of points to be highlighted (active when plotting a single scatter plot; see Value).
#' @param repel_labels logical; if \code{TRUE}, draws text labels of not highlighted points using repelling (active when plotting a single scatter plot; see Value).
#' @param text_label logical; if \code{TRUE}, draws a rectangle behind the labels of highlighted points (active when plotting a single scatter plot; see Value).
#' @param col.subset character, color for the labels and rectangles of highlighted points (active when plotting a single scatter plot; see Value).
#' @param zoom numeric vector with 4 elements; \code{c(xmin,xmax,ymin,ymax)} for the x- and y-axis limits of the plot (active when plotting a single scatter plot; see Value).
#' @param title character, plot title.
#' @param legend logical, if \code{legend=FALSE} legend is removed (active when plotting a single scatter plot with \code{z.var} not \code{NULL}; see Value).
#' @param upper list, may contain the variables \code{continuous}, \code{combo}, \code{discrete}, and \code{na} (active when plotting a matrix of scatter plot; see Value and \code{upper} in \code{\link[GGally]{ggpairs}})
#' @param lower list, may contain the variables \code{continuous}, \code{combo}, \code{discrete}, and \code{na} (active when plotting a matrix of scatter plot; see Value and \code{lower} in \code{\link[GGally]{ggpairs}})
#' @param diag list, may contain the variables \code{continuous}, \code{discrete}, and \code{na} (active when plotting a matrix of scatter plot; see Value and \code{diag} in \code{\link[GGally]{ggpairs}})
#' @return A \code{ggplot2} object with a single scatter plot if \code{length(data.var)=2} or a matrix of scatter plots if \code{length(data.var)>2}.
#' @seealso \code{\link[GGally]{ggpairs}}
#' @details If \code{length(data.var)=2}, the variable specified in \code{z.var} can be numeric or factor; if \code{length(data.var)>2}, the variable specified in \code{z.var} must be a factor.
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' # Single scatter plot
#' Pbox.sel <- subset(Pbox, MIN>= 500)
#' X <- data.frame(AST=Pbox.sel$AST/Pbox.sel$MIN,TOV=Pbox.sel$TOV/Pbox.sel$MIN)
#' X$PTSpm <- Pbox.sel$PTS/Pbox.sel$MIN
#' mypal <- colorRampPalette(c("blue","yellow","red"))
#' scatterplot(X, data.var=c("AST","TOV"), z.var="PTSpm", labels=1:nrow(X), palette=mypal)
#' # Matrix of scatter plots
#' data <- Pbox[1:50, c("PTS","P3M","P2M","OREB","Team")]
#' scatterplot(data, data.var=1:4, z.var="Team")
#' @export
#' @importFrom GGally ggpairs
#' @importFrom ggplot2 is.ggplot
scatterplot <- function(data, data.var, z.var=NULL, palette=NULL, labels=NULL, repel_labels=FALSE, text_label=TRUE,
subset = NULL, col.subset='gray50', zoom = NULL, title = NULL, legend=TRUE,
upper = list(continuous = "cor", combo = "box_no_facet", discrete = "facetbar", na = "na"),
lower=list(continuous = "points", combo = "facethist", discrete = "facetbar", na = "na"),
diag = list(continuous = "densityDiag", discrete = "barDiag", na = "naDiag")) {
x <- y <- z <- NULL
if (!is.data.frame(data)) {
stop("'data' must be a data frame")
} else if (is.data.frame(data) & ncol(data)==1) {
stop("The number of columns in 'data' must be 2 or more")
}
if (is.numeric(data.var)) {
nm.data.vars <- names(data)[data.var]
} else if (is.character(data.var)) {
nm.data.vars <- data.var
} else {
stop("'data.var' must be numeric or character")
}
if (length(z.var)>1) {
stop("The length of 'z.var' must be 1")
}
if (!is.null(z.var)) {
if (is.numeric(z.var)) {
nm.z.var <- names(data)[z.var]
} else if (is.character(z.var)) {
nm.z.var <- z.var
} else {
stop("'z.var' must be numeric or character")
}
}
if (length(data.var)==2) {
df <- data[, data.var]
names(df) <- c("x","y")
if (is.null(z.var)) {
df$text <- paste0(nm.data.vars[1],": ",df$x,"<br>",
nm.data.vars[2],": ",df$y,"<br>")
p <- ggplot(data=df, aes(x=x, y=y, text=text))
} else {
z <- data[, z.var]
if (is.character(z)) {
z <- factor(z)
df$z <- z
} else if (is.factor(z) | is.numeric(z)) {
df$z <- z
}
df$text <- paste0(nm.data.vars[1],": ",df$x,"<br>",
nm.data.vars[2],": ",df$y,"<br>", z.var,": ", z)
p <- ggplot(data=df, aes(x=x, y=y, color=z, text=text))
}
if (!is.null(zoom)) {
xmin <- zoom[1]
xmax <- zoom[2]
ymin <- zoom[3]
ymax <- zoom[4]
p <- p + xlim(c(xmin, xmax)) + ylim(c(ymin, ymax))
}
if (is.null(subset)) { ### if 'subset' is not defined
if (is.null(labels)) {
p <- p + geom_point()
} else {
if (repel_labels) {
p <- p + ggrepel::geom_text_repel(aes(label = labels), size = 3)
} else {
p <- p + geom_text(aes(label = labels), size = 3)
}
}
} else { ### if 'subset' is defined
subset1 <- df[-subset, ]
subset2 <- df[subset, ]
subset1.labels <- labels[-subset]
subset2.labels <- labels[subset]
if (is.null(labels)) {
p <- p + geom_point(data = subset1, size = 3) +
geom_point(data = subset2, size = 4, col = col.subset)
} else {
if (repel_labels) {
p <- p + ggrepel::geom_text_repel(data=subset1, aes(label=subset1.labels),
size = 3)
} else {
p <- p + geom_text(data=subset1, aes(label=subset1.labels),
size = 3)
}
if (text_label) {
p <- p + ggrepel::geom_label_repel(data = subset2, aes(label=subset2.labels),
size = 4, col = col.subset, fontface = 2)
} else {
p <- p + ggrepel::geom_text_repel(data = subset2, aes(label=subset2.labels),
size = 4, col = col.subset, fontface = 2)
}
}
}
if (!is.null(palette) & !is.null(z) & is.factor(z)) {
p <- p + scale_color_manual(name=nm.z.var, values=palette(length(unique(z))))
} else if (!is.null(palette) & !is.null(z) & !is.factor(z)) {
p <- p + scale_color_gradientn(name=nm.z.var, colors=palette(length(unique(z))))
}
p <- p + labs(title=title, x=nm.data.vars[1], y=nm.data.vars[2]) +
theme_bw()
} else if (length(data.var)>2) { ### Matrix of scatter plots ###
if (is.null(z.var)) {
df <- data[, data.var]
p <- GGally::ggpairs(df, title=title,
lower=lower, upper=upper, diag=diag)
} else {
df <- data[, data.var]
df$z <- data[, z.var]
if (is.numeric(z.var)) {
names(df)[ncol(df)] <- names(data)[z.var]
} else {
names(df)[ncol(df)] <- z.var
}
p <- GGally::ggpairs(df, mapping=aes_string(color=names(df)[ncol(df)]), title=title,
lower=lower, upper=upper, diag=diag)
}
}
p <- p + theme_bw()
if (!is.null(z.var) & !legend) {
p <- p + theme(legend.position="none")
}
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/scatterplot.R
|
#' Plots scoring probability of shots as a function of a given variable
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame whose rows are shots and with the following columns: \code{result}, \code{ShotType}, \code{player} (only if the \code{players} argument is not \code{NULL}) and at least one of \code{playlength}, \code{periodTime}, \code{totalTime}, \code{shot_distance} (the column specified in \code{var}, see Details).
#' @param var character, the string giving the name of the numerical variable according to which the scoring probability is estimated. Available options: \code{"playlength"}, \code{"periodTime"}, \code{"totalTime"}, \code{"shot_distance"}.
#' @param shot.type character, the type of shots to be analyzed; available options: \code{"2P"}, \code{"3P"}, \code{"FT"}, \code{"field"}.
#' @param players subset of players to be displayed (optional; it can be used only if the \code{player} column is present in \code{data}).
#' @param bw numeric, the smoothing bandwidth of the kernel density estimator (see \link[stats]{ksmooth}).
#' @param period.length numeric, the length of a quarter in minutes (default: 12 minutes as in NBA).
#' @param xlab character, x-axis label.
#' @param x.range numerical vector or character; available options: \code{NULL} (x-axis range defined by \code{ggplot2}, the default), \code{"auto"} (internally defined x-axis range), or a 2-component numerical vector (user-defined x-axis range).
#' @param title character, plot title.
#' @param palette color palette.
#' @param team character; if \code{TRUE} draws the scoring probability for all the shots in data.
#' @param col.team character, color of the scoring probability line for all the shots in data.
#' @param legend character; if \code{TRUE}, color legend is displayed (only when \code{players} is not \code{NULL}).
#' @details The \code{data} data frame could also be a play-by-play dataset provided that rows corresponding to events different from shots have \code{NA} in the \code{ShotType} variable.
#' @details Required columns:
#' @details * \code{result}, a factor with the following levels: \code{"made"} for made shots, \code{"miss"} for missed shots, and \code{""} for events different from shots
#' @details * \code{ShotType}, a factor with the following levels: \code{"2P"}, \code{"3P"}, \code{"FT"} (and \code{NA} for events different from shots)
#' @details * \code{player}, a factor with the name of the player who made the shot
#' @details * \code{playlength}, a numeric variable with time between the shot and the immediately preceding event
#' @details * \code{periodTime}, a numeric variable with seconds played in the quarter when the shot is attempted
#' @details * \code{totalTime}, a numeric variable with seconds played in the whole match when the shot is attempted
#' @details * \code{shot_distance}, a numeric variable with the distance of the shooting player from the basket (in feet)
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return A \code{ggplot2} plot
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' PbP.GSW <- subset(PbP, team=="GSW" & result!="")
#' players <- c("Kevin Durant","Draymond Green","Klay Thompson")
#' scoringprob(data=PbP.GSW, shot.type="2P", players=players,
#' var="shot_distance", col.team="gray")
#' @export
#' @importFrom stats ksmooth
#' @importFrom grDevices hcl
scoringprob <- function(data, var, shot.type, players=NULL, bw=20, period.length=12, xlab=NULL, x.range="auto", title=NULL,
palette=gg_color_hue, team=TRUE, col.team='dodgerblue', legend=TRUE) {
ShotType <- NULL
if (shot.type=="FT" & (var=="playlength" | var=="shot_distance")) {
print("FT & var: invalid selection")
}
if (is.null(title)) {
title <- shot.type
}
if (is.null(bw)) {
bw <- "nrd0"
}
if (shot.type!="FT" | (var!="playlength" & var!="shot_distance")) {
if (shot.type!="field") {
data <- subset(data, ShotType==shot.type)
} else {
data <- subset(data, ShotType=="2P" | ShotType=="3P")
}
data <- droplev_by_col(data)
data$result01 <- 0
data$result01[data$result=="made"] <- 1
data <- data[, c(var, "result01", "player")]
x <- data[, var]
if (length(x.range)==1 & is.character(x.range)) {
if (x.range=="auto") {
if (var=="playlength") {
xrng <- c(0, 24)
ntks <- 25
} else if (var=="totalTime") {
xrng <- c(0, period.length*4*60)
ntks <- 10
} else if (var=="periodTime") {
xrng <- c(0, period.length*60)
ntks <- 10
} else if (var=="shot_distance") {
xrng <- range(x, na.rm=TRUE)
ntks <- NULL
}
}
} else if (length(x.range)==2 & is.numeric(x.range)) {
xrng <- x.range
if (xrng[1]<min(x,na.rm=T)) xrng[1]=min(x,na.rm=T)
if (xrng[2]>max(x,na.rm=T)) xrng[2]=max(x,na.rm=T)
ntks <- NULL
} else if (is.null(x.range)) {
xrng <- NULL
ntks <- NULL
}
if (var=="playlength") {
if (is.null(xlab)) xlab <- "Play length"
} else if (var=="totalTime") {
if (is.null(xlab)) xlab <- "Total time"
} else if (var=="periodTime") {
if (is.null(xlab)) xlab <- "Period time"
} else if (var=="shot_distance") {
if (is.null(xlab)) xlab <- "Shot distance"
} else {
if (is.null(xlab)) xlab <- var
}
p <- ksplot(data, var=var, bw=bw, xrng=xrng, ntks=ntks, xlab=xlab, title=title, players=players,
legend=legend, palette=palette, team=team, col.team=col.team)
}
return(p)
}
#' @noRd
ksplot <- function(data, var, bw, xrng=NULL, ntks=NULL, players=NULL, xlab=NULL, ylab="Scoring probability", title=NULL,
palette=gg_color_hue, col.team="gray", legend=TRUE, team=TRUE) {
player <- Player <- NULL
x <- data[, var]
y <- data$result01
if (team) {
ksm <- stats::ksmooth(x=x, y=y, bandwidth=bw, kernel='normal')
ksm <- as.data.frame(ksm[c("x", "y")])
ksm$Player <- "Team"
if (!is.null(xrng)) {
ksm <- subset(ksm, x>=xrng[1] & x<=xrng[2])
}
}
npl <- 0
if (!is.null(players)) {
npl <- length(players)
kmslst <- vector(npl+1, mode="list")
for (k in 1:npl) {
playerk <- players[k]
datak <- subset(data, player==playerk)
xk <- datak[, var]
yk <- datak$result01
ksm_k <- stats::ksmooth(x=xk, y=yk, bandwidth=bw, kernel='normal')
ksm_k <- as.data.frame(ksm_k[c("x", "y")])
ksm_k$Player <- playerk
if (!is.null(xrng)) {
ksm_k <- subset(ksm_k, x>=xrng[1] & x<=xrng[2])
}
kmslst[[k]] <- ksm_k
}
if (team) kmslst[[npl+1]] <- ksm
ksm <- do.call(rbind, kmslst)
players <- sort(unique(ksm$Player))
cols <- palette(length(players))
cols[players=="Team"] <- col.team
p <- ggplot(ksm, aes(x=x, y=y, color=Player)) +
geom_line(size=1.5) +
scale_color_manual(values=cols, breaks=players)
} else {
p <- ggplot(ksm, aes(x=x, y=y)) +
geom_line(color = col.team, size=1.5)
}
p <- p + labs(title = title) +
scale_y_continuous(name=ylab) +
theme_bw()
if (!is.null(ntks) & !is.null(xrng)) {
p <- p + scale_x_continuous(name=xlab, limits=c(xrng[1], xrng[2]),
breaks=seq(xrng[1],xrng[2],length.out=ntks),
labels=seq(xrng[1],xrng[2],length.out=ntks))
} else if (is.null(ntks) & !is.null(xrng)) {
p <- p + xlim(xrng) + xlab(xlab)
} else {
p <- p + xlab(xlab)
}
if (!legend) {
p <- p + theme(legend.position="none")
}
return(p)
}
#' @noRd
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
grDevices::hcl(h = hues, l = 65, c = 100)[1:n]
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/scoringprob.R
|
#' Plots different kinds of charts based on shot coordinates
#'
#' @param data A data frame whose rows are field shots and columns are half-court shot coordinates x and y, and optionally additional variables to be specified in \code{z} and/or \code{result} (see Details).
#' @param x character, indicating the variable name of the x coordinate.
#' @param y character, indicating the variable name of the y coordinate.
#' @param z character, indicating the name of the variable used to color the points (if \code{type=NULL}) or the sectors (if \code{type="sectors"}, in this case \code{z} must be a numeric variable).
#' @param z.fun function (active when \code{type="sectors"}), used to summarize the values of \code{z} variable within each sector (recommended: \code{mean}, \code{median}).
#' @param result character (active when \code{type="sectors"} and \code{scatter=FALSE}), indicating the name of the factor with the shot result (allowed categories \code{made} and \code{missed}).
#' @param type character, indicating the plot type; available option are \code{NULL}, \code{"sectors"}, \code{"density-polygons"}, \code{"density-raster"}, \code{"density-hexbin"}.
#' @param scatter logical, if TRUE a scatter plot of the shots is added to the plot.
#' @param num.sect integer (active when \code{type="sectors"}), number of sectors.
#' @param n integer (active when \code{type="sectors"}), number of points used to draw arcs (must be > 500).
#' @param col.limits numeric vector, (active when \code{z} is a numeric variable), limits \code{c(min, max)} for the gradient color scale of \code{z} variable.
#' @param courtline.col color of court lines.
#' @param sectline.col color of sector lines (active when \code{type="sectors"}).
#' @param text.col color of text annotation within sectors (active when \code{type="sectors"}).
#' @param pt.col color of points in the scatter plot.
#' @param bg.col background color.
#' @param legend logical, if TRUE a legend for \code{z} is plotted.
#' @param drop.levels logical, if TRUE unused levels of the \code{z} variable are dropped.
#' @param palette color palette; available options \code{"main"}, \code{"cool"}, \code{"hot"}, \code{"mixed"}, \code{"grey"}, \code{"bwr"} (blue, white, red).
#' @param pt.alpha numeric, transparency of points in the scatter plot.
#' @param nbins integer (active when \code{type="density-hexbin"}), number of bins.
#' @return A ggplot2 object.
#' @details The \code{data} dataframe could also be a play-by-play dataset provided that rows corresponding to events different from field shots have missing \code{x} and \code{y} coordinates.
#' @details \code{x} and \code{y} coordinates must be expressed in feets; the origin of the axes is positioned at the center of the field.
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @seealso \code{\link{drawNBAcourt}}, \code{\link[ggplot2]{geom_density_2d}}, \code{\link[ggplot2]{geom_hex}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @examples
#' PbP <- PbPmanipulation(PbP.BDB)
#' subdata <- subset(PbP, player=="Kevin Durant")
#' subdata$xx <- subdata$original_x/10
#' subdata$yy <- subdata$original_y/10-41.75
#' shotchart(data=subdata, x="xx", y="yy", scatter=TRUE)
#' shotchart(data=subdata, x="xx", y="yy", scatter=TRUE, z="result")
#' shotchart(data=subdata, x="xx", y="yy", scatter=TRUE, z="result",
#' bg.col="black", courtline.col="white", palette="hot")
#' shotchart(data=subdata, x="xx", y="yy", result="result",
#' type="sectors", sectline.col="gray", text.col="red")
#' shotchart(data=subdata, x="xx", y="yy", z="playlength", result="result",
#' type="sectors", num.sect=5)
#' shotchart(data=subdata, x="xx", y="yy", type="density-polygons", palette="bwr")
#' shotchart(data=subdata, x="xx", y="yy", type="density-raster",
#' scatter=TRUE, pt.col="tomato", pt.alpha=0.1)
#' shotchart(data=subdata, x="xx", y="yy", type="density-hexbin", nbins=30)
#' @export
#' @importFrom ggplot2 scale_color_manual
#' @importFrom ggplot2 scale_fill_manual
#' @importFrom ggplot2 scale_color_gradientn
#' @importFrom ggplot2 scale_fill_distiller
#' @importFrom ggplot2 stat_density_2d
#' @importFrom ggplot2 geom_hex
#' @importFrom ggplot2 theme_void
#' @importFrom ggplot2 coord_fixed
#' @importFrom ggplot2 guides
#' @importFrom ggplot2 ggplot_build
#' @importFrom PBSmapping as.PolySet
#' @importFrom PBSmapping calcCentroid
#' @importFrom sp point.in.polygon
#' @importFrom stats median
shotchart <- function(data, x, y, z=NULL, z.fun=median, result=NULL,
type=NULL, scatter=FALSE, num.sect=7, n=1000, col.limits=c(NA,NA),
courtline.col = "black", bg.col="white", sectline.col="white", text.col="white",
legend=FALSE, drop.levels=TRUE,
pt.col="black", pt.alpha=0.5, nbins=25, palette="mixed") {
if (num.sect<4) {
stop("The number of sectors 'num.sect' must be >=4")
}
if (n<500) {
stop("The number of points 'n' must be >=500")
}
fancy_scientific <- function(l) {
l <- format(l, digits=3, scientific = TRUE)
l <- gsub("^(.*)e", "'\\1'e", l)
l <- gsub("e", "%*%10^", l)
parse(text=l)
}
X <- Y <- angle <- nsegm <- sector <- ..density.. <- ..level.. <- NULL
pal <- BbA_pal(palette=palette)
df1 <- data.frame(x=data[,x], y=data[,y], z=data[,z], result=data[,result])
filt.na <- !apply(df1, 1, function(x) any(is.na(x)))
df1 <- subset(df1, filt.na & y<=0)
list_sects <- generateSectors(num.sect, npts=n)
sects <- list_sects[[1]]
if (is.null(type) & !scatter) { ##################
p <- ggplot(data=data.frame(x=0,y=0), aes(x,y))
p <- drawNBAcourt(p, full=FALSE, size=0.75, col=courtline.col) +
coord_fixed() + themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
} else if (is.null(type) & scatter) { ##################
p <- ggplot(data=data.frame(x=0,y=0), aes(x,y))
p <- drawNBAcourt(p, full=FALSE, size=0.75, col=courtline.col)
if (is.null(z)) {
p <- p + geom_point(data=df1, aes(x=x, y=y), fill=pt.col, color=pt.col, alpha=pt.alpha,
shape=21, size=3, inherit.aes=FALSE)
} else {
p <- p + geom_point(data=df1, aes(x=x, y=y, fill=z, color=z), alpha=pt.alpha,
shape=21, size=3, inherit.aes=FALSE)
zvar <- df1$z
if (is.factor(zvar)) {
if (drop.levels) {
ncols <- length(unique(droplevels(zvar)))
cols <- rev(pal(ncols))
p <- p +
scale_fill_manual(name=z, values=cols, drop=TRUE) +
scale_color_manual(name=z, values=cols, drop=TRUE)
} else {
ncols <- length(table(zvar))
cols <- rev(pal(ncols))
p <- p +
scale_fill_manual(name=z, values=cols, drop=FALSE) +
scale_color_manual(name=z, values=cols, drop=FALSE)
}
} else {
p <- p +
scale_fill_gradientn(name=z, colours = pal(256), limits=col.limits) +
scale_color_gradientn(name=z, colours = pal(256), limits=col.limits)
}
}
p <- p + coord_fixed() + themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
} else if (type=="sectors") { ##################
stats_by_sect <- sapply(sort(unique(sects$sector)), function(k) {
sectk <- subset(sects, sector==k)
filtk <- sp::point.in.polygon(point.x=df1$x, point.y=df1$y, pol.x=sectk$x, pol.y=sectk$y)==1
mnk <- if (!is.null(z)) z.fun(df1$z[filtk], na.rm=T) else NA
totk <- sum(filtk)
madek <- sum(df1$result[filtk]=="made")
pctk <- round(100*madek/totk)
c(mnk,madek,totk,pctk)
})
sects$z <- stats_by_sect[1,][sects$sector+1]
sects$pos <- unlist(sapply(unique(sects$sector), function(k) {
x <- subset(sects, sector==k)
return(1:nrow(x))
}))
s <- PBSmapping::as.PolySet(data.frame(X=sects$x, Y=sects$y, POS=sects$pos, PID=sects$sector))
centroids <- data.frame(PBSmapping::calcCentroid(s),
text=paste0(stats_by_sect[4,],"%\n (",stats_by_sect[2,],"/",stats_by_sect[3,],")"))
centroids$angle <- rep(0, nrow(centroids))
centroids$angle[4] <- 90
centroids$angle[nrow(centroids)] <- -90
p <- ggplot(data=data.frame(x=0,y=0), aes(x,y))
if (!is.null(z)) {
p <- p + geom_polygon(data=sects, aes(x=x, y=y, group=sector, fill=z)) +
scale_fill_gradientn(name=z, colours = pal(256), limits=col.limits)
} else {
if (bg.col==text.col | bg.col==sectline.col) warning("Using this color setting, sector lines and/or text annotations are not visible. Set different bg.col, sectline.col, text.col.")
}
p <- drawNBAcourt(p, full=FALSE, size=1, col=courtline.col) +
themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
if (scatter) {
p <- p + geom_point(data=df1, aes(x=x, y=y), color=pt.col, alpha=pt.alpha,
shape=21, size=3, fill=pt.col, inherit.aes=FALSE)
} else if (!scatter & !is.null(result)) {
p <- p + geom_text(data=centroids, aes(x=X,y=Y, label=text, angle=angle), col=text.col)
}
p <- p +
geom_line(data=list_sects[[2]], aes(x=x, y=y, group=nsegm), size=0.8,
color=sectline.col, alpha=0.75, inherit.aes=FALSE)+
geom_line(data=list_sects[[3]], aes(x=x, y=y), size=0.8,
color=sectline.col, alpha=0.75, inherit.aes=FALSE) +
coord_fixed() + themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
} else if (type=="density-polygons") { ##################
p <- ggplot(data=df1, aes(x=x, y=y)) +
stat_density_2d(aes(fill = ..level..), geom = "polygon", colour="white") +
scale_fill_gradientn(name="Density\n(log)", colours = pal(256), trans='log', labels=fancy_scientific)
if (scatter) {
p <- p + geom_point(data=df1, aes(x=x, y=y), fill=pt.col,
color=pt.col, alpha=pt.alpha, shape=21, size=3, inherit.aes=FALSE)
}
p <- drawNBAcourt(p, full=FALSE, size=1, col=courtline.col)
p <- p + themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
if (!legend) {
p <- p + theme(legend.position = 'none')
}
plot_xrange <- ggplot_build(p)$layout$panel_params[[1]]$x.range
plot_yrange <- ggplot_build(p)$layout$panel_params[[1]]$y.range
p <- p + scale_x_continuous(limits = plot_xrange * 1.25) +
scale_y_continuous(limits = plot_yrange * 1.25) +
coord_fixed(xlim=plot_xrange, ylim=plot_yrange)
} else if (type=="density-raster") { ##################
p <- ggplot(data=df1, aes(x=x, y=y)) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = F) +
scale_fill_distiller(palette="Spectral", direction=-1, labels=fancy_scientific)
if (scatter) {
p <- p + geom_point(data=df1, aes(x=x, y=y), fill=pt.col, color=pt.col,
alpha=pt.alpha, shape=21, size=3, inherit.aes=FALSE)
}
p <- drawNBAcourt(p, full=FALSE, size=1, col=courtline.col)
p <- p + coord_fixed()+ themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
if (!legend) {
p <- p + theme(legend.position = 'none')
}
} else if (type=="density-hexbin") { ##################
p <- ggplot(data=df1, aes(x=x, y=y)) +
geom_hex(bins=nbins) +
scale_fill_gradientn(name="Density\n(log)", colours = pal(256), trans='log', labels=fancy_scientific)
if (scatter) {
p <- p + geom_point(data=df1, aes(x=x, y=y), fill=pt.col, color=pt.col,
alpha=pt.alpha, shape=21, size=3, inherit.aes=FALSE)
}
p <- drawNBAcourt(p, full=FALSE, size=1, col=courtline.col)
p <- p + coord_fixed() + themeBbA(plot.bgcolor=bg.col, legend.bgcolor=bg.col)
if (!legend) {
p <- p + theme(legend.position = 'none')
}
} else { ##############
stop("Please, select a valid plot type and/or a scatter plot")
}
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/shotchart.R
|
#' Simple linear and nonparametric regression
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param x numerical vector, input x values.
#' @param y numerical vector, input y values.
#' @param type character, type of regression; available options are: \code{lin} (linear regression, the default), \code{pol} (local polynomial regression of degree 2), \code{ks} (nonparametric kernel smoothing).
#' @param sp numeric, parameter to control the degree of smoothing; span for local polynomial regression and bandwidth for ksmooth.
#' @seealso \code{\link{loess}}, \code{\link{ksmooth}}
#' @references P. Zuccolotto and M. Manisera (2020) Basketball Data Science: With Applications in R. CRC Press.
#' @return An object of class \code{simplereg}, i.e. a list with the following objects:
#' @return * \code{Model}, the output model (linear regression, local polynomial regression, or kernel smoothing)
#' @return * \code{R2}, (in-sample) coefficient of determination
#' @return * \code{x}, input x values
#' @return * \code{y}, input y values
#' @return * \code{type}, type of regression
#' @examples
#' Pbox.sel <- subset(Pbox, MIN >= 500)
#' X <- Pbox.sel$AST/Pbox.sel$MIN
#' Y <- Pbox.sel$TOV/Pbox.sel$MIN
#' Pl <- Pbox.sel$Player
#' mod <- simplereg(x=X, y=Y, type="lin")
#' @export
#' @importFrom stats ksmooth
#' @importFrom stats var
#' @importFrom stats lm
simplereg <- function(x, y, type = "lin", sp = NULL) {
lin <- function(x, y) {
mod <- stats::lm(y ~ x)
b <- mod$coefficients
R2 <- cor(x, y)^2
return(list(Model = mod, R2 = R2, x = x, y = y, type = type))
}
pol <- function(x, y) {
if (is.null(sp)) {
mod <- loess(y ~ x, control = loess.control(surface = "direct"), degree = 2)
} else {
mod <- loess(y ~ x, control = loess.control(surface = "direct"), degree = 2,
span = sp)
}
R2 <- 1 - stats::var(mod$residuals)/var(y)
return(list(Model = mod, R2 = R2, x = x, y = y, type = type))
}
ks <- function(x, y) {
if (is.null(sp)) {
mod <- stats::ksmooth(x, y, kernel = "normal", x.points = x)
} else {
mod <- stats::ksmooth(x, y, kernel = "normal", x.points = x, bandwidth = sp)
}
ord <- order(x)
yoss <- y[ord]
res <- yoss - mod$y
R2 <- 1 - stats::var(res)/var(y)
return(list(Model = mod, R2 = R2, x = x, y = y, type = type))
}
lst <- switch(type, lin = lin(x, y), pol = pol(x, y), ks <- ks(x, y))
class(lst) <- append("simplereg", class(lst))
return(lst)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/simplereg.R
|
#' @noRd
themeBbA <- function(plot.bgcolor=NULL, legend.bgcolor=NULL) {
if (!is.null(plot.bgcolor)) {
plot.elem.bckgrnd <- element_rect(fill=plot.bgcolor)
} else {
plot.elem.bckgrnd <- element_blank()
}
if (!is.null(legend.bgcolor)) {
legend.elem.bckgrnd <- element_rect(fill=legend.bgcolor, colour="transparent")
} else {
legend.elem.bckgrnd <- element_blank()
}
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.background=plot.elem.bckgrnd,
legend.key=legend.elem.bckgrnd)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/themeBbA.R
|
#' Variability analysis
#'
#' @author Marco Sandri, Paola Zuccolotto, Marica Manisera (\email{[email protected]})
#' @param data a data frame.
#' @param data.var a vector of variable names or of column numbers defining (numeric) variables whose variability will be analyzed by \code{variability}.
#' @param size.var a vector of variable names or of column numbers defining variables for weights (active only if \code{weight=TRUE}).
#' @param VC logical; if \code{TRUE}, calculates variation coefficients of variables in \code{data.var}.
#' @param weight logical; if TRUE, calculates weighted variation coefficients and standard deviations.
#' @return A list with the following elements: ranges, standard deviations, variation coefficients, and two dataframes (data, size).
#' @examples
#' Pbox.BC <- subset(Pbox, Team=="Oklahoma City Thunder" & MIN >= 500,
#' select=c("P2p","P3p","FTp","P2A","P3A","FTA"))
#' list_variability <- variability(data=Pbox.BC, data.var=c("P2p","P3p","FTp"),
#' size.var=c("P2A","P3A","FTA"), weight=TRUE)
#' print(list_variability)
#' plot(list_variability, leg.brk=c(10,25,50,100,500,1000), max.circle=30)
#' @export
variability <- function(data, data.var, size.var, VC=TRUE, weight = FALSE) {
cvfun <- function(x, VC) {
mn <- mean(x, na.rm=TRUE)
s = sqrt(mean((x-mn)^2, na.rm=TRUE)) # Population SD
rg <- max(x, na.rm=TRUE) - min(x, na.rm=TRUE)
if (VC) {
cv = s/abs(mn)
c(s, rg, cv)
} else {
c(s, rg)
}
}
wcvfun <- function(x, w) {
wmean <- stats::weighted.mean(x, w)
wsd <- sqrt(stats::weighted.mean(x^2, w) - wmean^2)
rg <- max(x) - min(x)
c(wsd, rg, wsd/abs(wmean))
}
data <- stats::na.omit(data)
if (is.character(data.var) & is.character(size.var)) {
sel.data.var <- names(data) %in% data.var
if (all(!sel.data.var))
stop(paste(data.var, "not column(s) of 'data'"))
sel.size.var <- names(data) %in% size.var
if (all(!sel.size.var))
stop(paste(size.var, "not column(s) of 'data'"))
df.data <- data[, sel.data.var, drop = F]
df.size <- data[, sel.size.var, drop = F]
} else if (is.numeric(data.var) & is.numeric(size.var)) {
df.data <- data[, data.var, drop = F]
df.size <- data[, size.var, drop = F]
}
nc.data <- ncol(df.data)
nc.size <- ncol(df.size)
if ((nc.data!=nc.size & nc.size!=1)) {
stop("'data.var' and 'size.var' must have the same number of elements")
}
if (weight) {
if (nc.data == nc.size) {
mtx <- mapply(wcvfun, df.data, df.size)
} else if (nc.size == 1) {
mtx <- apply(df.data, 2, wcvfun, w = df.size[, 1])
}
} else {
mtx <- apply(df.data, 2, cvfun, VC=VC)
}
if (VC) {
lst <- list(weight = weight, SD = mtx[1, ], range = mtx[2, ], VC = mtx[3, ], data = df.data, size = df.size)
} else {
lst <- list(weight = weight, SD = mtx[1, ], range = mtx[2, ], data = df.data, size = df.size)
}
class(lst) <- append("variability", class(lst))
return(lst)
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/variability.R
|
.onAttach <- function(libname, pkgname) {
packageStartupMessage(
'\nIf you want to reproduce the figures contained in the book of\nZuccolotto and Manisera (2020) and\nif the version of your R machine is >= 3.6.0, you need to type\nRNGkind(sample.kind = "Rounding")\nat the beginning of your working session')
}
|
/scratch/gouwar.j/cran-all/cranData/BasketballAnalyzeR/R/zzz.R
|
makeAlgorithm = function(id, fun) {
setClasses(list(id = id, fun = fun), "Algorithm")
}
#' @title Add an algorithm to registry.
#'
#' @description
#' Add an algorithm to registry and stores it on disk.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Name of algorithm.
#' @param fun [\code{function(job, static, dynamic, ...)}]\cr
#' Function which applies the algorithm to a problem instance.
#' Takes a \code{\link[BatchJobs]{Job}} object, the \code{static} problem part and the evaluated \code{dynamic}
#' problem part as arguments.
#' You may omit any of \code{job}, \code{static} or \code{dynamic}.
#' In this case, the respective arguments will not get passed to \code{fun}.
#' Further parameters from \link{Design} are passed to ... argument.
#' If you are using multiple result files this function must return a named list.
#'
#' To retrieve job informations from the \code{job} object
#' see the documentation on \link{ExperimentJob}.
#' @param overwrite [\code{logical(1)}]\cr
#' Overwrite the algorithm file if it already exists?
#' Default is \code{FALSE}.
#' @return [\code{character(1)}]. Invisibly returns the id.
#' @aliases Algorithm
#' @family add
#' @export
addAlgorithm = function(reg, id, fun, overwrite = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = TRUE)
checkIdValid(id)
assertFlag(overwrite)
if (id %in% dbGetAllProblemIds(reg))
stopf("Problem with same id as your algorithm already exists: %s", id)
if (!overwrite && id %in% dbGetAllAlgorithmIds(reg))
stopf("Algorithm with same id already exists and overwrite = FALSE: %s", id)
algorithm = makeAlgorithm(id, fun)
fn = getAlgorithmFilePath(reg$file.dir, id)
info("Writing algorithm file: %s", fn)
save(file = fn, algorithm)
dbAddAlgorithm(reg, id)
invisible(id)
}
#' @export
print.Algorithm = function(x, ...) {
cat("Algorithm:", x$id, "\n")
}
loadAlgorithm = function(reg, id) {
load2(getAlgorithmFilePath(reg$file.dir, id), "algorithm")
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/Algorithm.R
|
#' @title ExperimentJob
#'
#' @description
#' You can access job properties using the \code{job} object which is optionally passed
#' to dynamic problem functions and algorithms. The object is a named list with the following
#' elements:
#' \describe{
#' \item{\code{id} [\code{integer(1)}]:}{Job ID.}
#' \item{\code{prob.id} [\code{character(1)}]:}{Problem ID.}
#' \item{\code{prob.pars} [\code{list}]:}{Problem parameters as named list.}
#' \item{\code{algo.id} [\code{character(1)}]:}{algo.id}{Algorithm ID.}
#' \item{\code{algo.pars} [\code{list}]:}{Algorithm parameters as named list.}
#' \item{\code{repl} [\code{integer(1)}]:}{Replication number of this experiment.}
#' \item{\code{seed} [\code{integer(1)}]:}{Seed set right before algorithm execution.}
#' \item{\code{prob.seed} [\code{integer(1)}]:}{Seed set right before generation of problem instance.}
#' }
#' @name ExperimentJob
#' @rdname ExperimentJob
NULL
makeExperimentJob = function(id = NA_integer_, prob.id, prob.pars, algo.id, algo.pars, repl, seed, prob.seed) {
setClasses(list(id = id, prob.id = prob.id, prob.pars = prob.pars, algo.id = algo.id,
algo.pars = algo.pars, repl = repl, seed = seed, prob.seed = prob.seed),
c("ExperimentJob", "Job"))
}
#' @export
print.ExperimentJob = function(x, ...) {
cat("Experiment:", "\n")
cat(" Problem:", x$prob.id, "\n")
cat(" Problem parameters:", convertToShortString(x$prob.pars), "\n")
cat(" Algorithm:", x$algo.id, "\n")
cat(" Algorithm parameters:", convertToShortString(x$algo.pars), "\n")
cat(" Replication:", x$repl, "\n")
cat(" Seed:", x$seed, "\n")
cat(" Problem seed:", x$prob.seed, "\n")
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/Experiment.R
|
#' @title Construct a registry object for experiments.
#'
#' @description
#' Note that if you don't want links in your paths (\code{file.dir}, \code{work.dir}) to get resolved and have
#' complete control over the way the path is used internally, pass an absolute path which begins with \dQuote{/}.
#'
#' Every object is a list that contains the passed arguments of the constructor.
#
#' @param id [\code{character(1)}]\cr
#' Name of registry. Displayed e.g. in mails or in cluster queue.
#' Default is \dQuote{BatchExperimentRegistry}.
#' @param file.dir [\code{character(1)}]\cr
#' Path where files regarding the registry / jobs should be saved.
#' Default is dQuote{<name of registry>_files} in current working directory.
#' @param sharding [\code{logical(1)}]\cr
#' Enable sharding to distribute result files into different subdirectories?
#' Important if you have many experiments.
#' Default is \code{TRUE}.
#' @param work.dir [\code{character(1)}]\cr
#' Working directory for R process when experiment is executed.
#' Default is the current working directory when registry is created.
#' @param multiple.result.files [\code{logical(1)}]\cr
#' Should a result file be generated for every list element of the
#' returned list of the algorithm function?
#' Note that your algorithm functions in \code{\link{addAlgorithm}} must
#' return named lists if this is set to \code{TRUE}.
#' The result file will be named \dQuote{<id>-result-<element name>.RData}
#' instead of \dQuote{<id>-result.RData}.
#' Default is \code{FALSE}.
#' @param seed [\code{integer(1)}]\cr
#' Start seed for experiments. The first experiment in the registry will use this
#' seed, for the subsequent ones the seed is incremented by 1.
#' Default is a random number from 1 to \code{.Machine$integer.max/2}.
#' @param packages [\code{character}]\cr
#' Packages that will always be loaded on each node.
#' Default is \code{character(0)}.
#' @param src.dirs [\code{character}]\cr
#' Directories relative to your \code{work.dir} containing R scripts
#' to be sourced on registry load (both on slave and master).
#' Files not matching the pattern \dQuote{\\.[Rr]$} are ignored.
#' Useful if you have many helper functions that are needed during the execution of your jobs.
#' These files should only contain function definitions and no executable code.
#' Default is \code{character(0)}.
#' @param src.files [\code{character}]\cr
#' R scripts files relative to your \code{work.dir}
#' to be sourced on registry load (both on slave and master).
#' Useful if you have many helper functions that are needed during the execution of your jobs.
#' These files should only contain function definitions and no executable code.
#' Default is \code{character(0)}.
#' @param skip [\code{logical(1)}]\cr
#' Skip creation of a new registry if a registry is found in \code{file.dir}.
#' Defaults to \code{TRUE}.
#' @return [\code{\link{ExperimentRegistry}}]
#' @export
#' @aliases ExperimentRegistry
makeExperimentRegistry = function(id = "BatchExperimentRegistry", file.dir, sharding = TRUE, work.dir, multiple.result.files = FALSE,
seed, packages = character(0L), src.dirs = character(0L), src.files = character(0L), skip = TRUE) {
if (missing(file.dir))
file.dir = file.path(getwd(), paste0(id, "-files"))
assertFlag(skip)
if (skip && isRegistryDir(file.dir))
return(loadRegistry(file.dir = file.dir))
reg = makeRegistryInternal(id, file.dir, sharding,
work.dir, multiple.result.files, seed, c("BatchExperiments", packages),
src.dirs, src.files)
reg$packages$BatchExperiments$mandatory = TRUE
class(reg) = c("ExperimentRegistry", "Registry")
dbCreateJobStatusTable(reg, extra.cols = ", repl INTEGER, prob_seed INTEGER", constraints = ", UNIQUE(job_def_id, repl)")
BatchJobs::dbCreateJobDefTable(reg)
dbCreateExtraTables(reg)
dbCreateExpandedJobsViewBE(reg)
checkDir(file.path(reg$file.dir, "problems"), create = TRUE)
checkDir(file.path(reg$file.dir, "algorithms"), create = TRUE)
saveRegistry(reg)
return(reg)
}
#' @export
print.ExperimentRegistry = function(x, ...) {
cat("Experiment registry:", x$id, "\n")
cat(" Number of problems:", length(dbGetAllProblemIds(x)), "\n")
cat(" Number of algorithms:", length(dbGetAllAlgorithmIds(x)), "\n")
cat(" Number of jobs:", getJobNr(x), "\n")
cat(" Files dir:", x$file.dir, "\n")
cat(" Work dir:", x$work.dir, "\n")
cat(" Multiple result files:", x$multiple.result.files, "\n")
cat(" Seed:", x$seed, "\n")
cat(" Required packages:", collapse(names(x$packages), ", "), "\n")
}
checkExperimentRegistry = function(reg, strict = FALSE, writeable = TRUE) {
cl = class(reg)
expected = "ExperimentRegistry"
if (strict) {
if (head(cl, 1L) != expected)
stopf("Registry class mismatch: Expected argument with first class '%s'", expected)
} else {
if (expected %nin% cl)
stopf("Registry class mismatch: Expected argument of class '%s'", expected)
}
if (writeable && isTRUE(reg$read.only))
stop("Registry is read-only. Operation not permitted.")
invisible(TRUE)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/ExperimentRegistry.R
|
makeProblem = function(id, static, dynamic) {
setClasses(list(id = id, static = static, dynamic = dynamic), "Problem")
}
#FIXME the seed mechansim is described slighlty wrong! fix! random seed!
#' @title Add a problem to registry.
#'
#' @description
#' Add a algorithm to problem and stores it on disk.
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#'
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Name of problem.
#' @param static [any]\cr
#' Static part of problem that never changes and is not dependent on parameters.
#' Default is \code{NULL}.
#' @param dynamic [\code{function(job, static, ...)}]\cr
#' R generator function that creates dynamic / stochastic part of problem instance, which might be dependent on parameters.
#' First parameter \code{job} is a \code{\link[BatchJobs]{Job}} object, second is static problem part \code{static}.
#' Further parameters from design are passed to ... argument on instance creation time.
#' The arguments \code{job} and \code{static} may be omitted.
#' To retrieve job informations from the \code{job} object
#' see the documentation on \link{ExperimentJob}.
#' Default is \code{NULL}.
#' @param seed [\code{integer(1)}]\cr
#' Start seed for this problem. This allows the \dQuote{synchronization} of a stochastic
#' problem across algorithms, so that different algorithms are evaluated on the same stochastic instance.
#' The seeding mechanism works as follows, if a problem seed is defined:
#' (1) Before the dynamic part of a problem is instantiated,
#' the seed of the problem + replication - 1 is set, so for the first
#' replication the exact problem seed is used. (2) The stochastic part of the problem is
#' instantiated (3) From now on the usual experiment seed of the registry is used,
#' see \code{\link{ExperimentRegistry}}.
#' If \code{seed} is set to \code{NULL} this extra problem seeding is switched off, meaning
#' different algorithms see different stochastic versions of the same problem.
#' Default is \code{NULL}.
#' @param overwrite [\code{logical(1)}]\cr
#' Overwrite the problem file if it already exists?
#' Default is \code{FALSE}.
#' @return [\code{character(1)}]. Invisibly returns the id.
#' @aliases Problem
#' @family add
#' @export
addProblem = function(reg, id, static = NULL, dynamic = NULL, seed = NULL, overwrite = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = TRUE)
checkIdValid(id)
if (!is.null(seed))
seed = asInt(seed)
assertFlag(overwrite)
if (is.null(static) && is.null(dynamic))
stop("One of args 'static' or 'dynamic' must not be NULL!")
if (id %in% dbGetAllAlgorithmIds(reg))
stopf("Algorithm with same id as your problem already exists: %s", id)
if (!overwrite && id %in% dbGetAllProblemIds(reg))
stopf("Problem with same id already exists and overwrite = FALSE: %s", id)
fn = getProblemFilePaths(reg$file.dir, id)
info("Writing problem files: %s", collapse(fn, sep = ", "))
save(file = fn["static"], static)
save(file = fn["dynamic"], dynamic)
dbAddProblem(reg, id, seed)
invisible(id)
}
#' @export
print.Problem = function(x, ...) {
cat("Problem:", x$id, "\n")
}
loadProblem = function(reg, id, seed = TRUE) {
parts = getProblemFilePaths(reg$file.dir, id)
prob = makeProblem(id = id,
static = load2(parts["static"], "static", impute = NULL),
dynamic = load2(parts["dynamic"], "dynamic", impute = NULL))
if (seed) {
query = sprintf("SELECT pseed FROM %s_prob_def WHERE prob_id = '%s'", reg$id, id)
prob$seed = batchQuery(reg, query)$pseed
}
prob
}
calcDynamic = function(reg, job, static, dynamic.fun) {
if (is.null(dynamic.fun))
return(NULL)
prob.use = c("job", "static")
prob.use = setNames(prob.use %in% names(formals(dynamic.fun)), prob.use)
f = switch(sum(c(1L, 2L)[prob.use]) + 1L,
function(...) dynamic.fun(...),
function(...) dynamic.fun(job = job, ...),
function(...) dynamic.fun(static = static, ...),
function(...) dynamic.fun(job = job, static = static, ...))
info("Generating problem %s ...", job$prob.id)
seed = seeder(reg, job$prob.seed)
on.exit(seed$reset())
do.call(f, job$prob.pars)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/Problem.R
|
#' @title Add experiemts to the registry.
#'
#' @description
#' Add experiments for running algorithms on problems
#' to the registry, so they can be executed later.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param prob.designs [\code{character} | \code{\link{Design}} | list of \code{\link{Design}}]\cr
#' Either problem ids, a single problem design or a list of problem designs,
#' the latter two created by \code{\link{makeDesign}}.
#' If missing, all problems are selected (without associating a design),
#' and this is the default.
#' @param algo.designs [\code{character} | \code{\link{Design}} | list of \code{\link{Design}}]\cr
#' Either algorithm ids, a single algorithm design or a list of algorithm designs,
#' the latter two created by \code{\link{makeDesign}}.
#' If missing, all algorithms are selected (without associating a design),
#' and this is the default.
#' @param repls [\code{integer(1)}]\cr
#' Number of replications.\cr
#' Default is 1.
#' @param skip.defined [\code{logical}]\cr
#' If set to \code{TRUE}, already defined experiments get skipped. Otherwise an error is thrown.\cr
#' Default is FALSE.
#' @family add
#' @return Invisibly returns vector of ids of added experiments.
#' @examples
#' ### EXAMPLE 1 ###
#' reg = makeExperimentRegistry(id = "example1", file.dir = tempfile())
#'
#' # Define a problem:
#' # Subsampling from the iris dataset.
#' data(iris)
#' subsample = function(static, ratio) {
#' n = nrow(static)
#' train = sample(n, floor(n * ratio))
#' test = setdiff(seq(n), train)
#' list(test = test, train = train)
#' }
#' addProblem(reg, id = "iris", static = iris,
#' dynamic = subsample, seed = 123)
#'
#' # Define algorithm "tree":
#' # Decision tree on the iris dataset, modeling Species.
#' tree.wrapper = function(static, dynamic, ...) {
#' library(rpart)
#' mod = rpart(Species ~ ., data = static[dynamic$train, ], ...)
#' pred = predict(mod, newdata = static[dynamic$test, ], type = "class")
#' table(static$Species[dynamic$test], pred)
#' }
#' addAlgorithm(reg, id = "tree", fun = tree.wrapper)
#'
#' # Define algorithm "forest":
#' # Random forest on the iris dataset, modeling Species.
#' forest.wrapper = function(static, dynamic, ...) {
#' library(randomForest)
#' mod = randomForest(Species ~ ., data = static, subset = dynamic$train, ...)
#' pred = predict(mod, newdata = static[dynamic$test, ])
#' table(static$Species[dynamic$test], pred)
#' }
#' addAlgorithm(reg, id = "forest", fun = forest.wrapper)
#'
#' # Define problem parameters:
#' pars = list(ratio = c(0.67, 0.9))
#' iris.design = makeDesign("iris", exhaustive = pars)
#'
#' # Define decision tree parameters:
#' pars = list(minsplit = c(10, 20), cp = c(0.01, 0.1))
#' tree.design = makeDesign("tree", exhaustive = pars)
#'
#' # Define random forest parameters:
#' pars = list(ntree = c(100, 500))
#' forest.design = makeDesign("forest", exhaustive = pars)
#'
#' # Add experiments to the registry:
#' # Use previously defined experimental designs.
#' addExperiments(reg, prob.designs = iris.design,
#' algo.designs = list(tree.design, forest.design),
#' repls = 2) # usually you would set repls to 100 or more.
#'
#' # Optional: Short summary over problems and algorithms.
#' summarizeExperiments(reg)
#'
#' # Optional: Test one decision tree job and one expensive (ntree = 1000)
#' # random forest job. Use findExperiments to get the right job ids.
#' do.tests = FALSE
#' if (do.tests) {
#' id1 = findExperiments(reg, algo.pattern = "tree")[1]
#' id2 = findExperiments(reg, algo.pattern = "forest",
#' algo.pars = (ntree == 1000))[1]
#' testJob(reg, id1)
#' testJob(reg, id2)
#' }
#'
#' # Submit the jobs to the batch system
#' submitJobs(reg)
#'
#' # Calculate the misclassification rate for all (already done) jobs.
#' reduce = function(job, res) {
#' n = sum(res)
#' list(mcr = (n-sum(diag(res)))/n)
#' }
#' res = reduceResultsExperiments(reg, fun = reduce)
#' print(res)
#'
#' # Aggregate results using 'ddply' from package 'plyr':
#' # Calculate the mean over all replications of identical experiments
#' # (same problem, same algorithm and same parameters)
#' library(plyr)
#' vars = setdiff(names(res), c("repl", "mcr"))
#' aggr = ddply(res, vars, summarise, mean.mcr = mean(mcr))
#' print(aggr)
#'
#' \dontrun{
#' ### EXAMPLE 2 ###
#' # define two simple test functions
#' testfun1 = function(x) sum(x^2)
#' testfun2 = function(x) -exp(-sum(abs(x)))
#'
#' # Define ExperimentRegistry:
#' reg = makeExperimentRegistry("example02", seed = 123, file.dir = tempfile())
#'
#' # Add the testfunctions to the registry:
#' addProblem(reg, "testfun1", static = testfun1)
#' addProblem(reg, "testfun2", static = testfun2)
#'
#' # Use SimulatedAnnealing on the test functions:
#' addAlgorithm(reg, "sann", fun = function(static, dynamic) {
#' upp = rep(10, 2)
#' low = -upp
#' start = sample(c(-10, 10), 2)
#' res = optim(start, fn = static, lower = low, upper = upp, method = "SANN")
#' res = res[c("par", "value", "counts", "convergence")]
#' res$start = start
#' return(res)
#' })
#'
#' # add experiments and submit
#' addExperiments(reg, repls = 10)
#' submitJobs(reg)
#'
#' # Gather informations from the experiments, in this case function value
#' # and whether the algorithm convergenced:
#' reduceResultsExperiments(reg, fun = function(job, res) res[c("value", "convergence")])
#' }
#' @aliases Experiment
#' @export
addExperiments = function(reg, prob.designs, algo.designs, repls = 1L, skip.defined = FALSE) {
UseMethod("addExperiments")
}
#' @method addExperiments ExperimentRegistry
#' @export
addExperiments.ExperimentRegistry = function(reg, prob.designs, algo.designs, repls = 1L, skip.defined = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = TRUE)
syncRegistry(reg)
# check prob.designs
if (missing(prob.designs)) {
prob.designs = lapply(dbGetAllProblemIds(reg), makeDesign)
} else {
if (is.character(prob.designs)) {
prob.designs = lapply(prob.designs, makeDesign)
} else if (inherits(prob.designs, "Design")) {
prob.designs = list(prob.designs)
} else if (is.list(prob.designs)) {
checkListElementClass(prob.designs, "Design")
} else {
stop("Format of prob.designs not supported. Must be a character vector, a design or list of designs")
}
ids = unique(extractSubList(prob.designs, "id"))
found = ids %in% dbGetAllProblemIds(reg)
if (! all(found))
stopf("%i problems have not been added to registry for designs: %s",
sum(!found), collapse(ids[!found]))
}
# check algo.designs
if (missing(algo.designs)) {
algo.designs = lapply(dbGetAllAlgorithmIds(reg), makeDesign)
} else {
if (is.character(algo.designs)) {
algo.designs = lapply(algo.designs, makeDesign)
} else if (inherits(algo.designs, "Design")) {
algo.designs = list(algo.designs)
} else if (is.list(algo.designs)) {
checkListElementClass(algo.designs, "Design")
} else {
stop("Format of algo.designs not supported. Must be a character vector, a design or list of designs")
}
ids = unique(extractSubList(algo.designs, "id"))
found = ids %in% dbGetAllAlgorithmIds(reg)
if (! all(found))
stopf("%i algorithms have not been added to registry for designs: %s",
sum(!found), collapse(ids[!found]))
}
repls = asCount(repls, positive = TRUE)
assertFlag(skip.defined)
f = function(xs) viapply(xs, function(x) x$designIter$n.states)
n.exps = sum(outer(f(prob.designs), f(algo.designs)))
info("Adding %i experiments / %i jobs to DB.", n.exps, n.exps*repls)
if (n.exps == 0L)
return(invisible(integer(0L)))
# internal helper functions
mq = function(lines, ..., con, bind.data = NULL) {
q = sprintf(collapse(lines, sep = " "), ...)
if(is.null(bind.data)) {
res = NULL
dbi.res = dbSendQuery(con, q)
if (startsWith(q, "SELECT") || !dbHasCompleted(dbi.res))
res = dbFetch(dbi.res)
dbClearResult(dbi.res)
return(res)
}
res = dbSendQuery(con, q)
for (i in seq_row(bind.data)) {
row = unname(as.list(bind.data[i, ]))
ok = dbBind(res, row)
if (startsWith(q, "SELECT") || !dbHasCompleted(res))
ok = try(dbFetch(res))
if(is.error(ok)) {
dbClearResult(res)
dbRollback(con)
stopf("Error in dbAddData: %s", as.character(ok))
}
}
dbClearResult(res)
}
seripars = function(x) {
rawToChar(serialize(x, connection = NULL, ascii = TRUE))
}
writeJobDefs = function(job.defs) {
data = rbindlist(job.defs)[, c("prob_id", "prob_pars", "algo_id", "algo_pars"), with = FALSE]
mq("INSERT INTO tmp(prob_id, prob_pars, algo_id, algo_pars) VALUES(?, ?, ?, ?)",
con = con, bind.data = data)
}
# establish persistent connection and create temporary table to fill
# with job definitions
con = dbConnectToJobsDB(reg, "rw")
on.exit(dbDisconnect(con))
# create temporary table for job definitions
mq(c("CREATE TEMP TABLE tmp(job_def_id INTEGER, prob_id TEXT,",
"prob_pars TEXT, algo_id TEXT, algo_pars TEXT)"), con = con)
# write auxiliary temporary table with replication numbers
mq("CREATE TEMP TABLE repls(repl INTEGER)", con = con)
mq("INSERT INTO repls(repl) VALUES(?)",
con = con, bind.data = data.frame(repl = seq_len(repls)))
# create temporary view on cross product of repls and job_def_id
mq(c("CREATE TEMP VIEW cp AS SELECT repls.repl, tmp.job_def_id FROM tmp",
"CROSS JOIN repls"), con = con)
# iterate to generate job definitions
# write to temporary table every x definitions
job.defs = buffer("list", 5000L, writeJobDefs)
for (pd in prob.designs) {
pd$designIter$reset()
while (pd$designIter$hasNext()) {
prob.pars = seripars(pd$designIter$nextElem())
for (ad in algo.designs) {
ad$designIter$reset()
while (ad$designIter$hasNext()) {
algo.pars = seripars(ad$designIter$nextElem())
job.defs$push(list(prob_id = pd$id, prob_pars = prob.pars,
algo_id = ad$id, algo_pars = algo.pars))
}
}
}
}
# add (remaining) defs to temporary job_defs table
job.defs$clear()
rm(job.defs)
# query job_id to keep track of new ids
max.job.id = mq("SELECT COALESCE(MAX(job_id), 0) AS x FROM %s_job_status", reg$id, con = con)$x
# match for known job_def_id
mq(c("UPDATE tmp SET job_def_id = (SELECT job_def_id FROM %s_job_def AS jd",
"WHERE jd.prob_id = tmp.prob_id AND jd.algo_id = tmp.algo_id AND",
"jd.prob_pars = tmp.prob_pars AND jd.algo_pars = tmp.algo_pars)"),
reg$id, con = con)
# test whether we would overwrite existing experiments
if(!skip.defined) {
if (mq("SELECT COUNT(job_def_id) AS n FROM tmp", con = con)$n > 0L)
stop(paste("You have added identical experiments.",
"Either there are duplicated problem or algorithm ids or you have defined an experiment with the same parameters twice.",
"For the latter case use replications.",
"If you know what you're doing, look at skip.defined = TRUE.",
sep = "\n"))
}
# we start the transaction here, everything above is temporary
dbBegin(con)
ok = try({
# insert new job defs
mq(c("INSERT INTO %s_job_def(prob_id, prob_pars, algo_id, algo_pars)",
"SELECT prob_id, prob_pars, algo_id, algo_pars FROM tmp",
"WHERE job_def_id IS NULL"), reg$id, con = con)
# update temporary table with new job defs
mq(c("UPDATE tmp SET job_def_id = (SELECT job_def_id FROM %s_job_def AS jd WHERE",
"jd.prob_id = tmp.prob_id AND jd.algo_id = tmp.algo_id AND",
"jd.prob_pars = tmp.prob_pars AND jd.algo_pars = tmp.algo_pars)",
"WHERE tmp.job_def_id IS NULL"), reg$id, con = con)
# insert into job status table
mq(c("INSERT INTO %1$s_job_status(job_def_id, repl)",
"SELECT cp.job_def_id, cp.repl FROM cp WHERE NOT EXISTS",
"(SELECT * FROM %1$s_job_status AS js WHERE",
"cp.job_def_id = js.job_def_id AND cp.repl = js.repl)"),
reg$id, con = con)
# We could do this w/o bulk insert, but we are not allowed to
# use external RNGs
df = mq("SELECT job_id, pseed, repl FROM %s_expanded_jobs WHERE job_id > %i",
reg$id, max.job.id, con = con)
if(nrow(df) > 0L) {
df$seed = addIntModulo(df$job_id, reg$seed - 1L)
na = is.na(df$pseed)
df$prob_seed[ na] = getRandomSeed(sum(na))
df$prob_seed[!na] = addIntModulo(df$pseed[!na], df$repl[!na] - 1L)
mq("UPDATE %s_job_status SET seed = ?, prob_seed = ? WHERE job_id = ?",
reg$id, con = con, bind.data = df[c("seed", "prob_seed", "job_id")])
}
}, silent = TRUE)
if(is.error(ok)) {
dbRollback(con)
errmsg = as.character(ok)
# not really clean to match the english message here...
# lets hope there are not localized versions of (R)SQLite out there
if(grepl("UNIQUE constraint failed", errmsg, fixed = TRUE)) {
stop(paste("You have added identical experiments.",
"Either there are duplicated problem or algorithm ids or you have defined an experiment with the same parameters twice.",
"For the latter case use replications.",
"If you know what you're doing, look at skip.defined = TRUE.",
sep = "\n"))
} else {
stopf("Error inserting new experiments: %s", errmsg)
}
}
dbCommit(con)
createShardedDirs(reg, df$job_id)
invisible(df$job_id)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/addExperiments.R
|
#' @method applyJobFunction ExperimentRegistry
#' @export
applyJobFunction.ExperimentRegistry = function(reg, job, cache) {
algo = cache(getAlgorithmFilePath(reg$file.dir, job$algo.id),
slot = "algo", parts = "algorithm")$fun
algo.use = c("job", "static", "dynamic")
algo.use = setNames(algo.use %in% names(formals(algo)), algo.use)
# encapsulate the loading into functions for lazy loading
#
# IMPORTANT: Note that the order of the messages in the log files can be confusing.
# This is caused by lazy evaluation, but we cannot live w/o it.
# Therefore it is possible to get errors on the slave with the last message being
# "Generating problem[...]", but the actual error is thrown in the algorithm
parts = getProblemFilePaths(reg$file.dir, job$prob.id)
static = function() cache(parts["static"], slot = "static", impute = NULL)
dynamic = function() calcDynamic(reg, job, static(), cache(parts["dynamic"], slot = "dynamic", impute = NULL))
# switch on algo formals and apply algorithm function
f = switch(sum(c(1L, 2L, 4L)[algo.use]) + 1L,
function(...) algo(...),
function(...) algo(job = job, ...),
function(...) algo(static = static(), ...),
function(...) algo(job = job, static = static(), ...),
function(...) algo(dynamic = dynamic(), ...),
function(...) algo(job = job, dynamic = dynamic(), ...),
function(...) algo(static = static(), dynamic = dynamic(), ...),
function(...) algo(job = job, static = static(), dynamic = dynamic(), ...))
messagef("Applying Algorithm %s ...", job$algo.id)
do.call(f, job$algo.pars)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/applyJobFunction.R
|
#' @export
dbCreateJobDefTable.ExperimentRegistry = function(reg) {
query = sprintf(paste("CREATE TABLE %s_job_def (job_def_id INTEGER PRIMARY KEY,",
"prob_id TEXT, prob_pars TEXT, algo_id TEXT, algo_pars TEXT,",
"UNIQUE(prob_id, prob_pars, algo_id, algo_pars))"), reg$id)
batchQuery(reg, query, flags = "rwc")
}
dbCreateExtraTables = function(reg) {
query = sprintf("CREATE TABLE %s_prob_def (prob_id TEXT PRIMARY KEY, pseed INTEGER)", reg$id)
batchQuery(reg, query, flags = "rwc")
query = sprintf("CREATE TABLE %s_algo_def (algo_id TEXT PRIMARY KEY)", reg$id)
batchQuery(reg, query, flags = "rwc")
}
dbCreateExpandedJobsViewBE = function(reg) {
query = sprintf(paste("CREATE VIEW %1$s_expanded_jobs AS",
"SELECT * FROM %1$s_job_status AS job_status",
"LEFT JOIN %1$s_job_def AS job_def USING(job_def_id)",
"LEFT JOIN %1$s_prob_def AS prob_def USING (prob_id)"), reg$id)
batchQuery(reg, query, flags = "rw")
}
dbSelectWithIds = function(reg, query, ids, where = TRUE, group.by, reorder = TRUE) {
if(!missing(ids))
query = sprintf("%s %s job_id IN (%s)", query, ifelse(where, "WHERE", "AND"), collapse(ids))
if(!missing(group.by))
query = sprintf("%s GROUP BY %s", query, collapse(group.by))
res = batchQuery(reg, query)
if(missing(ids) || !reorder)
return(res)
return(res[na.omit(match(ids, res$job_id)),, drop = FALSE])
}
#' @method dbGetJobs ExperimentRegistry
#' @export
dbGetJobs.ExperimentRegistry = function(reg, ids) {
query = sprintf("SELECT job_id, prob_id, prob_pars, algo_id, algo_pars, seed, prob_seed, repl FROM %s_expanded_jobs", reg$id)
tab = dbSelectWithIds(reg, query, ids)
lapply(seq_row(tab), function(i) {
x = tab[i,]
prob.pars = unserialize(charToRaw(x$prob_pars))
algo.pars = unserialize(charToRaw(x$algo_pars))
makeExperimentJob(id = x$job_id, prob.id = x$prob_id, prob.pars = prob.pars,
algo.id = x$algo_id, algo.pars = algo.pars, seed = x$seed, repl = x$repl, prob.seed = x$prob_seed)
})
}
dbSummarizeExperiments = function(reg, ids, show) {
if (all(show %in% c("prob", "algo", "repl"))) {
cols = setNames(c("prob_id", "algo_id", "repl"), c("prob", "algo", "repl"))
cols = cols[match(show, names(cols))]
query = sprintf("SELECT %s, COUNT(job_id) FROM %s_expanded_jobs", collapse(cols), reg$id)
summary = setNames(dbSelectWithIds(reg, query, ids, group.by = cols, reorder = FALSE),
c(show, ".count"))
} else {
uc = function(x) unserialize(charToRaw(x))
query = sprintf("SELECT job_id, prob_id AS prob, prob_pars, algo_id AS algo, algo_pars, repl FROM %s_expanded_jobs", reg$id)
tab = as.data.table(dbSelectWithIds(reg, query, ids, reorder = FALSE))
pars = rbindlist(lapply(tab$prob_pars, uc), fill = TRUE)
if (nrow(pars) > 0L)
tab = cbind(tab, pars)
pars = rbindlist(lapply(tab$algo_pars, uc), fill = TRUE)
if (nrow(pars) > 0L)
tab = cbind(tab, pars)
diff = setdiff(show, colnames(tab))
if (length(diff) > 0L)
stopf("Trying to select columns in arg 'show' which are not available: %s", collapse(diff))
summary = as.data.frame(tab[, list(.count = .N), by = show])
}
summary
}
dbFindExperiments = function(reg, ids, prob.pattern, algo.pattern, repls, like = TRUE, regexp = FALSE) {
clause = character(0L)
if (!missing(repls))
clause = c(clause, sprintf("repl IN (%s)", collapse(repls)))
if (regexp) {
query = sprintf("SELECT job_id, prob_id, algo_id from %s_expanded_jobs", reg$id)
tab = dbSelectWithIds(reg, query, ids, where = TRUE)
ss = rep(TRUE, nrow(tab))
if (!missing(prob.pattern))
ss = ss & grepl(prob.pattern, tab$prob_id)
if (!missing(algo.pattern))
ss = ss & grepl(algo.pattern, tab$algo_id)
return(tab$job_id[ss])
}
if (!missing(prob.pattern)) {
if (like)
clause = c(clause, sprintf("prob_id LIKE '%%%s%%'", prob.pattern))
else
clause = c(clause, sprintf("prob_id = '%s'", prob.pattern))
}
if (!missing(algo.pattern)) {
if (like)
clause = c(clause, sprintf("algo_id LIKE '%%%s%%'", algo.pattern))
else
clause = c(clause, sprintf("algo_id = '%s'", algo.pattern))
}
query = sprintf("SELECT job_id from %s_expanded_jobs", reg$id)
if (length(clause) > 0L)
query = paste(query, "WHERE", collapse(clause, sep = " AND "))
dbSelectWithIds(reg, query, ids, where = length(clause) == 0L)$job_id
}
dbAddProblem = function(reg, id, seed) {
#FIXME: replace OR REPLACE with an option, this is not supported by all DBMS
query = sprintf("INSERT OR REPLACE INTO %s_prob_def (prob_id, pseed) VALUES ('%s', %s)",
reg$id, id, ifelse(is.null(seed), "NULL", seed))
batchQuery(reg, query, flags = "rw")
}
dbAddAlgorithm = function(reg, id) {
#FIXME: replace OR REPLACE with an option, this is not supported by all DBMS
query = sprintf("INSERT OR REPLACE INTO %s_algo_def (algo_id) VALUES ('%s')", reg$id, id)
batchQuery(reg, query, flags = "rw")
}
dbRemoveProblem = function(reg, id) {
query = sprintf("DELETE FROM %s_prob_def WHERE prob_id='%s'", reg$id, id)
batchQuery(reg, query, flags = "rw")
}
dbRemoveAlgorithm = function(reg, id) {
query = sprintf("DELETE FROM %s_algo_def WHERE algo_id='%s'", reg$id, id)
batchQuery(reg, query, flags = "rw")
}
dbGetAllProblemIds = function(reg) {
query = sprintf("SELECT prob_id FROM %s_prob_def", reg$id)
batchQuery(reg, query)$prob_id
}
dbGetAllAlgorithmIds = function(reg) {
query = sprintf("SELECT algo_id FROM %s_algo_def", reg$id)
batchQuery(reg, query)$algo_id
}
dbGetProblemIds = function(reg, ids) {
query = sprintf("SELECT job_id, prob_id FROM %s_expanded_jobs", reg$id)
dbSelectWithIds(reg, query, ids)$prob_id
}
dbGetAlgorithmIds = function(reg, ids) {
query = sprintf("SELECT job_id, algo_id FROM %s_expanded_jobs", reg$id)
dbSelectWithIds(reg, query, ids)$algo_id
}
dbRemoveJobs = function(reg, ids) {
query = sprintf("DELETE FROM %s_job_status WHERE job_id IN (%s)", reg$id, collapse(ids))
batchQuery(reg, query, flags = "rw")
query = sprintf("DELETE FROM %1$s_job_def WHERE job_def_id NOT IN (SELECT DISTINCT job_def_id FROM %1$s_job_status)", reg$id)
batchQuery(reg, query, flags = "rw")
return(invisible(TRUE))
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/database.R
|
# Generates crossproduct of exhaustive options joined with rows of a given design data.frame.
# State-based object with iterator functions is returned.
# If both arguments are empty, the a design is created with corresponds to one 'point' that
# defines a function call with no arguments.
# @param ex [\code{list}]\cr
# Named list of parameters settings which should be exhaustively tried.
# All elements of the list must be primitive vectors like numeric, integer, factor, etc.
# @param .design [\code{data.frame}]\cr
# The design. Rows define one 'point'.
# @return List of funs. nextElem returns a named list (ordered by list element names).
designIterator = function(ex, .design = data.frame()) {
nextState = function(state, pos = 1L) {
if (state[pos] < state.last[pos])
replace(state, pos, state[pos] + 1L)
else
nextState(replace(state, pos, 1L), pos + 1L)
}
nextElem = function() {
state <<- nextState(state)
counter <<- counter + 1L
x = c(as.list(.design[state[! is.ex.state], , drop = FALSE]),
mapply(function(n, s) ex[[n]][s], n = names.ex.state, s = state[is.ex.state], SIMPLIFY = FALSE))
x[order(names2(x))]
}
hasNext = function() {
counter < counter.max
}
reset = function() {
state <<- state.init
counter <<- 0L
invisible(TRUE)
}
state.last = sort(setNames(c(vapply(ex, length, 1L), max(nrow(.design), 1L)), c(names(ex), ".design.row")), decreasing = TRUE)
state.init = setNames(c(0L, rep.int(1L, length(state.last) - 1L)), names(state.last))
counter.max = prod(state.last)
if (counter.max > .Machine$integer.max)
stop("The generated design is too big. Designs with up to ",
.Machine$integer.max, " rows are supported!")
counter.max = as.integer(counter.max)
is.ex.state = (names(state.init) != ".design.row")
names.ex.state = names(state.init)[is.ex.state]
state = state.init
counter = 0L
list(nextElem = nextElem,
hasNext = hasNext,
reset = reset,
n.states = counter.max,
storage = c(vapply(.design, storage.mode, character(1L)),
vapply(ex, storage.mode, character(1L))))
}
#' @title Create parameter designs for problems and algorithms.
#'
#' @description
#' Create a parameter design for either a problem or an algorithm that you
#' can use in \code{\link{addExperiments}}.
#' All parameters in \code{design} and \code{exhaustive} be \dQuote{primitive}
#' in the sense that either \code{is.atomic} is \code{TRUE} or \code{is.factor} is \code{TRUE}.
#'
#' Be aware of R's default behaviour of converting strings into factors if you use the \code{design}
#' parameter. See option \code{stringsAsFactors} in \code{\link{data.frame}} to turn this off.
#' @param id [\code{character(1)}]\cr
#'
#' Id of algorithm or problem.
#' @param design [\code{data.frame}]\cr
#' The design. Must have named columns corresponding to parameters.
#' Default is an empty \code{data.frame()}.
#' @param exhaustive [\code{list}]\cr
#' Named list of parameters settings which should be exhaustively tried.
#' Names must correspond to parameters.
#' Default is empty list.
#' @return [\code{\link{Design}}].
#' @export
#' @aliases Design
#' @examples \dontrun{
#' # simple design for algorithm "a1" with no parameters:
#' design = makeDesign("a1")
#'
#' # design for problem "p1" using predefined parameter combinations
#' design = makeDesign("p1", design = data.frame(alpha = 0:1, beta = c(0.1, 0.2)))
#'
#' # creating a list of designs for several algorithms at once, all using the same
#' # exhaustive grid of parameters
#' designs = lapply(c("a1", "a2", "a3"), makeDesign,
#' exhaustive = list(alpha = 0:1, gamma = 1:10/10))
#' }
makeDesign = function(id, design = data.frame(), exhaustive = list()) {
# ... if we had the registry here, we could do some sanity checks, e.g.
# test if the storage mode of parameters matches the storage mode of those
# in the database
# if we push out a not backward compatible version, do this here.
assertString(id)
assertDataFrame(design, types = "atomic")
assertList(exhaustive, types = "atomic", names = "named")
if (any(viapply(exhaustive, length) == 0L))
stop("All elements of exhaustive must have at least have length 1!")
if (anyDuplicated(c(names(design), names(exhaustive))) > 0L)
stop("Duplicated design parameters found!")
setClasses(list(id = id, designIter = designIterator(exhaustive, .design = design)), "Design")
}
#' @export
print.Design = function(x, ...) {
n = x$designIter$n.states
storage = x$designIter$storage
catf("Design for %s with %i row%s", x$id, n, ifelse(n == 1L, "", "s"))
cat(collapse(sprintf(" %-10s: %s", names(storage), storage), "\n"), "\n")
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/designs.R
|
getAlgorithmFilePath = function(file.dir, id) {
# fix for case-insensitive file names
id = gsub("([[:upper:]])", "@\\1", id)
file.path(file.dir, "algorithms", sprintf("%s.RData", id))
}
getProblemFilePaths = function(file.dir, id) {
# fix for case-insensitive file names
id = gsub("([[:upper:]])", "@\\1", id)
parts = c("static", "dynamic")
setNames(file.path(file.dir, "problems", sprintf("%s_%s.RData", id, parts)), parts)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/filenames.R
|
#' @title Find ids of experiments that match a query.
#'
#' @description
#' Find job ids by querying problem/algorithm ids, problem/algorithm parameters or
#' replication number.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [\code{integer}]\cr
#' Ids of selected experiments to restrict to.
#' Default is all experiments.
#' @param prob.pattern [\code{character(1)}]\cr
#' If not missing, all problem ids that match this string are selected.
#' @param prob.pars [R expression]\cr
#' If not missing, all problems whose parameters match
#' the given expression are selected.
#' @param algo.pattern [\code{character(1)}]\cr
#' If not missing, all algorithm ids that match this string are selected.
#' @param algo.pars [R expression]\cr
#' If not missing, all algorithms whose parameters match
#' the given expression are selected.
#' @param repls [\code{integer}]\cr
#' If not missing, restrict to jobs with given replication numbers.
#' @param match.substring [\code{logical(1)}]\cr
#' Is a match in \code{prob.pattern} and \code{algo.pattern} if the id contains
#' the pattern as substring or must the id exactly match?
#' Default is \code{TRUE}.
#' @param regexp [\code{logical(1)}]\cr
#' Are \code{prob.pattern} and \code{algo.pattern} regular expressions?
#' Note that this is significantly slower than substring matching.
#' If set to \code{TRUE} the argument \code{match.substring} has no effect.
#' Default is \code{FALSE}.
#' @return [\code{integer}]. Ids for experiments which match the query.
#' @export
#' @examples
#' reg = makeExperimentRegistry(id = "example1", file.dir = tempfile())
#' p1 = addProblem(reg, "one", 1)
#' p2 = addProblem(reg, "two", 2)
#' a = addAlgorithm(reg, "A", fun = function(static, n) static + n)
#' addExperiments(reg, algo.design = makeDesign(a, exhaustive = list(n = 1:4)))
#' findExperiments(reg, prob.pattern = "one")
#' findExperiments(reg, prob.pattern = "o")
#' findExperiments(reg, algo.pars = (n > 2))
findExperiments = function(reg, ids, prob.pattern, prob.pars, algo.pattern, algo.pars,
repls, match.substring = TRUE, regexp = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
if (!missing(prob.pattern))
assertString(prob.pattern)
if (!missing(algo.pattern))
assertString(algo.pattern)
if (!missing(repls))
repls = asInteger(repls, lower = 0, any.missing = FALSE)
assertFlag(match.substring)
assertFlag(regexp)
ids = dbFindExperiments(reg, ids, prob.pattern, algo.pattern, repls, like = match.substring, regexp = regexp)
# skip possible expensive calculations if possible
if (length(ids) == 0L || (missing(prob.pars) && missing(algo.pars)))
return(ids)
jobs = getJobs(reg, ids, check.ids = FALSE)
if (!missing(prob.pars)) {
ind = vapply(jobs, function(job, pars, ee) eval(pars, job$prob.pars, ee),
logical(1L), pars = substitute(prob.pars), ee = parent.frame())
jobs = jobs[!is.na(ind) & ind]
}
if (!missing(algo.pars)) {
ind = vapply(jobs, function(job, pars, ee) eval(pars, job$algo.pars, ee),
logical(1L), pars = substitute(algo.pars), ee = parent.frame())
jobs = jobs[!is.na(ind) & ind]
}
return(extractSubList(jobs, "id", element.value = integer(1L)))
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/findExperiments.R
|
#' @title Generate dynamic part of problem.
#'
#' @description
#' Calls the dynamic problem function on the static problem part and
#' thereby creates the problem instance.
#' The seeding mechanism is identical to execution on the slave.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Id of job.
#' @return Dynamic part of problem.
#' @aliases Instance
#' @export
generateProblemInstance = function(reg, id) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
job = getJob(reg, id, check.id = TRUE)
prob = getProblem(reg, job$prob.id)
calcDynamic(reg, job, prob$static, prob$dynamic)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/generateProblemInstance.R
|
#' @title Get algorithm from registry by id.
#'
#' @description
#' The requested object is loaded from disk.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Id of algorithm.
#' @return [\code{\link{Algorithm}}].
#' @family get
#' @export
getAlgorithm = function(reg, id) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
assertString(id, "character")
aids = dbGetAllAlgorithmIds(reg)
if (id %nin% aids)
stop("Unknown algorithm id, possible candidates are: ", collapse(aids))
loadAlgorithm(reg, id)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getAlgorithm.R
|
#' @title Get ids of algorithms in registry.
#'
#' @description
#' Get algorithm ids for jobs.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [code{integer}]\cr
#' Job ids to restrict returned algorithm ids to.
#' @return [\code{character}].
#' @family get
#' @export
getAlgorithmIds = function(reg, ids) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
if (missing(ids))
return(dbGetAllAlgorithmIds(reg))
ids = checkIds(reg, ids)
unique(dbGetAlgorithmIds(reg, ids))
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getAlgorithmIds.R
|
#' @title Get all parts required to run a single job.
#'
#' @description
#' Get all parts which define an \code{\link{Experiment}}.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{integer(1)}]\cr
#' Id of a job.
#' @return [named list]. Returns the \link{Job}, \link{Problem}, \link{Instance} and \link{Algorithm}.
#' @family get
#' @export
getExperimentParts = function(reg, id) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
id = checkIds(reg, id, len = 1L)
res = namedList(c("job", "prob", "instance", "algo"))
res$job = dbGetJobs(reg, id)[[1L]]
res$prob = loadProblem(reg, res$job$prob.id)
# use insert to keep the slot even if this is NULL
res = insert(res, list(instance = calcDynamic(reg, res$job, res$prob$static, res$prob$dynamic)))
res$algo = loadAlgorithm(reg, res$job$algo.id)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getExperimentParts.R
|
#' @title Group experiments.
#'
#' @description
#' Creates a list of \code{\link{factor}} to use in functions like \code{\link{tapply}}, \code{\link{by}}
#' or \code{\link{aggregate}}.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [\code{integer}]\cr
#' If not missing, restict grouping to this subset of experiment ids.
#' @param by.prob [\code{logical}]\cr
#' Group experiments by problem. Default is \code{FALSE}.
#' @param by.algo [\code{logical}]\cr
#' Group experiments by algorithm. Default is \code{FALSE}.
#' @param by.repl [\code{logical}]\cr
#' Group experiments by replication. Default is \code{FALSE}.
#' @param by.prob.pars [R expression]\cr
#' If not missing, group experiments by this R expression.
#' The expression is evaluated in the environment of problem parameters and
#' converted to a factor using \code{as.factor}.
#' @param by.algo.pars [R expression]\cr
#' If not missing, group experiments by this R expression.
#' The expression is evaluated in the environment of algorithm parameters and
#' converted to a factor using \code{\link{as.factor}}.
#' @param enclos [\code{environment}]\cr
#' Enclosing frame for evaluation of parameters used by \code{by.prob.pars} and
#' \code{by.algo.pars}, see \code{\link[base]{eval}}. Defaults to the parent
#' frame.
#' @return [\code{list}]. List of factors.
#' @export
#' @examples
#' # create a registry and add problems and algorithms
#' reg = makeExperimentRegistry("getIndex", file.dir = tempfile(""))
#' addProblem(reg, "prob", static = 1)
#' addAlgorithm(reg, "f0", function(static, dynamic) static)
#' addAlgorithm(reg, "f1", function(static, dynamic, i, k) static * i^k)
#' ad = list(makeDesign("f0"), makeDesign("f1", exhaustive = list(i = 1:5, k = 1:3)))
#' addExperiments(reg, algo.designs = ad)
#' submitJobs(reg)
#'
#' # get grouped job ids
#' ids = getJobIds(reg)
#' by(ids, getIndex(reg, by.prob = TRUE, by.algo = TRUE), identity)
#' ids = findExperiments(reg, algo.pattern = "f1")
#' by(ids, getIndex(reg, ids, by.algo.pars = (k == 1)), identity)
#'
#' # groupwise reduction
#' ids = findExperiments(reg, algo.pattern = "f1")
#' showStatus(reg, ids)
#' f = function(aggr, job, res) aggr + res
#' by(ids, getIndex(reg, ids, by.algo.pars = k), reduceResults, reg = reg, fun = f)
#' by(ids, getIndex(reg, ids, by.algo.pars = i), reduceResults, reg = reg, fun = f)
getIndex = function(reg, ids, by.prob = FALSE, by.algo = FALSE, by.repl = FALSE,
by.prob.pars, by.algo.pars, enclos = parent.frame()) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
if (!missing(ids))
ids = checkIds(reg, ids)
assertFlag(by.prob)
assertFlag(by.algo)
assertFlag(by.repl)
if (missing(by.prob.pars) && missing(by.algo.pars)) {
# if not dealing with parameters, we can get the groups directly
# from the database
cols = c("job_id", "prob_id", "algo_id", "repl")[c(TRUE, by.prob, by.algo, by.repl)]
query = sprintf("SELECT %s FROM %s_expanded_jobs", collapse(cols), reg$id)
index = dbSelectWithIds(reg, query, ids)[, -1L, drop = FALSE]
names(index) = c("prob", "algo", "repl")[c(by.prob, by.algo, by.repl)]
} else {
# otherwise we have to get all jobs and calculate the groups on them
exprToIndex = function(jobs, pars, enclos, name) {
ind = try(lapply(jobs, function(job, pars, enclos, name) eval(pars, job[[name]], enclos),
pars = pars, enclos = enclos, name = name), silent = TRUE)
if (is.error(ind))
stopf("Your %s expression resulted in an error:\n%s", name, as.character(ind))
ind = try(as.factor(unlist(ind)))
str.expr = capture.output(print(pars))
if (is.error(ind) || length(ind) != length(jobs))
stopf("The return value of expression %s ('%s') is not convertible to a factor", name, str.expr)
namedList(sprintf("%s: %s", name, str.expr), ind)
}
jobs = getJobs(reg, ids, check.ids = FALSE)
index = list()
force(enclos)
if (by.prob)
index = c(index, list(prob = extractSubList(jobs, "prob.id", character(1L))))
if (by.algo)
index = c(index, list(algo = extractSubList(jobs, "algo.id", character(1L))))
if (by.repl)
index = c(index, list(repl = extractSubList(jobs, "repl", integer(1L))))
if (!missing(by.prob.pars)) {
index = c(index, exprToIndex(jobs, substitute(by.prob.pars), enclos, "prob.pars"))
}
if (!missing(by.algo.pars)) {
index = c(index, exprToIndex(jobs, substitute(by.algo.pars), enclos, "algo.pars"))
}
}
lapply(index, as.factor)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getIndex.R
|
#' @title Get jobs (here: experiments) from registry by id.
#'
#' @description
#' Constructs an \code{\link{Experiment}} for each job id provided.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [\code{integer}]\cr
#' Ids of job.
#' Default is all jobs.
#' @param check.ids [\code{logical(1)}]\cr
#' Check the job ids?
#' Default is \code{TRUE}.
#' @return [list of \code{Experiment}].
#' @method getJobs ExperimentRegistry
#' @family get
#' @export
getJobs.ExperimentRegistry = function(reg, ids, check.ids = TRUE) {
if (!missing(ids) && check.ids)
ids = checkIds(reg, ids)
dbGetJobs(reg, ids)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getJob.R
|
#' @method getJobInfo ExperimentRegistry
#' @export
getJobInfo.ExperimentRegistry = function(reg, ids, pars = FALSE, prefix.pars = FALSE, select, unit = "seconds") {
syncRegistry(reg)
assertFlag(pars)
columns = c(id = "job_id", prob = "prob_id", algo = "algo_id", repl = "repl")
if (pars)
columns = c(columns, c(prob.pars = "prob_pars", algo.pars = "algo_pars"))
tab = getJobInfoInternal(reg, ids, select, unit, columns)
# unserialize parameters
if (pars) {
if (!is.null(tab$prob.pars)) {
pars = convertListOfRowsToDataFrame(lapply(tab$prob.pars, function(x) unserialize(charToRaw(x))), strings.as.factors = FALSE)
if (prefix.pars)
names(pars) = sprintf("prob.par.%s", names(pars))
tab = cbind(subset(tab, select = setdiff(names(tab), "prob.pars")), pars)
}
if (!is.null(tab$algo.pars)) {
pars = convertListOfRowsToDataFrame(lapply(tab$algo.pars, function(x) unserialize(charToRaw(x))), strings.as.factors = FALSE)
if (prefix.pars)
names(pars) = sprintf("algo.par.%s", names(pars))
tab = cbind(subset(tab, select = setdiff(names(tab), "algo.pars")), pars)
}
}
return(tab)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getJobInfo.R
|
#' @title Get problem from registry by id.
#'
#' @description
#' The requested object is loaded from disk.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Id of problem.
#' @return [\code{\link{Problem}}].
#' @family get
#' @export
getProblem = function(reg, id) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
assertString(id)
pids = dbGetAllProblemIds(reg)
if (id %nin% pids)
stop("Unknown problem id, possible candidates are: ", collapse(pids))
loadProblem(reg, id)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getProblem.R
|
#' @title Get ids of problems in registry.
#'
#' @description
#' Get problem ids for jobs.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [code{integer}]\cr
#' Job ids to restrict returned problem ids to.
#' @return [\code{character}].
#' @family get
#' @export
getProblemIds = function(reg, ids) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
if (missing(ids))
return(dbGetAllProblemIds(reg))
checkIds(reg, ids)
unique(dbGetProblemIds(reg, ids))
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/getProblemIds.R
|
info = function(...) {
if (getOption("BatchJobs.verbose", default = TRUE))
message(sprintf(...))
}
# check for valid algorithm and problem ids
# we can be more relaxed her, this does not affect
# sql table names (unlike the registry id)
checkIdValid = function(id, allow.minus = TRUE) {
assertString(id)
if (allow.minus)
pattern = "^[a-zA-Z]+[0-9a-zA-Z_.-]*$"
else
pattern = "^[a-zA-Z]+[0-9a-zA-Z_.]*$"
if (!grepl(pattern, id))
stopf("Id does not comply with pattern %s: %s", pattern, id)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/helpers.R
|
#' @title Reduce results into a data.frame with all relevant information.
#'
#' @description
#' Generates a \code{data.frame} with one row per job id. The columns are: ids of problem and algorithm
#' (named \dQuote{prob} and \dQuote{algo}), one column per parameter of problem or algorithm (named by the parameter name),
#' the replication number (named \dQuote{repl}) and all columns defined in the function to collect the values.
#' Note that you cannot rely on the order of the columns.
#' If a parameter does not have a setting for a certain job / experiment it is set to \code{NA}.
#' Have a look at \code{\link{getResultVars}} if you want to use something like \code{\link[plyr]{ddply}} on the
#' results.
#'
#' The rows are ordered as \code{ids} and named with \code{ids}, so one can easily index them.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [\code{integer}]\cr
#' Ids of selected experiments.
#' Default is all jobs for which results are available.
#' @param part [\code{character}]
#' Only useful for multiple result files, then defines which result file part(s) should be loaded.
#' \code{NA} means all parts are loaded, which is the default.
#' @param fun [\code{function(job, res, ...)}]\cr
#' Function to collect values from \code{job} and result \code{res} object, the latter from stored result file.
#' Must return a named object which can be coerced to a \code{data.frame} (e.g. a \code{list}).
#' Default is a function that simply returns \code{res} which may or may not work, depending on the type
#' of \code{res}. We recommend to always return a named list.
#' @param ... [any]\cr
#' Additional arguments to \code{fun}.
#' @param strings.as.factors [\code{logical(1)}]
#' Should all character columns in result be converted to factors?
#' Default is \code{FALSE}.
#' @param block.size [\code{integer(1)}]
#' Results will be fetched in blocks of this size.
#' Default is max(100, 5 percent of ids).
#' @param impute.val [\code{named list}]\cr
#' If not missing, the value of \code{impute.val} is used as a replacement for the
#' return value of function \code{fun} on missing results. An empty list is allowed.
#' @param apply.on.missing [\code{logical(1)}]\cr
#' Apply the function on jobs with missing results? The argument \dQuote{res} will be \code{NULL}
#' and must be handled in the function.
#' This argument has no effect if \code{impute.val} is set.
#' Default ist \code{FALSE}.
#' @template arg_progress_bar
#' @return [\code{data.frame}]. Aggregated results, containing problem and algorithm paramaters and collected values.
#' @aliases ReducedResultsExperiments
#' @export
reduceResultsExperiments = function(reg, ids, part = NA_character_, fun, ...,
strings.as.factors = FALSE, block.size, impute.val,
apply.on.missing = FALSE, progressbar = TRUE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
syncRegistry(reg)
assertFlag(apply.on.missing)
if (missing(ids)) {
ids = done = findDone(reg)
with.impute = FALSE
} else {
ids = checkIds(reg, ids)
done = findDone(reg, ids)
with.impute = !missing(impute.val)
if (with.impute) {
if (!is.list(impute.val) || !isProperlyNamed(impute.val))
stop("Argument 'impute.val' must be a properly named list")
} else if (!apply.on.missing) {
not.done = setdiff(ids, done)
if (length(not.done) > 0L)
stopf("No results available for jobs with ids: %s", collapse(not.done))
}
}
checkPart(reg, part)
if (missing(fun))
fun = function(job, res) res
else
assertFunction(fun, c("job", "res"))
assertFlag(strings.as.factors)
if (missing(block.size)) {
block.size = max(100L, as.integer(0.05 * length(ids)))
} else {
block.size = asCount(block.size)
}
assertFlag(progressbar)
n = length(ids)
info("Reducing %i results...", n)
impute = if (with.impute) function(job, res, ...) impute.val else fun
getRow = function(j, reg, part, .fun, missing.ok, ...)
c(list(id = j$id, prob = j$prob.id), j$prob.pars, list(algo = j$algo.id), j$algo.pars, list(repl = j$repl),
.fun(j, getResult(reg, j$id, part, missing.ok), ...))
aggr = data.table()
ids2 = chunk(ids, chunk.size = block.size, shuffle = FALSE)
if (progressbar) {
bar = makeProgressBar(max = length(ids2), label = "reduceResultsExperiments")
bar$set()
} else {
bar = makeProgressBar(style = "off")
}
prob.pars = character(0L)
algo.pars = character(0L)
tryCatch({
for(id.chunk in ids2) {
jobs = getJobs(reg, id.chunk, check.ids = FALSE)
prob.pars = unique(c(prob.pars, unlist(lapply(jobs, function(j) names(j$prob.pars)))))
algo.pars = unique(c(algo.pars, unlist(lapply(jobs, function(j) names(j$algo.pars)))))
id.chunk.done = id.chunk %in% done
results = c(lapply(jobs[ id.chunk.done], getRow, reg = reg, part = part, .fun = fun, missing.ok = apply.on.missing, ...),
lapply(jobs[!id.chunk.done], getRow, reg = reg, part = part, .fun = impute, missing.ok = apply.on.missing, ...))
aggr = rbind(aggr, rbindlist(results, fill = TRUE), fill = TRUE)
bar$inc(1L)
}
}, error = bar$error)
aggr = setDF(aggr)
aggr = convertDataFrameCols(aggr, chars.as.factor = strings.as.factors)
# name rows with ids so one can easily index
# THEN RESORT WRT TO IDS from call
# NB: in the for-loop above we potentially changed that order if we used imputing,
# see lines after id.chunk.done = ...
if (nrow(aggr) > 0L) {
aggr = setRowNames(aggr, aggr$id)
aggr = aggr[as.character(ids), ]
}
aggr = addClasses(aggr, "ReducedResultsExperiments")
attr(aggr, "prob.pars.names") = prob.pars
attr(aggr, "algo.pars.names") = algo.pars
return(aggr)
}
#' Get variable groups of reduced results.
#'
#' Useful helper for e.g. package plyr and such.
#'
#' @param data [\code{\link{ReducedResultsExperiments}}]\cr
#' Result data.frame from \code{\link{reduceResultsExperiments}}.
#' @param type [\code{character(1)}]\cr
#' Can be \dQuote{prob} (prob + pars), \dQuote{prob.pars} (only problem pars),
#' \dQuote{algo} (algo + pars), \dQuote{algo.pars} (only algo pars),
#' \dQuote{group} (prob + problem pars + algo + algo pars), \dQuote{result} (result column names).
#' Default is \dQuote{group}.
#' @return [\code{character}]. Names of of columns.
#' @export
#' @examples
#' reg = makeExperimentRegistry("BatchExample", seed = 123, file.dir = tempfile())
#' addProblem(reg, "p1", static = 1)
#' addProblem(reg, "p2", static = 2)
#' addAlgorithm(reg, id = "a1",
#' fun = function(static, dynamic, alpha) c(y = static*alpha))
#' addAlgorithm(reg, id = "a2",
#' fun = function(static, dynamic, alpha, beta) c(y = static*alpha+beta))
#' ad1 = makeDesign("a1", exhaustive = list(alpha = 1:2))
#' ad2 = makeDesign("a2", exhaustive = list(alpha = 1:2, beta = 5:6))
#' addExperiments(reg, algo.designs = list(ad1, ad2), repls = 2)
#' submitJobs(reg)
#' data = reduceResultsExperiments(reg)
#' library(plyr)
#' ddply(data, getResultVars(data, "group"), summarise, mean_y = mean(y))
getResultVars = function(data, type = "group") {
assertClass(data, "ReducedResultsExperiments")
assertChoice(type, c("prob", "prob.pars", "algo", "algo.pars", "group", "result"))
switch(type,
prob = c("prob", attr(data, "prob.pars.names")),
prob.pars = attr(data, "prob.pars.names"),
algo = c("algo", attr(data, "algo.pars.names")),
algo.pars = attr(data, "algo.pars.names"),
group = c("prob", "algo", attr(data, "prob.pars.names"), attr(data, "algo.pars.names")),
result = setdiff(colnames(data), c("id", "algo", "prob", "repl", attr(data, "prob.pars.names"), attr(data, "algo.pars.names")))
)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/reduceResultsExperiments.R
|
#' @title Reduce very many results in parallel.
#'
#' @description
#' Basically the same as \code{\link{reduceResultsExperiments}} but creates a few (hopefully short) jobs
#' to reduce the results in parallel. The function internally calls \code{\link{batchMapQuick}},
#' does \dQuote{busy-waiting} till
#' all jobs are done and cleans all temporary files up.
#'
#' The rows are ordered as \code{ids} and named with \code{ids}, so one can easily index them.
#'
#' @inheritParams reduceResultsExperiments
#' @param timeout [\code{integer(1)}]
#' Seconds to wait for completion. Passed to \code{\link[BatchJobs]{waitForJobs}}.
#' Default is 648400 (one week).
#' @param njobs [\code{integer(1)}]
#' Number of parallel jobs to create.
#' Default is 20.
#' @return [\code{data.frame}]. Aggregated results, containing problem and algorithm paramaters and collected values.
#' @export
reduceResultsExperimentsParallel = function(reg, ids, part = NA_character_, fun, ...,
timeout = 604800L, njobs = 20L, strings.as.factors = FALSE, impute.val,
apply.on.missing = FALSE, progressbar = TRUE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
syncRegistry(reg)
assertFlag(apply.on.missing)
if (missing(ids)) {
ids = done = findDone(reg)
} else {
ids = checkIds(reg, ids)
done = findDone(reg, ids)
if (!missing(impute.val)) {
if (!is.list(impute.val) || !isProperlyNamed(impute.val))
stop("Argument 'impute.val' must be a properly named list")
} else if (!apply.on.missing) {
not.done = which(ids %nin% done)
if (length(not.done) > 0L)
stopf("No results available for jobs with ids: %s", collapse(not.done))
}
}
checkPart(reg, part)
if (missing(fun)){
fun = function(job, res) res
} else {
fun = match.fun(fun)
assertFunction(fun, c("job", "res"))
}
njobs = asCount(njobs, positive = TRUE)
assertFlag(strings.as.factors)
assertFlag(progressbar)
n = length(ids)
if (n == 0) {
res = data.frame()
attr(res, "prob.pars.names") = character(0L)
attr(res, "algo.pars.names") = character(0L)
return(addClasses(res, "ReducedResultsExperiments"))
}
info("Reducing %i results...", n)
ch = chunk(ids, n.chunks = njobs, shuffle = FALSE)
more.args = c(list(reg = reg, part = part, fun = fun, strings.as.factors = strings.as.factors, apply.on.missing = apply.on.missing), list(...))
if (!missing(impute.val))
more.args$impute.val = impute.val
prefix = "reduceExperimentsParallel"
file.dir.new = file.path(reg$file.dir, basename(tempfile(prefix)))
if (length(dir(reg$file.dir, pattern = sprintf("^%s", prefix))))
warningf("Found cruft directories from previous calls to reduceResultsExperimentsParallel in %s", reg$file.dir)
reg2 = batchMapQuick(function(reg, ii, fun, part, strings.as.factors, impute.val, apply.on.missing, ...) {
# FIXME this synchronizes the registry on the node!
reduceResultsExperiments(reg, ii, part = part, fun = fun,
strings.as.factors = strings.as.factors,
impute.val = impute.val, apply.on.missing = apply.on.missing, progressbar = progressbar, ...)
}, ch, more.args = more.args, file.dir = file.dir.new)
waitForJobs(reg2, timeout = timeout, stop.on.error = TRUE, progressbar = progressbar)
res = reduceResultsList(reg2, progressbar = progressbar)
unlink(reg2$file.dir, recursive = TRUE)
df = rbindlist(res, fill = TRUE)
setDF(df)
attr(df, "prob.pars.names") = unique(unlist(lapply(res, attr, "prob.pars.names")))
attr(df, "algo.pars.names") = unique(unlist(lapply(res, attr, "algo.pars.names")))
rownames(df) = df$id
return(addClasses(df[as.character(ids),, drop = FALSE], "ReducedResultsExperiments"))
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/reduceResultsExperimentsParallel.R
|
#' @title Remove algorithm from registry.
#'
#' @description
#' THIS DELETES ALL FILES REGARDING THIS ALGORITHM, INCLUDING ALL JOBS AND RESULTS!
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Id of algorithm.
#' @param force [\code{logical(1)}]\cr
#' Also remove jobs which seem to be still running.
#' Default is \code{FALSE}.
#' @return Nothing.
#' @family remove
#' @export
removeAlgorithm = function(reg, id, force = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = TRUE)
syncRegistry(reg)
assertString(id)
if (id %nin% dbGetAllAlgorithmIds(reg))
stop("Algorithm not present in registry: ", id)
info("Removing Experiments from database")
ids = dbFindExperiments(reg, algo.pattern = id, like = FALSE)
removeExperiments(reg, ids = ids, force = force)
info("Removing Algorithm from database")
dbRemoveAlgorithm(reg, id)
fn = getAlgorithmFilePath(reg$file.dir, id)
info("Deleting algorithm file: %s", fn)
ok = file.remove(fn)
if (!ok)
warningf("Could not remove algorithm file: %s", fn)
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/removeAlgorithm.R
|
#' @title Remove jobs from registry.
#'
#' @description
#' THIS DELETES ALL FILES REGARDING THE JOBS, INCLUDING RESULTS!
#' If you really know what you are doing, you may set \code{force}
#' to \code{TRUE} to omit sanity checks on running jobs.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [\code{integer}]\cr
#' Ids of jobs you want to remove.
#' Default is none.
#' @param force [\code{logical(1)}]\cr
#' Also remove jobs which seem to be still running.
#' Default is \code{FALSE}.
#' @return Vector of type \code{integer} of removed job ids.
#' @family remove
#' @export
removeExperiments = function(reg, ids, force = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = TRUE)
syncRegistry(reg)
if (missing(ids))
return(integer(0L))
ids = checkIds(reg, ids)
if (!force) {
cf = getConfig()$cluster.functions
if(is.null(cf$listJobs) || is.null(cf$killJobs)) {
stop("Listing or killing of jobs not supported by your cluster functions\n",
"You need to set force = TRUE to remove jobs, but note the warning in ?removeExperiments")
}
running = findRunning(reg, ids)
if (length(running) > 0L)
stopf("Can't remove jobs which are still running. You have to kill them first.\nRunning: %s",
collapse(running))
}
info("Removing %i experiments ...", length(ids))
dbRemoveJobs(reg, ids)
fmt = "^%i(\\.(R|out)|-result(-.+)*\\.RData)$"
for (id in ids) {
fs = list.files(getJobLocation(reg, id), pattern = sprintf(fmt, id), full.names = TRUE)
ok = file.remove(fs)
if (!all(ok))
warningf("Could not remove files for experiment with id=%i", id)
}
invisible(ids)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/removeExperiments.R
|
#' @title Remove problem from registry.
#'
#' @description
#' THIS DELETES ALL FILES REGARDING THIS PROBLEM, INCLUDING ALL JOBS AND RESULTS!
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param id [\code{character(1)}]\cr
#' Id of problem.
#' @param force [\code{logical(1)}]\cr
#' Also remove jobs which seem to be still running.
#' Default is \code{FALSE}.
#' @return Nothing.
#' @family remove
#' @export
removeProblem = function(reg, id, force = FALSE) {
checkExperimentRegistry(reg, strict = TRUE, writeable = TRUE)
syncRegistry(reg)
assertString(id)
if (id %nin% dbGetAllProblemIds(reg))
stop("Problem not present in registry: ", id)
info("Removing Experiments from database")
ids = dbFindExperiments(reg, prob.pattern = id, like = FALSE)
removeExperiments(reg, ids = ids, force = force)
info("Removing Problem from database")
dbRemoveProblem(reg, id)
fn = getProblemFilePaths(reg$file.dir, id)
info("Deleting problem files: ", collapse(fn, sep = ", "))
ok = file.remove(fn)
if (!all(ok))
warningf("Could not remove problem files: %s", collapse(fn[!ok], sep = ", "))
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/removeProblem.R
|
#' @export
setJobFunction.ExperimentRegistry = function(reg, ids, fun, more.args = list(), reset = TRUE, force = FALSE) {
stop("setJobFunction not available for BatchExperiments. Please use addProblem or addAlgorithm with overwrite = TRUE")
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/setJobFunction.R
|
#' @title Summarize selected experiments.
#'
#' @description
#' A data.frame is returned that contains summary information
#' about the selected experiments. The data.frame is constructed
#' by building the columns \dQuote{prob, <prob.pars>, algo, <algo.pars>, repl}.
#' Now only the columns in \code{show} will be selected, how many of such experiments
#' exist will be counted in a new column \dQuote{.count}.
#'
#' @param reg [\code{\link{ExperimentRegistry}}]\cr
#' Registry.
#' @param ids [\code{integer}]\cr
#' Selected experiments.
#' Default is all experiments.
#' @param show [\code{character}]\cr
#' Should detailed information for each single experiment be printed?
#' Default is \code{c("prob", "algo")}.
#' @return [\code{data.frame}].
#' @export
#' @examples
#' reg = makeExperimentRegistry("summarizeExperiments", seed = 123, file.dir = tempfile())
#' p1 = addProblem(reg, "p1", static = 1)
#' a1 = addAlgorithm(reg, id = "a1", fun = function(static, dynamic, alpha, beta) 1)
#' a2 = addAlgorithm(reg, id = "a2", fun = function(static, dynamic, alpha, gamma) 2)
#' ad1 = makeDesign(a1, exhaustive = list(alpha = 1:2, beta = 1:2))
#' ad2 = makeDesign(a2, exhaustive = list(alpha = 1:2, gamma = 7:8))
#' addExperiments(reg, algo.designs = list(ad1, ad2), repls = 2)
#' print(summarizeExperiments(reg))
#' print(summarizeExperiments(reg, show = c("prob", "algo", "alpha", "gamma")))
summarizeExperiments = function(reg, ids, show = c("prob", "algo")) {
checkExperimentRegistry(reg, strict = TRUE, writeable = FALSE)
syncRegistry(reg)
assertCharacter(show, min.len = 1, any.missing = FALSE)
dbSummarizeExperiments(reg, ids, show)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/summarizeExperiments.R
|
#' @export
copyRequiredJobFiles.ExperimentRegistry = function(reg1, reg2, id) {
job = getJob(reg1, id, check.id = FALSE)
src = getProblemFilePaths(reg1$file.dir, job$prob.id)
dest = getProblemFilePaths(reg2$file.dir, job$prob.id)
info("Copying problem files: %s", collapse(src, sep = ", "))
file.copy(src, dest)
src = getAlgorithmFilePath(reg1$file.dir, job$algo.id)
dest = getAlgorithmFilePath(reg2$file.dir, job$algo.id)
info("Copying algorithm file: %s", src)
file.copy(src, dest)
}
|
/scratch/gouwar.j/cran-all/cranData/BatchExperiments/R/testJob.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.